Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,133 @@
//------------------------------------------------------------------------------
// <copyright file="AppDomainResourcePerfCounters.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System;
using System.Configuration;
using System.Web;
using System.Threading;
internal class AppDomainResourcePerfCounters {
private const uint NUM_SECONDS_TO_POLL = 5;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal static void Init() {
if (_fInit)
return;
lock (_InitLock) {
if (_fInit)
return;
if (AppDomain.MonitoringIsEnabled) {
PerfCounters.SetCounter(AppPerfCounter.APP_CPU_USED_BASE, 100);
_Timer = new Timer((new AppDomainResourcePerfCounters()).TimerCallback, null,
NUM_SECONDS_TO_POLL * 1000, NUM_SECONDS_TO_POLL * 1000);
}
_fInit = true;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal static void Stop() {
if (_Timer == null)
return; // already stopped
_StopRequested = true;
lock (_InitLock) {
if (_Timer != null) {
((IDisposable)_Timer).Dispose();
_Timer = null;
}
}
// Wait for the _inProgressLock lock
while (_inProgressLock != 0) {
Thread.Sleep(100);
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Static data
private static bool _fInit = false;
private static object _InitLock = new object();
private static Timer _Timer = null;
private static int _inProgressLock = 0;
private static bool _StopRequested = false;
// Instance data
private int _MemUsageLastReported = 0;
private int _CPUUsageLastReported = 0;
private TimeSpan _TotalCPUTime;
private DateTime _LastCollectTime;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private AppDomainResourcePerfCounters() {
_TotalCPUTime = AppDomain.CurrentDomain.MonitoringTotalProcessorTime;
_LastCollectTime = DateTime.UtcNow;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private void TimerCallback(Object state) {
if ( _StopRequested || // Stop has been called -- exit immediately
!AppDomain.MonitoringIsEnabled || // Monitoring APIs will throw NotSupportedException if not-enabled
Interlocked.Exchange(ref _inProgressLock, 1) != 0) // Is some thread currently executing the callback
{
return;
}
try {
SetPerfCounters();
} catch { // don't bubble up exceptions, since we are on a timer thread
} finally {
Interlocked.Exchange(ref _inProgressLock, 0);
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private void SetPerfCounters() {
////////////////////////////////////////////////////////////
// Calculate memory: Limited to 2TB (Int32.MaxValue * 1024 bytes)
long memInKB = (AppDomain.CurrentDomain.MonitoringSurvivedMemorySize / 1024); // Mem used in KB
_MemUsageLastReported = (int) Math.Min(Int32.MaxValue, Math.Max(0, memInKB)); // Make sure its within 0 and Int32.MaxValue
PerfCounters.SetCounter(AppPerfCounter.APP_MEMORY_USED, _MemUsageLastReported);
////////////////////////////////////////////////////////////
// Calculate CPU
DateTime dtUtcNow = DateTime.UtcNow;
TimeSpan newTotalCPUTime = AppDomain.CurrentDomain.MonitoringTotalProcessorTime;
double timeElapsed = (dtUtcNow - _LastCollectTime).TotalMilliseconds; // Total time since last collect
double cpuTimeUsed = (newTotalCPUTime - _TotalCPUTime).TotalMilliseconds; // Total CPU time used since last collect
int cpuPercent = (int) ((cpuTimeUsed * 100) / timeElapsed); // Percent of CPU time used
_CPUUsageLastReported = Math.Min(100, Math.Max(0, cpuPercent)); // Make sure it's within 0 and 100
PerfCounters.SetCounter(AppPerfCounter.APP_CPU_USED, _CPUUsageLastReported);
// Update variables for next time
_TotalCPUTime = newTotalCPUTime;
_LastCollectTime = dtUtcNow;
}
}
}

View File

@@ -0,0 +1,91 @@
//------------------------------------------------------------------------------
// <copyright file="BufferedWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System;
using System.Web;
using System.Diagnostics;
using System.Web.Util;
using System.Web.Configuration;
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Security;
using Debug=System.Web.Util.Debug;
using System.Security.Permissions;
// Interface for buffered event provider
public abstract class BufferedWebEventProvider : WebEventProvider {
bool _buffer = true;
string _bufferMode;
WebEventBuffer _webEventBuffer;
public override void Initialize(string name, NameValueCollection config)
{
// create buffer according to the buffer mode settings specified, like we do in sql/mail providers
// wire up the delegate to the ProcessEventFlush method
Debug.Trace("BufferedWebEventProvider", "Initializing: name=" + name);
ProviderUtil.GetAndRemoveBooleanAttribute(config, "buffer", name, ref _buffer);
if (_buffer) {
ProviderUtil.GetAndRemoveRequiredNonEmptyStringAttribute(config, "bufferMode", name, ref _bufferMode);
_webEventBuffer = new WebEventBuffer(this, _bufferMode, new WebEventBufferFlushCallback(this.ProcessEventFlush));
}
else {
ProviderUtil.GetAndRemoveStringAttribute(config, "bufferMode", name, ref _bufferMode);
}
base.Initialize(name, config);
ProviderUtil.CheckUnrecognizedAttributes(config, name);
}
public bool UseBuffering {
get { return _buffer; }
}
public string BufferMode {
get { return _bufferMode; }
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
if (_buffer) {
// register the event with the buffer instead of writing it out
Debug.Trace("BufferedWebEventProvider", "Saving event to buffer: event=" + eventRaised.GetType().Name);
_webEventBuffer.AddEvent(eventRaised);
}
else {
WebEventBufferFlushInfo flushInfo = new WebEventBufferFlushInfo(
new WebBaseEventCollection(eventRaised),
EventNotificationType.Unbuffered,
0,
DateTime.MinValue,
0,
0);
ProcessEventFlush(flushInfo);
}
}
public abstract void ProcessEventFlush(WebEventBufferFlushInfo flushInfo);
public override void Flush() {
if (_buffer) {
_webEventBuffer.Flush(Int32.MaxValue, FlushCallReason.StaticFlush);
}
}
public override void Shutdown() {
if (_webEventBuffer != null) {
_webEventBuffer.Shutdown();
}
}
}
}

View File

@@ -0,0 +1,298 @@
//------------------------------------------------------------------------------
// <copyright file="EventlogProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Security.Principal;
using System.Web.Util;
using System.Globalization;
using System.Collections;
using System.Web.UI;
using System.Security.Permissions;
using System.Text;
////////////
// Events
////////////
public sealed class EventLogWebEventProvider : WebEventProvider, IInternalWebEventProvider {
const int EventLogParameterMaxLength = 30 * 1024 - 2;
const string _truncateWarning = "...";
int _maxTruncatedParamLen;
internal EventLogWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config)
{
Debug.Trace("WebEventLogEventProvider", "Initializing: name=" + name);
_maxTruncatedParamLen = EventLogParameterMaxLength - _truncateWarning.Length;
base.Initialize(name, config);
ProviderUtil.CheckUnrecognizedAttributes(config, name);
}
void AddBasicDataFields(ArrayList dataFields, WebBaseEvent eventRaised) {
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
// Data contained in WebBaseEvent
dataFields.Add(eventRaised.EventCode.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(eventRaised.Message);
dataFields.Add(eventRaised.EventTime.ToString());
dataFields.Add(eventRaised.EventTimeUtc.ToString());
dataFields.Add(eventRaised.EventID.ToString("N", CultureInfo.InstalledUICulture));
dataFields.Add(eventRaised.EventSequence.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(eventRaised.EventOccurrence.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(eventRaised.EventDetailCode.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(appInfo.ApplicationDomain);
dataFields.Add(appInfo.TrustLevel);
dataFields.Add(appInfo.ApplicationVirtualPath);
dataFields.Add(appInfo.ApplicationPath);
dataFields.Add(appInfo.MachineName);
if (eventRaised.IsSystemEvent) {
dataFields.Add(null); // custom event details
}
else {
WebEventFormatter formatter = new WebEventFormatter();
eventRaised.FormatCustomEventDetails(formatter);
dataFields.Add(formatter.ToString());
}
}
void AddWebProcessInformationDataFields(ArrayList dataFields, WebProcessInformation processEventInfo) {
dataFields.Add(processEventInfo.ProcessID.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(processEventInfo.ProcessName);
dataFields.Add(processEventInfo.AccountName);
}
void AddWebRequestInformationDataFields(ArrayList dataFields, WebRequestInformation reqInfo) {
string user;
string authType;
bool authed;
IPrincipal iprincipal = reqInfo.Principal;
if (iprincipal == null) {
user = null;
authed = false;
authType = null;
}
else {
IIdentity id = iprincipal.Identity;
user = id.Name;
authed = id.IsAuthenticated;
authType = id.AuthenticationType;
}
dataFields.Add(HttpUtility.UrlDecode(reqInfo.RequestUrl));
dataFields.Add(reqInfo.RequestPath);
dataFields.Add(reqInfo.UserHostAddress);
dataFields.Add(user);
dataFields.Add(authed.ToString());
dataFields.Add(authType);
dataFields.Add(reqInfo.ThreadAccountName);
}
void AddWebProcessStatisticsDataFields(ArrayList dataFields, WebProcessStatistics procStats) {
dataFields.Add(procStats.ProcessStartTime.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.ThreadCount.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.WorkingSet.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.PeakWorkingSet.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.ManagedHeapSize.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.AppDomainCount.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.RequestsExecuting.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.RequestsQueued.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(procStats.RequestsRejected.ToString(CultureInfo.InstalledUICulture));
}
private const int MAX_CHARS_IN_EXCEPTION_MSG = 8000;
void AddExceptionDataFields(ArrayList dataFields, Exception exception) {
if (exception == null) {
dataFields.Add(null);
dataFields.Add(null);
}
else {
dataFields.Add(exception.GetType().Name);
// Get the message and stack with all InnerExceptions
StringBuilder sb = new StringBuilder(1024);
for(int totalLength = 0; totalLength<MAX_CHARS_IN_EXCEPTION_MSG && exception != null; ) {
// Append message
// Dev10 720406: ReportEvent treats %N as an insertion string, so we can't include this in the message.
string msg = ReplaceInsertionStringPlaceholders(exception.Message);
sb.Append(msg); // Always append full message (shouldn't be too big)
totalLength += msg.Length;
int remainingSpace = MAX_CHARS_IN_EXCEPTION_MSG - totalLength;
if (remainingSpace > 0) {
// Append stack if there is space
string stackTrace = exception.StackTrace;
if (!String.IsNullOrEmpty(stackTrace)) {
if (stackTrace.Length > remainingSpace) {
stackTrace = stackTrace.Substring(0, remainingSpace);
}
sb.Append("\n");
sb.Append(stackTrace);
totalLength += stackTrace.Length + 1;
}
sb.Append("\n\n");
totalLength += 2;
}
// deal with next InnerException in next iteration
exception = exception.InnerException;
}
dataFields.Add(sb.ToString());
}
}
void AddWebThreadInformationDataFields(ArrayList dataFields, WebThreadInformation threadInfo) {
dataFields.Add(threadInfo.ThreadID.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(threadInfo.ThreadAccountName);
dataFields.Add(threadInfo.IsImpersonating.ToString(CultureInfo.InstalledUICulture));
dataFields.Add(threadInfo.StackTrace);
}
void AddViewStateExceptionDataFields(ArrayList dataFields, ViewStateException vse) {
dataFields.Add(SR.GetString(vse.ShortMessage));
dataFields.Add(vse.RemoteAddress);
dataFields.Add(vse.RemotePort);
dataFields.Add(vse.UserAgent);
dataFields.Add(vse.PersistedState);
dataFields.Add(vse.Referer);
dataFields.Add(vse.Path);
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
Debug.Trace("EventLogWebEventProvider", "ProcessEvent: event=" + eventRaised.GetType().Name);
int hr;
ArrayList dataFields = new ArrayList(35);
WebEventType eventType = WebBaseEvent.WebEventTypeFromWebEvent(eventRaised);
// !!! IMPORTANT note:
// The order of fields added to dataFields MUST match that of the fields defined in the events
// in msg.mc
AddBasicDataFields(dataFields, eventRaised);
if (eventRaised is WebManagementEvent) {
AddWebProcessInformationDataFields(dataFields, ((WebManagementEvent)eventRaised).ProcessInformation);
}
if (eventRaised is WebHeartbeatEvent) {
AddWebProcessStatisticsDataFields(dataFields, ((WebHeartbeatEvent)eventRaised).ProcessStatistics);
}
if (eventRaised is WebRequestEvent) {
AddWebRequestInformationDataFields(dataFields, ((WebRequestEvent)eventRaised).RequestInformation);
}
if (eventRaised is WebBaseErrorEvent) {
AddExceptionDataFields(dataFields, ((WebBaseErrorEvent)eventRaised).ErrorException);
}
if (eventRaised is WebAuditEvent) {
AddWebRequestInformationDataFields(dataFields, ((WebAuditEvent)eventRaised).RequestInformation);
}
if (eventRaised is WebRequestErrorEvent) {
AddWebRequestInformationDataFields(dataFields, ((WebRequestErrorEvent)eventRaised).RequestInformation);
AddWebThreadInformationDataFields(dataFields, ((WebRequestErrorEvent)eventRaised).ThreadInformation);
}
if (eventRaised is WebErrorEvent) {
AddWebRequestInformationDataFields(dataFields, ((WebErrorEvent)eventRaised).RequestInformation);
AddWebThreadInformationDataFields(dataFields, ((WebErrorEvent)eventRaised).ThreadInformation);
}
if (eventRaised is WebAuthenticationSuccessAuditEvent) {
dataFields.Add(((WebAuthenticationSuccessAuditEvent)eventRaised).NameToAuthenticate);
}
if (eventRaised is WebAuthenticationFailureAuditEvent) {
dataFields.Add(((WebAuthenticationFailureAuditEvent)eventRaised).NameToAuthenticate);
}
if (eventRaised is WebViewStateFailureAuditEvent) {
AddViewStateExceptionDataFields(dataFields, ((WebViewStateFailureAuditEvent)eventRaised).ViewStateException );
}
for (int i = 0; i < dataFields.Count; i++) {
object field = dataFields[i];
if (field == null) {
continue;
}
int len = ((string)field).Length;
if (len > EventLogParameterMaxLength) {
// Truncate it and append a warning message to the end
dataFields[i] = ((string)field).Substring(0, _maxTruncatedParamLen) + _truncateWarning;
}
}
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
hr = UnsafeNativeMethods.RaiseEventlogEvent((int)eventType, (string[])dataFields.ToArray(typeof(string)), dataFields.Count);
if (hr != 0) {
throw new HttpException(SR.GetString(SR.Event_log_provider_error, "0x" + hr.ToString("X8", CultureInfo.InstalledUICulture)));
}
#endif // !FEATURE_PAL
}
public override void Flush() {
}
public override void Shutdown() {
}
// Dev10 720406: ReportEvent treats %N as an insertion string, so we can't include this in the message.
// Instead, we will replace such occurrences with [%]N.
private static string ReplaceInsertionStringPlaceholders(string s) {
if (String.IsNullOrEmpty(s)) {
return s;
}
int len = s.Length;
int maxIndex = len - 1;
int matches = 0;
for (int i = 0; i < maxIndex; i++) {
if (s[i] == '%' && Char.IsDigit(s[i+1])) {
matches++;
}
}
if (matches == 0) {
return s;
}
char[] newChars = new char[len + (2 * matches)];
int idx = 0;
for (int i = 0; i < maxIndex; i++) {
if (s[i] == '%' && Char.IsDigit(s[i+1])) {
newChars[idx++] = '[';
newChars[idx++] = '%';
newChars[idx++] = ']';
}
else {
newChars[idx++] = s[i];
}
}
newChars[newChars.Length-1] = s[maxIndex];
return new String(newChars);
}
}
}

View File

@@ -0,0 +1,13 @@
//------------------------------------------------------------------------------
// <copyright file="IInternalWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
// Used internally to mark our providers
internal interface IInternalWebEventProvider {
}
}

View File

@@ -0,0 +1,58 @@
//------------------------------------------------------------------------------
// <copyright file="IisTraceWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Web.Hosting;
using System.Security.Permissions;
////////////
// Events
////////////
public sealed class IisTraceWebEventProvider : WebEventProvider {
public IisTraceWebEventProvider() {
// only supported on IIS version 7 and later
HttpContext context = HttpContext.Current;
if (context != null) {
if (!HttpRuntime.UseIntegratedPipeline && !(context.WorkerRequest is ISAPIWorkerRequestInProcForIIS7)) {
throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_7));
}
}
}
public override void Initialize(string name, NameValueCollection config)
{
Debug.Trace("IisTraceWebEventProvider", "Initializing: name=" + name);
base.Initialize(name, config);
ProviderUtil.CheckUnrecognizedAttributes(config, name);
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
HttpContext context = HttpContext.Current;
if (context != null) {
context.WorkerRequest.RaiseTraceEvent(eventRaised);
}
}
public override void Flush() {
}
public override void Shutdown() {
}
}
}

View File

@@ -0,0 +1,258 @@
//------------------------------------------------------------------------------
// <copyright file="MailWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Net.Mail;
using System.Globalization;
using System.Web.Configuration;
using System.Text;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
/*
The class MailWebEventProvider is supposed to be used internally. But if I don't mark it public,
I will get this compiler error CS0060 for TemplatedMailWebEventProvider and SimpleMailWebEventProvider
because the two children classes are public and the base class accessibility has to be the same.
The solution here is to introduce an internal constructor so user can't inherit from it.
*/
public abstract class MailWebEventProvider : BufferedWebEventProvider {
internal const int DefaultMaxMessagesPerNotification = 10;
internal const int DefaultMaxEventsPerMessage = 50;
internal const int MessageSequenceBase = 1; // 1-based
string _from;
string _to;
string _cc;
string _bcc;
string _subjectPrefix;
SmtpClient _smtpClient;
int _maxMessagesPerNotification = DefaultMaxMessagesPerNotification;
int _maxEventsPerMessage = DefaultMaxEventsPerMessage;
internal MailWebEventProvider() {}
override public void Initialize(string name, NameValueCollection config)
{
Debug.Trace("MailWebEventProvider", "Initializing: name=" + name);
ProviderUtil.GetAndRemoveRequiredNonEmptyStringAttribute(config, "from", name, ref _from);
// Read "to", "cc" and "bcc"
ProviderUtil.GetAndRemoveStringAttribute(config, "to", name, ref _to);
ProviderUtil.GetAndRemoveStringAttribute(config, "cc", name, ref _cc);
ProviderUtil.GetAndRemoveStringAttribute(config, "bcc", name, ref _bcc);
if (String.IsNullOrEmpty(_to) &&
String.IsNullOrEmpty(_cc) &&
String.IsNullOrEmpty(_bcc) )
{
throw new ConfigurationErrorsException(
SR.GetString(SR.MailWebEventProvider_no_recipient_error, this.GetType().ToString(),
name));
}
ProviderUtil.GetAndRemoveStringAttribute(config, "subjectPrefix", name, ref _subjectPrefix);
ProviderUtil.GetAndRemoveNonZeroPositiveOrInfiniteAttribute(config, "maxMessagesPerNotification", name, ref _maxMessagesPerNotification);
ProviderUtil.GetAndRemoveNonZeroPositiveOrInfiniteAttribute(config, "maxEventsPerMessage", name, ref _maxEventsPerMessage);
_smtpClient = CreateSmtpClientWithAssert();
base.Initialize(name, config);
}
[SmtpPermission(SecurityAction.Assert, Access = "Connect")]
[EnvironmentPermission(SecurityAction.Assert, Read = "USERNAME")]
internal static SmtpClient CreateSmtpClientWithAssert() {
return new SmtpClient();
}
internal string SubjectPrefix {
get { return _subjectPrefix; }
}
internal string GenerateSubject(int notificationSequence, int messageSequence, WebBaseEventCollection events, int count) {
WebBaseEvent eventRaised = events[0];
if (count == 1) {
return HttpUtility.HtmlEncode(SR.GetString(SR.WebEvent_event_email_subject,
new string[] {
notificationSequence.ToString(CultureInfo.InstalledUICulture),
messageSequence.ToString(CultureInfo.InstalledUICulture),
_subjectPrefix,
eventRaised.GetType().ToString(),
WebBaseEvent.ApplicationInformation.ApplicationVirtualPath}
));
}
else {
return HttpUtility.HtmlEncode(SR.GetString(SR.WebEvent_event_group_email_subject,
new string[] {
notificationSequence.ToString(CultureInfo.InstalledUICulture),
messageSequence.ToString(CultureInfo.InstalledUICulture),
_subjectPrefix,
count.ToString(CultureInfo.InstalledUICulture),
WebBaseEvent.ApplicationInformation.ApplicationVirtualPath}
));
}
}
internal MailMessage GetMessage() {
MailMessage msg = new System.Net.Mail.MailMessage(_from, _to);
if (!String.IsNullOrEmpty(_cc)) {
msg.CC.Add(new MailAddress(_cc));
}
if (!String.IsNullOrEmpty(_bcc)) {
msg.Bcc.Add(new MailAddress(_bcc));
}
return msg;
}
[SmtpPermission(SecurityAction.Assert, Access = "Connect")]
internal void SendMail(MailMessage msg) {
try {
Debug.Trace("MailWebEventProvider", "Sending a message: subject=" + msg.Subject);
_smtpClient.Send(msg);
}
catch (Exception e) {
throw new HttpException(
SR.GetString(SR.MailWebEventProvider_cannot_send_mail),
e);
}
}
internal abstract void SendMessage(WebBaseEvent eventRaised);
public override void ProcessEvent(WebBaseEvent eventRaised)
{
Debug.Trace("MailWebEventProvider", "ProcessEvent: type =" + eventRaised.GetType() +
", ID=" + eventRaised.EventID + ", buffer=" + UseBuffering);
if (UseBuffering) {
base.ProcessEvent(eventRaised);
}
else {
SendMessage(eventRaised);
}
}
public override void Shutdown() {
Flush();
}
public override void ProcessEventFlush(WebEventBufferFlushInfo flushInfo) {
int eventsInNotification = flushInfo.Events.Count;
int eventsRemaining = eventsInNotification;
bool split = false;
int messageSequence = MessageSequenceBase;
int messagesInNotification;
int eventsToBeDiscarded = 0;
bool fatalError = false;
if (eventsInNotification == 0) {
return;
}
WebBaseEventCollection eventsToSend;
WebBaseEvent[] eventsChunk = null;
// We will split based on MaxEventsPerMessage
if (eventsInNotification > MaxEventsPerMessage) {
split = true;
// I use the below clumsy calculation instead of (a+b-1)/b is to avoid
// Int32 overflow.
messagesInNotification = eventsInNotification/MaxEventsPerMessage;
if (eventsInNotification > messagesInNotification*MaxEventsPerMessage) {
messagesInNotification++;
}
// We will exceed the limit.
if (messagesInNotification > MaxMessagesPerNotification) {
eventsToBeDiscarded = eventsInNotification - MaxMessagesPerNotification * MaxEventsPerMessage;
messagesInNotification = MaxMessagesPerNotification;
eventsInNotification -= eventsToBeDiscarded;
}
}
else {
messagesInNotification = 1;
}
// In each email we only send a max of MaxEventsPerMessage events
for(int eventsSent = 0;
eventsSent < eventsInNotification;
messageSequence++) {
if (split) {
int chunkSize = Math.Min(MaxEventsPerMessage, eventsInNotification - eventsSent);
if (eventsChunk == null || eventsChunk.Length != chunkSize) {
eventsChunk = new WebBaseEvent[chunkSize];
}
for(int i = 0; i < chunkSize; i++) {
eventsChunk[i] = flushInfo.Events[i + eventsSent];
}
eventsToSend = new WebBaseEventCollection(eventsChunk);
}
else {
eventsToSend = flushInfo.Events;
}
Debug.Trace("MailWebEventProvider", "Calling SendMessageInternal; # of events: " + eventsToSend.Count);
SendMessage(
eventsToSend,
flushInfo,
eventsInNotification,
eventsInNotification - (eventsSent + eventsToSend.Count), // eventsRemaining
messagesInNotification,
eventsToBeDiscarded,
messageSequence,
eventsSent,
out fatalError);
if (fatalError) {
Debug.Trace("MailWebEventProvider", "Stop sending because we hit a fatal error");
break;
}
eventsSent += eventsToSend.Count;
}
}
internal abstract void SendMessage(WebBaseEventCollection events,
WebEventBufferFlushInfo flushInfo,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence,
int eventsSent,
out bool fatalError);
internal int MaxMessagesPerNotification {
get { return _maxMessagesPerNotification; }
}
internal int MaxEventsPerMessage {
get { return _maxEventsPerMessage; }
}
}
}

View File

@@ -0,0 +1,268 @@
//------------------------------------------------------------------------------
// <copyright file="SimpleMailWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Net.Mail;
using System.Globalization;
using System.Web.Configuration;
using System.Text;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
using System.Threading;
public sealed class SimpleMailWebEventProvider : MailWebEventProvider, IInternalWebEventProvider {
const int DefaultMaxEventLength = 8 * 1024;
const int MessageIdDiscard = 100;
const int MessageIdEventsToDrop = 101;
static string s_header_warnings = SR.GetString(SR.MailWebEventProvider_Warnings);
static string s_header_summary = SR.GetString(SR.MailWebEventProvider_Summary);
static string s_header_app_info = SR.GetString(SR.MailWebEventProvider_Application_Info);
static string s_header_events = SR.GetString(SR.MailWebEventProvider_Events);
string _separator = "---------------\n";
string _bodyHeader;
string _bodyFooter;
int _maxEventLength = DefaultMaxEventLength; // in no of chars
int _nonBufferNotificationSequence = 0;
internal SimpleMailWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config)
{
string temp = null;
Debug.Trace("SimpleMailWebEventProvider", "Initializing: name=" + name);
ProviderUtil.GetAndRemoveStringAttribute(config, "bodyHeader", name, ref _bodyHeader);
if (_bodyHeader != null) {
_bodyHeader += "\n";
}
ProviderUtil.GetAndRemoveStringAttribute(config, "bodyFooter", name, ref _bodyFooter);
if (_bodyFooter != null) {
_bodyFooter += "\n";
}
ProviderUtil.GetAndRemoveStringAttribute(config, "separator", name, ref temp);
if (temp != null) {
_separator = temp + "\n";
}
ProviderUtil.GetAndRemovePositiveOrInfiniteAttribute(config, "maxEventLength", name, ref _maxEventLength);
base.Initialize(name, config);
}
void GenerateWarnings(StringBuilder sb, DateTime lastFlush, int discardedSinceLastFlush,
int seq, int eventsToDrop) {
if (!UseBuffering) {
return;
}
bool headerAdded = false;
bool hasWarnings = false;
// This warning is issued only in the 1st message (vswhidbey 217578)
if (discardedSinceLastFlush != 0 && seq == MessageSequenceBase) {
sb.Append(s_header_warnings);
sb.Append("\n");
sb.Append(_separator);
headerAdded = true;
sb.Append(SR.GetString(SR.MailWebEventProvider_discard_warning,
MessageIdDiscard.ToString(CultureInfo.InstalledUICulture),
discardedSinceLastFlush.ToString(CultureInfo.InstalledUICulture),
lastFlush.ToString("r", CultureInfo.InstalledUICulture)));
sb.Append("\n\n");
hasWarnings = true;
}
if (eventsToDrop > 0) {
if (!headerAdded) {
sb.Append(s_header_warnings);
sb.Append("\n");
sb.Append(_separator);
headerAdded = true;
}
sb.Append(SR.GetString(SR.MailWebEventProvider_events_drop_warning,
MessageIdEventsToDrop.ToString(CultureInfo.InstalledUICulture),
eventsToDrop.ToString(CultureInfo.InstalledUICulture)));
sb.Append("\n\n");
hasWarnings = true;
}
if (hasWarnings) {
sb.Append("\n");
}
}
void GenerateApplicationInformation(StringBuilder sb) {
sb.Append(s_header_app_info);
sb.Append("\n");
sb.Append(_separator);
sb.Append(WebBaseEvent.ApplicationInformation.ToString());
sb.Append("\n\n");
}
void GenerateSummary(StringBuilder sb, int firstEvent, int lastEvent, int eventsInNotif, int eventsInBuffer) {
if (!UseBuffering) {
return;
}
sb.Append(s_header_summary);
sb.Append("\n");
sb.Append(_separator);
// The sequence numbers will be displayed as one-baesd.
firstEvent++;
lastEvent++;
sb.Append(SR.GetString(SR.MailWebEventProvider_summary_body,
firstEvent.ToString(CultureInfo.InstalledUICulture),
lastEvent.ToString(CultureInfo.InstalledUICulture),
eventsInNotif.ToString(CultureInfo.InstalledUICulture),
eventsInBuffer.ToString(CultureInfo.InstalledUICulture)));
sb.Append("\n\n");
sb.Append("\n");
}
string GenerateBody(WebBaseEventCollection events,
int begin,
DateTime lastFlush,
int discardedSinceLastFlush,
int eventsInBuffer,
int messageSequence,
int eventsInNotification,
int eventsLostDueToMessageLimit) {
StringBuilder sb = new StringBuilder();
int totalEvents = events.Count;
if (_bodyHeader != null) {
sb.Append(_bodyHeader);
}
// Warnings
GenerateWarnings(sb, lastFlush, discardedSinceLastFlush, messageSequence, eventsLostDueToMessageLimit);
// Event Summary
GenerateSummary(sb, begin, begin + totalEvents - 1, eventsInNotification, eventsInBuffer);
// Application Info
Debug.Assert(events.Count > 0, "events.Count > 0");
GenerateApplicationInformation(sb);
// Please note that it's a text message, and thus we shouldn't need to HtmlEncode it.
for (int i = 0; i < totalEvents; i++) {
WebBaseEvent eventRaised = events[i];
string details = eventRaised.ToString(false, true);
if (_maxEventLength != ProviderUtil.Infinite &&
details.Length > _maxEventLength) {
details = details.Substring(0, _maxEventLength);
}
if (i == 0) {
sb.Append(s_header_events);
sb.Append("\n");
sb.Append(_separator);
}
sb.Append(details);
sb.Append("\n");
sb.Append(_separator);
}
if (_bodyFooter != null) {
sb.Append(_bodyFooter);
}
return sb.ToString();
}
internal override void SendMessage(WebBaseEvent eventRaised) {
WebBaseEventCollection events = new WebBaseEventCollection(eventRaised);
SendMessageInternal(
events, // events
Interlocked.Increment(ref _nonBufferNotificationSequence), // notificationSequence
0, // begin
DateTime.MinValue, // lastFlush
0, // discardedSinceLastFlush
0, // eventsInBuffer
MessageSequenceBase,// messageSequence
1, // messagesInNotification
1, // eventsInNotification
0); // eventsLostDueToMessageLimit
}
internal override void SendMessage(WebBaseEventCollection events,
WebEventBufferFlushInfo flushInfo,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence,
int eventsSent,
out bool fatalError) {
SendMessageInternal(events,
flushInfo.NotificationSequence,
eventsSent,
flushInfo.LastNotificationUtc,
flushInfo.EventsDiscardedSinceLastNotification,
flushInfo.EventsInBuffer,
messageSequence,
messagesInNotification,
eventsInNotification,
eventsLostDueToMessageLimit);
fatalError = false;
}
void SendMessageInternal(WebBaseEventCollection events,
int notificationSequence,
int begin,
DateTime lastFlush,
int discardedSinceLastFlush,
int eventsInBuffer,
int messageSequence,
int messagesInNotification,
int eventsInNotification,
int eventsLostDueToMessageLimit) {
using (MailMessage msg = GetMessage()) {
// Don't report eventsLostDueToMessageLimit unless it's the last message in this notification
if (messageSequence != messagesInNotification) {
eventsLostDueToMessageLimit = 0;
}
msg.Body = GenerateBody(events,
begin,
lastFlush,
discardedSinceLastFlush,
eventsInBuffer,
messageSequence,
eventsInNotification,
eventsLostDueToMessageLimit);
msg.Subject = GenerateSubject(notificationSequence, messageSequence, events, events.Count);
SendMail(msg);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,290 @@
//------------------------------------------------------------------------------
// <copyright file="events.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.DataAccess;
using System.Web.Util;
////////////
// Events
////////////
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
public class SqlWebEventProvider : BufferedWebEventProvider, IInternalWebEventProvider {
const int SQL_MAX_NTEXT_SIZE = 1073741823;
const int NO_LIMIT = -1;
const string SP_LOG_EVENT = "dbo.aspnet_WebEvent_LogEvent";
string _sqlConnectionString;
int _maxEventDetailsLength = NO_LIMIT;
int _commandTimeout = -1;
int _SchemaVersionCheck;
int _connectionCount = 0;
DateTime _retryDate = DateTime.MinValue; // Won't try sending unless DateTime.UtcNow is > _retryDate
protected internal SqlWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config) {
Debug.Trace("SqlWebEventProvider", "Initializing: name=" + name);
_SchemaVersionCheck = 0;
string temp = null;
ProviderUtil.GetAndRemoveStringAttribute(config, "connectionStringName", name, ref temp);
ProviderUtil.GetAndRemoveStringAttribute(config, "connectionString", name, ref _sqlConnectionString);
if (!String.IsNullOrEmpty(temp)) {
if (!String.IsNullOrEmpty(_sqlConnectionString)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Only_one_connection_string_allowed));
}
_sqlConnectionString = SqlConnectionHelper.GetConnectionString(temp, true, true);
if (_sqlConnectionString == null || _sqlConnectionString.Length < 1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Connection_string_not_found, temp));
}
}
else {
// If a connection string is specified explicitly, verify that its not using integrated security
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_sqlConnectionString);
if (builder.IntegratedSecurity) {
throw new ConfigurationErrorsException(SR.GetString(SR.Cannot_use_integrated_security));
}
}
if (String.IsNullOrEmpty(_sqlConnectionString)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Must_specify_connection_string_or_name, temp));
}
ProviderUtil.GetAndRemovePositiveOrInfiniteAttribute(config, "maxEventDetailsLength", name, ref _maxEventDetailsLength);
if (_maxEventDetailsLength == ProviderUtil.Infinite) {
_maxEventDetailsLength = NO_LIMIT;
}
else if (_maxEventDetailsLength > SQL_MAX_NTEXT_SIZE) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_max_event_details_length, name, _maxEventDetailsLength.ToString(CultureInfo.CurrentCulture)));
}
ProviderUtil.GetAndRemovePositiveAttribute(config, "commandTimeout", name, ref _commandTimeout);
base.Initialize(name, config);
}
private void CheckSchemaVersion(SqlConnection connection) {
string[] features = { "Health Monitoring" };
string version = "1";
SecUtility.CheckSchemaVersion( this, connection, features, version, ref _SchemaVersionCheck );
}
public override void ProcessEventFlush(WebEventBufferFlushInfo flushInfo) {
Debug.Trace("SqlWebEventProvider", "EventBufferFlush called: " +
"NotificationType=" + flushInfo.NotificationType +
", NotificationSequence=" + flushInfo.NotificationSequence +
", Events.Count=" + flushInfo.Events.Count);
WriteToSQL(flushInfo.Events, flushInfo.EventsDiscardedSinceLastNotification,
flushInfo.LastNotificationUtc);
}
void PrepareParams(SqlCommand sqlCommand) {
sqlCommand.Parameters.Add(new SqlParameter("@EventId", SqlDbType.Char, 32));
sqlCommand.Parameters.Add(new SqlParameter("@EventTimeUtc", SqlDbType.DateTime));
sqlCommand.Parameters.Add(new SqlParameter("@EventTime", SqlDbType.DateTime));
sqlCommand.Parameters.Add(new SqlParameter("@EventType", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@EventSequence", SqlDbType.Decimal));
sqlCommand.Parameters.Add(new SqlParameter("@EventOccurrence", SqlDbType.Decimal));
sqlCommand.Parameters.Add(new SqlParameter("@EventCode", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@EventDetailCode", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, 1024));
sqlCommand.Parameters.Add(new SqlParameter("@ApplicationPath", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@ApplicationVirtualPath", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@MachineName", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@RequestUrl", SqlDbType.NVarChar, 1024));
sqlCommand.Parameters.Add(new SqlParameter("@ExceptionType", SqlDbType.NVarChar, 256));
sqlCommand.Parameters.Add(new SqlParameter("@Details", SqlDbType.NText));
}
void FillParams(SqlCommand sqlCommand, WebBaseEvent eventRaised) {
Exception exception = null;
WebRequestInformation reqInfo = null;
string details = null;
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
int n = 0;
sqlCommand.Parameters[n++].Value = eventRaised.EventID.ToString("N", CultureInfo.InstalledUICulture); // @EventId
sqlCommand.Parameters[n++].Value = eventRaised.EventTimeUtc; // @EventTimeUtc
sqlCommand.Parameters[n++].Value = eventRaised.EventTime; // @EventTime
sqlCommand.Parameters[n++].Value = eventRaised.GetType().ToString(); // @EventType
sqlCommand.Parameters[n++].Value = eventRaised.EventSequence; // @EventSequence
sqlCommand.Parameters[n++].Value = eventRaised.EventOccurrence; // @EventOccurrence
sqlCommand.Parameters[n++].Value = eventRaised.EventCode; // @EventCode
sqlCommand.Parameters[n++].Value = eventRaised.EventDetailCode; // @EventDetailCode
sqlCommand.Parameters[n++].Value = eventRaised.Message; // @Message
sqlCommand.Parameters[n++].Value = appInfo.ApplicationPath; // @ApplicationPath
sqlCommand.Parameters[n++].Value = appInfo.ApplicationVirtualPath; // @ApplicationVirtualPath
sqlCommand.Parameters[n++].Value = appInfo.MachineName; // @MachineName
//
// @RequestUrl
if (eventRaised is WebRequestEvent) {
reqInfo = ((WebRequestEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebRequestErrorEvent) {
reqInfo = ((WebRequestErrorEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebErrorEvent) {
reqInfo = ((WebErrorEvent)eventRaised).RequestInformation;
}
else if (eventRaised is WebAuditEvent) {
reqInfo = ((WebAuditEvent)eventRaised).RequestInformation;
}
sqlCommand.Parameters[n++].Value = (reqInfo != null) ? reqInfo.RequestUrl : Convert.DBNull;
// @ExceptionType
if (eventRaised is WebBaseErrorEvent) {
exception = ((WebBaseErrorEvent)eventRaised).ErrorException;
}
sqlCommand.Parameters[n++].Value = (exception != null) ? exception.GetType().ToString() : Convert.DBNull;
// @Details
details = eventRaised.ToString();
if (_maxEventDetailsLength != NO_LIMIT &&
details.Length > _maxEventDetailsLength) {
details = details.Substring(0, _maxEventDetailsLength);
}
sqlCommand.Parameters[n++].Value = details;
}
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
[SqlClientPermission(SecurityAction.Assert, Unrestricted = true)]
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
void WriteToSQL(WebBaseEventCollection events, int eventsDiscardedByBuffer, DateTime lastNotificationUtc) {
// We don't want to send any more events until we've waited until the _retryDate (which defaults to minValue)
if (_retryDate > DateTime.UtcNow) {
return;
}
try {
SqlConnectionHolder sqlConnHolder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
SqlCommand sqlCommand = new SqlCommand(SP_LOG_EVENT);
CheckSchemaVersion(sqlConnHolder.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlConnHolder.Connection;
if (_commandTimeout > -1) {
sqlCommand.CommandTimeout = _commandTimeout;
}
PrepareParams(sqlCommand);
try {
sqlConnHolder.Open(null, true);
Interlocked.Increment(ref _connectionCount);
if (eventsDiscardedByBuffer != 0) {
WebBaseEvent infoEvent = new WebBaseEvent(
SR.GetString(SR.Sql_webevent_provider_events_dropped,
eventsDiscardedByBuffer.ToString(CultureInfo.InstalledUICulture),
lastNotificationUtc.ToString("r", CultureInfo.InstalledUICulture)),
null,
WebEventCodes.WebEventProviderInformation,
WebEventCodes.SqlProviderEventsDropped);
FillParams(sqlCommand, infoEvent);
sqlCommand.ExecuteNonQuery();
}
foreach (WebBaseEvent eventRaised in events) {
FillParams(sqlCommand, eventRaised);
sqlCommand.ExecuteNonQuery();
}
}
#if DBG
catch (Exception e) {
Debug.Trace("SqlWebEventProvider", "ExecuteNonQuery failed: " + e);
throw;
}
#endif
finally {
sqlConnHolder.Close();
Interlocked.Decrement(ref _connectionCount);
}
#if (!DBG)
try {
#endif
EventProcessingComplete(events);
#if (!DBG)
}
catch {
// Ignore all errors.
}
#endif
}
catch {
// For any failure, we will wait at least 30 seconds or _commandTimeout before trying again
double timeout = 30;
if (_commandTimeout > -1) {
timeout = (double)_commandTimeout;
}
_retryDate = DateTime.UtcNow.AddSeconds(timeout);
throw;
}
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
if (UseBuffering) {
base.ProcessEvent(eventRaised);
}
else {
Debug.Trace("SqlWebEventProvider", "Writing event to SQL: event=" + eventRaised.GetType().Name);
WriteToSQL(new WebBaseEventCollection(eventRaised), 0, new DateTime(0));
}
}
protected virtual void EventProcessingComplete(WebBaseEventCollection raisedEvents) {
}
public override void Shutdown() {
try {
Flush();
}
finally {
base.Shutdown();
}
// VSWhidbey 531556: Need to wait until all connections are gone before returning here
// Sleep for 2x the command timeout in 1 sec intervals then give up, default timeout is 30 sec
if (_connectionCount > 0) {
int sleepAttempts = _commandTimeout*2;
if (sleepAttempts <= 0) {
sleepAttempts = 60;
}
// Check every second
while (_connectionCount > 0 && sleepAttempts > 0) {
--sleepAttempts;
Thread.Sleep(1000);
}
}
}
}
}

View File

@@ -0,0 +1,474 @@
//------------------------------------------------------------------------------
// <copyright file="TemplatedMailWebEventProvider .cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Net.Mail;
using System.Globalization;
using System.Web.Configuration;
using System.Text;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
using System.Threading;
public sealed class TemplatedMailWebEventProvider : MailWebEventProvider, IInternalWebEventProvider {
int _nonBufferNotificationSequence = 0;
string _templateUrl;
bool _detailedTemplateErrors = false;
class TemplatedMailErrorFormatterGenerator : ErrorFormatterGenerator {
int _eventsRemaining;
bool _showDetails;
bool _errorFormatterCalled;
internal TemplatedMailErrorFormatterGenerator(int eventsRemaining, bool showDetails) {
_eventsRemaining = eventsRemaining;
_showDetails = showDetails;
}
internal bool ErrorFormatterCalled {
get { return _errorFormatterCalled; }
}
internal override ErrorFormatter GetErrorFormatter(Exception e) {
Exception inner = e.InnerException;
_errorFormatterCalled = true;
while (inner != null) {
if (inner is HttpCompileException) {
return new TemplatedMailCompileErrorFormatter((HttpCompileException)inner, _eventsRemaining, _showDetails);
}
else {
inner = inner.InnerException;
}
}
return new TemplatedMailRuntimeErrorFormatter(e, _eventsRemaining, _showDetails);
}
}
internal TemplatedMailWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config)
{
Debug.Trace("TemplatedMailWebEventProvider", "Initializing: name=" + name);
ProviderUtil.GetAndRemoveStringAttribute(config, "template", name, ref _templateUrl);
if (_templateUrl == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Provider_missing_attribute, "template", name));
}
_templateUrl = _templateUrl.Trim();
if (_templateUrl.Length == 0) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_provider_attribute, "template", name, _templateUrl));
}
if (!UrlPath.IsRelativeUrl(_templateUrl)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_mail_template_provider_attribute,
"template", name, _templateUrl));
}
_templateUrl = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, _templateUrl);
// VSWhidbey 440081: Guard against templates outside the AppDomain path
if (!HttpRuntime.IsPathWithinAppRoot(_templateUrl)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_mail_template_provider_attribute,
"template", name, _templateUrl));
}
ProviderUtil.GetAndRemoveBooleanAttribute(config, "detailedTemplateErrors", name, ref _detailedTemplateErrors);
base.Initialize(name, config);
}
void GenerateMessageBody(
MailMessage msg,
WebBaseEventCollection events,
DateTime lastNotificationUtc,
int discardedSinceLastNotification,
int eventsInBuffer,
int notificationSequence,
EventNotificationType notificationType,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence,
out bool fatalError) {
StringWriter writer = new StringWriter(CultureInfo.InstalledUICulture);
MailEventNotificationInfo info = new MailEventNotificationInfo(
msg,
events,
lastNotificationUtc,
discardedSinceLastNotification,
eventsInBuffer,
notificationSequence,
notificationType,
eventsInNotification,
eventsRemaining,
messagesInNotification,
eventsLostDueToMessageLimit,
messageSequence);
CallContext.SetData(CurrentEventsName, info);
try {
TemplatedMailErrorFormatterGenerator gen = new TemplatedMailErrorFormatterGenerator(events.Count + eventsRemaining, _detailedTemplateErrors);
HttpServerUtility.ExecuteLocalRequestAndCaptureResponse(_templateUrl, writer, gen);
fatalError = gen.ErrorFormatterCalled;
if (fatalError) {
msg.Subject = HttpUtility.HtmlEncode(SR.GetString(SR.WebEvent_event_email_subject_template_error,
notificationSequence.ToString(CultureInfo.InstalledUICulture),
messageSequence.ToString(CultureInfo.InstalledUICulture),
SubjectPrefix));
}
msg.Body = writer.ToString();
msg.IsBodyHtml = true;
}
finally {
CallContext.FreeNamedDataSlot(CurrentEventsName);
}
}
internal override void SendMessage(WebBaseEvent eventRaised) {
WebBaseEventCollection events = new WebBaseEventCollection(eventRaised);
bool templateError;
SendMessageInternal(events, // events
DateTime.MinValue, // lastNotificationUtc
0, // discardedSinceLastNotification
0, // eventsInBuffer
Interlocked.Increment(ref _nonBufferNotificationSequence), // notificationSequence
EventNotificationType.Unbuffered, // notificationType
1, // eventsInNotification
0, // eventsRemaining
1, // messagesInNotification
0, // eventsLostDueToMessageLimit
MessageSequenceBase, // messageSequence
out templateError); // templateError
}
internal override void SendMessage(WebBaseEventCollection events,
WebEventBufferFlushInfo flushInfo,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence,
int eventsSent,
out bool fatalError) {
SendMessageInternal(events,
flushInfo.LastNotificationUtc,
flushInfo.EventsDiscardedSinceLastNotification,
flushInfo.EventsInBuffer,
flushInfo.NotificationSequence,
flushInfo.NotificationType,
eventsInNotification,
eventsRemaining,
messagesInNotification,
eventsLostDueToMessageLimit,
messageSequence,
out fatalError);
}
void SendMessageInternal(WebBaseEventCollection events,
DateTime lastNotificationUtc,
int discardedSinceLastNotification,
int eventsInBuffer,
int notificationSequence,
EventNotificationType notificationType,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence,
out bool fatalError) {
using (MailMessage msg = GetMessage()) {
msg.Subject = GenerateSubject(notificationSequence, messageSequence, events, events.Count);
GenerateMessageBody(
msg,
events,
lastNotificationUtc,
discardedSinceLastNotification,
eventsInBuffer,
notificationSequence,
notificationType,
eventsInNotification,
eventsRemaining,
messagesInNotification,
eventsLostDueToMessageLimit,
messageSequence,
out fatalError);
SendMail(msg);
}
}
internal const string CurrentEventsName = "_TWCurEvt";
public static MailEventNotificationInfo CurrentNotification {
get {
return (MailEventNotificationInfo)CallContext.GetData(CurrentEventsName);
}
}
}
public sealed class MailEventNotificationInfo {
WebBaseEventCollection _events;
DateTime _lastNotificationUtc;
int _discardedSinceLastNotification;
int _eventsInBuffer;
int _notificationSequence;
EventNotificationType _notificationType;
int _eventsInNotification;
int _eventsRemaining;
int _messagesInNotification;
int _eventsLostDueToMessageLimit;
int _messageSequence;
MailMessage _msg;
internal MailEventNotificationInfo(
MailMessage msg,
WebBaseEventCollection events,
DateTime lastNotificationUtc,
int discardedSinceLastNotification,
int eventsInBuffer,
int notificationSequence,
EventNotificationType notificationType,
int eventsInNotification,
int eventsRemaining,
int messagesInNotification,
int eventsLostDueToMessageLimit,
int messageSequence) {
_events = events;
_lastNotificationUtc = lastNotificationUtc;
_discardedSinceLastNotification = discardedSinceLastNotification;
_eventsInBuffer = eventsInBuffer;
_notificationSequence = notificationSequence;
_notificationType = notificationType;
_eventsInNotification = eventsInNotification;
_eventsRemaining = eventsRemaining ;
_messagesInNotification = messagesInNotification;
_eventsLostDueToMessageLimit = eventsLostDueToMessageLimit;
_messageSequence = messageSequence;
_msg = msg;
}
public WebBaseEventCollection Events {
get { return _events; }
}
public EventNotificationType NotificationType {
get { return _notificationType; }
}
public int EventsInNotification {
get { return _eventsInNotification; }
}
public int EventsRemaining {
get { return _eventsRemaining; }
}
public int MessagesInNotification {
get { return _messagesInNotification; }
}
public int EventsInBuffer {
get { return _eventsInBuffer; }
}
public int EventsDiscardedByBuffer {
get { return _discardedSinceLastNotification; }
}
public int EventsDiscardedDueToMessageLimit {
get { return _eventsLostDueToMessageLimit; }
}
public int NotificationSequence {
get { return _notificationSequence; }
}
public int MessageSequence {
get { return _messageSequence; }
}
public DateTime LastNotificationUtc {
get { return _lastNotificationUtc; }
}
public MailMessage Message {
get { return _msg; }
}
}
internal class TemplatedMailCompileErrorFormatter : DynamicCompileErrorFormatter {
int _eventsRemaining;
bool _showDetails;
internal TemplatedMailCompileErrorFormatter(HttpCompileException e, int eventsRemaining,
bool showDetails) :
base(e) {
_eventsRemaining = eventsRemaining;
_showDetails = showDetails;
_hideDetailedCompilerOutput = true;
_dontShowVersion = true;
}
protected override string ErrorTitle {
get {
return SR.GetString(SR.MailWebEventProvider_template_compile_error,
_eventsRemaining.ToString(CultureInfo.InstalledUICulture));
}
}
protected override string Description {
get {
if (_showDetails) {
return base.Description;
}
else {
return SR.GetString(SR.MailWebEventProvider_template_error_no_details);
}
}
}
protected override string MiscSectionTitle {
get {
if (_showDetails) {
return base.MiscSectionTitle;
}
else {
return null;
}
}
}
protected override string MiscSectionContent {
get {
if (_showDetails) {
return base.MiscSectionContent;
}
else {
return null;
}
}
}
}
internal class TemplatedMailRuntimeErrorFormatter : UnhandledErrorFormatter {
int _eventsRemaining;
bool _showDetails;
internal TemplatedMailRuntimeErrorFormatter(Exception e, int eventsRemaining,
bool showDetails) :
base(e) {
_eventsRemaining = eventsRemaining;
_showDetails = showDetails;
_dontShowVersion = true;
}
protected override string ErrorTitle {
get {
if (HttpException.GetHttpCodeForException(Exception) == 404) {
return SR.GetString(SR.MailWebEventProvider_template_file_not_found_error,
_eventsRemaining.ToString(CultureInfo.InstalledUICulture));
}
else {
return SR.GetString(SR.MailWebEventProvider_template_runtime_error,
_eventsRemaining.ToString(CultureInfo.InstalledUICulture));
}
}
}
protected override string ColoredSquareTitle {
get { return null;}
}
protected override string ColoredSquareContent {
get { return null; }
}
protected override string Description {
get {
if (_showDetails) {
return base.Description;
}
else {
return SR.GetString(SR.MailWebEventProvider_template_error_no_details);
}
}
}
protected override string MiscSectionTitle {
get {
if (_showDetails) {
return base.MiscSectionTitle;
}
else {
return null;
}
}
}
protected override string MiscSectionContent {
get {
if (_showDetails) {
return base.MiscSectionContent;
}
else {
return null;
}
}
}
protected override string ColoredSquare2Title {
get {
if (_showDetails) {
return base.ColoredSquare2Title;
}
else {
return null;
}
}
}
protected override string ColoredSquare2Content {
get {
if (_showDetails) {
return base.ColoredSquare2Content;
}
else {
return null;
}
}
}
}
}

View File

@@ -0,0 +1,436 @@
//------------------------------------------------------------------------------
// <copyright file="WebEventCodes.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Globalization;
using System.Collections;
using Debug=System.Web.Util.Debug;
using System.Security.Permissions;
// this class is a container for pre-defined event codes
// all APIs will take integers so application defined
// codes or new codes added through servicing are supported
public sealed class WebEventCodes {
private WebEventCodes() {
}
static WebEventCodes()
{
InitEventArrayDimensions();
}
// (not bit flags)
// we're not using an enum for extensibility reasons
public const int InvalidEventCode = -1;
public const int UndefinedEventCode = 0;
public const int UndefinedEventDetailCode = 0;
// ----------------------------------
// Application Codes
// ----------------------------------
public const int ApplicationCodeBase = 1000;
public const int ApplicationStart = ApplicationCodeBase + 1;
public const int ApplicationShutdown = ApplicationCodeBase + 2;
public const int ApplicationCompilationStart = ApplicationCodeBase + 3;
public const int ApplicationCompilationEnd = ApplicationCodeBase + 4;
public const int ApplicationHeartbeat = ApplicationCodeBase + 5;
internal const int ApplicationCodeBaseLast = ApplicationCodeBase + 5;
// ----------------------------------
// Request Codes
// ----------------------------------
public const int RequestCodeBase = 2000;
public const int RequestTransactionComplete = RequestCodeBase+1;
public const int RequestTransactionAbort = RequestCodeBase+2;
internal const int RequestCodeBaseLast = RequestCodeBase+2;
// ----------------------------------
// Error Codes
// ----------------------------------
public const int ErrorCodeBase = 3000;
// Errors during request processing related to client input
// or behavior
public const int RuntimeErrorRequestAbort = ErrorCodeBase + 1;
public const int RuntimeErrorViewStateFailure = ErrorCodeBase + 2;
public const int RuntimeErrorValidationFailure = ErrorCodeBase + 3;
public const int RuntimeErrorPostTooLarge = ErrorCodeBase + 4;
public const int RuntimeErrorUnhandledException = ErrorCodeBase + 5;
// Errors related to configuration or invalid code
public const int WebErrorParserError = ErrorCodeBase + 6;
public const int WebErrorCompilationError = ErrorCodeBase + 7;
public const int WebErrorConfigurationError = ErrorCodeBase + 8;
public const int WebErrorOtherError = ErrorCodeBase + 9;
public const int WebErrorPropertyDeserializationError = ErrorCodeBase + 10;
public const int WebErrorObjectStateFormatterDeserializationError = ErrorCodeBase + 11;
public const int RuntimeErrorWebResourceFailure = ErrorCodeBase + 12;
internal const int ErrorCodeBaseLast = ErrorCodeBase + 12;
// ----------------------------------
// Audit codes
// ----------------------------------
public const int AuditCodeBase = 4000;
// success codes
public const int AuditFormsAuthenticationSuccess = AuditCodeBase + 1;
public const int AuditMembershipAuthenticationSuccess = AuditCodeBase + 2;
public const int AuditUrlAuthorizationSuccess = AuditCodeBase + 3;
public const int AuditFileAuthorizationSuccess = AuditCodeBase + 4;
// failure codes
public const int AuditFormsAuthenticationFailure = AuditCodeBase +5;
public const int AuditMembershipAuthenticationFailure = AuditCodeBase + 6;
public const int AuditUrlAuthorizationFailure = AuditCodeBase + 7;
public const int AuditFileAuthorizationFailure = AuditCodeBase + 8;
public const int AuditInvalidViewStateFailure = AuditCodeBase + 9;
public const int AuditUnhandledSecurityException = AuditCodeBase + 10;
public const int AuditUnhandledAccessException = AuditCodeBase + 11;
internal const int AuditCodeBaseLast = AuditCodeBase + 11;
// Misc events
public const int MiscCodeBase = 6000;
public const int WebEventProviderInformation = MiscCodeBase + 1;
internal const int MiscCodeBaseLast = MiscCodeBase + 1;
// Last code base
internal const int LastCodeBase = 6000;
/////////////////////////////////////////////////////
// Detail Codes
/////////////////////////////////////////////////////
public const int ApplicationDetailCodeBase = 50000;
public const int ApplicationShutdownUnknown = ApplicationDetailCodeBase + 1;
public const int ApplicationShutdownHostingEnvironment = ApplicationDetailCodeBase + 2;
public const int ApplicationShutdownChangeInGlobalAsax = ApplicationDetailCodeBase + 3;
public const int ApplicationShutdownConfigurationChange = ApplicationDetailCodeBase + 4;
public const int ApplicationShutdownUnloadAppDomainCalled = ApplicationDetailCodeBase + 5;
public const int ApplicationShutdownChangeInSecurityPolicyFile = ApplicationDetailCodeBase + 6;
public const int ApplicationShutdownBinDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 7;
public const int ApplicationShutdownBrowsersDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 8;
public const int ApplicationShutdownCodeDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 9;
public const int ApplicationShutdownResourcesDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 10;
public const int ApplicationShutdownIdleTimeout = ApplicationDetailCodeBase + 11;
public const int ApplicationShutdownPhysicalApplicationPathChanged = ApplicationDetailCodeBase + 12;
public const int ApplicationShutdownHttpRuntimeClose = ApplicationDetailCodeBase + 13;
public const int ApplicationShutdownInitializationError = ApplicationDetailCodeBase + 14;
public const int ApplicationShutdownMaxRecompilationsReached = ApplicationDetailCodeBase + 15;
public const int StateServerConnectionError = ApplicationDetailCodeBase + 16;
public const int ApplicationShutdownBuildManagerChange = ApplicationDetailCodeBase + 17;
// Audit detail codes
public const int AuditDetailCodeBase = 50200;
public const int InvalidTicketFailure = AuditDetailCodeBase + 1;
public const int ExpiredTicketFailure = AuditDetailCodeBase + 2;
public const int InvalidViewStateMac = AuditDetailCodeBase + 3;
public const int InvalidViewState = AuditDetailCodeBase + 4;
// Web Event provider detail codes
public const int WebEventDetailCodeBase = 50300;
public const int SqlProviderEventsDropped = WebEventDetailCodeBase + 1;
// Application extensions should start from here
public const int WebExtendedBase = 100000;
internal static string MessageFromEventCode(int eventCode, int eventDetailCode) {
string msg = null;
string detailMsg = null;
if (eventDetailCode != 0) {
switch(eventDetailCode) {
case ApplicationShutdownUnknown:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownUnknown);
break;
case ApplicationShutdownHostingEnvironment:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownHostingEnvironment);
break;
case ApplicationShutdownChangeInGlobalAsax:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownChangeInGlobalAsax);
break;
case ApplicationShutdownConfigurationChange:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownConfigurationChange);
break;
case ApplicationShutdownUnloadAppDomainCalled:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownUnloadAppDomainCalled);
break;
case ApplicationShutdownChangeInSecurityPolicyFile:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownChangeInSecurityPolicyFile);
break;
case ApplicationShutdownBinDirChangeOrDirectoryRename:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBinDirChangeOrDirectoryRename);
break;
case ApplicationShutdownBrowsersDirChangeOrDirectoryRename:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBrowsersDirChangeOrDirectoryRename);
break;
case ApplicationShutdownCodeDirChangeOrDirectoryRename:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownCodeDirChangeOrDirectoryRename);
break;
case ApplicationShutdownResourcesDirChangeOrDirectoryRename:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownResourcesDirChangeOrDirectoryRename);
break;
case ApplicationShutdownIdleTimeout:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownIdleTimeout);
break;
case ApplicationShutdownPhysicalApplicationPathChanged:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownPhysicalApplicationPathChanged);
break;
case ApplicationShutdownHttpRuntimeClose:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownHttpRuntimeClose);
break;
case ApplicationShutdownInitializationError:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownInitializationError);
break;
case ApplicationShutdownMaxRecompilationsReached:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownMaxRecompilationsReached);
break;
case ApplicationShutdownBuildManagerChange:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBuildManagerChange);
break;
case StateServerConnectionError:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_StateServerConnectionError);
break;
case InvalidTicketFailure:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidTicketFailure);
break;
case ExpiredTicketFailure:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ExpiredTicketFailure);
break;
case InvalidViewStateMac:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidViewStateMac);
break;
case InvalidViewState:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidViewState);
break;
case SqlProviderEventsDropped:
detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_SqlProviderEventsDropped);
break;
default:
break;
}
}
switch(eventCode) {
case ApplicationStart:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationStart);
break;
case ApplicationShutdown:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationShutdown);
break;
case ApplicationCompilationStart:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationCompilationStart);
break;
case ApplicationCompilationEnd:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationCompilationEnd);
break;
case ApplicationHeartbeat:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationHeartbeat);
break;
case RequestTransactionComplete:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RequestTransactionComplete);
break;
case RequestTransactionAbort:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RequestTransactionAbort);
break;
case RuntimeErrorRequestAbort:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorRequestAbort);
break;
case RuntimeErrorViewStateFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorViewStateFailure);
break;
case RuntimeErrorValidationFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorValidationFailure);
break;
case RuntimeErrorPostTooLarge:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorPostTooLarge);
break;
case RuntimeErrorUnhandledException:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorUnhandledException);
break;
case WebErrorParserError:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorParserError);
break;
case WebErrorCompilationError:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorCompilationError);
break;
case WebErrorConfigurationError:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorConfigurationError);
break;
case AuditUnhandledSecurityException:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUnhandledSecurityException);
break;
case AuditInvalidViewStateFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditInvalidViewStateFailure);
break;
case AuditFormsAuthenticationSuccess:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFormsAuthenticationSuccess);
break;
case AuditUrlAuthorizationSuccess:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUrlAuthorizationSuccess);
break;
case AuditFileAuthorizationFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFileAuthorizationFailure);
break;
case AuditFormsAuthenticationFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFormsAuthenticationFailure);
break;
case AuditFileAuthorizationSuccess:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFileAuthorizationSuccess);
break;
case AuditMembershipAuthenticationSuccess:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditMembershipAuthenticationSuccess);
break;
case AuditMembershipAuthenticationFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditMembershipAuthenticationFailure);
break;
case AuditUrlAuthorizationFailure:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUrlAuthorizationFailure);
break;
case AuditUnhandledAccessException:
msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUnhandledAccessException);
break;
default:
Debug.Assert(false, "ASP.NET event code " + eventCode.ToString(CultureInfo.InvariantCulture) + " doesn't have message string mapped to it");
return String.Empty;
}
if (detailMsg != null) {
msg += " " + detailMsg;
}
return msg;
}
// Both WebBaseEvents and HealthMonitoringSectionHelper has to store information per {event type, event code}.
// But for system event type, eventCode and event type has a N:1 relationship. Meaning every event
// code can be mapped to one and only one event type. So instead of using {event type, event code} as
// the key, we can use just the event code as the key.
// The simplest way is to use a hashtable. But in order to boost performance, we store those
// information using an array with event code as the key. However, because the event code range is not
// continuous, and has large gap between categories, instead we use an NxM array, when N is number
// of major event code categories (e.g. ApplicationCodeBase and RequestCodeBase), and M is the
// max number of per category event code among all the catogories.
// WebBaseEvents and HealthMonitoringSectionHelper will each maintain its own NxM arrays, and it
// depends on the following functions to calculate the sizes of the array, and to convert an event
// code into a (x,y) coordinate.
internal static int[] s_eventArrayDimensionSizes = new int[2];
internal static int GetEventArrayDimensionSize(int dim) {
Debug.Assert(dim == 0 || dim == 1, "dim == 0 || dim == 1");
return s_eventArrayDimensionSizes[dim];
}
// Convert an event code into a (x,y) coordinate.
internal static void GetEventArrayIndexsFromEventCode(int eventCode, out int index0, out int index1) {
index0 = eventCode/1000 - 1;
index1 = eventCode - (eventCode/1000)*1000 - 1;
Debug.Assert(index0 >= 0 && index0 < GetEventArrayDimensionSize(0), "Index0 of system eventCode out of expected range: " + eventCode);
Debug.Assert(index1 >= 0 && index1 < GetEventArrayDimensionSize(1), "Index1 of system eventCode out of expected range: " + eventCode);
}
static void InitEventArrayDimensions()
{
int sizeOf2ndDim = 0;
int size;
// Below is the manual way to figure out the size of the 2nd dimension.
size = WebEventCodes.ApplicationCodeBaseLast - WebEventCodes.ApplicationCodeBase;
if (size > sizeOf2ndDim) {
sizeOf2ndDim = size;
}
size = WebEventCodes.RequestCodeBaseLast - WebEventCodes.RequestCodeBase;
if (size > sizeOf2ndDim) {
sizeOf2ndDim = size;
}
size = WebEventCodes.ErrorCodeBaseLast - WebEventCodes.ErrorCodeBase;
if (size > sizeOf2ndDim) {
sizeOf2ndDim = size;
}
size = WebEventCodes.AuditCodeBaseLast - WebEventCodes.AuditCodeBase;
if (size > sizeOf2ndDim) {
sizeOf2ndDim = size;
}
size = WebEventCodes.MiscCodeBaseLast - WebEventCodes.MiscCodeBase;
if (size > sizeOf2ndDim) {
sizeOf2ndDim = size;
}
s_eventArrayDimensionSizes[0] = WebEventCodes.LastCodeBase/1000;
s_eventArrayDimensionSizes[1] = sizeOf2ndDim;
}
}
}

View File

@@ -0,0 +1,48 @@
//------------------------------------------------------------------------------
// <copyright file="TraceWebEventProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Security.Permissions;
////////////
// Events
////////////
public sealed class TraceWebEventProvider : WebEventProvider, IInternalWebEventProvider {
internal TraceWebEventProvider() { }
public override void Initialize(string name, NameValueCollection config)
{
Debug.Trace("TraceWebEventProvider", "Initializing: name=" + name);
base.Initialize(name, config);
ProviderUtil.CheckUnrecognizedAttributes(config, name);
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
if (eventRaised is WebBaseErrorEvent) {
System.Diagnostics.Trace.TraceError(eventRaised.ToString());
}
else {
System.Diagnostics.Trace.TraceInformation(eventRaised.ToString());
}
}
public override void Flush() {
}
public override void Shutdown() {
}
}
}

View File

@@ -0,0 +1 @@
f7c17a34926fd7ed2e6e72a7d6022a3ca3326ad1

View File

@@ -0,0 +1,458 @@
//------------------------------------------------------------------------------
// <copyright file="EventlogProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
using System.Web.Util;
using System.Web.Configuration;
using System.Text;
using System.Reflection;
using System.Security.Permissions;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
[ComImport, Guid("c84f668a-cc3f-11d7-b79e-505054503030"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IRegiisUtility {
void ProtectedConfigAction(long actionToPerform,
[In, MarshalAs(UnmanagedType.LPWStr)] string firstArgument,
[In, MarshalAs(UnmanagedType.LPWStr)] string secondArgument,
[In, MarshalAs(UnmanagedType.LPWStr)] string providerName,
[In, MarshalAs(UnmanagedType.LPWStr)] string appPath,
[In, MarshalAs(UnmanagedType.LPWStr)] string site,
[In, MarshalAs(UnmanagedType.LPWStr)] string cspOrLocation,
int keySize,
out IntPtr exception);
void RegisterSystemWebAssembly(int doReg, out IntPtr exception);
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
void RegisterAsnetMmcAssembly(int doReg, [In, MarshalAs(UnmanagedType.LPWStr)] string assemblyName, [In, MarshalAs(UnmanagedType.LPWStr)] string binaryDirectory, out IntPtr exception);
void RemoveBrowserCaps(out IntPtr exception);
}
public sealed class RegiisUtility : IRegiisUtility {
// The following two sets of constants are copied from register.cxx
const int WATSettingLocalOnly = 0;
const int WATSettingRequireSSL = 1;
const int WATSettingAuthSettings = 2;
const int WATSettingAuthMode = 3;
const int WATSettingMax = 4;
const int WATValueDoNothing = 0;
const int WATValueTrue = 1;
const int WATValueFalse = 2;
const int WATValueHosted = 3;
const int WATValueLocal = 4;
const int WATValueForms = 5;
const int WATValueWindows = 6;
// Note: this name has to match the name used in System.Configuration.RsaProtectedConfigurationProvider
const string DefaultRsaKeyContainerName = "NetFrameworkConfigurationKey";
const string NewLine = "\n\r";
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
public void RegisterSystemWebAssembly(int doReg, out IntPtr exception)
{
exception = IntPtr.Zero;
try {
Assembly webAssembly = Assembly.GetExecutingAssembly();
RegistrationServices rs = new RegistrationServices();
if (doReg != 0)
{
if (!rs.RegisterAssembly(webAssembly, AssemblyRegistrationFlags.None))
exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_Register_Assembly, webAssembly.FullName))).ToString());
}
else
{
if (!rs.UnregisterAssembly(webAssembly))
exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_UnRegister_Assembly, webAssembly.FullName))).ToString());
}
}
catch (Exception e) {
exception = Marshal.StringToBSTR(e.ToString());
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public void RegisterAsnetMmcAssembly(int doReg, string typeName, string binaryDirectory, out IntPtr exception)
{
exception = IntPtr.Zero;
try
{
Assembly webAssembly = Assembly.GetAssembly(Type.GetType(typeName, true));
RegistrationServices rs = new RegistrationServices();
if (doReg != 0)
{
if (!rs.RegisterAssembly(webAssembly, AssemblyRegistrationFlags.None))
exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_Register_Assembly, webAssembly.FullName))).ToString());
TypeLibConverter converter = new TypeLibConverter();
ConversionEventSink eventHandler = new ConversionEventSink();
IRegisterCreateITypeLib typeLib = (IRegisterCreateITypeLib)converter.ConvertAssemblyToTypeLib(webAssembly, System.IO.Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"), 0, eventHandler);
typeLib.SaveAllChanges();
}
else
{
// Consider deleting tlb file
if (!rs.UnregisterAssembly(webAssembly))
exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_UnRegister_Assembly, webAssembly.FullName))).ToString());
try {
File.Delete(System.IO.Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"));
}
catch {
}
}
}
catch (Exception e)
{
exception = Marshal.StringToBSTR(e.ToString());
}
}
[ComImport, GuidAttribute("00020406-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false)]
interface IRegisterCreateITypeLib
{
void CreateTypeInfo();
void SetName();
void SetVersion();
void SetGuid();
void SetDocString();
void SetHelpFileName();
void SetHelpContext();
void SetLcid();
void SetLibFlags();
void SaveAllChanges();
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
private const long DO_RSA_ENCRYPT = 0x0000000100000000;
private const long DO_RSA_DECRYPT = 0x0000000200000000;
private const long DO_RSA_ADD_KEY = 0x0000000400000000;
private const long DO_RSA_DEL_KEY = 0x0000000800000000;
private const long DO_RSA_ACL_KEY_ADD = 0x0000001000000000;
private const long DO_RSA_ACL_KEY_DEL = 0x0000002000000000;
private const long DO_RSA_EXPORT_KEY = 0x0000004000000000;
private const long DO_RSA_IMPORT_KEY = 0x0000008000000000;
private const long DO_RSA_PKM = 0x0000080000000000;
private const long DO_RSA_PKU = 0x0000100000000000;
private const long DO_RSA_EXPORTABLE = 0x0000400000000000;
private const long DO_RSA_FULL_ACCESS = 0x0000800000000000;
private const long DO_RSA_PRIVATE = 0x0001000000000000;
private const long DO_RSA_ENCRYPT_FILE = 0x0004000000000000;
private const long DO_RSA_DECRYPT_FILE = 0x0008000000000000;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
public void ProtectedConfigAction(long options, string firstArgument, string secondArgument, string providerName, string appPath, string site, string cspOrLocation, int keySize, out IntPtr exception)
{
exception = IntPtr.Zero;
try {
if ((options & DO_RSA_ENCRYPT) != 0) {
DoProtectSection(firstArgument, providerName, appPath, site, cspOrLocation, (options & DO_RSA_PKM) != 0);
} else if ((options & DO_RSA_DECRYPT) != 0) {
DoUnprotectSection(firstArgument, appPath, site, cspOrLocation, (options & DO_RSA_PKM) != 0);
} else if ((options & DO_RSA_ENCRYPT_FILE) != 0) {
DoProtectSectionFile(firstArgument, secondArgument, providerName);
} else if ((options & DO_RSA_DECRYPT_FILE) != 0) {
DoUnprotectSectionFile(firstArgument, secondArgument);
} else if ((options & DO_RSA_ADD_KEY) != 0) {
DoKeyCreate(firstArgument, cspOrLocation, options, keySize);
} else if ((options & DO_RSA_DEL_KEY) != 0) {
DoKeyDelete(firstArgument, cspOrLocation, options);
} else if ((options & DO_RSA_EXPORT_KEY) != 0) {
DoKeyExport(firstArgument, secondArgument, cspOrLocation, options);
} else if ((options & DO_RSA_IMPORT_KEY) != 0) {
DoKeyImport(firstArgument, secondArgument, cspOrLocation, options);
} else if ((options & DO_RSA_ACL_KEY_ADD) != 0 || (options & DO_RSA_ACL_KEY_DEL) != 0) {
DoKeyAclChange(firstArgument, secondArgument, cspOrLocation, options);
} else {
exception = Marshal.StringToBSTR(SR.GetString(SR.Command_not_recognized));
}
} catch (Exception e) {
StringBuilder sb = new StringBuilder();
GetExceptionMessage(e, sb);
exception = Marshal.StringToBSTR(sb.ToString());
}
}
private void GetExceptionMessage(Exception exception, StringBuilder sb) {
if (sb.Length != 0) {
sb.Append(NewLine);
}
if (exception is ConfigurationErrorsException) {
foreach(ConfigurationErrorsException e in ((ConfigurationErrorsException)exception).Errors) {
sb.Append(e.Message);
sb.Append(NewLine);
if (e.InnerException != null) {
sb.Append(NewLine);
sb.Append(e.InnerException.Message);
sb.Append(NewLine);
}
}
}
else {
sb.Append(exception.Message );
sb.Append(NewLine);
if (exception.InnerException != null) {
GetExceptionMessage(exception.InnerException, sb);
}
}
}
private void DoProtectSection(string configSection, string providerName, string appPath, string site, string location, bool useMachineConfig)
{
Configuration config;
ConfigurationSection section = GetConfigSection(configSection, appPath, site, location, useMachineConfig, out config);
if (section == null) // Throw an error that the section was not found.
throw new Exception(SR.GetString(SR.Configuration_Section_not_found, configSection));
section.SectionInformation.ProtectSection(providerName);
config.Save();
}
private void DoUnprotectSection(string configSection, string appPath, string site, string location, bool useMachineConfig)
{
Configuration config;
ConfigurationSection section = GetConfigSection(configSection, appPath, site, location, useMachineConfig, out config);
if (section == null) // Throw an error that the section was not found.
throw new Exception(SR.GetString(SR.Configuration_Section_not_found, configSection));
section.SectionInformation.UnprotectSection();
config.Save();
}
private void DoProtectSectionFile(string configSection, string dirName, string providerName)
{
Configuration config;
ConfigurationSection section = GetConfigSectionFile(configSection, dirName, out config);
if (section == null) // Throw an error that the section was not found.
throw new Exception(SR.GetString(SR.Configuration_Section_not_found, configSection));
section.SectionInformation.ProtectSection(providerName);
config.Save();
}
private void DoUnprotectSectionFile(string configSection, string dirName)
{
Configuration config;
ConfigurationSection section = GetConfigSectionFile(configSection, dirName, out config);
if (section == null) // Throw an error that the section was not found.
throw new Exception(SR.GetString(SR.Configuration_Section_not_found, configSection));
section.SectionInformation.UnprotectSection();
config.Save();
}
private ConfigurationSection GetConfigSectionFile(string configSection, string dirName, out Configuration config)
{
if (dirName == ".") {
dirName = Environment.CurrentDirectory;
} else {
if (!Path.IsPathRooted(dirName))
dirName = Path.Combine(Environment.CurrentDirectory, dirName);
if (!Directory.Exists(dirName))
throw new Exception(SR.GetString(SR.Configuration_for_physical_path_not_found, dirName));
}
WebConfigurationFileMap fileMap = new WebConfigurationFileMap();
string appVPath = dirName.Replace('\\', '/');
if (appVPath.Length > 2 && appVPath[1] == ':')
appVPath = appVPath.Substring(2);
else if (appVPath.StartsWith("//", StringComparison.Ordinal)) // UNC share?
appVPath = "/";
fileMap.VirtualDirectories.Add(appVPath, new VirtualDirectoryMapping(dirName, true));
try {
config = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, appVPath);
}
catch (Exception e) {
throw new Exception(SR.GetString(SR.Configuration_for_physical_path_not_found, dirName), e);
}
return config.GetSection(configSection);
}
private ConfigurationSection GetConfigSection(string configSection, string appPath, string site, string location, bool useMachineConfig, out Configuration config)
{
if (string.IsNullOrEmpty(appPath)) {
appPath = null;
} else {
Debug.Assert(appPath.StartsWith("/", StringComparison.Ordinal), "This check is done in main.cxx in regiis");
}
if (string.IsNullOrEmpty(location))
location = null;
try {
if (useMachineConfig)
config = WebConfigurationManager.OpenMachineConfiguration(location);
else
config = WebConfigurationManager.OpenWebConfiguration(appPath, site, location);
}
catch (Exception e) {
if (useMachineConfig) {
throw new Exception(SR.GetString(SR.Configuration_for_machine_config_not_found), e);
}
else {
throw new Exception(SR.GetString(SR.Configuration_for_path_not_found, appPath,
String.IsNullOrEmpty(site) ? SR.GetString(SR.DefaultSiteName) : site), e);
}
}
return config.GetSection(configSection);
}
private void DoKeyCreate(string containerName, string csp, long options, int keySize)
{
if (containerName == null || containerName.Length < 1) {
containerName = DefaultRsaKeyContainerName;
}
uint returnHR = (uint)UnsafeNativeMethods.DoesKeyContainerExist(containerName, csp, ((options & DO_RSA_PKU) == 0) ? 1 : 0);
switch (returnHR) {
case 0:
throw new Exception(SR.GetString(SR.RSA_Key_Container_already_exists));
case 0x80090016: // Not found -- create it
RsaProtectedConfigurationProvider rsaProv = CreateRSAProvider(containerName, csp, options);
try {
rsaProv.AddKey(keySize, (options & DO_RSA_EXPORTABLE) != 0);
} catch {
rsaProv.DeleteKey();
throw;
}
return;
case 0x80070005:
throw new Exception(SR.GetString(SR.RSA_Key_Container_access_denied));
default:
Marshal.ThrowExceptionForHR((int)returnHR);
return;
}
}
private void DoKeyDelete(string containerName, string csp, long options)
{
if (containerName == null || containerName.Length < 1) {
containerName = DefaultRsaKeyContainerName;
}
MakeSureContainerExists(containerName, csp, (options & DO_RSA_PKU) == 0);
RsaProtectedConfigurationProvider rsaProv = CreateRSAProvider(containerName, csp, options);
rsaProv.DeleteKey();
}
private void DoKeyExport(string containerName, string fileName, string csp, long options)
{
if (!Path.IsPathRooted(fileName))
fileName = Path.Combine(Environment.CurrentDirectory, fileName);
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(fileName)))
throw new System.IO.DirectoryNotFoundException();
if (containerName == null || containerName.Length < 1) {
containerName = DefaultRsaKeyContainerName;
}
MakeSureContainerExists(containerName, csp, (options & DO_RSA_PKU) == 0);
RsaProtectedConfigurationProvider rsaProv = CreateRSAProvider(containerName, csp, options);
rsaProv.ExportKey(fileName, (options & DO_RSA_PRIVATE) != 0);
}
private void DoKeyImport(string containerName, string fileName, string csp, long options)
{
if (!System.IO.File.Exists(fileName))
throw new System.IO.FileNotFoundException();
if (containerName == null || containerName.Length < 1) {
containerName = DefaultRsaKeyContainerName;
}
RsaProtectedConfigurationProvider rsaProv = CreateRSAProvider(containerName, csp, options);
rsaProv.ImportKey(fileName, (options & DO_RSA_EXPORTABLE) != 0);
}
private void DoKeyAclChange(string containerName, string account, string csp, long options)
{
if (containerName == null || containerName.Length < 1) {
containerName = DefaultRsaKeyContainerName;
}
MakeSureContainerExists(containerName, csp, (options & DO_RSA_PKU) == 0);
int flags = 0;
if ((options & DO_RSA_ACL_KEY_ADD) != 0)
flags |= 0x1; // Add access
if ((options & DO_RSA_PKU) == 0)
flags |= 0x2;
if ((options & DO_RSA_FULL_ACCESS) != 0)
flags |= 0x4;
int returnHR = UnsafeNativeMethods.ChangeAccessToKeyContainer(containerName, account, csp, flags);
if (returnHR != 0)
Marshal.ThrowExceptionForHR(returnHR);
}
private RsaProtectedConfigurationProvider CreateRSAProvider(string containerName, string csp, long options)
{
RsaProtectedConfigurationProvider prov = new RsaProtectedConfigurationProvider();
NameValueCollection nvc = new NameValueCollection();
nvc.Add("keyContainerName", containerName);
nvc.Add("cspProviderName", csp);
nvc.Add("useMachineContainer", ((options & DO_RSA_PKU) != 0) ? "false" : "true");
prov.Initialize("foo", nvc);
return prov;
}
private static void MakeSureContainerExists(string containerName, string csp, bool machineContainer) {
uint returnHR = (uint) UnsafeNativeMethods.DoesKeyContainerExist(containerName, csp, machineContainer ? 1 : 0);
switch (returnHR) {
case 0:
return; // success!
case 0x80090016:
throw new Exception(SR.GetString(SR.RSA_Key_Container_not_found));
case 0x80070005:
throw new Exception(SR.GetString(SR.RSA_Key_Container_access_denied));
default:
Marshal.ThrowExceptionForHR((int)returnHR);
return;
}
}
public void RemoveBrowserCaps(out IntPtr exception) {
try {
BrowserCapabilitiesCodeGenerator generator = new BrowserCapabilitiesCodeGenerator();
generator.UninstallInternal();
exception = IntPtr.Zero;
}
catch (Exception e) {
exception = Marshal.StringToBSTR(e.Message);
}
}
}
class ConversionEventSink : ITypeLibExporterNotifySink
{
public void ReportEvent(ExporterEventKind eventKind, int eventCode, string eventMsg)
{
// Handle the warning event here.
}
public Object ResolveRef(Assembly assemblyReference)
{
// Resolve the reference here and return a correct type library.
return null;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,248 @@
//------------------------------------------------------------------------------
// <copyright file="events.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Management {
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.Util;
using System.Security.Principal;
using System.Configuration;
using System.Text;
using System;
using System.Globalization;
using System.Web.UI;
using System.Security.Permissions;
////////////
// Events
////////////
public class WmiWebEventProvider : WebEventProvider {
public override void Initialize(string name, NameValueCollection config)
{
Debug.Trace("WmiWebEventProvider", "Initializing: name=" + name);
int hr;
hr = UnsafeNativeMethods.InitializeWmiManager();
if (hr != 0) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Wmi_provider_cant_initialize, "0x" + hr.ToString("X8", CultureInfo.CurrentCulture)));
}
base.Initialize(name, config);
ProviderUtil.CheckUnrecognizedAttributes(config, name);
}
string WmiFormatTime(DateTime dt) {
// CIM DATETIME has this format:
// yyyymmddHHMMSS.mmmmmmsUUU
// where s = [+|-}
// UUU = Three-digit offset indicating the number of minutes that the
// originating time zone deviates from UTC.
StringBuilder sb = new StringBuilder(26);
sb.Append(dt.ToString("yyyyMMddHHmmss.ffffff", CultureInfo.InstalledUICulture));
double offset = TimeZone.CurrentTimeZone.GetUtcOffset(dt).TotalMinutes;
if (offset >= 0) {
sb.Append('+');
}
sb.Append(offset);
return sb.ToString();
}
void FillBasicWmiDataFields(ref UnsafeNativeMethods.WmiData wmiData, WebBaseEvent eventRaised) {
WebApplicationInformation appInfo = WebBaseEvent.ApplicationInformation;
wmiData.eventType = (int)WebBaseEvent.WebEventTypeFromWebEvent(eventRaised);
// Note: WMI sint64 requires a string param
// Data contained in WebBaseEvent
wmiData.eventCode = eventRaised.EventCode;
wmiData.eventDetailCode = eventRaised.EventDetailCode;
wmiData.eventTime = WmiFormatTime(eventRaised.EventTime);
wmiData.eventMessage = eventRaised.Message;
wmiData.sequenceNumber = eventRaised.EventSequence.ToString(CultureInfo.InstalledUICulture);
wmiData.occurrence = eventRaised.EventOccurrence.ToString(CultureInfo.InstalledUICulture);
wmiData.eventId = eventRaised.EventID.ToString("N", CultureInfo.InstalledUICulture);
wmiData.appDomain = appInfo.ApplicationDomain;
wmiData.trustLevel = appInfo.TrustLevel;
wmiData.appVirtualPath = appInfo.ApplicationVirtualPath;
wmiData.appPath = appInfo.ApplicationPath;
wmiData.machineName = appInfo.MachineName;
if (eventRaised.IsSystemEvent) {
wmiData.details = String.Empty;
}
else {
WebEventFormatter formatter = new WebEventFormatter();
eventRaised.FormatCustomEventDetails(formatter);
wmiData.details = formatter.ToString();
}
}
void FillRequestWmiDataFields(ref UnsafeNativeMethods.WmiData wmiData, WebRequestInformation reqInfo) {
string user;
string authType;
bool authed;
IPrincipal iprincipal = reqInfo.Principal;
if (iprincipal == null) {
user = String.Empty;
authType = String.Empty;
authed = false;
}
else {
IIdentity id = iprincipal.Identity;
user = id.Name;
authed = id.IsAuthenticated;
authType = id.AuthenticationType;
}
wmiData.requestUrl = reqInfo.RequestUrl;
wmiData.requestPath = reqInfo.RequestPath;
wmiData.userHostAddress = reqInfo.UserHostAddress;
wmiData.userName = user;
wmiData.userAuthenticated = authed;
wmiData.userAuthenticationType = authType;
wmiData.requestThreadAccountName = reqInfo.ThreadAccountName;
}
void FillErrorWmiDataFields(ref UnsafeNativeMethods.WmiData wmiData, WebThreadInformation threadInfo) {
wmiData.threadId = threadInfo.ThreadID;
wmiData.threadAccountName = threadInfo.ThreadAccountName;
wmiData.stackTrace = threadInfo.StackTrace;
wmiData.isImpersonating = threadInfo.IsImpersonating;
}
public override void ProcessEvent(WebBaseEvent eventRaised)
{
Debug.Trace("WmiWebEventProvider", "ProcessEvent: event=" + eventRaised.GetType().Name);
UnsafeNativeMethods.WmiData wmiData = new UnsafeNativeMethods.WmiData();
// Note: WMI sint64 requires a string param
FillBasicWmiDataFields(ref wmiData, eventRaised);
if (eventRaised is WebApplicationLifetimeEvent) {
// Nothing special for this class.
}
if (eventRaised is WebManagementEvent) {
WebProcessInformation processEventInfo = ((WebManagementEvent)eventRaised).ProcessInformation;
wmiData.processId = processEventInfo.ProcessID;
wmiData.processName = processEventInfo.ProcessName;
wmiData.accountName = processEventInfo.AccountName;
}
if (eventRaised is WebRequestEvent) {
FillRequestWmiDataFields(ref wmiData, ((WebRequestEvent)eventRaised).RequestInformation);
}
if (eventRaised is WebAuditEvent) {
FillRequestWmiDataFields(ref wmiData, ((WebAuditEvent)eventRaised).RequestInformation);
}
if (eventRaised is WebAuthenticationSuccessAuditEvent) {
wmiData.nameToAuthenticate = ((WebAuthenticationSuccessAuditEvent)eventRaised).NameToAuthenticate;
}
if (eventRaised is WebAuthenticationFailureAuditEvent) {
wmiData.nameToAuthenticate = ((WebAuthenticationFailureAuditEvent)eventRaised).NameToAuthenticate;
}
if (eventRaised is WebViewStateFailureAuditEvent) {
ViewStateException vse = ((WebViewStateFailureAuditEvent)eventRaised).ViewStateException;
wmiData.exceptionMessage = SR.GetString(vse.ShortMessage);
wmiData.remoteAddress = vse.RemoteAddress;
wmiData.remotePort = vse.RemotePort;
wmiData.userAgent = vse.UserAgent;
wmiData.persistedState = vse.PersistedState;
wmiData.referer = vse.Referer;
wmiData.path = vse.Path;
}
if (eventRaised is WebHeartbeatEvent) {
#if DBG
try {
#endif
WebHeartbeatEvent hbEvent = eventRaised as WebHeartbeatEvent;
WebProcessStatistics procStats = hbEvent.ProcessStatistics;
wmiData.processStartTime = WmiFormatTime(procStats.ProcessStartTime);
wmiData.threadCount = procStats.ThreadCount;
wmiData.workingSet = procStats.WorkingSet.ToString(CultureInfo.InstalledUICulture);
wmiData.peakWorkingSet = procStats.PeakWorkingSet.ToString(CultureInfo.InstalledUICulture);
wmiData.managedHeapSize = procStats.ManagedHeapSize.ToString(CultureInfo.InstalledUICulture);
wmiData.appdomainCount = procStats.AppDomainCount;
wmiData.requestsExecuting = procStats.RequestsExecuting;
wmiData.requestsQueued = procStats.RequestsQueued;
wmiData.requestsRejected = procStats.RequestsRejected;
#if DBG
}
catch (Exception e) {
Debug.Trace("WmiWebEventProvider", e.ToString());
throw;
}
#endif
}
if (eventRaised is WebBaseErrorEvent) {
Exception exception = ((WebBaseErrorEvent)eventRaised).ErrorException;
if (exception == null) {
wmiData.exceptionType = String.Empty;
wmiData.exceptionMessage = String.Empty;
}
else {
wmiData.exceptionType = exception.GetType().Name;
wmiData.exceptionMessage = exception.Message;
}
}
if (eventRaised is WebRequestErrorEvent) {
WebRequestErrorEvent reEvent = eventRaised as WebRequestErrorEvent;
WebRequestInformation reqInfo = reEvent.RequestInformation;
WebThreadInformation threadInfo = reEvent.ThreadInformation;
FillRequestWmiDataFields(ref wmiData, reqInfo);
FillErrorWmiDataFields(ref wmiData, threadInfo);
}
if (eventRaised is WebErrorEvent) {
WebErrorEvent eEvent = eventRaised as WebErrorEvent;
WebRequestInformation reqInfo = eEvent.RequestInformation;
WebThreadInformation threadInfo = eEvent.ThreadInformation;
FillRequestWmiDataFields(ref wmiData, reqInfo);
FillErrorWmiDataFields(ref wmiData, threadInfo);
}
int hr = UnsafeNativeMethods.RaiseWmiEvent(ref wmiData, AspCompatApplicationStep.IsInAspCompatMode);
if (hr != 0) {
throw new HttpException(SR.GetString(SR.Wmi_provider_error, "0x" + hr.ToString("X8", CultureInfo.InstalledUICulture)));
}
}
public override void Flush() {
}
public override void Shutdown() {
}
}
}