/// <summary> /// Initializes a new instance of the LogTarget class /// </summary> /// <param name="minSeverity">the minimum severity of the logger</param> /// <param name="maxSeverity">the maximum severity of the logger</param> /// <param name="contextFilter">A n Expression that can be used to filter the context of provided messages</param> /// <param name="initialStatus">the initial status of this logger</param> /// <param name="debugEnabled">indicates whether to log debug-messages</param> protected LogTarget(int minSeverity, int maxSeverity, string contextFilter, bool initialStatus, bool debugEnabled) : this() { MinSeverity = minSeverity; MaxSeverity = maxSeverity; enabled = initialStatus; ContextFilter = contextFilter; EnableDebugMessages = debugEnabled; if (debugEnabled) { LogEnvironment.EnableDebugMessages(); } }
public static void RevokeTemporaryPermission(string service, string permission) { if (services.TryGetValue(service, out var user)) { var list = grantTable.GetOrAdd(user, s => new List <string>()); lock (list) { LogEnvironment.LogDebugEvent($"Revoking Grant {permission} for {user}.", LogSeverity.Report); list.RemoveAll(n => n == permission); } } }
private void IncomingData(object?sender, IncomingDataEventArgs e) { Task.Run(async() => { var context = new DataTransferContext(); string requestId = null; var obj = JsonHelper.FromJsonStringStrongTyped <object>(e.Data); LogEnvironment.LogDebugEvent($"Message-Type: {obj.GetType()}", LogSeverity.Report); if (obj is Request req) { obj = req.Payload; requestId = req.RequestId; if (!string.IsNullOrEmpty(req.Identity)) { context.Identity = JsonHelper.FromJsonStringStrongTyped <TransferIdentity>(req.Identity).ToIdentity(); } } else if (obj is Response rep) { obj = null; var ok = waitingOperations.TryRemove(rep.RequestId, out var wait); if (ok) { wait.ServerResponse.SetResult(rep.Payload); } else { throw new CommunicationException("The given operation is not open."); } } if (obj != null) { var evData = new ObjectReceivedEventArgs { Value = obj, Context = context }; OnObjectReceived(evData); if (!string.IsNullOrEmpty(requestId) && outgoing != null) { await WriteAsync(new Response { RequestId = requestId, Payload = evData.Result }); } else if (evData.Result != null) { await WriteAsync(evData.Result); } } }); }
public ServiceDiscoverResponseMessage DiscoverService(ServiceDiscoverMessage serviceDiscoverMessage) { try { var ret = channel.Request(serviceDiscoverMessage).ConfigureAwait(false).GetAwaiter().GetResult(); return((ServiceDiscoverResponseMessage)ret); } catch (Exception ex) { LogEnvironment.LogDebugEvent(ex.OutlineException(), LogSeverity.Error); throw; } }
/// <summary> /// Unwraps a file and requests for each entry a new stream providing the inner entryname /// </summary> /// <param name="inputStream">the stream that contains the data that needs to be unwrapped</param> /// <param name="getStreamForFileCallback">a callback that will be called for each entry in the wrapped file</param> /// <param name="unwrappedFiles">a FileMap object containing all files that have been unwrapped</param> /// <returns>a value indicating whether the unwrapping of the file was successful</returns> public override bool Unwrap(Stream inputStream, Func <FileMapEntry, Stream> getStreamForFileCallback, out FileMap unwrappedFiles) { try { unwrappedFiles = UnwrapZip(inputStream, ".", true, getStreamForFileCallback); return(true); } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } unwrappedFiles = null; return(false); }
/// <summary> /// Dumps a single event to all dumpers attached to this listener /// </summary> /// <param name="record">the event record that needs to be delivered to each connected dumper</param> protected void DumpEvent(ParserEventRecord record) { foreach (var dumper in dumpers) { try { dumper.DumpEvent(record); } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); } } }
/// <summary> /// Registers a regular Shutdown on a previously registered service /// </summary> /// <param name="machine">the machine on which the service is about to stop</param> /// <param name="serviceName">the name of the service that is stopping</param> /// <param name="processName">the name of the process that runs the service</param> /// <param name="processId">the current processId of the service</param> public void RegisterRegularShutdown(string machine, string serviceName, string processName, int processId) { SetProcessStatus(machine, processName, processId, false, out var processStatus); var meta = processStatus.MetaData <WindowsServiceMetaData>(); if (meta != null) { meta.RegularShutdown = true; } else { LogEnvironment.LogEvent($"No Service-Metadata found for service {serviceName}...", LogSeverity.Warning); } }
/// <summary> /// Stellt die Implementierung für Vorgänge bereit, die einen Wert nach Index festlegen.Von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Vorgänge anzugeben, die auf Objekte mit einem angegebenen Index zugreifen. /// </summary> /// <returns> /// true, wenn der Vorgang erfolgreich ist, andernfalls false.Wenn die Methode false zurückgibt, wird das Verhalten vom Laufzeitbinder der Sprache bestimmt.(In den meisten Fällen wird eine sprachspezifische Laufzeitausnahme ausgelöst.) /// </returns> /// <param name="binder">Stellt Informationen zum Vorgang bereit. </param><param name="indexes">Die Indizes, die bei dem Vorgang verwendet werden.Beim sampleObject[3] = 10-Vorgang in C# (sampleObject(3) = 10 in Visual Basic), bei dem sampleObject von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitet wird, entspricht <paramref name="indexes[0]"/> z. B. 3.</param><param name="value">Der Wert, der auf das Objekt mit dem angegebenen Index festgelegt werden soll.Beim sampleObject[3] = 10-Vorgang in C# (sampleObject(3) = 10 in Visual Basic), bei dem sampleObject von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitet wird, entspricht <paramref name="value"/> z. B. 10.</param> public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { try { client.SetProperty(objectName, "", indexes, value); } catch (Exception ex) { LogEnvironment.LogDebugEvent(ex.ToString(), LogSeverity.Error); throw; } return(true); }
/// <summary> /// Enqueues a single task that needs to be done /// </summary> /// <param name="action">the action that needs to be executed</param> public static void EnqueueSingleTask(Action action) { ThreadPool.QueueUserWorkItem(o => { try { action(); } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } }); }
private void TryReconnect(object state) { if (Monitor.TryEnter(reconnLock)) { try { if (hubClient != null && !hubClient.Operational) { try { hubClient.MessageArrived -= ClientInvokation; if (hubClient is not LocalServiceHubConsumer) { hubClient.OperationalChanged -= ConnectedChanges; } hubClient.Dispose(); } catch (Exception ex) { LogEnvironment.LogDebugEvent($"Un-Expected Disconnection Error: {ex.OutlineException()}", LogSeverity.Error); } finally { hubClient = null; } } if (hubClient == null) { try { ConnectToHub(); } catch (Exception ex) { LogEnvironment.LogEvent($"Error when connecting to hub: {ex.OutlineException()}", LogSeverity.Warning); } } else { reconnector.Change(Timeout.Infinite, Timeout.Infinite); } } finally { Monitor.Exit(reconnLock); } } }
/// <summary> /// 使用配置节点对当前配置进行初始化。 /// </summary> /// <param name="configuration">对应的配置节点。</param> public override void Bind(IConfiguration configuration) { Bind(configuration, "settings", func: c => new LoggingConfigurationSetting { Name = c.Key, LogType = Type.GetType(c.GetSection("type").Value, false, true) }); DefaultInstanceName = configuration.GetSection("default").Value; Level = LogEnvironment.GetLevel(configuration.GetSection("level").Value); base.Bind(configuration); }
/// <summary> /// Registers public static /// </summary> /// <param name="type">the type on which accessible methods are registered</param> public static void RegisterClass(Type type) { string[] names; MethodInfo[] methods = ExternalMethodAttribute.GetMethods(type, out names); for (int i = 0; i < names.Length; i++) { if (!expressionMethods.TryAdd(names[i], methods[i])) { LogEnvironment.LogDebugEvent(null, string.Format( "Failed to register method {0} because the method has already been registered with the same signature", names[i]), (int)LogSeverity.Warning, "Scripting"); } } }
/// <summary> /// Decrypts an AES encrypted string using the specified password /// </summary> /// <param name="input">the string to encrypt</param> /// <param name="entropy">the password for encryption</param> /// <param name="useDeriveKey">Indicates whether use key-derivation for the provided key</param> /// <returns>an encrypted string</returns> public static string Decrypt(string input, byte[] entropy, bool useDeriveKey = true) { byte[] raw = Convert.FromBase64String(input); byte[] pre = Encoding.UTF8.GetPreamble(); int offset = 0; var retVal = Decrypt(raw, entropy, useDeriveKey); if (pre.SequenceEqual(retVal.Take(pre.Length))) { offset = pre.Length; LogEnvironment.LogEvent("An encrypted value contains a BOM. Consider re-encrypting it.", LogSeverity.Warning); } return(Encoding.UTF8.GetString(retVal, offset, retVal.Length - offset)); }
/// <summary> /// Unwraps a file and requests for each entry a new stream providing the inner entryname /// </summary> /// <param name="inputStream">the stream that contains the data that needs to be unwrapped</param> /// <param name="targetDirectory">the directory in which to unwrap the files</param> /// <param name="unwrappedFiles">a FileMap object containing all files that have been unwrapped</param> /// <returns>a value indicating whether the unwrapping of the file was successful</returns> public override bool Unwrap(Stream inputStream, string targetDirectory, out FileMap unwrappedFiles) { try { unwrappedFiles = UnwrapZip(inputStream, targetDirectory, true); return(true); } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } unwrappedFiles = null; return(false); }
public static SPOptions WithCertificate(this SPOptions providerOptions, string pathToPfx, string passwordForPfx) { try { var cert = new X509Certificate2(pathToPfx, passwordForPfx.Secure(), X509KeyStorageFlags.PersistKeySet); providerOptions.ServiceCertificates.Add(cert); SamlRequestsSigned = true; } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); } return(providerOptions); }
/// <summary> /// Rgisters this ProcessWatchDog instance for a specific critical component object /// </summary> /// <param name="targetComponent">the registered target object</param> public void RegisterFor(ICriticalComponent targetComponent) { targetComponent.CriticalError += (s, e) => { if (Initialized) { LogEnvironment.LogDebugEvent("Sending request to remote-Watchdog to end this process...", LogSeverity.Warning); remoteWatchDog.SetProcessStatus(machineName, processName, processId, true); } else { LogEnvironment.LogEvent("Initializeation probably failed. RemoteWatchdog is not available", LogSeverity.Error); } }; }
/// <summary> /// Parses the content of the given File into a json object /// </summary> /// <typeparam name="T">the desired object-type</typeparam> /// <returns>the parsed value</returns> public T ParseJsonFile <T>() { T retVal = default(T); try { retVal = JsonConvert.DeserializeObject <T>(FileText); } catch (Exception ex) { LogEnvironment.LogEvent($"Failed to deserialize Dump-Configuration. {ex.OutlineException()}", LogSeverity.Error); } return(retVal); }
/// <summary> /// Manages all processes that have registered on this watchDog instance /// </summary> public void ManageProcesses() { var machines = processStates.ToArray(); foreach (var m in machines) { var procs = m.Value.ToArray(); foreach (var proc in procs) { bool processAlive; if ((processAlive = ProcessAlive(m.Key, proc.Key, proc.Value.ProcessName, out var procInst)) && proc.Value.RebootRequired) { LogEnvironment.LogEvent($"Process {proc.Key}({proc.Value.ProcessName}) on {m.Key} requires a restart...", LogSeverity.Warning); StopProcess(procInst, m.Value); }
/// <summary> /// Stellt die Implementierung für Vorgänge bereit, die einen Wert nach Index abrufen.Von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Indexvorgänge anzugeben. /// </summary> /// <returns> /// true, wenn der Vorgang erfolgreich ist, andernfalls false.Wenn die Methode false zurückgibt, wird das Verhalten vom Laufzeitbinder der Sprache bestimmt.(In den meisten Fällen wird eine Laufzeitausnahme ausgelöst.) /// </returns> /// <param name="binder">Stellt Informationen zum Vorgang bereit. </param><param name="indexes">Die Indizes, die bei dem Vorgang verwendet werden.Beim sampleObject[3]-Vorgang in C# (sampleObject(3) in Visual Basic), bei dem sampleObject von der DynamicObject-Klasse abgeleitet wird, entspricht <paramref name="indexes[0]"/> z. B. 3.</param><param name="result">Das Ergebnis des Indexvorgangs.</param> public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { try { result = client.GetProperty(objectName, "", indexes); } catch (Exception ex) { result = null; LogEnvironment.LogDebugEvent(ex.ToString(), LogSeverity.Error); throw; } return(true); }
/// <summary> /// Checks whether the remote object is still alive /// </summary> /// <param name="sessionId">the client object to test for validity</param> /// <returns>a value indicating whether the connection was successful</returns> private bool TestRemoteConnection(string sessionId) { bool retVal = false; try { retVal = Test(sessionId); } catch (Exception ex) { LogEnvironment.LogEvent(ex.Message, LogSeverity.Error); } return(retVal); }
/// <summary> /// Reads a resource and deserializes it to an object using a json-deserializer /// </summary> /// <typeparam name="T">the target type</typeparam> /// <param name="localizer">the localizer instance</param> /// <param name="name">the name of the resource to deserialize</param> /// <returns>an object of the requested type</returns> public static T FromJson <T>(this IStringLocalizer localizer, string name) where T : class, new() { var raw = localizer[name]; try { return(JsonHelper.FromJsonString <T>(raw)); } catch (Exception ex) { LogEnvironment.LogDebugEvent($"Error translating value to object: {ex.Message}", LogSeverity.Error); } return(new T()); }
protected void LogException(SerializedException ex, bool debug) { if (CollectExceptions) { exceptionCollector.Add(ex); } if (debug) { LogEnvironment.LogDebugEvent(null, ex.ToString(), (int)LogSeverity.Error, null); } else { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } }
/// <summary> /// Gets the value of the provided FieldName /// </summary> /// <param name="memberName">the membername that belongs to the requested value</param> /// <param name="requestedType">the type in which the returned value should be converted</param> /// <returns>the value identified with the provided membername</returns> public dynamic this[string memberName, Type requestedType] { get { dynamic retVal; if (!GetValue(memberName, requestedType, out retVal)) { LogEnvironment.LogDebugEvent(null, string.Format("Unknown Member {0}", memberName), (int)LogSeverity.Warning, "DataAccess"); } return(retVal); } set { SetValue(memberName, value); } }
/// <summary> /// 使用配置节点对当前配置进行初始化。 /// </summary> /// <param name="section">对应的配置节点。</param> public override void Initialize(XmlNode section) { InitializeNode(section, "logging", func: node => new LoggingConfigurationSetting { Name = node.GetAttributeValue("name"), LogType = Type.GetType(node.GetAttributeValue("type"), false, true) }); //取默认实例 DefaultInstanceName = section.GetAttributeValue("default"); Level = LogEnvironment.GetLevel(section.GetAttributeValue("level")); base.Initialize(section); }
/// <summary> /// Initializes this deferred initializable object /// </summary> void IHubConnection.Initialize() { if (!initialized) { try { InitHubConnection(); initialized = true; OnOperationalChanged(true); } catch (Exception ex) { LogEnvironment.LogEvent($"Reconnect changed: {ex.Message}", LogSeverity.Error); } } }
public static IEnumerable ReadForeignKey(this DbContext context, string tableName, IServiceProvider services, string id = null, Dictionary <string, object> postedFilter = null) { if (context is IForeignKeyProvider provider) { IEnumerable retVal; if (postedFilter == null && id == null) { retVal = provider.GetForeignKeyFilterQuery(tableName); } else if (id != null) { retVal = provider.GetForeignKeyResolveQuery(tableName, id); } else { retVal = provider.GetForeignKeyFilterQuery(tableName, postedFilter); } if (retVal != null) { return(retVal); } } if (id == null) { var query = CreateRawQuery(context, tableName, postedFilter, services, out var filterDecl); var typeName = context.GetType().Name; query = $@"{typeName} db = Global.Db; {filterDecl} return {query}"; LogEnvironment.LogDebugEvent(query, LogSeverity.Report); //query = string.Format(query, $"t.{labelColumn}.Contains(filter)"); return(RunQuery(context, query, RosFkConfig, postedFilter)); } else { var query = CreateRawResolveQuery(context, tableName, services); var typeName = context.GetType().Name; query = $@"{typeName} db = Global.Db; {query}"; //query = string.Format(query, $"t.{labelColumn}.Contains(filter)"); return(RunQuery(context, query, RosFkConfig, new Dictionary <string, object> { { "Id", id } })); } }
private T TryReadSectionXml <T>(XmlElement source, Type explicitType) { XmlSerializer serializer = new XmlSerializer(explicitType); T retVal = default(T); try { StringReader str = new StringReader(source.InnerXml); retVal = (T)serializer.Deserialize(str); } catch (Exception x) { LogEnvironment.LogEvent(x.OutlineException(), LogSeverity.Error); } return(retVal); }
private void TryClose(IMemoryChannel channel) { try { channel.Write(new ConnectionDispose()); } catch (Exception ex) { LogEnvironment.LogDebugEvent(ex.Message, LogSeverity.Warning); } finally { channel.ObjectReceived -= ClientComm; channel.ConnectionStatusChanged -= ClientConnectionChanged; channel.Dispose(); } }
/// <summary> /// Writes an error dump for the serialization error that occurred when saving or loading a runtime status /// </summary> /// <param name="ex">the exception that has occurred</param> private void WriteErrorDump(Exception ex) { try { using ( StreamWriter wr = new StreamWriter(string.Format("{0}_crash_{1}.log", DateTime.Now.Ticks, Process.GetCurrentProcess().ProcessName))) { wr.WriteLine(ex.OutlineException()); } } catch (Exception nex) { LogEnvironment.LogEvent(nex.ToString(), LogSeverity.Error); } }
/// <summary> /// Initializes the security module with a specific entropy /// </summary> /// <param name="entropy">the entropy used to decrypt values</param> public static void Initialize(string entropy, DataProtectionScope scope) { if (!initialized) { if (entropy != null) { PasswordSecurity.entropy = Encoding.UTF32.GetBytes(entropy); } else { LogEnvironment.LogDebugEvent(null, "Passwordsecurity is initialized without entropy!", (int)LogSeverity.Warning, null); } PasswordSecurity.scope = scope; initialized = true; } }