SafeEventLogWriteHandle.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Runtime.Interop
  5. {
  6. using Microsoft.Win32.SafeHandles;
  7. using System.Runtime.InteropServices;
  8. using System.Runtime.Versioning;
  9. using System.Globalization;
  10. using System.Diagnostics;
  11. using System.Security;
  12. [Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
  13. [SecurityCritical]
  14. sealed class SafeEventLogWriteHandle : SafeHandleZeroOrMinusOneIsInvalid
  15. {
  16. // Note: RegisterEventSource returns 0 on failure
  17. [Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
  18. [SecurityCritical]
  19. SafeEventLogWriteHandle() : base(true) { }
  20. [ResourceConsumption(ResourceScope.Machine)]
  21. [Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
  22. [SecurityCritical]
  23. public static SafeEventLogWriteHandle RegisterEventSource(string uncServerName, string sourceName)
  24. {
  25. SafeEventLogWriteHandle retval = UnsafeNativeMethods.RegisterEventSource(uncServerName, sourceName);
  26. int error = Marshal.GetLastWin32Error();
  27. if (retval.IsInvalid)
  28. {
  29. Debug.Print("SafeEventLogWriteHandle::RegisterEventSource[" + uncServerName + ", " + sourceName + "] Failed. Last Error: " +
  30. error.ToString(CultureInfo.InvariantCulture));
  31. }
  32. return retval;
  33. }
  34. [DllImport("advapi32", SetLastError = true)]
  35. [ResourceExposure(ResourceScope.None)]
  36. static extern bool DeregisterEventSource(IntPtr hEventLog);
  37. [Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
  38. [SecurityCritical]
  39. protected override bool ReleaseHandle()
  40. {
  41. return DeregisterEventSource(this.handle);
  42. }
  43. }
  44. }