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

Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]

.pdf
Скачиваний:
107
Добавлен:
16.08.2013
Размер:
29.8 Mб
Скачать

658 C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

writer.Write(_FileContent); writer.Flush();

stream.Seek(0, SeekOrigin.Begin); return stream;

}

}

The class’s constructor gets the virtual path as well as the content of the file. In the Open method, the string with the actual content gets saved to a MemoryStream, and this stream is then returned. ASP.NET uses the stream for reading the contents as if they were read from the file system—thanks to the abstraction of bytes through Stream classes.

The next step is to complete the VirtualPathProvider class. It needs to read the actual data for the files from the database. If a file doesn’t exist in the database, the provider just forwards the request to its previous provider (which has been selected by the infrastructure while registering in the static AppInitialize method). Add a method for retrieving the contents from the database to the MyProvider class introduced previously:

private string GetFileFromDB(string virtualPath)

{

string contents;

string fileName = virtualPath.Substring( virtualPath.IndexOf('/', 1) + 1);

// Read the file from the database SqlConnection conn = new SqlConnection();

conn.ConnectionString = "data source=(local);Integrated " + "Security=SSPI;initial catalog=AspContent";

conn.Open();

try

{

SqlCommand cmd = new SqlCommand(

"SELECT FileContents FROM AspContent " + "WHERE FileName=@fn", conn);

cmd.Parameters.Add("@fn", fileName); contents = cmd.ExecuteScalar() as string; if (contents == null)

contents = string.Empty;

}

catch

{

contents = string.Empty;

}

finally

{

conn.Close();

}

return contents;

}

The GetFileFromDB function does nothing other than get the filename from the virtual path and then read the contents for the filename from the database. (Remember, the filename is the primary key in the database defined, as shown in Figure 18-27.) This method is then used by both, the FileExists as well as the GetFile method, as shown in the following code snippet:

C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

659

public override bool FileExists(string virtualPath)

{

string contents = this.GetFileFromDB(virtualPath); if (contents.Equals(string.Empty))

return false;

else

return true;

}

public override System.Web.Hosting.VirtualFile GetFile(string virtualPath)

{

string contents = this.GetFileFromDB(virtualPath); if (contents.Equals(string.Empty))

return Previous.GetFile(virtualPath);

else

return new MyVirtualFile(virtualPath, contents);

}

}

With those functions in place, the application is ready to run. Of course, the VirtualPathProvider class works for resources connected with the ASP.NET ISAPI extension only. Therefore, if you want to use your own filename extensions in your application, you first have to connect this extension with the aspnet_isapi.dll ISAPI filter extension. Figure 18-28 shows the application in action. You can see three browsers in the figure, one trying to access the physical file, a second trying to access a file from the database, and a third trying to access a resource that is not available, neither in the database nor on the file system.

Figure 18-28. The VirtualPathProvider in action

660 C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

Health Monitoring in ASP.NET 2.0

Health monitoring is a process for verifying the application’s state while being operated in production environments. It is used for several reasons, such as catching errors, getting notified in case of errors, analyzing the performance of the application, getting information about the payload for the application, and much more. Monitoring usually is implemented through a mechanism called instrumentation, which is a technique used for adding events, performance counters, and tracing capabilities to an application.

Through these tracing capabilities, administrators, operational staff, and developers have the possibility of monitoring the application based on several aspects. However, instrumentation is something that has to be integrated into the application’s architecture in a way that makes monitoring useful and convenient.

ASP.NET 2.0 ships with an integrated health monitoring system that is completely consumable through a health monitoring API. Therefore, the instrumentation capabilities are integrated into the platform itself. You will now learn about the fundamentals of this instrumentation system.

Understanding the Basic Structure

The system is split up into two major parts: types of events that are implemented in a set of event classes and providers that are responsible for processing different types of events. You can see this when looking at the basic structure of the health monitoring configuration that is part of the web.config configuration file:

<healthMonitoring Enabled="true|false" heartBeatInterval="time interval"> <providers>... </providers>

<eventMappings>... </eventMappings> <profiles>... </profiles> <rules>... </rules>

</healthMonitoring>

Through the <providers> element you can configure a number of providers responsible for event processing. The events that can be processed are registered through the <eventMappings> element. The connection between providers and events is drawn through the <rules> element, which defines the provider responsible for processing an event and some additional parameters.

The <rules> section on its own may reference profiles that are defined in the <profiles> section. These profiles are some additional parameters that can be used for configuring the behavior of the event processing mechanism. Examples for such parameters are the number of times the event has to happen until it is raised by the monitoring system and the time that has to take place between two events.

Events and Providers

The reasons for splitting events and providers into two components are of course extensibility and flexibility. The event itself defines a situation that has become reality in the application, and the provider specifies how the event will be processed. ASP.NET ships with several event providers for catching the following types of events that are all defined in the System.Web.Management namespace:

Heartbeats are events that are raised in a regular interval defined in the web.config configuration file. They provide you with information about the running process in regular intervals for monitoring memory consumption, CPU processor load, and much more. The class that implements this event is the WebHeartBeatEvent class.

C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

661

Application lifetime events enable you to catch several events raised during the application’s life cycle such as startup, shutdown, session starts, session ends, and much more. These types of events are encapsulated in the WebApplicationLifetimeEvent class.

The WebAuditEvent class encapsulates security audit events such as failed logons or attempts for accessing resources without the necessary permissions.

Request-based and response-based events are encapsulated in the WebRequestEvent class. You can catch several types of events such as the start of a request, its end, information about response generated, and much more.

Finally, you can catch and monitor several types of errors, either general application errors happening on startup/shutdown or request-based errors. These errors are encapsulated in the WebErrorEvent class for general errors and the WebRequestErrorEvent class for requestspecific errors.

All these events are already registered with corresponding friendly names in the machine-wide configuration of the default installation of ASP.NET. Of course, if you create your own type of event generated by the application, you can register it in the <eventMappings> section of the <healthMonitoring> section in the web.config file. The syntax is basically the same as shown for the default events in machine.config in the following code snippet:

<healthMonitoring>

<eventMappings>

<add name="All Events" type="System.Web.Management.WebBaseEvent,

System.Web,Version=2.0.0.0,Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a" startEventCode="0" endEventCode="2147483647" />

<add name="HeartBeats" type="System.Web.Management.WebHeartBeatEvent, System.Web,Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

startEventCode="0" endEventCode="2147483647" />

...

</eventMappings>

</healthMonitoring>

Of course, just a couple of events are registered in the machine-wide configuration. You can find a full list of the events with their friendly names in Table 18-5.

Table 18-5. List of Events Available on a Default Installation

Event Name

Event Type

Description

All Events

WebBaseEvent

Mapping for all events

 

 

available, as all events inherit

 

 

from this class.

HeartBeats

WebHeartBeatEvent

Heartbeat event for delivering

 

 

information about the process

 

 

in regular intervals.

Application Lifetime Events

WebApplicationLifetimeEvent

Delivers application-specific

 

 

events such as startup or

 

 

shutdown.

Request Processing Events

WebRequestEvent

Basic configuration for

 

 

delivering all request

 

 

processing events available.

Continued

662 C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

Table 18-5. Continued

Event Name

Event Type

Description

All Errors

WebBaseErrorEvent

Catches all types of error

 

 

events, as this is the base class

 

 

for errors in general.

Infrastructure Errors

WebErrorEvent

While All Errors focuses on all

 

 

errors happening within the

 

 

web application, this type of

 

 

error includes infrastructure

 

 

errors of the ASP.NET runtime

 

 

itself as well.

Request Processing Errors

WebRequestErrorEvent

Errors that occur within the

 

 

processing of one request.

All Audits

WebAuditEvent

Catches all types of audits, as

 

 

this is the general base class

 

 

for audit events.

Failure Audits

WebFailureAuditEvent

Catches all audits designated

 

 

to failures such as invalid

 

 

logins or “access denied”

 

 

errors.

Success Audits

WebSuccessAuditEvent

Catches all audits designated

 

 

to succeeding operations.

 

 

 

Basically, any type of provider can process these events. Again, the system ships with a couple of providers, but only some of them are really configured in the machine-wide configuration, as shown in the following code snippet:

<healthMonitoring...> <providers>

<add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider,

System.Web,Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

<add name="SqlWebEventProvider" ConnectionStringName="LocalSqlServer" maxEventDetailsLength="1073741823"

buffer="false" bufferMode="Notification" type="System.Web.Management.SqlWebEventProvider,

System.Web,Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

<add name="WmiWebEventProvider" type="System.Web.Management.WmiWebEventProvider,

System.Web,Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</healthMonitoring>

Although only the three providers shown in the previous code snippet are configured by default, the framework ships with five providers. If you need another provider, just write a class inherited from the ProviderBase class of the namespace System.Configuration.Provider, and register the provider in the <providers> section of the <healthMonitoring> section in your own web.config in the same way as in the previous code snippet. The framework ships with the following providers:

C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

663

EventLogWebEventProvider: EventLogWebEventProvider is responsible for adding different types of events to the Windows event log of the local system.

MailWebEventProvider: MailWebEventProvider is a provider for sending events via SMTP to a configured e-mail address. The e-mail address is added as a parameter to the provider entry in the same way as the ConnectionStringName parameter of the SqlWebEventProvider shown in the previous code snippet.

SqlWebEventProvider: SqlWebEventProvider offers the possibility for storing events into a SQL Server–based database. Of course, the database requires some standard tables for the provider in place. The SQL scripts for creating and dropping those tables are available in the InstallWebEventSqlProvider.sql as well as UninstallWebEventSqlProvider.sql files in the .NET Framework directory.

TraceWebEventProvider: TraceWebEventProvider enables you to catch and add events to the ASP.NET trace, which can be viewed through the trace.axd handler of the runtime.

WmiWebEventProvider: WmiWebEventProvider allows you to publish events through WMI. You can catch these events like you do any other type of WMI event through the System.Management API or the unmanaged WMI provider APIs available for Windows.

Now that you know events define situations that might happen in the application and providers define the delivery mechanism for those events (which means how these events are processed), you can configure a simple application for using the health monitoring infrastructure. You just need to take any of the samples created previously, or create a new website with an empty Default.aspx page, and add the following configuration to the web.config file:

<healthMonitoring enabled="true"> <providers>

<add name="EmailProvider" type="System.Web.Management.SimpleMailWebEventProvider" from="testhealth@vpcbase.local" to="testdest@vpc.local"

subjectPrefix="Testing Health" buffer="true" bufferMode="Notification"/>

</providers>

<rules>

<add provider="EmailProvider" name="All App Events"

eventName="Application Lifetime Events"/> </rules>

</healthMonitoring>

In the previous example, you have added the e-mail provider for sending an e-mail in case of every application lifetime event. The defined element in the <rules> section connects the previously configured e-mail provider to the actual events. For the rule definition, you should use the friendly name defined for the registered event in the <eventMappings> section.

Tip If you want to test this scenario quickly, you can use the POP3 server that ships with Windows Server 2003. When you set up the POP3 server, you can either configure it to create mailboxes based on Windows accounts or use password-based authentication and therefore create a user name/password combination for every mailbox you configure. After you have installed the POP3 server, just create a mailbox, launch Microsoft Outlook, and configure the previously configured mailbox. (The SMTP and POP3 server are both localhost in that case.) Afterward, you just need to configure the SMTP server for the ASP.NET application through the web administration site that results in adding the necessary configuration entries to the web.config file of the application. When starting and shutting down the application together with the web server, you will receive the appropriate events for the application.

664 C H A P T E R 1 8 W E B S I T E D E P L OY M E N T

Summary

In this chapter you learned how to configure your web application on the target environment. For this step, IIS—the web hosting software included with Windows—plays a key role; you saw the different aspects of installing and configuring IIS on Windows 2000/XP and Windows Server 2003 systems.

You also learned about the process architecture of IIS 5.x and IIS 6.0, and you learned about the differences between those two architectures. While IIS 5.x uses a single process model and ASP.NET executes in a separate worker process called aspnet_wp.exe for executing managed applications, IIS 6.0 favors the more secure and reliable worker process model where you can configure as many processes as you want for running your web applications. Every worker process is configured through so-called application pools. Based on these pools you can configure recycling settings, performance and health settings, and a custom identity for every process. By default each process runs under the restricted Network Service account, but if additional permissions are required, you can configure your own identity.

Then you learned about how Windows and IIS share web applications through virtual directories. You learned how to configure those virtual directories and how to put them into their designated application pool when using IIS 6.0. You also learned how to create and configure application pools.

In addition, you learned all the details about deploying ASP.NET applications to the target environment. Although deploying ASP.NET applications merely requires copying them onto the target web server and sharing the directory as a virtual directory through IIS, you need to keep a couple of things in mind, such as validating the ASP.NET configuration, selecting the appropriate ASP.NET runtime because more than one version of ASP.NET can be installed on the target machine, and viewing the details of the different compilation possibilities when it comes to ASP.NET deployment.

Finally, we discussed the fundamentals of the health monitoring subsystem included with ASP.NET. This system gives you a basic infrastructure to instrument and monitor ASP.NET web applications based on events and providers. Events are just states that can become true in a web application, and providers are components for processing those events.

Basically the topics you learned in this chapter are the most important topics for website deployment. In addition, you might want to refer to the command-line administration available since IIS 6.0. Together with some other scripts (such as database scripts imported through osql.exe), they provide a mechanism for deploying ASP.NET web applications with simple scripts automatically.

P A R T 4

■ ■ ■

Security

C H A P T E R 1 9

■ ■ ■

The ASP.NET Security Model

Security is an essential part of web applications and should be taken into consideration from the first stage of the development process. Essentially, security is all about protecting your assets from unauthorized actions. You use several mechanisms to this end, including identifying users, granting or denying access to sensitive resources, and protecting the data that’s stored on the server and transmitted over the wire. In all of these cases, you need an underlying framework that provides basic security functionality. ASP.NET fills this need with built-in functionality that you can use for implementing security in your web applications.

The ASP.NET security framework includes classes for authenticating and authorizing users as well as for dealing with authenticated users in your applications. Furthermore, the .NET Framework on its own provides you with a set of base classes for implementing confidentiality and integrity through encryption and digital signatures.

With ASP.NET 2.0, the security infrastructure is extended significantly with a higher-level model for managing users and roles, both programmatically and with built-in administrative tools. This functionality (which is accessible through the Membership and Roles APIs) builds on the existing security infrastructure that has been present since ASP.NET 1.x. Best of all, this security infrastructure is completely extensible through the provider design pattern, as you’ll see in Chapter 26.

This chapter provides a road map to the security features in ASP.NET. In subsequent chapters, you’ll dig deeper into each of the topics covered in this chapter. Here, you’ll get a quick introduction to the key features of .NET security. You’ll see how the .NET authentication providers and authorization modules are structured, and you’ll learn how the user’s security context is represented with identity and principal objects. Most important, you’ll get a basic understanding of how you can incorporate security into your application architecture and design, and you’ll see what the most important factors are for creating secure software.

What It Means to Create Secure Software

Although the security framework provided by .NET and ASP.NET is powerful, it’s essential to keep some basic principles in mind and use the features correctly and at the right time. In all too many projects, security is treated as an afterthought, and architects and developers fail to consider it in the early stages. But when you don’t keep security in mind from the beginning—which means in your application architecture and design—how can you use all the security features offered by the

.NET Framework correctly and at the right time?

Therefore, it’s essential to include security from the first moment of your development process. That’s the only way to make the right security-related decisions when creating your architecture and designs.

667