Presentation is loading. Please wait.

Presentation is loading. Please wait.

Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: Administration.

Similar presentations


Presentation on theme: "Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: Administration."— Presentation transcript:

1 Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: http://www.codearchitects.com E-mail: mbellinaso@codearchitects.com Administration and Management with ASP.NET 2.0

2 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

3 ASP.NET MMC Snap-In GUI for applying configuration settings

4 Name Title Microsoft Corporation ASP.NET MMC Snap-In

5 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

6 Name Title Microsoft Corporation Web Site Administration Tool

7 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

8 Web.config Structure......... Section groups Sections

9 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 and sections Sections and SectionGroups properties provide access to all other sections

10 Key Configuration Methods NameDescription OpenMachineConfigurationReturns a Configuration object representing configuration settings for the specified server OpenWebConfigurationReturns a Configuration object representing configuration settings for the specified Web application GetSectionGroupReturns a ConfigurationSectionGroup object representing the specified section group SaveRecords changes in the relevant configuration file GetSectionReturns a ConfigurationSection object representing the specified section (e.g., GetSectionGroup SaveRecords changes in the relevant configuration file GetSectionReturns a ConfigurationSection object representing the specified section (e.g.,

11 Key Configuration Properties NameDescription AppSettingsReturns an AppSettingsSection object representing the section ConnectionStringsReturns a ConnectionStringsSection object representing the section HasFileTrue if there's a corresponding configuration file, false if not SectionGroupsReturns a ConfigurationSectionGroupCollection representing all section groups SectionsReturns a ConfigurationSectionCollection representing all sections PathPath to the app represented by this Configuration object

12 Reading and Writing // Read a value from string connect = ConfigurationSettings.AppSettings["Northwind"]; // Add a value to Configuration config = WebConfigurationManager.OpenWebConfiguration ( " ~ " ); config.AppSettings.Add ("Northwind", "server=localhost;database=northwind;integrated security=true"); config.Save (); // Important!

13 Reading and Writing // Read a connection string from string connect = ConfigurationSettings.ConnectionStrings["Northwind"].ConnectionString; // Add a connection string to Configuration config = WebConfigurationManager.OpenWebConfiguration ("~"); config.ConnectionStrings.ConnectionStrings.Add (new ConnectionStringSettings ("Northwind", "server=localhost;database=northwind;integrated security=true"); config.Save (); // Important!

14 ConfigurationSectionGroup Represents configuration section groups such as and Sections and SectionGroups properties provide access to sections and section groups contained therein Useful for enumerating configuration sections

15 Key CSG Properties NameDescription NameName of section group (e.g., "caching") PathPath to section group (e.g., "system.web/caching") SectionGroupsConfigurationSectionGroupCollection representing contained section groups SectionsConfigurationSectionCollection representing contained sections

16 Enumerating Sections // Enumerate the sections in 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 + " "); // Output section name }

17 ConfigurationSection Represents individual configuration sections (,, 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

18 Key CS Methods NameDescription GetParentSectionReturns a ConfigurationSection representing parent section GetRawXmlRetrieves the raw XML for the section UpdateRawXmlModifies the section using raw XML as input ProtectSectionEncrypts the section using specified protection provider UnProtectSectionDecrypts the section

19 Key CS Properties NameDescription NameSection name (e.g., "compilation") PathPath to section (e.g., " system.web/compilation") AllowDefinitionSection scope (machine, application, etc.) IsDeclaredIndicates whether section is declared in local config file IsProtectedIndicates whether this section is currently encrypted RestartOnExternalChangesIndicates whether external change causes app restart

20 Encrypting Configuration config = WebConfigurationManager.OpenWebConfiguration ( " ~ " ); ConfigurationSection section = config.Sections["connectionStrings"]; if (!section.IsProtected) { section.ProtectSection ("DataProtectionConfigurationProvider"); config.Update (); }

21 Decrypting Configuration config = WebConfigurationManager.OpenWebConfiguration ("~"); ConfigurationSection section = config.Sections["connectionStrings"]; if (section.IsProtected) { section.UnProtectSection (); config.Update (); }

22 ConfigurationSection Derivatives System.Web.Configuration namespace contains ConfigurationSection derivatives representing sections CompilationSection ( ) SessionStateSection ( ) PagesSection ( ) and more Derived types provide strongly typed access to ASP.NET configuration sections

23 Reading Settings // Read the element's debug setting Configuration config = WebConfigurationManager.OpenWebConfiguration ( " ~ " ); ConfigurationSectionGroup group = config.SectionGroups["system.web"]; CompilationSection section = (CompilationSection) group.Sections["compilation"]; bool debug = section.Debug;

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

25 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., / ) Supports declarative validation via attributes Vastly simplifies custom config sections

26 Custom Section Example... Web.config

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

28 Handler Registration <section name="acme" type="AcmeConfigurationSection,..." allowDefinition="MachineToApplication" restartOnExternalChanges="false" />... Web.config

29 Name Title Microsoft Corporation Configuration API

30 ASP.NET 2.0 Instrumentation New facilities for analyzing health and performance and diagnosing failures NameDescription Performance countersNew peformance counters supplement the ones introduced in ASP.NET 1.x Windows event tracingIntegration with ETW subsystem to support low-overhead tracing of HTTP requests through the system Application tracingASP.NET trace facility upgraded with new features and to allow coupling to System.Diagnostics.Trace Health monitoringNew provider-based subsystem for logging notable events ("Web events") that occur during an application's lifetime

31 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

32 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

33 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

34 Enabling Circular Trace Buffering

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

36 Redirecting Diagnostics Trace Output to ASP.NET Trace Output <add name="WebPageTraceListener" type="System.Web.WebPageTraceListener, System.Web,..." />

37 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} ", record.Category, record.Message)); }

38 Name Title Microsoft Corporation Application Tracing

39 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

40 Web Event Providers NameDescription SqlWebEventProviderLogs Web events in a SQL Server database SimpleMailWebEventProviderResponds to Web events by sending e-mail TemplatedMailWebEventProviderResponds to Web events by sending templated e-mail (e-mail generated by a specified ASPX) EventLogProviderLogs Web events in the Windows event log WmiWebEventProviderForwards Web events to the WMI subsystem TraceWebEventProviderForwards Web events to registered trace listeners

41 Web Event Classes WebBaseEvent WebApplicationLifetimeEvent WebSuccessAuditEvent WebFailureAuditEvent WebManagementEvent WebAuditEvent WebBaseErrorEvent WebHeartBeatEvent WebRequestEvent WebErrorEvent WebRequestErrorEvent All Events Failure Audits Success Audits HeartBeats Request Processing Events Request Processing Errors All Audits Application Lifetime Events All Errors Infrastructure Errors

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

43 Application Lifetime Events Fire at key junctures during application's lifetime corresponding to starts and stops Application start Application end Compilation start Compilation end

44 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

45 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

46 Request Processing Events Fire when either of the following occurs: Automatic transaction initiated by a request commits Automatic transaction initiated by a request aborts

47 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

48 Configuration section for health monitoring............... 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

49 <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="Failure Audits" type="System.Web.Management.WebFailureAuditEvent,..." /> <add name="Success Audits" type="System.Web.Management.WebSuccessAuditEvent,..." />

50 <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" minInterval="00:00:00" minInstances="1" maxLimit="Infinite" />... Event type (friendly name) Provider * Denotes optional attribute Minimum time interval between log entries* Number of instances before logging begins* Maximum number of instances logged*

51 <add name="LowOverhead" minInterval="00:01:00" minInstances="1" maxLimit="10" />... Log no more than 1 event per minute Begin logging on first instance Log maximum of 10 events <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" profile="LowOverhead" />... Use settings in "LowOverhead" profile

52 Logging HeartBeats in the Windows Event Log <add name="Microsoft.com Heartbeats" eventName="HeartBeats" provider="EventLogProvider" profile="Default" />

53 Logging Failure Audits in SQL Server <add name="Failure Audits Default" eventName="Failure Audits" provider="SqlWebEventProvider" profile="Default" />

54 Custom Web Events To define a custom Web event: Derive from WebBaseEvent Add custom constructors (if desired) Override FormatCustomEventDetails To fire a custom Web event: Instantiate custom Web event class Call static WebBaseEvent.Raise method Require manual compilation!

55 Defining Custom Web Events using 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); }

56 Firing Custom Web Events UpdateErrorWebEvent uewe = new UpdateErrorWebEvent ("Update failure", null, 100001, exception); WebBaseEvent.Raise (uewe); Event code must be 100000 or higher

57 Registering Custom Web Events <add name="Update Error Web Events" type="UpdateErrorWebEvent, UpdateErrorWebEvent" /> <add name="Update Errors" eventName="Update Error Web Events" provider="EventLogProvider" profile="Critical" />

58 Name Title Microsoft Corporation Health Monitoring

59


Download ppt "Marco Bellinaso Senior Trainer & Consultant Code Architects Srl Web: Administration."

Similar presentations


Ads by Google