/// <summary> /// Adds a reference to a specific Assembly. You can either specify the assembly with path, Name (i.e. System.dll) or with its AssemblyName /// </summary> /// <param name="configuration">the configuration to use for adding the specified assembly-reference</param> /// <param name="reference">the reference identifying the required assembly</param> public static void AddReference(string configuration, string reference) { var cfg = configurations.GetOrAdd(configuration, new NativeConfiguration()); lock (cfg) { if (reference == "--ROSLYN--") { LogEnvironment.LogEvent("Legacy Reference '--ROSLYN--' is ignored.", LogSeverity.Warning); } else if (reference == "--AUTOREF--") { cfg.AutoReferences = true; } else if (reference == "--NOAUTOREF--") { cfg.AutoReferences = false; } else { if (!cfg.References.Contains(reference, StringComparer.OrdinalIgnoreCase)) { cfg.References.Add(reference); } } } }
private void LogToOrigin(ParserEventRecord record) { DynamicResult dr = record.SourceData as DynamicResult; if (dr != null) { if (dr.ContainsKey("$origin")) { string origin = dr["$origin"]; int id = origin.LastIndexOf("::", StringComparison.Ordinal); if (id != -1) { string sheetName = origin.Substring(0, id); int line = int.Parse(origin.Substring(id + 2)); var sheet = GetSheet(sheetName, false); try { sheet.AddMessage(line, record.Message); } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); } } } } }
public override async Task ServiceReady(ServiceSessionOperationMessage request, IMemoryChannel channel, DataTransferContext context) { try { if (string.IsNullOrEmpty(request.ResponderFor)) { CheckAuth(context, "ActAsService"); } else { CheckAuth(context, "ConnectAnyService", request.ResponderFor); } await base.ServiceReady(request, channel, context); } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); throw; } finally { TemporaryGrants.UnRegisterService(request.ServiceName); if (!string.IsNullOrEmpty(request.ResponderFor)) { TemporaryGrants.RevokeTemporaryPermission(request.ResponderFor, request.ServiceName); } } }
/// <summary> /// Informs this object about a remote event that has ocurred /// </summary> /// <param name="eventName">the eventname that was raised</param> /// <param name="arguments">the arguments for the specified event</param> protected bool RaiseEvent(string eventName, object[] arguments) { lock (Sync) { eventName.LocalOwner(threadsOwner); try { ReverseArguments(arguments, arguments); bool retVal = false; if (eventSubscriptions.ContainsKey(eventName)) { Delegate[] subscribers = eventSubscriptions[eventName].ToArray(); foreach (Delegate dlg in subscribers) { retVal = true; try { dlg.DynamicInvoke(arguments); } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } } } return(retVal); } finally { PrepareProxyRequest(arguments); eventName.LocalOwner(null); } } }
/// <summary> /// Gets the model for this DataReader's currents result /// </summary> /// <param name="reader">the reader having a current result open</param> /// <param name="targetType">the targetType into which to convert the reader's value</param> /// <param name="rules">a set of rules that applies to the current type</param> /// <param name="fieldNames">a set of names provided by the current reader</param> /// <returns>an instance representing the value of the current result of the reader</returns> internal static object GetModel(this IDataReader reader, Type targetType, MapRule[] rules, string[] fieldNames) { object retVal = targetType.GetConstructor(Type.EmptyTypes).Invoke(null); for (int i = 0; i < rules.Length; i++) { MapRule r = rules[i]; if (r != null && fieldNames.Any(n => n.Equals(r.FieldName, StringComparison.OrdinalIgnoreCase))) { try { object val = reader[r.FieldName]; if (!r.UseExpression) { r[retVal] = val; } else { r[retVal] = ProcessResolveExpression(r.ValueResolveExpression, val); } } catch (Exception ex) { LogEnvironment.LogEvent($"Error during model bind! {ex.OutlineException()}", LogSeverity.Warning); } } else if (r != null) { LogEnvironment.LogDebugEvent($"No Value found for MapRule {r.FieldName} ({r.UseExpression};{r.ValueResolveExpression}", LogSeverity.Report); } } return(retVal); }
/// <summary> /// Registers a specific event-subscription on the server /// </summary> /// <param name="uniqueName">the unique-name of the target-object</param> /// <param name="eventName">the event on the target-object to subscribe to</param> protected override void RegisterServerEvent(string uniqueName, string eventName) { if (!useEvents) { throw new InvalidOperationException("Unable to Register an Event-Subscription in an unidirectional environment!"); } if (connected) { LogEnvironment.LogEvent($@"Subscribe {eventName} on {UniqueName} for {connection.ServiceName}. TargetService: {targetService}", LogSeverity.Report); var ret = TestMessage <RegisterEventResponseMessage>(connection.InvokeServiceAsync(targetService, JsonHelper.ToJsonStrongTyped(new RegisterEventRequestMessage { TargetObject = uniqueName, EventName = eventName, RespondChannel = connection.ServiceName, AuthenticatedUser = identityProvider?.CurrentIdentity }, true))).ConfigureAwait(false).GetAwaiter().GetResult(); if (!ret.Ok) { throw new InterProcessException("Register-Event was not successful", null); } } else { throw new InterProcessException("Not connected!", null); } }
/// <summary> /// Removes the subscription for a specific event on the remote service /// </summary> /// <param name="eventName">the event for which to remove the notification subscription</param> /// <returns>a value indicating whether the subscription removal was successful</returns> protected bool UnSubscribeEvent(string objectName, string eventName, string sessionId, IIdentity authenticatedUser) { bool retVal = false; try { string eventIdentifyer = string.Format("{0}_{1}", objectName, eventName); //OperationContext.Current. if (sessions.TryGetValue(sessionId, out var status)) { lock (resourceLock) { if (eventSubscriptions.ContainsKey(eventIdentifyer)) { List <string> subscribers = eventSubscriptions[eventIdentifyer]; if (subscribers.Contains(sessionId)) { subscribers.Remove(sessionId); retVal = true; } } } } } catch (Exception ex) { LogEnvironment.LogEvent(string.Format(@"{0} {1}", ex.Message, ex.StackTrace), LogSeverity.Error); retVal = false; } return(retVal); }
public async Task <bool> MoveNext() { var t = Fetch(); try { Current = await t.ConfigureAwait(false); if (Current == null) { LogEnvironment.LogEvent("Current message was set to null!", LogSeverity.Warning); } return(Current != null); } catch (TaskCanceledException) { LogEnvironment.LogEvent("Read cancelled!", LogSeverity.Warning); } catch (Exception ex) { LogEnvironment.LogDebugEvent($"Un-Expected Error @MoveNext: {ex.OutlineException()}", LogSeverity.Error); throw; } return(false); }
/// <summary> /// Stellt die Implementierung für Vorgänge bereit, die einen Member aufrufen.Von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Vorgänge wie das Aufrufen einer Methode 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 sprachspezifische Laufzeitausnahme ausgelöst.) /// </returns> /// <param name="binder">Stellt Informationen zum dynamischen Vorgang bereit.Die binder.Name-Eigenschaft gibt den Namen des Members an, für den der dynamische Vorgang ausgeführt wird.Für die Anweisung sampleObject.SampleMethod(100), in der sampleObject eine von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Instanz der Klasse ist, gibt binder.Name z. B. "SampleMethod" zurück.Die binder.IgnoreCase-Eigenschaft gibt an, ob der Membername die Groß-/Kleinschreibung berücksichtigt.</param><param name="args">Die Argumente, die während des Aufrufvorgangs an den Objektmember übergeben werden.Für die Anweisung sampleObject.SampleMethod(100), in der sampleObject von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitet ist, entspricht <paramref name="args[0]"/> z. B. 100.</param><param name="result">Das Ergebnis des Memberaufrufs.</param> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { bool retVal = false; result = null; try { MethodInfo method = FindMethod(binder.Name, args); if (method != null) { result = method.Invoke(null, args); retVal = true; } else if (wrapped.Value != null) { retVal = wrapped.Value.TryInvokeMember(binder, args, out result); } } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } return(retVal); }
private void ConnectToHub() { try { hubClient = hubFactory.CreateConnection(); hubClient.MessageArrived += ClientInvokation; hubClient.OperationalChanged += ConnectedChanges; if (initCalled) { hubClient.Initialize(); } } catch (Exception ex) { LogEnvironment.LogEvent($"Error connecting to hub: {ex.OutlineException()}", LogSeverity.Warning); throw; } finally { if (!hubClient.Operational && initCalled) { reconnector.Change(reconnectTimeout, reconnectTimeout); } else { reconnector.Change(Timeout.Infinite, Timeout.Infinite); } } }
/// <summary> /// Gets an available Database Connection from the pool of available connections /// </summary> /// <param name="useTransaction">indicates whether to begin a transaction for the returned database connection</param> /// <param name="database">the database that is available for usage</param> /// <returns>a connection that is unused at the moment</returns> public IResourceLock AcquireConnection(bool useTransaction, out IDbWrapper database) { while (!disposed) { try { database = factory.LoadPlugin <IDbWrapper>("dummy", databaseConstructor, false); ITransaction trans = null; if (useTransaction) { trans = database.AcquireTransaction(); } OnConnectionAcquiring(database); return(new ResourceDisposer(database, trans)); } catch (Exception ex) { LogEnvironment.LogEvent(ex.Message, LogSeverity.Error, "DataAccess"); } } database = null; return(null); }
public static TypeDescriptor[] DescribeAssembly(string assemblyName, Action <Type, TypeDescriptor> analyzeType = null, Action <ConstructorInfo, ConstructorDescriptor> analyzeConstructor = null, Action <ParameterInfo, ConstructorParameterDescriptor> analyzeParameter = null) { int objectId = 1; try { var plug = typeof(IPlugin); var location = AssemblyResolver.ResolveAssemblyLocation(assemblyName, out var exists); if (exists) { using (AssemblyResolver.AcquireTemporaryLoadContext(out var isolatedContext)) { Assembly analyzed = isolatedContext.LoadFromAssemblyPath(Path.GetFullPath(location)); //Assembly.LoadFrom(assemblyName); var pluginTypes = (from t in analyzed.GetTypes() where plug.IsAssignableFrom(t) && !t.IsAbstract select t); return((from t in pluginTypes select DescribeType(t, ref objectId, analyzeType, analyzeConstructor, analyzeParameter)).ToArray()); } } } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error, "PluginSystem"); } return(null); }
public override Task <RegisterServiceResponseMessage> RegisterService(RegisterServiceMessage request, DataTransferContext context) { try { if (string.IsNullOrEmpty(request.ResponderFor)) { CheckAuth(context, "ActAsService"); TemporaryGrants.RegisterService(request.ServiceName, context.Identity.Name); } else { CheckAuth(context, "ConnectAnyService", request.ResponderFor); TemporaryGrants.GrantTemporaryPermission(request.ResponderFor, request.ServiceName); } return(base.RegisterService(request, context)); } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); return(Task.FromResult(new RegisterServiceResponseMessage { Ok = false, Reason = ex.Message })); } }
/// <summary> /// Unwraps a file and requests for each entry a new stream providing the inner entryname /// </summary> /// <param name="file">the wrapped file</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(string file, Func <string, Stream> getStreamForFileCallback, out FileMap unwrappedFiles) { try { using (FileStream fst = new FileStream(file, FileMode.Open, FileAccess.Read)) { if (getStreamForFileCallback != null) { unwrappedFiles = UnwrapZip(fst, ".", true, n => getStreamForFileCallback(n.ArchiveFileName)); } else { unwrappedFiles = UnwrapZip(fst, ".", true); } return(true); } } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } unwrappedFiles = null; return(false); }
/// <summary> /// Checks whether the given service is available /// </summary> /// <param name="serviceName">the name of the service</param> /// <returns>a value indicating whether the requested service is available</returns> public bool DiscoverService(string serviceName) { ServiceDiscoverResponseMessage ret = null; try { ret = client.DiscoverService(new ServiceDiscoverMessage { TargetService = serviceName }); } catch (RpcException ex) { LogEnvironment.LogEvent($"Discovery on {serviceAddr} for {serviceName} failed.", LogSeverity.Warning); ret = new ServiceDiscoverResponseMessage { Ok = false, Reason = ex.Message }; } if (!ret.Ok) { LogEnvironment.LogEvent($"Service not available: {ret.Reason}", LogSeverity.Warning); } return(ret.Ok); }
/// <summary> /// Maps the data of the dynamicResult instance into the T - Instance /// </summary> /// <param name="item">the item that contains the original data</param> /// <param name="target">the target instance into which the data is mapped</param> /// <param name="modelType">the meta-type used to identify mapped columns</param> public static void ToModel(this DynamicResult item, object target, Type modelType) { string[] fieldNames = item.GetDynamicMemberNames().ToArray(); MapRule[] rules = DbColumnAttribute.GetRules(modelType).Clone() as MapRule[]; for (int i = 0; i < rules.Length; i++) { MapRule r = rules[i]; if (r != null && fieldNames.Any(n => n.Equals(r.FieldName, StringComparison.OrdinalIgnoreCase)))//Array.IndexOf(fieldNames, r.FieldName.ToLower()) != -1)))) { try { object val = item[r.FieldName]; if (!r.UseExpression) { r[target] = val; } else { r[target] = ProcessResolveExpression(r.ValueResolveExpression, val); } } catch (Exception ex) { LogEnvironment.LogEvent(string.Format("Failed to set value{1}{0}", ex.OutlineException(), Environment.NewLine), LogSeverity.Warning, "DataAccess"); } } else if (r != null) { LogEnvironment.LogDebugEvent($"No Value found for MapRule {r.FieldName} ({r.UseExpression};{r.ValueResolveExpression}", LogSeverity.Report); } } }
/// <summary> /// Works tasks that need to be done /// </summary> private static void Work() { lock (initializer) { exit.Reset(); } while (!exit.WaitOne(50)) { bool foundTask = false; lock (subSequentTasks) { foundTask |= subSequentTasks.Count != 0; foreach ( ActionPackage a in subSequentTasks.Where( n => DateTime.Now.Subtract(n.LastExecution).TotalMilliseconds > n.TimeoutInMilliseconds && !n.Queued)) { a.Queued = true; ThreadPool.QueueUserWorkItem(o => { try { a.Action(); } catch (Exception ex) { LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error); } finally { a.LastExecution = DateTime.Now; a.Queued = false; } }); } } if (!foundTask) { lock (initializer) { DateTime now = DateTime.Now; if (now.Subtract(lastActualUsage).TotalSeconds > 10) { initialized = false; break; } } continue; } lastActualUsage = DateTime.Now; } }
/// <summary> /// Writes all buffered bytes into the base stream /// </summary> public override void Flush() { string line = null; while ((line = FindNextLine()) != null) { LogEnvironment.LogEvent(line, severity); } }
/// <summary> /// Sends a manual alert using the default alerting-path /// </summary> /// <param name="e">the information about the changed entity</param> public static void Alert(EntityChangedEventArgs e) { try { OnEntityChanged(e); } catch (Exception ex) { LogEnvironment.LogEvent($"Error when trying to alert an entity-change: {ex.OutlineException()}", LogSeverity.Error); } }
/// <summary> /// Initializes all Event-Dumpers /// </summary> /// <param name="dumper">the dumper that will write the collected events of this listener</param> private void TryFinalizeDumper(IParserEventDumper dumper) { try { dumper.FinalizeEventDump(); } catch (Exception ex) { LogEnvironment.LogEvent(ex.OutlineException(), LogSeverity.Error); } }
public override void CopyTableData(string src, string dst, bool ignoreMissingColumn = false, bool whatIf = false) { var srcColumns = DescribeTable(src, false, out _); var dstColumns = DescribeTable(dst, false, out _); var diff = DynamicTableHelper.CompareDefinitions(srcColumns, dstColumns); List <string> columns = new List <string>(); foreach (var item in diff) { if (item.Table2Def == null && !ignoreMissingColumn) { if (!whatIf) { throw new InvalidOperationException("CopyJob with possible loss of data is not supported!"); } else { LogEnvironment.LogEvent("CopyJob would fail due to data-loss!", LogSeverity.Error, "ITVComponents.EFRepo.SqlServer.SqlDynamicDataAdapter"); } } if (item.Table1Def != null && item.Table2Def != null) { columns.Add($"[{item.ColumnName}]"); if (!item.Table1Def.DataType.Equals(item.Table2Def.DataType, StringComparison.OrdinalIgnoreCase)) { if (!whatIf) { throw new InvalidOperationException("Changing the DataType is not supported!"); } else { LogEnvironment.LogEvent("CopyJob would fail due to non-equal Data-Types between source and destination-table!", LogSeverity.Error, "ITVComponents.EFRepo.SqlServer.SqlDynamicDataAdapter"); } } } } var joinedColumns = string.Join(", ", columns); var rawQuery = $"insert into [{dst}] ({joinedColumns}) select {joinedColumns} from [{src}]"; if (!whatIf) { using (Facade.UseConnection(out DbCommand cmd)) { cmd.CommandText = rawQuery; cmd.ExecuteNonQuery(); } } else { LogEnvironment.LogEvent($"CopyJob would execute the following SQL-Command: {{{rawQuery}}}", LogSeverity.Error, "ITVComponents.EFRepo.SqlServer.SqlDynamicDataAdapter"); } }
/// <summary> /// Sends a tick request to the service /// </summary> /// <param name="state">nothing</param> private void SendTick(object?state) { try { client.ServiceTick(session); } catch (RpcException ex) { LogEnvironment.LogEvent($"Connection problems... {ex.Message}", LogSeverity.Error); LostConnection(); } }
/// <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> /// 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); } }); }
/// <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); } }
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> /// 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> /// 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> /// 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); } }; }