本文整理汇总了C#中System.Diagnostics.EventLogPermission.Demand方法的典型用法代码示例。如果您正苦于以下问题:C# EventLogPermission.Demand方法的具体用法?C# EventLogPermission.Demand怎么用?C# EventLogPermission.Demand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Diagnostics.EventLogPermission
的用法示例。
在下文中一共展示了EventLogPermission.Demand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteEvent
public void WriteEvent(EventInstance instance, byte[] data, params Object[] values) {
if (instance == null)
throw new ArgumentNullException("instance");
if (Source.Length == 0)
throw new ArgumentException(SR.GetString(SR.NeedSourceToWrite));
string currentMachineName = machineName;
if (!boolFlags[Flag_writeGranted]) {
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
boolFlags[Flag_writeGranted] = true;
}
VerifyAndCreateSource(Source, currentMachineName);
string[] strings = null;
if (values != null) {
strings = new string[values.Length];
for (int i=0; i<values.Length; i++) {
if (values[i] != null)
strings[i] = values[i].ToString();
else
strings[i] = String.Empty;
}
}
InternalWriteEvent((uint) instance.InstanceId, (ushort) instance.CategoryId, instance.EntryType, strings, data, currentMachineName);
}
示例2: GetLogName
private string GetLogName(string currentMachineName)
{
if ((logName == null || logName.Length == 0) && sourceName != null && sourceName.Length!=0) {
// they've told us a source, but they haven't told us a log name.
// try to deduce the log name from the source name.
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
logName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName);
}
return logName;
}
示例3: WriteEntry
/// <devdoc>
/// <para>
/// Writes an entry of the specified type with the
/// user-defined <paramref name="eventID"/> and <paramref name="category"/> to the event log, and appends binary data to
/// the message. The Event Viewer does not interpret this data; it
/// displays raw data only in a combined hexadecimal and text format.
/// </para>
/// </devdoc>
public void WriteEntry(string message, EventLogEntryType type, int eventID, short category,
byte[] rawData) {
if (eventID < 0 || eventID > ushort.MaxValue)
throw new ArgumentException(SR.GetString(SR.EventID, eventID, 0, (int)ushort.MaxValue));
if (Source.Length == 0)
throw new ArgumentException(SR.GetString(SR.NeedSourceToWrite));
if (!Enum.IsDefined(typeof(EventLogEntryType), type))
throw new InvalidEnumArgumentException("type", (int)type, typeof(EventLogEntryType));
string currentMachineName = machineName;
if (!boolFlags[Flag_writeGranted]) {
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
boolFlags[Flag_writeGranted] = true;
}
VerifyAndCreateSource(sourceName, currentMachineName);
// now that the source has been hooked up to our DLL, we can use "normal"
// (message-file driven) logging techniques.
// Our DLL has 64K different entries; all of them just display the first
// insertion string.
InternalWriteEvent((uint)eventID, (ushort)category, type, new string[] { message}, rawData, currentMachineName);
}
示例4: EventLogInternal
public EventLogInternal(string logName, string machineName, string source, EventLog parent) {
//look out for invalid log names
if (logName == null)
throw new ArgumentNullException("logName");
if (!ValidLogName(logName, true))
throw new ArgumentException(SR.GetString(SR.BadLogName));
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, machineName);
permission.Demand();
this.machineName = machineName;
this.logName = logName;
this.sourceName = source;
readHandle = null;
writeHandle = null;
boolFlags[Flag_forwards] = true;
this.parent = parent;
}
示例5: LogNameFromSourceName
/// <devdoc>
/// Gets the name of the log that the given source name is registered in.
/// </devdoc>
public static string LogNameFromSourceName(string source, string machineName) {
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
return _InternalLogNameFromSourceName(source, machineName);
}
示例6: VerifyAndCreateSource
private void VerifyAndCreateSource(string sourceName, string currentMachineName) {
if (boolFlags[Flag_sourceVerified])
return;
if (!EventLog.SourceExists(sourceName, currentMachineName, true)) {
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
if (!EventLog.SourceExists(sourceName, currentMachineName, true)) {
if (GetLogName(currentMachineName) == null)
this.logName = "Application";
// we automatically add an entry in the registry if there's not already
// one there for this source
EventLog.CreateEventSource(new EventSourceCreationData(sourceName, GetLogName(currentMachineName), currentMachineName));
// The user may have set a custom log and tried to read it before trying to
// write. Due to a quirk in the event log API, we would have opened the Application
// log to read (because the custom log wasn't there). Now that we've created
// the custom log, we should close so that when we re-open, we get a read
// handle on the _new_ log instead of the Application log.
Reset(currentMachineName);
}
else {
string rightLogName = EventLog.LogNameFromSourceName(sourceName, currentMachineName);
string currentLogName = GetLogName(currentMachineName);
if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0)
throw new ArgumentException(SR.GetString(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName));
}
}
finally {
if (mutex != null) {
mutex.ReleaseMutex();
mutex.Close();
}
}
}
else {
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
string rightLogName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName);
string currentLogName = GetLogName(currentMachineName);
if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0)
throw new ArgumentException(SR.GetString(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName));
}
boolFlags[Flag_sourceVerified] = true;
}
示例7: ModifyOverflowPolicy
public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) {
string currentMachineName = this.machineName;
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, currentMachineName);
permission.Demand();
if (action < OverflowAction.DoNotOverwrite || action > OverflowAction.OverwriteOlder)
throw new InvalidEnumArgumentException("action", (int)action, typeof(OverflowAction));
// this is a long because in the if statement we may need to store values as
// large as UInt32.MaxValue - 1. This would overflow an int.
long retentionvalue = (long) action;
if (action == OverflowAction.OverwriteOlder) {
if (retentionDays < 1 || retentionDays > 365)
throw new ArgumentOutOfRangeException(SR.GetString(SR.RentionDaysOutOfRange));
retentionvalue = (long) retentionDays * SecondsPerDay;
}
PermissionSet permissionSet = EventLog._UnsafeGetAssertPermSet();
permissionSet.Assert();
using (RegistryKey logkey = GetLogRegKey(currentMachineName, true))
logkey.SetValue("Retention", retentionvalue, RegistryValueKind.DWord);
}
示例8: Close
private void Close(string currentMachineName) {
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close");
//Trace("Close", "Closing the event log");
if (readHandle != null) {
try {
readHandle.Close();
}
catch (IOException) {
throw SharedUtils.CreateSafeWin32Exception();
}
readHandle = null;
//Trace("Close", "Closed read handle");
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed read handle");
}
if (writeHandle != null) {
try {
writeHandle.Close();
}
catch (IOException) {
throw SharedUtils.CreateSafeWin32Exception();
}
writeHandle = null;
//Trace("Close", "Closed write handle");
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed write handle");
}
if (boolFlags[Flag_monitoring])
StopRaisingEvents(/*currentMachineName,*/ GetLogName(currentMachineName));
if (messageLibraries != null) {
foreach (SafeLibraryHandle handle in messageLibraries.Values)
handle.Close();
messageLibraries = null;
}
boolFlags[Flag_sourceVerified] = false;
}
示例9: Exists
public static bool Exists(string logName, string machineName) {
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.GetString(SR.InvalidParameterFormat, "machineName"));
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
if (logName == null || logName.Length==0)
return false;
//Check environment before looking at the registry
SharedUtils.CheckEnvironment();
//SECREVIEW: Note that EventLog permission is demanded above.
PermissionSet permissionSet = _UnsafeGetAssertPermSet();
permissionSet.Assert();
RegistryKey eventkey = null;
RegistryKey logKey = null;
try {
eventkey = GetEventLogRegKey(machineName, false);
if (eventkey == null)
return false;
logKey = eventkey.OpenSubKey(logName, false); // try to find log file key immediately.
return (logKey != null );
}
finally {
if (eventkey != null) eventkey.Close();
if (logKey != null) logKey.Close();
// Revert registry and environment permission asserts
CodeAccessPermission.RevertAssert();
}
}
示例10: GetEventLogs
public static EventLog[] GetEventLogs(string machineName) {
if (!SyntaxCheck.CheckMachineName(machineName)) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
}
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
//Check environment before looking at the registry
SharedUtils.CheckEnvironment();
string[] logNames = new string[0];
//SECREVIEW: Note that EventLogPermission is just demmanded above
PermissionSet permissionSet = _UnsafeGetAssertPermSet();
permissionSet.Assert();
RegistryKey eventkey = null;
try {
// we figure out what logs are on the machine by looking in the registry.
eventkey = GetEventLogRegKey(machineName, false);
if (eventkey == null)
// there's not even an event log service on the machine.
// or, more likely, we don't have the access to read the registry.
throw new InvalidOperationException(SR.GetString(SR.RegKeyMissingShort, EventLogKey, machineName));
// Most machines will return only { "Application", "System", "Security" },
// but you can create your own if you want.
logNames = eventkey.GetSubKeyNames();
}
finally {
if (eventkey != null) eventkey.Close();
// Revert registry and environment permission asserts
CodeAccessPermission.RevertAssert();
}
// now create EventLog objects that point to those logs
EventLog[] logs = new EventLog[logNames.Length];
for (int i = 0; i < logNames.Length; i++) {
EventLog log = new EventLog(logNames[i], machineName);
logs[i] = log;
}
return logs;
}
示例11: DeleteEventSource
public static void DeleteEventSource(string source, string machineName) {
if (!SyntaxCheck.CheckMachineName(machineName)) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
}
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
//Check environment before looking at the registry
SharedUtils.CheckEnvironment();
//SECREVIEW: Note that EventLog permission is demanded above.
PermissionSet permissionSet = _UnsafeGetAssertPermSet();
permissionSet.Assert();
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
RegistryKey key = null;
// First open the key read only so we can do some checks. This is important so we get the same
// exceptions even if we don't have write access to the reg key.
using (key = FindSourceRegistration(source, machineName, true)) {
if (key == null) {
if (machineName == null)
throw new ArgumentException(SR.GetString(SR.LocalSourceNotRegistered, source));
else
throw new ArgumentException(SR.GetString(SR.SourceNotRegistered, source, machineName, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog"));
}
// Check parent registry key (Event Log Name) and if it's equal to source, then throw an exception.
// The reason: each log registry key must always contain subkey (i.e. source) with the same name.
string keyname = key.Name;
int index = keyname.LastIndexOf('\\');
if ( string.Compare(keyname, index+1, source, 0, keyname.Length - index, StringComparison.Ordinal) == 0 )
throw new InvalidOperationException(SR.GetString(SR.CannotDeleteEqualSource, source));
}
try {
// now open it read/write to try to do the actual delete
key = FindSourceRegistration(source, machineName, false);
key.DeleteSubKeyTree(source);
if (!SkipRegPatch) {
string[] sources = (string[]) key.GetValue("Sources");
ArrayList newsources = new ArrayList(sources.Length - 1);
for (int i=0; i<sources.Length; i++) {
if (sources[i] != source) {
newsources.Add(sources[i]);
}
}
string[] newsourcesArray = new string[newsources.Count];
newsources.CopyTo(newsourcesArray);
key.SetValue("Sources", newsourcesArray, RegistryValueKind.MultiString);
}
}
finally {
if (key != null) {
key.Flush();
key.Close();
}
// Revert registry and environment permission asserts
CodeAccessPermission.RevertAssert();
}
}
finally {
if (mutex != null)
mutex.ReleaseMutex();
}
}
示例12: Delete
public static void Delete(string logName, string machineName) {
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.GetString(SR.InvalidParameterFormat, "machineName"));
if (logName == null || logName.Length==0)
throw new ArgumentException(SR.GetString(SR.NoLogName));
if (!ValidLogName(logName, false))
throw new InvalidOperationException(SR.GetString(SR.BadLogName));
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
//Check environment before even trying to play with the registry
SharedUtils.CheckEnvironment();
//SECREVIEW: Note that EventLog permission is demanded above.
PermissionSet permissionSet = _UnsafeGetAssertPermSet();
permissionSet.Assert();
RegistryKey eventlogkey = null;
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
try {
eventlogkey = GetEventLogRegKey(machineName, true);
if (eventlogkey == null) {
// there's not even an event log service on the machine.
// or, more likely, we don't have the access to read the registry.
throw new InvalidOperationException(SR.GetString(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName));
}
using (RegistryKey logKey = eventlogkey.OpenSubKey(logName)) {
if (logKey == null)
throw new InvalidOperationException(SR.GetString(SR.MissingLog, logName, machineName));
//clear out log before trying to delete it
//that way, if we can't delete the log file, no entries will persist because it has been cleared
EventLog logToClear = new EventLog(logName, machineName);
try {
logToClear.Clear();
}
finally {
logToClear.Close();
}
//
string filename = null;
try {
//most of the time, the "File" key does not exist, but we'll still give it a whirl
filename = (string) logKey.GetValue("File");
}
catch { }
if (filename != null) {
try {
File.Delete(filename);
}
catch { }
}
}
// now delete the registry entry
eventlogkey.DeleteSubKeyTree(logName);
}
finally {
if (eventlogkey != null) eventlogkey.Close();
// Revert registry and environment permission asserts
CodeAccessPermission.RevertAssert();
}
}
finally {
if (mutex != null) mutex.ReleaseMutex();
}
}
示例13: CreateEventSource
public static void CreateEventSource(EventSourceCreationData sourceData) {
if (sourceData == null)
throw new ArgumentNullException("sourceData");
string logName = sourceData.LogName;
string source = sourceData.Source;
string machineName = sourceData.MachineName;
// verify parameters
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Checking arguments");
if (!SyntaxCheck.CheckMachineName(machineName)) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
}
if (logName == null || logName.Length==0)
logName = "Application";
if (!ValidLogName(logName, false))
throw new ArgumentException(SR.GetString(SR.BadLogName));
if (source == null || source.Length==0)
throw new ArgumentException(SR.GetString(SR.MissingParameter, "source"));
if (source.Length + EventLogKey.Length > 254)
throw new ArgumentException(SR.GetString(SR.ParameterTooLong, "source", 254 - EventLogKey.Length));
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName);
permission.Demand();
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
SharedUtils.EnterMutex(eventLogMutexName, ref mutex);
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Calling SourceExists");
if (SourceExists(source, machineName, true)) {
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: SourceExists returned true");
// don't let them register a source if it already exists
// this makes more sense than just doing it anyway, because the source might
// be registered under a different log name, and we don't want to create
// duplicates.
if (".".Equals(machineName))
throw new ArgumentException(SR.GetString(SR.LocalSourceAlreadyExists, source));
else
throw new ArgumentException(SR.GetString(SR.SourceAlreadyExists, source, machineName));
}
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting DllPath");
//SECREVIEW: Note that EventLog permission is demanded above.
PermissionSet permissionSet = _UnsafeGetAssertPermSet();
permissionSet.Assert();
RegistryKey baseKey = null;
RegistryKey eventKey = null;
RegistryKey logKey = null;
RegistryKey sourceLogKey = null;
RegistryKey sourceKey = null;
try {
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting local machine regkey");
if (machineName == ".")
baseKey = Registry.LocalMachine;
else
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
eventKey = baseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog", true);
if (eventKey == null) {
if (!".".Equals(machineName))
throw new InvalidOperationException(SR.GetString(SR.RegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source, machineName));
else
throw new InvalidOperationException(SR.GetString(SR.LocalRegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source));
}
// The event log system only treats the first 8 characters of the log name as
// significant. If they're creating a new log, but that new log has the same
// first 8 characters as another log, the system will think they're the same.
// Throw an exception to let them know.
logKey = eventKey.OpenSubKey(logName, true);
if (logKey == null && logName.Length >= 8) {
// check for Windows embedded logs file names
string logNameFirst8 = logName.Substring(0,8);
if ( string.Compare(logNameFirst8,"AppEvent",StringComparison.OrdinalIgnoreCase) ==0 ||
string.Compare(logNameFirst8,"SecEvent",StringComparison.OrdinalIgnoreCase) ==0 ||
string.Compare(logNameFirst8,"SysEvent",StringComparison.OrdinalIgnoreCase) ==0 )
throw new ArgumentException(SR.GetString(SR.InvalidCustomerLogName, logName));
string sameLogName = FindSame8FirstCharsLog(eventKey, logName);
if ( sameLogName != null )
throw new ArgumentException(SR.GetString(SR.DuplicateLogName, logName, sameLogName));
}
bool createLogKey = (logKey == null);
if (createLogKey) {
if (SourceExists(logName, machineName, true)) {
// don't let them register a log name that already
// exists as source name, a source with the same
// name as the log will have to be created by default
if (".".Equals(machineName))
throw new ArgumentException(SR.GetString(SR.LocalLogAlreadyExistsAsSource, logName));
else
throw new ArgumentException(SR.GetString(SR.LogAlreadyExistsAsSource, logName, machineName));
}
logKey = eventKey.CreateSubKey(logName);
//.........这里部分代码省略.........
示例14: BeginInit
/// <devdoc>
/// </devdoc>
public void BeginInit() {
string currentMachineName = this.machineName;
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Write, currentMachineName);
permission.Demand();
if (boolFlags[Flag_initializing]) throw new InvalidOperationException(SR.GetString(SR.InitTwice));
boolFlags[Flag_initializing] = true;
if (boolFlags[Flag_monitoring])
StopListening(GetLogName(currentMachineName));
}
示例15: OpenForRead
private void OpenForRead(string currentMachineName) {
Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::OpenForRead");
EventLogPermission permission = new EventLogPermission(EventLogPermissionAccess.Administer, currentMachineName);
permission.Demand();
//Cannot allocate the readHandle if the object has been disposed, since finalization has been suppressed.
if (this.boolFlags[Flag_disposed])
throw new ObjectDisposedException(GetType().Name);
string logname = GetLogName(currentMachineName);
if (logname == null || logname.Length==0)
throw new ArgumentException(SR.GetString(SR.MissingLogProperty));
if (!EventLog.Exists(logname, currentMachineName) ) // do not open non-existing Log [[....]]
throw new InvalidOperationException( SR.GetString(SR.LogDoesNotExists, logname, currentMachineName) );
//Check environment before calling api
SharedUtils.CheckEnvironment();
// Clean up cache variables.
// [[....]] The initilizing code is put here to guarantee, that first read of events
// from log file will start by filling up the cache buffer.
lastSeenEntry = 0;
lastSeenPos = 0;
bytesCached = 0;
firstCachedEntry = -1;
SafeEventLogReadHandle handle = SafeEventLogReadHandle.OpenEventLog(currentMachineName, logname);
if (handle.IsInvalid) {
Win32Exception e = null;
if (Marshal.GetLastWin32Error() != 0) {
e = SharedUtils.CreateSafeWin32Exception();
}
throw new InvalidOperationException(SR.GetString(SR.CantOpenLog, logname.ToString(), currentMachineName), e);
}
readHandle = handle;
}