
Beginning ASP.NET 2.0 With CSharp (2006) [eng]
.pdf
Chapter 16
USE aspnetdb
GO
sp_addrolemember ‘database_you_wish_to_grant_access_to, ‘Network Service’
Click Run to run the query, and this will have the same effect as the previous instructions.
Is Your Application Offline? (Using App_Offline.htm)
This is one of those things that I saw in the beta that really tripped me up; on one occasion I ran my Wrox United application to test it and was staggered to find that every single page returned an HTTP 404 error. Even stranger, I was browsing them from within Visual Web Developer at the time. It took me a few hours and help from the other people on the book to figure out what had happened. It actually turned out to be a really useful feature.
If you need to take your site offline very quickly, you can place a file called app_offline.htm in your main application folder. This makes your web site unavailable to everybody. You can place in the HTML file the text that you want your users to be able to view for the duration of the site’s downtime. The advantage is that ASP.NET is working throughout this downtime, and you are able to test the site without having to worry about what users can see in the outside world. However, there are times when this file is created for you, which led to the problems I had.
Apparently during some operations, the app_offline.htm file is temporarily copied to your application folder and then, in theory, it should be removed when the operation is completed. A crash during an operation can leave the file behind. Unfortunately, this was a zero-length file in beta 2, and this provided no clue to the user as to what occurred. The user was just left with every page in their site returning 404 errors. Normally, the app_offline.htm file should not be left behind, but unfortunately in some cases, it gets left over. In the final release of ASP.NET 2.0, there is a message that informs users of what happened so they know to remove the offending item (see Figure 16-11).
Figure 16-11
This can turn up quite a few times if your application is being unruly, so be warned. It will turn up in the root folder of your application folder. In Figure 16-11, you see the version of it that comes with Visual Web Developer by default.
608

Deployment, Builds, and Finishing Up
Problems with IIS
Of course, if you test your site with ASP.NET Development Server, you might encounter some problems when you deploy your site on IIS. First, make sure your application is configured as a virtual directory (this process is described in Appendix B). Occasionally IIS doesn’t work in the way it should, and often non-specific errors can be fixed if you run the aspnet_regiis executable with the –i switch.
To do this, go to the command prompt and go to the C:\Windows\Microsoft.Net\Framework\v2.0. 50727 folder. From this folder, type the following and press Enter:
aspnet_regiis –i
This quite often sorts out non-specific problems such as HTTP 500 errors.
Trial and Error
If you still have no success, go back, delete all the files, and try it again. If you are getting a particular error consistently, look up that error on http://support.microsoft.com and see if that has any solutions. If this doesn’t fix things, then another way is to copy the text of the error and paste it straight into Google or your favorite search engine. This usually comes up with some other people experiencing the same problems and solutions more often than not. If not, try posting on one of the online forums recommended later in this chapter.
Testing and Maintenance
After you’ve successfully negotiated deployment, you might be excused for doing a quick double take. Testing, haven’t you already done that? Given that this is the 21st century, you might have expected attitudes toward testing to have improved considerably — however, if anything, trends have reversed. For example, several very popular games arrived on the market in a practically unusable state because they hadn’t been tested correctly. Hastily compiled patches of 20–50MB were required to rectify the situation. However, as a developer, you will probably not have this luxury. You will probably see your client week in and week out, and if the application doesn’t work they will tell you about it and maybe withhold payment until the problem is rectified. They might still not grant you any extra time to test, but that is the name of the game.
Testing Before and After
Of course, while you’re building an application, you should test every component, but once the build is deployed and completed, you should also make time to test the application as a whole. In particular, you should sit alongside your prospective users and watch them test it. Some clients believe that testing is the whole responsibility of the developer, but the relationship the developer shares with his code is similar to that between the author and his text. You wouldn’t expect an author to be able to adequately edit his own text, and if an author uses incorrect grammar, then it’s quite likely that they won’t be able to spot their own incorrect grammar usage. If a developer creates a piece of logically unsound code, there’s a fair chance they might not be able to spot it either. Only in hard testing, when a user who puts in often totally unpredictable values, are some errors revealed. Some textbooks will tell you to put aside as much time as you took to develop the application for testing it. This isn’t over-cautious — the bigger the application, the greater the likelihood of bugs creeping in, and the longer it can take to find them. If possible
609

Chapter 16
with a web site for a client, get them to test it in-house, on a test server before they put it on a live server. And don’t be worried to admit to bugs. Finding bugs isn’t the sign of a bad developer — a bad developer is one who refuses to admit to the possibility of any bugs in the first place. The best advice is get your clients to test the application thoroughly and make sure they have time to do it. A couple of testing methods are worth mentioning here.
Unit Tests
Unit tests are a particular form of testing where you write a test for every non-trivial function or method in the code. You can separate the different sections of the program and demonstrate which parts are working in this way. Unit tests make it easier for programmers to change individual pieces of code because they can go back to the code and test the unit independently. So if you suddenly think of a new feature, you can add it without worrying about having to break the entire application.
Writing a Test Plan
Because unit tests, or indeed the whole practice of testing, can be time consuming, it’s best to have a test plan up front to aid the organization of testing. A test plan is simply a systematic written approach to testing, detailing the experiments and tests you want to perform on the code. Test plans don’t just apply to computer programs — they can apply to any kind of engineering. A single test case in a test plan for a dishwasher might be, “Test what happens when you open the dishwasher door halfway through a working cycle.” Some dishwashers would shower you with scalding water, some would refuse to open, and some would stop mid-cycle and let you retrieve the last cup in the house. There isn’t necessarily a right answer to what should happen, but you should write a list of scenarios that you would like to test, and record the outcomes and check that the scenarios and outcomes are what you both want, and what your end-user thinks is satisfactory.
Maintenance
Maintenance is the practice of keeping your site up and running after it has been successfully deployed. In some ways, it’s like a glorified debugging process — some bugs might not show up until long after the site’s deployment, but you’ll still be expected to fix them. In other ways, maintenance will be about performance monitoring: how fast is your site running? How many users is it handling? Can it cope with that? This is a science in itself. This is one area where ASP.NET 2.0 has come on in leaps and bounds, with the addition of instrumentation, and the capability to instrument your application.
Instrumentation and Health Monitoring
Instrumentation or instrumenting is a term you will come across if you have to do any monitoring or maintenance of your system. The instrumenting of your application is the monitoring of your system or your application’s function, checking to see that all is working the way it should be.
ASP.NET 2.0 has a lot of instrumentation features for the developer. You’ve already looked at the ability to run traces and logging and learned that there are performance counters that you can use, but are beyond the scope of this book. However, there is another new feature that is of great interest and of particular use after your application has been deployed, and that is the introduction of the
<healthMonitoring> element.
The <healthMonitoring> element can be used at the system or application level and enables you to monitor when specific events have occurred and write notifications of these events to an event log, a
610

Deployment, Builds, and Finishing Up
SQL Server database, or even to e-mail the administrator. Events that might be of interest could be a failed login, or an error occurring in the application. Besides logging events, the <healthMonitoring> element enables you to test the “health” of the system via a heartbeat attribute, which sets up an event that is generated at a predefined interval — if you can “hear” the heartbeat, you know your application is working fine. If you don’t receive this heartbeat, you know there might well be problems.
To enable health monitoring, all you need to do is place the <healthMonitoring> element in your Web.config file and set the enabled attribute to true. Health monitoring is handled by three elements within <healthMonitoring>, which have a close relationship with each other:
The <providers> element specifies where you want to send the information you have collected, which can be an event log or a database.
The <rules> element specifies the name of the provider you want to write your information to and the event name you want to instrument.
The <eventMappings> element specifies a name of event you want to monitor, and maps it to an actual event or set of events. The settings of this element must correspond to a valid event type. A list of valid types is contained within the <eventMappings> element in the Web. config.comments file.
It just takes a couple of attribute changes to alter an application that writes to the event log for failed logins, to one that e-mails the administrator with details.
Monitoring for Events
You can test for a range of events using the <healthMonitoring> element. These are as described in the following table.
Event Name |
Description of Event |
|
|
WebHeartbeatEvent |
A regular event that provides statistics about |
|
the application or system. |
WebManagementEvent |
A base class event for all events that carry |
|
application and worker process information. |
WebApplicationLifetimeEvent |
An event generated by every significant event |
|
that occurs in an application’s lifetime, such as |
|
startup, restart, and shutdown. |
WebRequestEvent |
An event that is raised with every web request |
|
and contains information about the request |
|
and the thread on which it’s executing. |
WebBaseErrorEvent |
A base class event for all health monitoring |
|
error events. |
WebErrorEvent |
An event generated when there are problems |
|
with configuration or application code. |
|
Table continued on following page |
611

Chapter 16
Event Name |
Description of Event |
|
|
WebRequestErrorEvent |
An event that is raised when an error occurs |
|
during a web request. This ignores common |
|
types of error such HTTP 404, and focuses on |
|
things like unhandled exceptions. |
WebFailureAuditEvent |
An event generated upon the failure of a secu- |
|
rity-related event, such as a file authorization, |
|
a URL authorization, or a login authentication. |
WebSuccessAuditEvent |
An event generated upon the success of |
|
a security-related event, such as a file autho- |
|
rization, a URL authorization, or a login |
|
authentication. |
WebAuthenticationFailureAuditEvent |
An event generated upon an unsuccessful |
|
login authentication. |
WebAuthenticationSuccessAuditEvent |
An event generated upon a successful login |
|
authentication. |
WebAuditEvent |
A base class for all audit events, both authenti- |
|
cation and authorization. |
WebViewStateFailureAuditEvent |
An event that is generated on view state fail- |
|
ure. The failure may indicate an attempt to |
|
tamper with the view state, or its reuse from |
|
another machine with a different key. |
|
|
There is also a broad range of providers (sources) to which you can write your event information. These can all be found in the System.Web.Management namespace, and are detailed in the following table.
Provider Name |
What the Provider Holds |
|
|
MailWebEventProvider |
Writes to an e-mail. |
SimpleMailWebEventProvider |
Writes to a simplified e-mail. |
TemplatedMailWebEventProvider |
Writes to a templated e-mail. |
TraceWebEventProvider |
Writes to a trace. |
EventLogWebEventProvider (the default provider) |
Writes to the Event Log. |
SqlWebEventProvider |
Writes to a SQL Server database. |
|
|
Which Events Are You Interested In?
You have a list of events, and a list of possible places where you can write the events about how they were monitored. However, at the moment this is information overkill. You need to get back to basics and answer a simple question: Which events are you interested in monitoring?
612

Deployment, Builds, and Finishing Up
Unfortunately, the answer is open-ended. It depends on what you want to monitor your application for. A lot of the events in your list generate huge numbers of events, both when the application is working correctly and when it isn’t.
A good place to start would be security. If you aren’t regularly changing code in your application, then most likely the greatest threat to your application’s longevity and well-being is someone trying to hack. A key to finding good security events to instrument for is to locate which events under normal circumstances shouldn’t be generating a large number, but in the event of an attack or suspicious data being provided, will generate a lot of events. When your system is being attacked, you are likely to see a number of such events, which in turn can help act as an early warning system.
The key events that monitor the security-related aspects of the application might be as follows:
WebErrorEvent
WebAuthenticationFailureAuditEvent
WebRequestErrorEvent
WebViewStateFailureAuditEvent
The WebError event should be monitored because any code failure is suspicious. The WebAuthenticationFailureAuditEvent should be monitored because any suspicious login activity should be carefully monitored. WebRequestErrorEvent and WebViewStateFailure AuditEvent might have failures if a hacker is trying to intercept responses from the server and forwarding his or her own fraudulent page in response. By default, the WebErrorEvent and WebAuthenticationFailureAuditEvent are turned on. This means that in the case of any failure,
they are automatically logged to the Event Log. So if such an error (for example, a division by zero error) occurs in your application, you would see what’s shown in Figure 16-12 in your Event Log under Application, under the source ASP.NET 2.050727.0 (or whichever version of ASP.NET is being run).
Figure 16-12
613

Chapter 16
Because failed logins are written to the event log by default, take a look at how you could also log successful logins to your application in the Event Log. In this Try It Out, you track when a user logs in to Wrox United successfully, and you write details about it to the Event Log.
Try It Out |
Adding Health Monitoring to Wrox United |
1.Open Web.config in the Wrox United application for this chapter. In <system.web>, add a
<healthMonitoring> element as follows:
<healthMonitoring enabled=”true”>
</healthMonitoring>
2.Create another child element inside <healthMonitoring> called <rules>:
<rules>
<add provider=”EventLogProvider” name=”Success Audits” eventName=” LoginSuccess” /> </rules>
3.Create another child element inside <healthMonitoring> underneath <rules> called
<eventMappings>:
<eventMappings>
<add name=”LoginSuccess” type=”System.Web.Management.WebAuthenticationSuccessAuditEvent,System.Web,Version=2
.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a” startEventCode=”0” endEventCode=”2147483647”/> </eventMappings>
4.Run the application and login as Dave, password dave@123.
5.Go to the Control Panel and select Administrative Tools Event Log, and you’ll see the screen shown in Figure 16-13.
Figure 16-13
614

Deployment, Builds, and Finishing Up
How It Works
The <healthMonitoring> element in the Web.config file does all of the work for you. You start by enabling <healthMonitoring> and then placing three elements inside it to make it work.
The <rules> element is used to map an event onto a provider. The <rules> element has three compulsory attributes: provider, name, and eventName. The provider attribute matches the name attribute specified in the <providers> element. You specify the Event Log in this element and a name for your rule, “Success Audits”:
<rules>
<add provider=”EventLogProvider” name=”Success Audits” eventName=”LoginSuccess” /> </rules>
The <eventMappings> element specifies a user-friendly name for the event and the specific type of the event you want to monitor. The type has to contain the system assembly details as well as information about that assembly such as the Version number, Culture, and PublicKeyToken:
<eventMappings>
<add name=”LoginSuccess” type=”System.Web.Management.WebAuthenticationSuccessAuditEvent,System.Web,Version=2
.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a” startEventCode=”0” endEventCode=”2147483647”/> </eventMappings>
Inside the global Web.config, you will find a tallying <providers> element, which is referenced by your <rules> element. The <providers> element specifies details about the source you write the error information to, such as Event Log or SQL Server database. Providers always have two compulsory attributes: name and type. The <provider> must use a name attribute corresponding with a name specified in <eventMappings>. Providers may have other compulsory attributes, but these will vary depending on the type of provider. The EventLogProvider only requires the name and type attributes. The EventLogProvider looks like this:
<providers>
<add name=”EventLogProvider” type=”System.Web.Management.EventLogWebEventProvider,System.Web,Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a” /></providers>
If you scroll down the Event Log entry, you will see a whole stack of useful information about the login. This information includes the event message, the time the error occurred, the location of the error, the error message, the user’s IP address, whether or not they were authenticated, and much more.
Mailing an Administrator
Wrox United now writes to an Event Log, but this is only of use if the administrator is on hand to check the Event Log. A more proactive approach might involve e-mailing the administrator each time the monitored event takes place. Doing this requires only minimal alteration of the <healthMonitoring> element. You only need to change the rules of which provider you are indicating and the provider itself, and also add a SMTP section to the Web.config file (if there isn’t an existing one). You can simply change the details of the <rules> element and the <providers> element and add an SMTP section.
615

Chapter 16
Note that this Try It Out requires a working SMTP server. You will only be able to do this exercise if you have IIS installed with the SMTP service (done via the Add or Remove Programs section of Control Panel), and it must be set up to relay e-mail. Relaying e-mail can be set up by right-clicking the SMTP server in IIS, selecting Properties, choosing the Access tab, clicking the Relay button, and making sure the number 127.0.0.1 (the number for localhost) is granted permission for relaying mail.
Try It Out |
Mailing the Administrator |
1.Open Web.config and alter the <rules> element so that it reads as follows:
<add provider=”EmailProvider” name=”My Failure Audit” eventName=”Failure Audits” />
2.Go to the <providers> element and change it so that it reads as follows:
<add name=”EmailProvider” type=”System.Web.Management.SimpleMailWebEventProvider”
from=”myemail@myserver.co.uk” to=”myemail@myserver.co.uk” subjectPrefix=”Failed Login Attempt:” buffer=”true” bufferMode=”Notification” />
Replace myemail@myserver.co.uk with your own SMTP server’s domain name. If your machine is TESTONE, replace it with myemail@testone.com.
3.You’ll also need to add a section to Web.config to configure the SMTP section. An example setting would look like the following, and of course you’d need to substitute in your own mail server’s settings:
<system.net>
<mailSettings>
<!-- these settings define the mail server settings
from: the user name from which the email is sent - this is the application that is sending the message
host: the name of your mail server
userName: the name the application will use to log into the mail server password: the password for the above user name
-->
<smtp from=”admin@your-domain.com”> <network host=”your-mail-server-name”
userName=”your-user-name” password=”your-password” />
</smtp>
</mailSettings>
</system.net>
4.Run the application and wait. You should receive an e-mail within a minute.
How It Works
Instead of placing something in the Event Log, you are now e-mailed the details that you previously viewed in the Application section of the Event Log. To do this, you changed the rules and provider elements to specify a different provider.
616

Deployment, Builds, and Finishing Up
The health monitoring features of ASP.NET 2.0 are a real plus for those of you trying to maintain an application and for either tracking down security breaches or hard-to-find bugs.
Scalability
The last scenario you might have to consider is what happens if the web site takes off. What happens if instead of the anticipated hundreds or thousands, you get millions of visitors? On one level, this might hit the performance of your application, it might exceed limits within your application, and it also might exceed the limits of your hardware.
For software considerations, it’s best not to impose small limits on arrays and databases when you create them. You should always take care to close any open database connections. If you open up too many connections, you can end up with a Connection Pooling error. Unlike classic ASP where it was common practice to set the connection to Nothing, all that’s needed is to close any open connections once you’ve finished them. The number of open connections that can be maintained is finite and connections are reused from a pool. If you have only one unclosed connection on a small site, you might never notice it, but on a large site, your users certainly will when they encounter this error.
For hardware considerations you might have to upgrade your server or servers, or even end up having to move your site onto a web farm (a collection of servers, any one of which can receive a request and deal with it). Web farms can have repercussions for the way you handle sessions, and you might be forced to change settings in Web.config to accommodate this. Normally ASP.NET handles sessions in memory, known as inproc, but you can change this so that either SQL Server or a separate state server process handles sessions. These options, though, can slow your site down. However, when creating your first site you’re unlikely to have to worry about these considerations, but it never hurts to make sure.
Where to Now?
Perhaps the most difficult question to answer in this entire book is “What should you do next?” You’ve built an application, and if you’ve managed to do the exercises as well, you will have a fairly good grounding in ASP.NET 2.0 already, but probably not one that will let you walk into a well-paid job. So how can you improve on it? If you follow some philosophies, you can find yourself signed up for thou- sand-dollar courses, or with a booklist the size of a wardrobe. Although these might be helpful, they aren’t essential or advised courses of action.
I’m often asked by readers what is the most important part of becoming a developer or programmer, and the answer I give is hands-on experience. You read about coding and coding techniques until you’re blue in the face, but until you’re faced with a problem that you have to solve, you can’t really get a feel for coding. The first tentative steps on most coders’ route are taking an existing application and modifying it. Improving it. Adding to it. That’s what you should start now. Go back to the Wrox United application and start amending it. Think how you could improve it. Would you change the design, the way it works? Add some news articles, some new players, and some new graphics, and get comfortable with the way it works. Then go away and think of an application that would be useful to you, but not too ambitious, and start creating that. If you can’t think of anything, then e-mail your friends to see if they’ve got anything that needs doing.
617