590 likes | 684 Views
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)
E N D
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) • Configuration API • Read/write access to configuration settings • Simplified custom configuration sections • Instrumentation • Perf counters, health monitoring, and more
ASP.NET MMC Snap-In • GUI for applying configuration settings
ASP.NET MMC Snap-In Name Title Microsoft Corporation
Web Site Administration Tool • Browser-based admin GUI Invoked by requesting Webadmin.axd or using the "ASP.NET Configuration" command in Visual Studio's Website menu
Web Site Administration Tool Name Title Microsoft Corporation
Configuration API • API for reading and writing config data • Access to local and remote servers and apps • Used by MMC snap-in and Webadmin.axd • Strongly typed access to config sections • Access to raw XML if desired • Core classes in System.Configuration • ASP.NET-specific classes in System.Web.Configuration
Web.config Structure <configuration> <appSettings> ... </appSettings> <connectionStrings> ... </connectionStrings> ... <system.web> <compilation> ... </compilation> <pages> ... </pages> ... </system.web> <system.net> ... <system.net> </configuration> Sections Section groups
The WebConfigurationManager Class • Gateway to the configuration API • Provides merged view of configuration settings for machine or application • AppSettings and ConnectionStrings properties provide access to <appSettings> and <connectionStrings> sections • Sections and SectionGroups properties provide access to all other sections
Key Configuration Methods Name Description OpenMachineConfiguration Returns a Configuration object representing configuration settings for the specified server OpenWebConfiguration Returns a Configuration object representing configuration settings for the specified Web application GetSectionGroup GetSectionGroup Returns a ConfigurationSectionGroup object representing the specified section group GetSection GetSection Returns a ConfigurationSection object representing the specified section (e.g., <appSettings> Returns a ConfigurationSection object representing the specified section (e.g., <appSettings> Save Save Records changes in the relevant configuration file Records changes in the relevant configuration file
Key Configuration Properties Name Description AppSettings Returns an AppSettingsSection object representing the <appSettings> section ConnectionStrings Returns a ConnectionStringsSection object representing the <connectionsStrings> section HasFile True if there's a corresponding configuration file, false if not Path Path to the app represented by this Configuration object SectionGroups Returns a ConfigurationSectionGroupCollection representing all section groups Sections Returns a ConfigurationSectionCollection representing all sections
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> // 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!
ConfigurationSectionGroup • Represents configuration section groups such as <system.web> and <system.net> • Sections and SectionGroups properties provide access to sections and section groups contained therein • Useful for enumerating configuration sections
Key CSG Properties Name Description Name Name of section group (e.g., "caching") Path Path to section group (e.g., "system.web/caching") SectionGroups ConfigurationSectionGroupCollection representing contained section groups Sections ConfigurationSectionCollection representing contained sections
Enumerating 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 }
ConfigurationSection • Represents individual configuration sections (<compilation>, <pages>, etc.) • Defines base properties for retrieving information about section groups • Defines base methods for operating on section groups (e.g., encrypting) • Derived types in System.Web.Configuration represent ASP.NET-specific sections
Key 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 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 RestartOnExternalChanges Indicates whether external change causes app restart
Encrypting <connectionStrings> Configuration config = WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSection section = config.Sections["connectionStrings"]; if (!section.IsProtected) { section.ProtectSection ("DataProtectionConfigurationProvider"); config.Update (); }
Decrypting <connectionStrings> Configuration config = WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSection section = config.Sections["connectionStrings"]; if (section.IsProtected) { section.UnProtectSection (); config.Update (); }
ConfigurationSection 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> Settings // Read the <compilation> element's debug setting Configuration config = WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSectionGroup group = config.SectionGroups["system.web"]; CompilationSection section = (CompilationSection) group.Sections["compilation"]; bool debug = section.Debug;
Writing <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 Sections • Old model left much to be desired • Read-only, manual parsing of XML, etc. • New model is simpler and more powerful • Supports persistence to and from XML • Handles merging and unmerging automatically • Supports collections (e.g., <add>/<remove>) • Supports declarative validation via attributes • Vastly simplifies custom config sections
Custom Section Example Web.config <configuration> ... <system.web> <acme enabled="true" maxFailedLogins="3" /> </system.web> </configuration>
Custom Section Handler using 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 Registration Web.config <configuration> <configSections> <sectionGroup name="system.web"> <section name="acme" type="AcmeConfigurationSection, ..." allowDefinition="MachineToApplication" restartOnExternalChanges="false" /> </sectionGroup> <configSections> ... </configuration>
Configuration API Name Title Microsoft Corporation
ASP.NET 2.0 Instrumentation • New facilities for analyzing health and performance and diagnosing failures Name Description Performance counters New peformance counters supplement the ones introduced in ASP.NET 1.x Windows event tracing Integration with ETW subsystem to support low-overhead tracing of HTTP requests through the system Application tracing ASP.NET trace facility upgraded with new features and to 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 Counters • ASP.NET 1.x defined ~60 perf counters • Global - Aggregated across all applications • Application - 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/sec • Application versions of several global counters • State service sessions active, abandoned, timed out, and total
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 Tracing • Trace facility upgraded with new features • Circular trace buffering • Programmatic access to trace output • Now supports coupling to System.Diagnostics.Trace • Systems.Diagnostics.Trace -> ASP.NET trace • ASP.NET trace ->System.Diagnostics.Trace • Web events -> System.Diagnostics.Trace
Enabling Circular Trace Buffering <trace enabled="true" mostRecent="true" />
Redirecting ASP.NET Trace Out-put to Diagnostics Trace Output <trace enabled="true" writeToDiagnosticsTrace="true" />
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 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)); }
Application Tracing Name Title Microsoft Corporation
Health Monitoring ("Web Events") • Framework for monitoring status of running applications and logging significant events • Application starts and stops • Failed logins and unhandled exceptions • "Heartbeats" and more • Log events in Windows event log, SQL Server database, and elsewhere • Extensible and provider-based
Web Event Providers Name Description SqlWebEventProvider Logs Web events in a SQL Server database SimpleMailWebEventProvider Responds to Web events by sending e-mail TemplatedMailWebEventProvider Responds to Web events by sending templated e-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 Classes All Events WebBaseEvent WebManagementEvent Application Lifetime Events WebApplicationLifetimeEvent All Audits WebAuditEvent Failure Audits WebFailureAuditEvent Success Audits WebSuccessAuditEvent All Errors WebBaseErrorEvent Infrastructure Errors WebErrorEvent Request Processing Errors WebRequestErrorEvent HeartBeats WebHeartBeatEvent Request Processing Events WebRequestEvent
The 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 Events • Fire at key junctures during application's lifetime corresponding to starts and stops • Application start • Application end • Compilation start • Compilation end
Audit Events • Report success or failure of key security-related events during application lifetime • Successful and failed login attempts through Membership.ValidateUser • Successful and failed URL and ACL authorizations by authenticated users • Valid and expired forms authentication tickets • View state validation failures and more • Great for detecting intrusion attempts
Error Events • WebErrorEvent • Parsing and compilation errors • Configuration errors • WebRequestErrorEvent • Unhandled exceptions • Request validation failures (XSS) • Posts that exceed maxRequestLength • Anything that causes request to abort
Request Processing Events • Fire when either of the following occurs: • Automatic transaction initiated by a request commits • Automatic transaction initiated by a request aborts
HeartBeat Events • Fire at user-specified intervals • Include process information and statistics • AppDomain count and thread count • Requests queued, processing, and rejected • Current and peak working set size • Process start time and more • Great for generating running record of vital process statistics
<healthMonitoring> • Configuration section for health monitoring <healthMonitoring enabled="true" ...> <bufferModes> ... </bufferModes> <providers> ... </providers> <eventMappings> ... </eventMappings> <profiles> ... </profiles> <rules> ... </rules> </healthMonitoring> Named sets of buffer settings Registered providers Event types and friendly names Named sets of filter criteria Events to process, associated providers, and buffering/filtering criteria
<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> Event type (friendly name) <rules> <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" minInterval="00:00:00" minInstances="1" maxLimit="Infinite" /> ... </rules> Provider Minimum time interval between log entries* Number of instances before logging begins* Maximum number of instances logged* * Denotes optional attribute