59
Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: http://www.codearchitects.com E-mail: [email protected] Administration and Management with ASP.NET 2.0

Administration and Management with ASP.NET 2.0

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Administration and Management with ASP.NET 2.0

Marco BellinasoSenior Trainer & ConsultantCode Architects Srl

Web: http://www.codearchitects.comE-mail: [email protected]

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

Page 2: Administration 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

Page 3: Administration and Management with ASP.NET 2.0

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

GUI for applying configuration settings

Page 4: Administration and Management with ASP.NET 2.0

NameTitleMicrosoft Corporation

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

Page 5: Administration and Management with ASP.NET 2.0

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

Page 6: Administration and Management with ASP.NET 2.0

NameTitleMicrosoft Corporation

Web Site Administration ToolWeb Site Administration Tool

Page 7: Administration and Management with ASP.NET 2.0

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

Page 8: Administration and Management with ASP.NET 2.0

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

Page 9: Administration and Management with ASP.NET 2.0

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

Page 10: Administration and Management with ASP.NET 2.0

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>

Page 11: Administration and Management with ASP.NET 2.0

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

Page 12: Administration and Management with ASP.NET 2.0

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!

Page 13: Administration and Management with ASP.NET 2.0

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!

Page 14: Administration and Management with ASP.NET 2.0

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

Page 15: Administration and Management with ASP.NET 2.0

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

Page 16: Administration and Management with ASP.NET 2.0

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}

Page 17: Administration and Management with ASP.NET 2.0

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

Page 18: Administration and Management with ASP.NET 2.0

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

Page 19: Administration and Management with ASP.NET 2.0

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

Page 20: Administration and Management with ASP.NET 2.0

Encrypting <connectionStrings>Encrypting <connectionStrings>Configuration config =

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

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

Page 21: Administration and Management with ASP.NET 2.0

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

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

Page 22: Administration and Management with ASP.NET 2.0

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

Page 23: Administration and Management with ASP.NET 2.0

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;

Page 24: Administration and Management with ASP.NET 2.0

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 ();

Page 25: Administration and Management with ASP.NET 2.0

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

Page 26: Administration and Management with ASP.NET 2.0

Custom Section ExampleCustom Section Example

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

Web.config

Page 27: Administration and Management with ASP.NET 2.0

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; } }}

Page 28: Administration and Management with ASP.NET 2.0

Handler RegistrationHandler Registration

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

Web.config

Page 29: Administration and Management with ASP.NET 2.0

NameTitleMicrosoft Corporation

Configuration APIConfiguration API

Page 30: Administration and Management with ASP.NET 2.0

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

Page 31: Administration and Management with ASP.NET 2.0

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

Page 32: Administration and Management with ASP.NET 2.0

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

Page 33: Administration and Management with ASP.NET 2.0

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

Page 34: Administration and Management with ASP.NET 2.0

Enabling Circular Trace BufferingEnabling Circular Trace Buffering

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

Page 35: Administration and Management with ASP.NET 2.0

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" />

Page 36: Administration and Management with ASP.NET 2.0

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>

Page 37: Administration and Management with ASP.NET 2.0

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));}

Page 38: Administration and Management with ASP.NET 2.0

NameTitleMicrosoft Corporation

Application TracingApplication Tracing

Page 39: Administration and Management with ASP.NET 2.0

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

Page 40: Administration and Management with ASP.NET 2.0

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

Page 41: Administration and Management with ASP.NET 2.0

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

Page 42: Administration and Management with ASP.NET 2.0

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 (...);}

Page 43: Administration and Management with ASP.NET 2.0

Application Lifetime EventsApplication Lifetime Events

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

Application startApplication endCompilation startCompilation end

Page 44: Administration and Management with ASP.NET 2.0

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

Page 45: Administration and Management with ASP.NET 2.0

Error EventsError Events

WebErrorEventParsing and compilation errorsConfiguration errors

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

Page 46: Administration and Management with ASP.NET 2.0

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

Page 47: Administration and Management with ASP.NET 2.0

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

Page 48: Administration and Management with ASP.NET 2.0

<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

Page 49: Administration and Management with ASP.NET 2.0

<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>

Page 50: Administration and Management with ASP.NET 2.0

<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*

Page 51: Administration and Management with ASP.NET 2.0

<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

Page 52: Administration and Management with ASP.NET 2.0

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>

Page 53: Administration and Management with ASP.NET 2.0

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>

Page 54: Administration and Management with ASP.NET 2.0

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!

Page 55: Administration and Management with ASP.NET 2.0

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); }}

Page 56: Administration and Management with ASP.NET 2.0

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

Page 57: Administration and Management with ASP.NET 2.0

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>

Page 58: Administration and Management with ASP.NET 2.0

NameTitleMicrosoft Corporation

Health MonitoringHealth Monitoring

Page 59: Administration and Management with ASP.NET 2.0