Administration and Management with ASP.NET 2.0

Preview:

DESCRIPTION

Administration and Management with ASP.NET 2.0. Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: http://www.codearchitects.com E-mail: mbellinaso@codearchitects.com. Agenda. Administrative tools ASP.NET MMC snap-in Web Site Administration Tool (Webadmin.axd) - PowerPoint PPT Presentation

Citation preview

Marco BellinasoSenior Trainer & ConsultantCode Architects Srl

Web: http://www.codearchitects.comE-mail: mbellinaso@codearchitects.com

Administration and Management with ASP.NET 2.0Administration and Management with ASP.NET 2.0

AgendaAgenda

Administrative toolsASP.NET MMC snap-inWeb Site Administration Tool (Webadmin.axd)

Configuration APIRead/write access to configuration settingsSimplified custom configuration sections

InstrumentationPerf counters, health monitoring, and more

ASP.NET MMC Snap-InASP.NET MMC Snap-In

GUI for applying configuration settings

NameTitleMicrosoft Corporation

ASP.NET MMC Snap-InASP.NET MMC Snap-In

Web Site Administration ToolWeb Site Administration Tool

Browser-based admin GUI

Invoked by requestingWebadmin.axd or usingthe "ASP.NET Configuration"command in Visual Studio'sWebsite menu

NameTitleMicrosoft Corporation

Web Site Administration ToolWeb Site Administration Tool

Configuration APIConfiguration API

API for reading and writing config dataAccess to local and remote servers and appsUsed by MMC snap-in and Webadmin.axd

Strongly typed access to config sectionsAccess to raw XML if desired

Core classes in System.ConfigurationASP.NET-specific classes in System.Web.Configuration

Web.config StructureWeb.config Structure<configuration> <appSettings> ... </appSettings> <connectionStrings> ... </connectionStrings> ... <system.web> <compilation> ... </compilation> <pages> ... </pages> ... </system.web> <system.net> ... <system.net></configuration>

Section groups

Sections

The WebConfigurationManager ClassThe WebConfigurationManager ClassGateway to the configuration APIProvides merged view of configuration settings for machine or applicationAppSettings and ConnectionStrings properties provide access to <appSettings> and <connectionStrings> sectionsSections and SectionGroups properties provide access to all other sections

Key Configuration MethodsKey Configuration Methods

Name Description

OpenMachineConfigurationReturns a Configuration object representingconfiguration settings for the specified server

OpenWebConfiguration Returns a Configuration object representingconfiguration settings for the specified Web application

GetSectionGroup Returns a ConfigurationSectionGroup objectrepresenting the specified section group

Save Records changes in the relevant configuration file

GetSection Returns a ConfigurationSection object representingthe specified section (e.g., <appSettings>

GetSectionGroup

Save Records changes in the relevant configuration file

GetSection Returns a ConfigurationSection object representingthe specified section (e.g., <appSettings>

Key Configuration PropertiesKey Configuration Properties

Name Description

AppSettings Returns an AppSettingsSection object representing the<appSettings> section

ConnectionStrings Returns a ConnectionStringsSection object representingthe <connectionsStrings> section

HasFile True if there's a corresponding configuration file, false if not

SectionGroups Returns a ConfigurationSectionGroupCollectionrepresenting all section groups

Sections Returns a ConfigurationSectionCollection representingall sections

Path Path to the app represented by this Configuration object

Reading and Writing <appSettings>Reading and Writing <appSettings>

// Read a value from <appSettings>string connect = ConfigurationSettings.AppSettings["Northwind"];

// Add a value to <appSettings>Configuration config =

WebConfigurationManager.OpenWebConfiguration ("~");config.AppSettings.Add ("Northwind", "server=localhost;database=northwind;integrated security=true");config.Save (); // Important!

Reading and Writing <connectionStrings>Reading and Writing <connectionStrings>

// Read a connection string from <connectionStrings>string connect = ConfigurationSettings.ConnectionStrings["Northwind"].ConnectionString;

// Add a connection string to <connectionStrings>Configuration config = WebConfigurationManager.OpenWebConfiguration ("~");config.ConnectionStrings.ConnectionStrings.Add (new ConnectionStringSettings ("Northwind", "server=localhost;database=northwind;integrated security=true");config.Save (); // Important!

ConfigurationSectionGroupConfigurationSectionGroup

Represents configuration section groups such as <system.web> and <system.net>Sections and SectionGroups properties provide access to sections and section groups contained thereinUseful for enumerating configuration sections

Key CSG PropertiesKey CSG Properties

Name Description

Name Name of section group (e.g., "caching")

Path Path to section group (e.g., "system.web/caching")

SectionGroups ConfigurationSectionGroupCollection representingcontained section groups

Sections ConfigurationSectionCollection representingcontained sections

Enumerating SectionsEnumerating Sections// Enumerate the sections in <system.web>Configuration config =

WebConfigurationManager.OpenWebConfiguration ("~");ConfigurationSectionGroup group = config.SectionGroups["system.web"];for (int i=0; i<group.Sections.Count; i++) { ConfigurationSection section = group.Sections[i]; Response.Write (section.Name + "<br>"); // Output section name}

ConfigurationSectionConfigurationSection

Represents individual configuration sections (<compilation>, <pages>, etc.)Defines base properties for retrieving information about section groupsDefines base methods for operating on section groups (e.g., encrypting)Derived types in System.Web.Configuration represent ASP.NET-specific sections

Key CS MethodsKey CS Methods

Name Description

GetParentSection Returns a ConfigurationSection representing parent section

GetRawXml Retrieves the raw XML for the section

UpdateRawXml Modifies the section using raw XML as input

ProtectSection Encrypts the section using specified protection provider

UnProtectSection Decrypts the section

Key CS PropertiesKey CS Properties

Name Description

Name Section name (e.g., "compilation")

Path Path to section (e.g., " system.web/compilation")

AllowDefinition Section scope (machine, application, etc.)

IsDeclared Indicates whether section is declared in local config file

IsProtected Indicates whether this section is currently encrypted

RestartOnExternalChangesIndicates whether external change causes app restart

Encrypting <connectionStrings>Encrypting <connectionStrings>Configuration config =

WebConfigurationManager.OpenWebConfiguration ("~");ConfigurationSection section = config.Sections["connectionStrings"];

if (!section.IsProtected) { section.ProtectSection ("DataProtectionConfigurationProvider"); config.Update ();}

Decrypting <connectionStrings>Decrypting <connectionStrings>Configuration config = WebConfigurationManager.OpenWebConfiguration ("~");ConfigurationSection section = config.Sections["connectionStrings"];

if (section.IsProtected) { section.UnProtectSection (); config.Update ();}

ConfigurationSection DerivativesConfigurationSection Derivatives

System.Web.Configuration namespace contains ConfigurationSection derivatives representing <system.web> sections

CompilationSection (<compilation>)SessionStateSection (<sessionState>)PagesSection (<pages>) and more

Derived types provide strongly typed access to ASP.NET configuration sections

Reading <compilation> SettingsReading <compilation> Settings// Read the <compilation> element's debug settingConfiguration config =

WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSectionGroup group = config.SectionGroups["system.web"];CompilationSection section = (CompilationSection) group.Sections["compilation"];bool debug = section.Debug;

Writing <compilation> SettingsWriting <compilation> Settings// Set <compilation debug="true" />Configuration config =

WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSectionGroup group = config.SectionGroups["system.web"];CompilationSection section = (CompilationSection) group.Sections["compilation"];section.Debug = true;config.Update ();

Custom Configuration SectionsCustom Configuration SectionsOld model left much to be desired

Read-only, manual parsing of XML, etc.

New model is simpler and more powerfulSupports persistence to and from XMLHandles merging and unmerging automaticallySupports collections (e.g., <add>/<remove>)Supports declarative validation via attributes

Vastly simplifies custom config sections

Custom Section ExampleCustom Section Example

<configuration> ... <system.web> <acme enabled="true" maxFailedLogins="3" /> </system.web></configuration>

Web.config

Custom Section HandlerCustom Section Handlerusing System;using System.Configuration;

public class AcmeConfigurationSection : ConfigurationSection{ [ConfigurationProperty ("enabled", DefaultValue="false")] public bool Enabled { get { return (bool) this["enabled"]; } set { this["enabled"] = value; } }

[ConfigurationProperty ("maxFailedLogins", DefaultValue="5")] [IntegerRangeValidation (1, 999)] public int MaxFailedLogins { get { return (int) this["maxFailedLogins"]; } set { this["maxFailedLogins"] = value; } }}

Handler RegistrationHandler Registration

<configuration> <configSections> <sectionGroup name="system.web"> <section name="acme" type="AcmeConfigurationSection, ..." allowDefinition="MachineToApplication" restartOnExternalChanges="false" /> </sectionGroup> <configSections> ...</configuration>

Web.config

NameTitleMicrosoft Corporation

Configuration APIConfiguration API

ASP.NET 2.0 InstrumentationASP.NET 2.0 Instrumentation

New facilities for analyzing health and performance and diagnosing failuresName Description

Performance countersNew peformance counters supplement the onesintroduced in ASP.NET 1.x

Windows event tracingIntegration with ETW subsystem to support low-overheadtracing of HTTP requests through the system

Application tracing ASP.NET trace facility upgraded with new features andto allow coupling to System.Diagnostics.Trace

Health monitoring New provider-based subsystem for logging notable events("Web events") that occur during an application's lifetime

Performance CountersPerformance Counters

ASP.NET 1.x defined ~60 perf countersGlobal - Aggregated across all applicationsApplication - Specific to application instance

ASP.NET 2.0 adds ~25 more, including:Several that relate to health monitoring, such as events raised total and events raised/secApplication versions of several global countersState service sessions active, abandoned, timed out, and total

Windows Event Tracing (ETW)Windows Event Tracing (ETW)

ETW support facilitates end-to-end tracing of requests through system

Request events (enter/leave IIS, AppDomain, HTTP module, HTTP handler, etc.)Page life-cycle events (e.g., Init, Load)Application services events (e.g., acquire session state, resolve role)Build provider events (e.g., start/end compile)

Extremely low overhead

Application TracingApplication Tracing

Trace facility upgraded with new featuresCircular trace bufferingProgrammatic access to trace output

Now supports coupling to System.Diagnostics.Trace

Systems.Diagnostics.Trace -> ASP.NET traceASP.NET trace ->System.Diagnostics.TraceWeb events -> System.Diagnostics.Trace

Enabling Circular Trace BufferingEnabling Circular Trace Buffering

<trace enabled="true" mostRecent="true" />

Redirecting ASP.NET Trace Out-put to Diagnostics Trace Output

Redirecting ASP.NET Trace Out-put to Diagnostics Trace Output

<trace enabled="true" writeToDiagnosticsTrace="true" />

Redirecting Diagnostics Trace Output to ASP.NET Trace Output

Redirecting Diagnostics Trace Output to ASP.NET Trace Output<system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="WebPageTraceListener" type="System.Web.WebPageTraceListener, System.Web, ..." /> </listeners> </trace></system.diagnostics>

Reading Trace Output ProgrammaticallyReading Trace Output Programmatically

void Page_Load (object sender, EventArgs e){ Trace.TraceFinished += new TraceContextEventHandler (OnTraceFinished);}

void OnTraceFinished (object sender, TraceContextEventArgs e){ foreach (TraceContextRecord record in e.TraceRecords) Response.Write (String.Format ("{0}: {1}<br>", record.Category, record.Message));}

NameTitleMicrosoft Corporation

Application TracingApplication Tracing

Health Monitoring ("Web Events")Health Monitoring ("Web Events")Framework for monitoring status of running applications and logging significant events

Application starts and stopsFailed logins and unhandled exceptions"Heartbeats" and more

Log events in Windows event log, SQL Server database, and elsewhereExtensible and provider-based

Web Event ProvidersWeb Event Providers

Name Description

SqlWebEventProvider Logs Web events in a SQL Server database

SimpleMailWebEventProvider Responds to Web events by sending e-mail

TemplatedMailWebEventProviderResponds to Web events by sending templatede-mail (e-mail generated by a specified ASPX)

EventLogProvider Logs Web events in the Windows event log

WmiWebEventProvider Forwards Web events to the WMI subsystem

TraceWebEventProvider Forwards Web events to registered trace listeners

Web Event ClassesWeb Event ClassesWebBaseEventWebBaseEvent

WebApplicationLifetimeEventWebApplicationLifetimeEvent

WebSuccessAuditEventWebSuccessAuditEvent

WebFailureAuditEventWebFailureAuditEvent

WebManagementEventWebManagementEvent

WebAuditEventWebAuditEvent

WebBaseErrorEventWebBaseErrorEvent

WebHeartBeatEventWebHeartBeatEvent

WebRequestEventWebRequestEvent

WebErrorEventWebErrorEvent

WebRequestErrorEventWebRequestErrorEvent

All Events

Failure Audits

Success Audits

HeartBeats

Request Processing Events

Request Processing Errors

All Audits

Application Lifetime Events

All Errors

Infrastructure Errors

The WebBaseEvent ClassThe WebBaseEvent Class

Defines infrastructure common to all events

public class WebBaseEvent : System.Object{ public static WebApplicationInformation ApplicationInformation { get; } public int EventCode { get; } public int EventDetailCode { get; } public Guid EventId { get; } public long EventSequence { get; } public object EventSource { get; } public DateTime EventTime { get; } public DateTime EventTimeUtc { get; } public string Message { get; } public virtual void FormatCustomEventDetails (...); public virtual void Raise (...);}

Application Lifetime EventsApplication Lifetime Events

Fire at key junctures during application's lifetime corresponding to starts and stops

Application startApplication endCompilation startCompilation end

Audit EventsAudit Events

Report success or failure of key security-related events during application lifetime

Successful and failed login attempts through Membership.ValidateUserSuccessful and failed URL and ACL authorizations by authenticated usersValid and expired forms authentication ticketsView state validation failures and more

Great for detecting intrusion attempts

Error EventsError Events

WebErrorEventParsing and compilation errorsConfiguration errors

WebRequestErrorEventUnhandled exceptionsRequest validation failures (XSS)Posts that exceed maxRequestLengthAnything that causes request to abort

Request Processing EventsRequest Processing Events

Fire when either of the following occurs:Automatic transaction initiated by a request commitsAutomatic transaction initiated by a request aborts

HeartBeat EventsHeartBeat Events

Fire at user-specified intervalsInclude process information and statistics

AppDomain count and thread countRequests queued, processing, and rejectedCurrent and peak working set sizeProcess start time and more

Great for generating running record of vital process statistics

<healthMonitoring><healthMonitoring>

Configuration section for health monitoring<healthMonitoring enabled="true" ...>

<bufferModes> ... </bufferModes> <providers> ... </providers> <eventMappings> ... </eventMappings> <profiles> ... </profiles> <rules> ... </rules></healthMonitoring>

Named sets of buffersettings

Registered providers

Event types andfriendly namesNamed sets of filtercriteria

Events to process,associated providers, andbuffering/filtering criteria

<eventMappings><eventMappings><eventMappings> <add name="All Events" type="System.Web.Management.WebBaseEvent, ..." /> <add name="HeartBeats" type="System.Web.Management.WebHeartBeatEvent, ..." /> <add name="Application Lifetime Events" type="System.Web.Management.WebApplicationLifetimeEvent, ..." /> <add name="Request Processing Events" type="System.Web.Management.WebRequestEvent, ..." /> <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent, ..." /> <add name="Infrastructure Errors" type="System.Web.Management.WebErrorEvent, ..." /> <add name="Request Processing Errors" type="System.Web.Management.WebRequestErrorEvent, ..." /> <add name="All Audits" type="System.Web.Management.WebAuditEvent, ..." /> <add name="Failure Audits" type="System.Web.Management.WebFailureAuditEvent, ..." /> <add name="Success Audits" type="System.Web.Management.WebSuccessAuditEvent, ..." /></eventMappings>

<rules><rules>

<rules> <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" minInterval="00:00:00" minInstances="1" maxLimit="Infinite" /> ...</rules>

Event type (friendly name)

Provider

* Denotes optional attribute

Minimum time intervalbetween log entries*

Number of instances beforelogging begins*

Maximum number ofinstances logged*

<profiles><profiles><profiles> <add name="LowOverhead" minInterval="00:01:00" minInstances="1" maxLimit="10" /> ...</profiles>

Log no more than 1event per minute

Begin logging on firstinstance

Log maximum of 10 events

<rules> <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" profile="LowOverhead" /> ...</rules>

Use settings in"LowOverhead" profile

Logging HeartBeats in the Windows Event LogLogging HeartBeats in the Windows Event Log<healthMonitoring enabled="true" heartBeatInterval="3600"> <rules> <add name="Microsoft.com Heartbeats" eventName="HeartBeats" provider="EventLogProvider" profile="Default" /> </rules></healthMonitoring>

Logging Failure Auditsin SQL ServerLogging Failure Auditsin SQL Server<healthMonitoring enabled="true"> <rules> <remove name="Failure Audits Default" /> <add name="Failure Audits Default" eventName="Failure Audits" provider="SqlWebEventProvider" profile="Default" /> </rules></healthMonitoring>

Custom Web EventsCustom Web Events

To define a custom Web event:Derive from WebBaseEventAdd custom constructors (if desired)Override FormatCustomEventDetails

To fire a custom Web event:Instantiate custom Web event classCall static WebBaseEvent.Raise method

Require manual compilation!

Defining Custom Web EventsDefining Custom Web Eventsusing System;using System.Web.Management;

public class UpdateErrorWebEvent : WebBaseEvent{ Exception _exception;

public UpdateErrorWebEvent (string message, object source, int eventCode, Exception exception) : base (message, source, eventCode) { _exception = exception; }

public override void FormatCustomEventDetails (WebEventFormatter formatter) { formatter.AppendLine (_exception.Message); }}

Firing Custom Web EventsFiring Custom Web Events

UpdateErrorWebEvent uewe = new UpdateErrorWebEvent ("Update failure", null, 100001, exception);WebBaseEvent.Raise (uewe);

Event code must be 100000 or higher

Registering Custom Web EventsRegistering Custom Web Events

<healthMonitoring enabled="true"> <eventMappings> <add name="Update Error Web Events" type="UpdateErrorWebEvent, UpdateErrorWebEvent" /> </eventMappings> <rules> <add name="Update Errors" eventName="Update Error Web Events" provider="EventLogProvider" profile="Critical" /> </rules></healthMonitoring>

NameTitleMicrosoft Corporation

Health MonitoringHealth Monitoring

Recommended