Once we get the pages converted, we’ll create the por-tal page itself by dynamically loading User Controls on the page in response tothe menu choices our users make.. You Will Need ✔Vis
Trang 1Table 5.1 The Checkbox Dialog Properties
CheckboxNLabel The text displayed next to the check box, describing the
option you are providing
CheckboxNProperty A name for the property that represents that value
stored in the check box This name will be referenced
by the Installer elsewhere and must be all uppercase
CheckboxNValue The initial value of the check box, Checked or
in the Checkbox1Property field, BINSTALLDB We will use this name later to refer to
the check box, allowing us to reference the value the user selected
That takes care of setting up and defining our dialog Now we have to make use ofthe check box we provided to the user We will set a File Condition that will only installthe database file if the check box is on Return to the File Editor and select theprj02.mdb file Enter the following condition into the Condition field of the Propertieswindow:
BINSTALLDB = 1
If this condition equates to true, meaning that the check box we created is, in fact,checked, the file will be installed Otherwise, it will be ignored
Adding a Custom Action
The Windows Installer gives you the opportunity to execute any code of your ownwhen an installation task (deployment, rollback, uninstall, etc.) has completed You caneither use a canned action that comes with the installation tools or write custom code
of your own To illustrate the process, we are going to create a simple custom processthat displays a Thank You message box to users, stating that we appreciate that theyhave installed our bug-tracking product
You can create any sort of executable that you like and run it when the installation isover I’m going to show you how to build a basic executable shell that you can use tolaunch other processes Using this simple shell, you could write all sorts of utilities thatwould be useful for an installation
Let’s build the custom action quickly using a step-by-step process We’ll start bybuilding the program we want to run during the custom action, and then we’ll add it
to the deployment project The instructions follow:
Trang 21 Create a new project in Visual Studio It should be of the Class Library type,and you should name it ThankYou.
2 In the Solution Explorer, delete the item called Class1.vb
3 Right-click on the project name in the Solution Explorer, and from the contextmenu, select Add Module When the dialog appears, name it ThankYouModuleand click OK This creates an empty namespace for us to work in,
4 Add the code we want to execute It looks just like this:
Public Sub Main() MsgBox(“We at Vulture Corporation wanted to say a “ & _
“special thanks for taking the time to install “ & _
“our bug-tracking system.” & vbCrLf & vbCrLf & _
“Feel free to contact our customer support line “ & _
“at (123) 555-1234 should you have any questions.” & _ vbCrLf & vbCrLf & _
“Good luck and good code!” MsgBoxStyle.Information, _
“Thanks!”) End Sub
The Public Sub Main is our standard entry point
5 In the Solution Explorer, select the project, right-click on it, and select Properties
from the context menu Set the Output Type to Windows Application, and the Startup Object to Sub Main.
6 Save the project and build it We have created a simple Windows EXE programthat displays a message box and has no other UI You can use the same tech-nique, replacing our message box code with any code you like
7 Test the application by locating ThankYou.exe in Windows Explorer and executing it It should display our message box and then go away
8 Close the ThankYou project and Load the deployment project In the File Editor,select the Add Assembly option and add our ThankYou.exe program to the filelist
9 In the Custom Actions Editor, select the Commit item from the event tree andright-click on it Select the Add Custom Action option In the selection dialog,open the Application Folder and choose the ThankYou.exe program that wejust added using the File Editor Click OK, and the new action should appear inthe tree underneath the Commit event
10 Make sure the new action, ThankYou.exe, is selected and examine the propertieswindow for that item Change the value of the property called InstallerClass tofalse
11 Save the deployment project and build it
You have now added a custom action to your deployment When you execute theinstallation, the custom action will run at approximately the end of the installationoperation
Deployment Packages 187
Team-Fly®
Trang 3Building and Running the Installation
There is one last setting to make On the toolbar, select Release mode And now thateverything is configured, you can build the installation
Select Build from the Build menu The tools build your installation package, detailingthe files it is adding in the Output window Take a look at this to see some of the items
in the runtime that are being added for you
When the installation build is complete, execute it by browsing to the Release tory under the project directory and double-click the MSI file This file type is associ-ated with the Microsoft Installer Engine and will run without a specific EXE This can
direc-be a useful deployment feature For one thing, the installation package is a littlesmaller because the engine is not part of the deal Additionally, some Web site admin-istrators will not allow EXE files to be placed on their servers as available downloadsfor security purposes MSI files, lacking the EXE extension, can be placed there withoutfear
Run the execution and take a look at it The welcome screen makes a nice firstimpression, especially with our new banner graphic Figure 5.25 shows the new wel-come screen with the new banner and our text updates
The next dialog is our custom options dialog, where you can see the check box thatprovides the database installation option Figure 5.26 shows what it looks like Leavethe box checked and click Next
Figure 5.25 The new installation welcome dialog.
Trang 4Figure 5.26 The customized checkbox dialog.
The installation dialog box is next, and it looks pretty normal One interesting ture of this dialog is the Disk Cost button, which is provided free A click of this buttonwill display a dialog for the user that details how much disk space the installation willtake It is illustrated in Figure 5.27
fea-Figure 5.27 The Disk Cost dialog.
Trang 5Finish everything else up and the installation begins to run When it’s all over, thecustom action we created launches the browser and loads our advertising page Theapplication is completely installed, including uninstall information in the Add/RemovePrograms control panel.
If we were to run our installation package again, without first uninstalling it, the UI
we see would be different We get a wizard panel that asks us if we want to uninstall orrepair the existing installation, which it will do for us if selected
to include the Windows Installation Bootstrap along with your deployment package.
This option adds a few extra files into your release or debug deployment directorywhen the package is built Instead of running the MSI file, you run the Setup.exe pro-gram This is a runtime version of the installation engine that you can use on Windowsplatforms that do not have the engine built in When you create your deploymentmedia, or move your deployment files to a network, simply include these few extrafiles and anyone will be able to install your program
Note that, although Windows ME includes the installation engine, it may notinclude the same version, 1.5, that comes with Visual Studio NET If it does not, clientswithout it will have to use the setup.exe program instead
Project 5c: Web Setup
Web Setup projects allow you to deploy projects to an IIS Web server I will be trating a slightly different method of creating a deployment project: using Project Outputs, which allows you to add a deployment project to your main project This notonly keeps the two projects together, but it makes it easier to add the correct files to theinstallation project
illus-We will be deploying the bug-tracking illus-Web service that we built in Project 3 to a illus-Webserver (make sure you have one around) Begin by opening the project file for prj03 inVisual Studio From the file menu, add a new project to the current solution In theNew Project dialog select the Web setup project type, and name it prj03setup ClickNext, and in the content selection dialog, check these options:
■■ Primary output
■■ Debug symbols
■■ Content files
Trang 6Figure 5.28 The Web setup content options dialog.
Figure 5.28 shows these selections checked This dialog lists all the outputs from theprimary project in the solution, in this case, the Web service Click Next to move on, andclick Next again to clear the Additional Files dialog Click Finish to create the project
The deployment project has been added to our solution, alongside our primary project When you build the solution (go ahead, try it now), it will build your primary project first and then the deployment project using the outputs from the pri-mary project
All that remains is to run the installation for the Web service Run through the lation, which should deploy the Web service to your instance of IIS You can test it out
instal-by pointing to the Web site it created, like this (assuming you installed it to your localmachine):
http://localhost/prj03setup/ProblemLogger.asmx
The successful execution will look like Figure 5.29 If it does not run properly, you may need to adjust the properties of the Web site in the IIS Admin tool Change the execute permissions on the prj03setup to Scripts and Executables, as shown in Figure 5.30
Trang 7Figure 5.29 Successful execution of the deployed Web service.
Figure 5.30 Adjusting the Web service execution permissions.
Trang 8That’s it for a Web setup deployment Very simple, especially for setting up a Webservice We don’t have to understand much about the deployment of a Web application
or the intricacies of IIS The setup tools know it all
Enhancing the Project
You’ve seen a lot of deployment capabilities and options in this project, but there aremany more Buried in the Installer tools documentation are features such as the ability
to create CAB file projects for the deployment of ActiveX controls; adding splashscreens, user registration, read me, or other dialogs; registry manipulations; and tons
of low-level details that make fine-tuning your control over your deployment a breeze.Although the installation tools won’t handle every situation you can throw at it, it’sorders of magnitude better than the tools that previously came with Visual Studio
There is a lot to cover in the topic of deployment and plenty of opportunities to usesome of the capabilities we didn’t get to, including:
Write another custom action. For the Web service deployment, create a custom
action to actually create the database it needs in SQL Server A little code and a
couple of SQL scripts would take care of it
Make the Merge Module global. With a little work, you can rebuild the
prj01classes component as a strongly named component This would allow you
to install it in the Global Assembly Cache, available for use by other applications
Add some splash. Create a splash screen and add it to your installation project
You could do the same thing with a read me file, or even add another check box
that would ask users if they want to see the read me
Register a user. Add functionality to handle user registration to the project You
can add custom dialogs to the project that make a great starting point for lettingusers register your product
WHAT’S COMING NEXT
Enter the world of ASP.NET development when we build a customizable Web portal It will
be an action-packed tour through ASP.NET, including Web development, a new ADO.NET
trick or two, and how to tune the project to suit your own needs.
Trang 10This ease of use has not come without a downside VBScript is an interpreted guage, requiring the Web server to parse and compile ASP pages on the server asrequests for them come in ASP script is inserted inline into the HTML output of apage, rapidly creating a spaghetti mess of code that is difficult to maintain andenhance WYSIWYG editors frequently squashed this server side code that it couldnot understand The popular Session object provided state maintenance in an
lan-Web Portal with ASP.NET
6
Trang 11intrinsically stateless environment, but the solution would not work in a Web farmenvironment No good infrastructure for server side caching of output existed Wecame close before the release of Windows 2000, with the IMDB, but this subsystemmysteriously vanished when the OS was released Although business objects imple-mented in a COM-compliant language and hosted in MTS provided fine separation
of the user interface from business logic, deploying and versioning these COM DLLswas a nightmare, especially on Web sites where high availability was a must, becausethe Web server must be stopped to update the DLLs Poor coding practices made itexceedingly easy to bring a Web site to its knees as the number of users increased(ever try storing a COM object instance in the Session object?)
Microsoft is well aware of all of these problems and has created the ASP.NETFramework from the ground up to address them
In this project we’ll be examining this new Framework in detail At first glance,ASP.NET can have a strong resemblance to traditional Active Server Pages Microsoftsays you can simply change the extension of an ASP page to ASPX and it will work inthe new Framework But as you dig deeper into the richness of the Framework, youbegin to see that the Framework is a total overhaul of ASP, and fully utilized, anASP.NET solution begins to look more like a VB6 solution than the mire of script codewe’ve become accustomed to
We are going to create a Web portal solution This is a site that demonstrates tionality that (depending on content) could be deployed on a company intranet or as apublic Internet site, aggregating custom content for our visitors We will see how to usethe new Framework to build custom content for different users, authenticate our visi-tors, drive content with relational data and XML, and build rich user interfaces formodification of our backend data stores All this will be done with standard, cross-browser compatible, W3C-compliant, HTML
func-THE PROBLEM:
We want to deliver public and corporate information to our employees in a secure
environment We want this information to be tailored to different employees and
different departments It needs to be easily extensible so that we can add functionality as our business needs change
THE SOLUTION:
We will deliver this solution using a custom portal for the users of our company’s
intranet This will be a secure site that renders content based on the user visiting the pages We’ll provide user interfaces so that users can select which content appears in specific areas based on their preferences We’ll also provide interfaces for managers to provide news to the people in their departments and an interface for an administrator to create and maintain a list of authorized users of the application.
Trang 121 Separate and implement the functionality We’ll start by building the
differ-ent areas of functionality as separate ASP.NET pages
2 Convert pages to User Controls After getting the different functional areas
implemented, we’ll convert them to User Controls so that we can use themtogether on the same page User Controls are an excellent vehicle for reuse ofcode that is new to ASP.Net
3 Create the portal page Once we get the pages converted, we’ll create the
por-tal page itself by dynamically loading User Controls on the page in response tothe menu choices our users make
You Will Need
✔Visual Basic NET
✔A basic knowledge of Visual Basic NET and Active Server Pages
applica-it generates the HTML output of the page The ASP.NET Framework is an entirely newruntime geared toward the generation of HTML Requests for files with an aspx exten-sion are delegated to aspnet_isapi.dll This is a managed component that createsinstances of NET classes in the service of the request
Web Portal with ASP.NET 197
Team-Fly®
Trang 13The ASP.NET Framework is a subset of the NET system classes Included are myriadclasses to dynamically create HTML for you, including a dozen types of lists, HTMLtables and forms, and validation logic; classes to manage state and caching and to con-figure and secure your application; and a set of classes to provide backward compati-bility to traditional ASP When you create an ASPX page, you are actually creating aclass that inherits from and extends the System.Web.Page class The runtime creates aninstance of this class when your page is requested, and its job is to return the HTML thatservices the request Because the class inherits from the Page object, there are standardmethods that the runtime knows to call to execute your page’s logic Using Visual Stu-dio NET, this infrastructure is provided for you, so the code you create can look verymuch like a traditional Active Server Page However, as you learn the services andinfrastructure of the Framework, your code will more likely resemble a Visual Basicform, with a file for the user interface elements and a separate file for your code.Because of the NET architecture, the code that you write is very object oriented.Need to set the current item of an HTML select list? Set the SelectedIndex property of
an HTMLSelect object Need to generate an HTML table based on a SELECT ment? Set the DataSource property of a DataGrid object and call DataBind on thatobject The work of HTML generation is done for you, under the hood, by these objects Does this all sound like a strange new environment? As we start to examine somecode and create our own ASP.NET pages, you’ll see that it’s not really that difficult atall And once you get used to the changes in the new Framework, you’ll find that yourwork is much easier than with traditional ASP Let’s start by comparing the newFramework to what we’re used to
state-How Is ASP.NET Different
from Traditional ASP?
There are a number of striking differences between ASP.NET and ASP For some ofthese differences, the benefits will be immediately obvious For others, we’ll have toget used to new ways of thinking about dynamic Web pages Among the changes are:
ASP.NET pages are compiled, not interpreted. A binary executable is compiledupon the first request to the page This image is stored in an in-memory cache
on the Web server, and subsequent requests to this page use this executable toservice the request
Because we no longer need a script interpreter, we have full access to the guage features of Visual Basic NET. We’ll actually be writing programs thatinteract with objects instead of writing script to output HTML Consider thegeneration of an HTML SELECT list to use as a combo box on a data entry form
lan-to populate a foreign key value With ASP your code would generate an
OPTION tag for each row in the recordset used to populate the list Each
OPTION tag generated would need to check that value against the foreign keyvalue, and if a match were found, it would output the SELECTED attribute onthe option tag With ASP.NET, you use an instance of the DropDownList ServerControl This object exposes an item collection To create the SELECT list, yousimply add a ListItem object to this collection for each row in your resultset To
Trang 14set the selected row, you set the SelectedIndex property The data binding
ser-vices exposed by this object actually reduce this task to four lines of code If it
sounds more like VB than ASP, it is
The Framework provides a very clean separation of code from content. With
ASP, because the HTML is generated as the page is interpreted, your page logic
must be embedded into the page at the location where you want the HTML erated by this logic to be output With ASP.NET, no HTML is generated until all
gen-of the code in your page has finished executing The entire task gen-of HTML
gener-ation is done in the page’s rendering step, which uses the properties of the
objects you’ve created to generate HTML for you This is great news for all of uswho consider script writing and HTML generation a poor substitute to sitting
down and writing real code
Of all the differences, this one is the biggest In ASP your task was to add script
code to the body of an HTML page The job of this script was to generate HTML.With ASP.NET you create and interact with objects, setting properties like Visi-
ble, calling methods, and using data binding services After all of your code has
executed, the HTML for the page is rendered, and the output is sent to the
client This leaves you with pages that have a clearer separation of content
from code and are easier to maintain; your code looks more like traditional
code than script that generates HTML This is accomplished by the abstraction
layer created between you and the HTML you’re generating by the ASP.NET
Framework
ASP.NET Framework maintains state for you. Do you ever have to post to the
server to apply validation logic to a data entry HTML form? When there’s a
problem, you must write code to repopulate every input on your HTML form
You must also execute script inline to add validation messages next to the fields
that have errors The resulting code is often a tangled mess If the business logic
changes, that’s a tough page to maintain With the ASP.NET Framework, this
state maintenance is done for you The fields maintain their value without a gle line of code written by you This applies not only to simple text inputs but
sin-also to SELECT lists, check boxes, radio buttons, and any other input types on
your form Built-in validation controls allow you to enforce your business logic
by adding a single tag to your page and simply checking the Page.IsValid
prop-erty when it posts to the server
ASP.NET runs events on the server. In ASP, because of the amount of script that
must be mixed with the HTML, it’s common to split a single functional area
across several pages One page may collect data from a user, whereas another
accepts the HTTP post and updates your relational data, telling your user the
result of the operation Although it’s possible to put this functionality into a gle ASP page, you do so at the risk of needing to maintain a garbled mess of
sin-code over the long haul Breaking these functions into separate pages causes the
number of files in your Web site to balloon With ASP.NET, you can set up server
side event traps This is similar to Remote Scripting, but it works with standard
HTML You can add an HTML button to a page and have its click event trapped
on the server, where a method of your page class applies validation, updates
Trang 15persistence, and informs the user of the result With this single event sink, theoperation is easily done without adding a smidgeon of code to the body of theHTML page All of the work is done in your method by interacting with theobjects exposed by the page.
ASP.NET provides a consistent event model. With ASP, script is executed on thepage in a top-down manner Although it’s possible to put your script withinfunctions that you call from the page body, there’s no event model that fires atspecific points in the lifecycle of your page With ASP.NET, this event model hasbeen added Most importantly, there’s an event fired whenever your pagebegins to load This is very much like the Form_Load event in VB The pageload event can be trapped in a script tag or from your code behind the page.This gives you a consistent model for setting up your output This is where you
do things like initialize database data you’re going to output on the page, populate form values, and apply custom attributes We’ll take a look at the pageload event in detail in a bit because you will probably be using it from most ofthe ASP.NET pages you create
pre-Before we jump into the project, you’ll need to be familiar with a few of the tant parts of the ASP.NET Framework Let’s take a look at them now
impor-Abstraction Layer between Code and HTML
The abstraction layer is created with a new suite of server-side objects These objectshave the sole task of generating HTML Exactly what HTML is generated is deter-mined by the properties and methods you call on these objects before the page is ren-dered Instances of these objects can be created declaratively in code, or you can usespecial tags in the body of your HTML document By declaring them on your page,you’re telling the Framework in advance where the HTML generated by the objectshould reside within the final output
The first set of objects we’ll look at are the HTML controls This is a set of objects thatgenerate a single HTML element for you, elements like anchor tags, image tags, andform inputs of different types You create an instance of an object by adding two attrib-utes to your HTML tag:
<a href='' runat=server id=objAnchor>Link Text</a>
Adding the attributes runat and id to the tag causes an instance of HTMLAnchorobject to be created when your page is requested This object exposes properties andmethods that are specific to an HTML anchor tag The HTMLAnchor object is part ofthe System.Web.UI.HTMLControls namespace Let’s take a look at a simple use of theobject from the Page_Load event of our page You can find the complete listing for thispage in HTMLControl.aspx in the demo folder
What we’re doing here is controlling what the hyperlink does and where it goes bythe season in which our user visits our page Let’s start at the top The footprint for thepage_load event looks like this:
Private Sub Page_Load _
Trang 16This footprint is very common in ASP.NET and is used by most event traps in theFramework The first parameter is always of type System.Object This is actually aninstance of the object that has raised the event So for example, when you’re trappingthe On_Click event for a button, the first parameter will contain a reference to aninstance of that button object The second parameter varies in type depending on theevent but is always a class that inherits from System.EventArgs These parameters areused less in the Page_Load event than in other, more specific types of event traps Thenext block of code sets up the dynamic output of the page:
Select Case aMonth
objAnchor.InnerText = "Images of " & sSeason
objAnchor.HRef = sURL
The first is the innerText property You may recognize this from working withDHTML on the client This is the text that appears between the begin and end tags ofany element on our page This is a property that is exposed by all of the HTML servercontrols It will cause the displayed text of the anchor tag to be equal to the value of thesSeason string The second property is specific to the HTML anchor control This is thetarget URL of the anchor, the page that the browser will navigate to when a user clicks
on the anchor’s text After the function executes, the page enters its rendering stage,and the HTML for the document is generated Notice that we have not written anycode to generate HTML The anchor object does this for us based on the properties wehave set from the code If we choose View Source from the browser, here is how theanchor tag gets rendered (in September):
<a id="objAnchor"
href="http://www.myneighborsgarden.com/summerpages/summerthumbnails.htm"
Trang 17Notice that the original text of the anchor tag and the runat=server attribute are notpart of the HTML that gets sent to the client The runat=server attribute is alwaysremoved when the element is rendered, and the original text of the anchor tag (LinkText) was replaced when we set the InnerHTML property of the object Notice also that,although we had to declare our string variables, there is no declaration for the objAn-chor class instance This is done for us under the hood by the Framework, driven bythe runat=server attribute on the declaration of the anchor tag.
We can add a runat=server attribute to any element on our page The attributes ofthese elements are then exposed as properties of the corresponding object that getsinstantiated In this way we can keep all server-side script tags we would have used intraditional ASP out of the body of our document, relying instead on the propertiesexposed on the object Some other HTML elements exposed as objects in the Sys-tem.Web.UI.HTMLControls namespace are listed in Table 6.1
Even tags not listed in the table can be created as server-side objects If a specificclass doesn’t exist for a tag you want programmatic access to on the server (for exam-ple, the BODY tag), you can still add a runat=server attribute to the tag declaration.The type of object that gets created will be an HTMLGenericControl This objectexposes properties that are common attributes of HTML elements Absent are specificproperties for more specialized tags All of the HTML control classes inherit from theHTMLContainerControl class
An ASP.NET page request follows this lifecycle:
■■ Request ASPX page
■■ Compile image or retrieve from cache
■■ Execute Page_Load event
■■ Execute events included with request
■■ Execute data binding called by event traps
■■ Execute Page_Unload event
■■ Enter render stage
■■ Use in-memory state of all server-side objects and VIEWSTATE
<asp:ControlName runat=server Id=ControlID />
When you declare a server control on your page, you can use the control from yourcode by using the ID as a variable name, as you can with HTML controls However,
Trang 18Table 6.1 Controls in the HTMLControls Namespace
instead of having properties that map directly to HTML attributes, the server controlsmore closely resemble VB6 controls For example, instead of exposing a VALUE prop-erty for controls that render as an INPUT type, the server controls expose a TEXTproperty, like a VB text box does Many of the server controls render as a single HTMLtag Table 6.2 lists of some of these server controls
Table 6.2 Simple Server Controls
<asp:Button> <input type=’submit or type=’button’>
<asp:Textbox> <input type=’text’> or <textarea>
<asp:Panel> <div>
<asp:Label> <span>
<asp:DropDownList> <select>
<asp:ListBox> <select size=’ ’>
<asp:RadioButton> <input type=’radio’>
<asp:CheckBox> <input type=’checkbox’>
<asp:HyperLink> <a>
<asp:Image> <img>
<asp:AdRotator> Advanced HTML Code Generator
<asp:Calendar> Advanced HTML Code Generator
Trang 19A few of the controls have more advanced capabilities The ASP:Calendar controlrenders a complete client-side calendar in standard HTML The control supports dayand week selection and has a look and feel that can easily be customized TheASP:Datagrid control exists solely to render an HTML table Remember the days ofopening a recordset, setting up a WHILE loop, and iterating the rows in the resultset togenerate a TD cell for each column of data in your recordset? Well, those days are over.Now you simply bind a data grid to a resultset and call the data binding engine Thedata grid does the rest for you We’ll be taking a closer look at this a bit later.
Support for Scalability
Access to the full language features of Visual Basic NET is not only a great benefit to
us during development, but it also enhances the scalability of our application The aspxpages are actually compiled into binary images and cached by the Web server as exe-cutables They run under the common language runtime, like any other managed com-ponent These aspx pages are going to perform much better than our traditional ASPpages, which were always interpreted at runtime by the script parser
Some changes have also been made to the Framework to support scalability in aWeb farm environment With Active Server Pages, the Session object was a great place
to store user-specific information as users used the application There was a problemwith this architecture in a Web farm environment, however, because the session infor-mation was stored in the memory space of the Web server and therefore could not beshared across the different servers in a Web farm With ASP.NET, there are two newoptions for where session information is stored The Framework ships with an NT ser-vice that will store session state This allows us to dedicate a single machine as our ses-sion server; it can be a dedicated machine or one of the Web servers in the Web farm.All information stored in the Session object is automatically shipped off to the stateserver, so it becomes a single resource shared by all of the Web servers If any of theservers goes down, the session information will be maintained on this dedicated box,and the user can continue unaffected by the outage
Our third option is to store session information in SQL Server The Framework ates a set of tables for doing this and automatically connects to the SQL Server andstores information put into the Session object there This configuration can be done at
cre-a mcre-achine level, or for specific cre-appliccre-ations on your server The code we write in thepage is totally unaffected This means that you can use the Session object and config-ure your server to store this information in-process with the Web server As your appli-cation use grows and you need to throw a couple more servers up to manage the load,you can change one simple entry in the configuration file, and your application willcontinue to work without a single code change Your session information will auto-matically move to the session server to be shared by the new machines
An excellent set of objects is also available for caching output on the Web server.Page output can be cached on the server This caching can depend on the page or varydepending on query string values in the URL Once a page is in the cache, the next timethis URL is requested, instead of executing your program logic again, the server willretrieve this page from an in-memory cache Page fragments can also be cached, allow-ing several pages to share cached resources that are retrieved from memory The cachecan be invalidated after a time out, when a file changes (great for caching parsed XMLdocs), or programmatically This allows you to store information that’s expensive toretrieve or calculate in memory, where it’s instantly available until some dependencychanges and the information needs to be retrieved or calculated again
Trang 20Configuration and Deployment
Configuration has been vastly simplified All configuration information for the work is stored in XML format There is a machine-specific file named machine.config,and each Web application has its own configuration file, called Web.config The infor-mation in these files is applied at the machine level first and then with applicationentries, overriding the machine configuration, much like CSS
Frame-Options for configuration include authorization and authentication; debugging,tracing, and error handling; what programs deal with which file types; where sessionstate is stored; and settings global to the application, like a connection string
Deployment is also much easier Ever hear of XCOPY? Go ahead and use it to moveall of your application’s files onto the Web server, even if your site currently has thou-sands of visitors The Web server will finish up all currently running requests with theold components, automatically load the new ones, and pick up from there No down-time, no locked files, no registry entries Just copy them over
Support for Extensibility
There are many more options for reuse than ASP includes Although the include tax is still supported for backward compatibility, you’ll throw this right out when yousee the new options available One of the best vehicles for reuse is called User Controls.User Controls are like a mix between ASP include files and ActiveX controls Theyallow you to take an arbitrary chunk of HTML and code and package it as its own con-trol When the control is placed on the page, whatever content it contains is rendered
syn-in that location This is very much like an syn-include However, with an ASP syn-include, thefile can only be placed on the page once You would never package the code to output
a text-type input with a specific look and feel in an ASP include because you couldn’tchange the caption on the control and text box contents if you included it more thanonce With User Controls, you can expose properties and methods on the control, andeach time the control is declared, an instance of an object is created Using the ID ofyour declaration, you have a unique reference to each instance and can therefore reusethe control as many times as you’d like per page You can also create User Controls pro-grammatically, radically altering the content on any portion of your page We’ll belooking at User Controls in detail when implementing our chapter project
With the services of the Common Language Runtime, you can also implement yourown server controls Want to create a list box that always gets its selected items via amany-to-many relationship in your database? You can simply inherit from and extendthe ASP:ListBox control, adding your own properties, methods, and behaviors, whileinheriting all of the existing functionality the control intrinsically supports
Example
Let’s take a look at a simple demonstration of some of the controls and features of theframework we’ve been talking about Figure 6.1 (PostBackIE.aspx in the Demo folder)starts out as a standard HTML form No code is executed on the server to generate thispage; it could be static HTML
Trang 21Figure 6.1 Demo page before post back.
After our users enter their name and make selections from the lists present, the page
is posted back to the server in response to the server-side event trap we’ve set up on thebutton control at the bottom of the form, as shown in Figure 6.2
Let’s start with the body of the page, where we declare our server-side controls:
<body runat=server id=objBody style='margin-left:50px'>
<form id="Form1" method="post" runat="server">
<asp:Image Runat=server id=imgSelected />
<asp:Label Runat=server ID=lblWelcome text='Welcome' />
<br><br>
Enter Your Name And Make Selections<br><br>
<asp:TextBox Runat=server ID=txtName />
Trang 22Figure 6.2 Demo page after post back.
The code is very straightforward For each runat=server attribute we’ve declared,there will be a corresponding object created for us behind the scenes to use from codewhen our page is requested The declarations here are of the simplest form, using onlythe runat and id attributes We’ll set these controls up from the page load event in code.The only additional thing we set up here is the event trap on the server for our buttoncontrol We declare that using the OnClick attribute of the control This will cause theFramework to render HTML that will post to the server when the button is clicked.Once posted, the Framework will look for a method that we’ve implemented namedProcessChoices We’ll examine our implementation of this trap in a minute First, let’stake a look at our implementation of the Page_Load event This is where we populateour lists and prepare the form Let’s start by looking at the event footprint:
Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs)
End Sub
The footprint for this event trap is the same as our last example This is a commonfootprint for event traps and is worth memorizing The If statement checks the IsPost-Back property, making sure this is the first time the page is rendered The page loadfunction fires every time the page is requested When our user clicks the button and
Web Portal with ASP.NET 207
Team-Fly®
Trang 23causes a post back, the page load will still fire We will almost always do different stuff
on a post back than we do on an initial rendering of the page, so this If block is a mon check to make in this trap
as both the value and the text for the OPTION tag that gets rendered for the item Thesecond footprint for the Add method takes an instance of a ListItem object The List-Item object is shared between DropDownLists, ListBoxes, CheckBoxLists, andRadioButtonLists Here’s the code:
chkImage.Items.Add(New ListItem("Priority One", _
" /images/priority1.gif")) chkImage.Items.Add(New ListItem("Priority Two", _
" /images/priority2.gif")) chkImage.Items.Add(New ListItem("Priority Three", _
" /images/priority3.gif"))
Rather than creating an instance of a ListItem object, we create one inline for theparameter value By using the New ListItem declaration, we get access to all of the con-structors for the ListItem object The footprint we’ll use accepts two string values,name and value The name is what’s displayed to the user, and the value controls thevalue of the control as the selection changes We’re going to use this value to display animage when the page gets posted back, so the string we pass is a complete relative ref-erence to the selected image
imgSelected.Visible = False
Because we’re not displaying an image until after the user submits his or her choices
on the form, we hide the image for the initial rendering of the page This is a goodexample of the power exposed by this programming model Not only is there no logicembedded in the body of our page, but this single line of code causes our Image con-trol to render no content at all On the post back we’ll set the Visible property back totrue, and the control will render its HTML output This model is so much simpler thandoing the same thing with ASP that once you start using the new Framework, you’llnever want to go back
After this function executes, our page enters the rendering stage and the output goes
to our client When the user clicks the submit button, all the values and state tion for the page are posted back to the server, the binary image of our page executable
informa-is retrieved from the Web server’s cache, our objects are re-created and their properties
Trang 24set according to the state information on the page (i.e., the txtName control has its textproperty set equal to whatever our user type in on the HTML text box), and our pageload event is fired Because the post back occurred when the user clicked the submitbutton, the ProcessChoices method is also fired Let’s take a look at that code:
Sub ProcessChoices(ByVal o As Object, ByVal e As EventArgs)
lblWelcome.Text = "Welcome " & txtName.Text
We set the background color of the page using the objBody HTMLGenericControl.This control exposes an attributes collection, which we can use to set any HTMLattribute we’d like to use In this case we’re going to set the BGCOLOR attribute equal
to whatever our user has chosen from the ListBox control We get this from the Valueproperty of the SelectedItem of ListBox Keep in mind that no HTML is generated asthis code executes; we’re simply setting the properties and methods of those objectsthat were exposed for us to work with HTML generation does not occur until our codehas finished executing and we enter the rendering stage of the page
The last couple lines set up our image control This will display a small image infront of our welcome message We set its visibility to false in the initial load of ourpage, so we toggle it back here We then set the ImageURL equal to the value that’sbeen selected from the RadioButtonList Because we set these values up to be relativereferences to image files on our site, the <img> tag rendered by our image control willdisplay the corresponding file
Notice also that when the page content is rendered, TextBbox, ListBox, andRadioButtonList all still have the values that they did when the page was posted.Because of the stateless nature of the HTTP protocol, we are completely regeneratingthis page before it goes back to the client This state maintenance does not occur auto-matically In traditional ASP this would actually require quite a bit of code, but it’s part
of the built-in state maintenance features of the ASP.NET Framework
Let’s Start the Project
The project we’re going to create is a Web portal of the type that would be used on acorporate intranet Our portal will have four main functional areas We will displaycurrent items that are specific to the department our user is in, and we will displaystock prices for tickers of our user’s choosing We will also have a main navigation area
on the left-hand side of our site This will provide links to all of the functional areasthat are exposed by our portal In this case the functional areas revolve mainly aroundconfiguration and preference settings for our Web portal, but they will illustrate theexposure of functionality that in an Enterprise environment would be solutions to spe-cific business problems The portal is shown in Figure 6.3
Trang 25Figure 6.3 The main page of the Web portal.
On the site, the left, and bottom areas will remain constant, and the middle one will
be our area for current content Clicking on the menu items on the left will cause thecontent pane to be updated with the user’s selection The department news items andthe factory image are displayed by default and considered the home page of the site.Configuration of the other areas is controlled by the different choices on the menu, andthe site will update to reflect those choices When users use the main content area tochoose a different stock, the marquee at the bottom of the page will update with pricesfor the stocks they have chosen
To work with the examples in this chapter, you will want to start by creating a newWeb application with Visual Studio NET Name it WebPortal and create it using yourlocal Web server Once the project has been created, use the Solution Explorer to addthe three directories from the WebPortal directory of the companion CD-ROM to yournew Web application project You can do this by dragging the three folders from Win-dows Explorer and dropping them on the Web portal project in the Solution Explorerwindow You will also need to execute the AtWorkWebPortal.sql file using the QueryAnalyzer This script will create the database and all the tables and other objects youneed and populate the database For this script to work, you will need to be connected
to your database as an administrator
Trang 26The Portal Framework
The main structure of the page will be controlled with an HTML table Using nations of rowspan and colspan, this is an amazingly flexible way to create frameset-like functionality You can see the raw declarations of this table with no content inFigure 6.4, which shows the WebPortalTemplate.htm This is the static HTML page thatwe’ll use as the starting point for later portal implementation
combi-Note that the source for this page is pure HTML We will develop each functional area
on its own so that we can test each piece separately to make sure that they all work beforeputting them together After each area is developed, we’ll convert them to ASP.NET UserControls This will allow us to add them to our Web portal template by simply replacingthe static descriptions there now with our own server-side elements that will create ourUser Controls This strategy is very flexible and also very easy to implement, as you’llsee The main content area will then be invoked programmatically, creating differentUser Controls and adding them to the content frame as our user makes different selec-tions This functional division is a good design architecturally because each User Control
is responsible for its own functionality, whereas the Framework uses any attributesexposed on the controls to modify its behavior in the larger context It’s a lot like a COMinterface-based design in that any context-specific behavior is exposed as properties ofthe control, whereas the implementation details are hidden within the individual con-trols If the behavior of a given area needs to change (i.e., business rules change), the onlything that needs to change is the implementation of the control The control will continue
to function in the context of the Framework, or in whatever other functional areas inwhich we’re using it, as long as the interface behavior does not change This is a lotcleaner in the NET Framework than in the world of COM because we don’t have classIDs, interfaces IDs, and AppIDs in the registry ready to inflict pain upon us if we changethe interface Because of their self-descriptive, reflective architecture, the managed com-ponents will adjust in real time after a simple file copy
The Database
The simple database that we’ll be using is geared around the storage of user ences This puts our UserPreferences table at the logical center of the schema In thistable we’re storing users ID, their e-mail address, and the department in which theywork, as shown in Figure 6.5
prefer-The other tables include:
Department. Stores department descriptions DepartmentID is carried as a foreignkey in the UserPreferences table, so each user belongs in a single department
DepartmentItem. Stores interest items that are specific to a department The
columns here are set up to provide some descriptive text and a URL to a
resource that has more information about the item The priority of the item is
used to control which bullet image to use when displaying the item Users will
see all department items for their department, filtered to those items where the
current date is between the begin and end date of the item