public static List <Type> LoadImplementations(this Type type, string binariesDirectory, bool excludeAbstractTypes, bool validateReferences = true) { List <Type> types = new List <Type>(); // Use application install directory for application. if (string.IsNullOrEmpty(binariesDirectory)) { binariesDirectory = FilePath.GetAbsolutePath(""); } // Loop through all files in the binaries directory. foreach (string bin in FilePath.GetFileList(binariesDirectory)) { // Only process DLLs and EXEs. if (!(string.Compare(FilePath.GetExtension(bin), ".dll", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(FilePath.GetExtension(bin), ".exe", StringComparison.OrdinalIgnoreCase) == 0)) { continue; } try { // Load the assembly in the current app domain. Assembly asm = Assembly.LoadFrom(bin); if (!validateReferences || asm.TryLoadAllReferences()) { // Process only the public types in the assembly. foreach (Type asmType in asm.GetExportedTypes()) { if (excludeAbstractTypes && asmType.IsAbstract) { continue; } // Either the current type is not abstract or it's OK to include abstract types. if (type.IsClass && asmType.IsSubclassOf(type)) { types.Add(asmType); // The type being tested is a class and current type derives from it. } if (type.IsInterface && asmType.GetInterface(type.FullName) is not null) { types.Add(asmType); // The type being tested is an interface and current type implements it. } if (type.GetRootType() == typeof(Attribute) && asmType.GetCustomAttributes(type, true).Length > 0) { types.Add(asmType); // The type being tested is an attribute and current type has the attribute. } } } } catch (Exception ex) { // Absorb any exception thrown while processing the assembly. LibraryEvents.OnSuppressedException(typeof(TypeExtensions), new Exception($"Type load exception: {ex.Message}", ex)); } } return(types); // Return the matching types found. }
/// <summary> /// Determines if the specified UDP destination is listening for data. /// </summary> /// <param name="targetIPEndPoint">The <see cref="IPEndPoint"/> for the UDP destination to be checked.</param> /// <returns>true if the UDP destination is listening for data; otherwise false.</returns> public static bool IsDestinationReachable(IPEndPoint targetIPEndPoint) { try { // Check if the target endpoint exists by sending empty data to it and waiting for a response, // if the endpoint doesn't exist then we'll receive a ConnectionReset socket exception EndPoint targetEndPoint = targetIPEndPoint; using Socket targetChecker = new Socket(targetIPEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp) { ReceiveTimeout = 1 }; targetChecker.SendTo(Array.Empty <byte>(), targetEndPoint); targetChecker.ReceiveFrom(Array.Empty <byte>(), ref targetEndPoint); } catch (SocketException ex) { // Connection reset means that the target endpoint is unreachable if (ex.SocketErrorCode == SocketError.ConnectionReset) { return(false); } } catch (Exception ex) { // We'll ignore any other exceptions we might encounter and assume destination is reachable LibraryEvents.OnSuppressedException(typeof(Transport), new InvalidOperationException($"Failed while checking if IP end point destination is reachable via UDP: {ex.Message}", ex)); } return(true); }
/// <summary> /// Resets <see cref="TransportProvider{T}"/>. /// </summary> public void Reset() { ReceiveBuffer = null; SendBuffer = null; BytesReceived = -1; // Reset the statistics. Statistics.Reset(); // Cleanup the provider. try { if (Provider is IDisposable provider) { provider.Dispose(); } } catch (Exception ex) { // Ignore encountered exception during dispose. LibraryEvents.OnSuppressedException(this, ex); } finally { Provider = default !;
private List <Type> LoadNewAssemblies() { List <Type> types = new List <Type>(); try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (m_loadedAssemblies.Contains(assembly)) { continue; } m_loadedAssemblies.Add(assembly); if (!assembly.IsDynamic) { FindAllModules(types, assembly); } } } catch (Exception ex) { LibraryEvents.OnSuppressedException(this, new Exception($"Static constructor exception: {ex.Message}", ex)); } return(types); }
private void FindAllTypes(List <Type> newlyFoundObjects, Module module) { Type[] types; try { types = module.GetTypes(); } catch (ReflectionTypeLoadException ex) { // Since its possible that during enumeration, the GetTypes method can error, this will allow us // to enumerate the types that did not error. LibraryEvents.OnSuppressedException(this, new Exception($"Reflection load exception: {ex.Message}", ex)); types = ex.Types; } foreach (Type assemblyType in types) { try { if (assemblyType is not null) { newlyFoundObjects.Add(assemblyType); } } catch (Exception ex) { LibraryEvents.OnSuppressedException(this, new Exception($"Static constructor exception: {ex.Message}", ex)); } } }
private static bool TryLoadAllReferences(Assembly assembly, ISet <string> validNames) { try { // Base case: all referenced assemblies' names are present in the set of valid names IEnumerable <AssemblyName> referencedAssemblyNames = assembly.GetReferencedAssemblies() .Where(referencedAssemblyName => !validNames.Contains(referencedAssemblyName.ToString())); // Load each referenced assembly and recursively load their references as well foreach (AssemblyName referencedAssemblyName in referencedAssemblyNames) { Assembly referencedAssembly = Assembly.Load(referencedAssemblyName); validNames.Add(referencedAssemblyName.ToString()); if (!TryLoadAllReferences(referencedAssembly, validNames)) { return(false); } } // All referenced assemblies loaded successfully return(true); } catch (Exception ex) { LibraryEvents.OnSuppressedException(typeof(AssemblyExtensions), new Exception($"TryLoadAllReferences exception: {ex.Message}", ex)); // Error loading a referenced assembly return(false); } }
public void RemoveEvent(int id) { using (LinqToSqlDataContext dataContext = new LinqToSqlDataContext()) { LibraryEvents removedEvent = dataContext.LibraryEvents.FirstOrDefault(ev => ev.ID == id); dataContext.LibraryEvents.DeleteOnSubmit(removedEvent); dataContext.SubmitChanges(); } }
public void UpdateEvent(int id, DateTime time, int stateId, int userId, bool isBorrowingEvent) { using (LinqToSqlDataContext dataContext = new LinqToSqlDataContext()) { LibraryEvents updatedEvent = dataContext.LibraryEvents.FirstOrDefault(ev => ev.ID == id); updatedEvent.Time = time; updatedEvent.StateId = stateId; updatedEvent.UserId = userId; updatedEvent.isBorrowingEvent = isBorrowingEvent; dataContext.SubmitChanges(); } }
private void TryHandleException(Exception ex) { void SuppressException(Exception suppressedException) { string message = $"Synchronized operation exception handler exception: {suppressedException.Message}"; AggregateException aggregateException = new AggregateException(message, suppressedException, ex); LibraryEvents.OnSuppressedException(this, aggregateException); } try { ExceptionHandler?.Invoke(ex); } catch (Exception handlerException) { SuppressException(handlerException); } }
public int AddEvent(DateTime time, int stateId, int userId, bool isBorrowingEvent) { using (LinqToSqlDataContext dataContext = new LinqToSqlDataContext()) { LibraryEvents newEvent = new LibraryEvents { Time = time, StateId = stateId, UserId = userId, isBorrowingEvent = isBorrowingEvent }; dataContext.LibraryEvents.InsertOnSubmit(newEvent); dataContext.SubmitChanges(); return(newEvent.ID); } }
public Cipher() { const string FipsKeyOld = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Lsa"; const string FipsKeyNew = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\FipsAlgorithmPolicy"; // Determine if the user needs to use FIPS-compliant algorithms try { SystemAllowsManagedEncryption = (Registry.GetValue(FipsKeyNew, "Enabled", 0) ?? Registry.GetValue(FipsKeyOld, "FIPSAlgorithmPolicy", 0)).ToString() == "0"; } catch (Exception ex) { SystemAllowsManagedEncryption = true; LibraryEvents.OnSuppressedException(this, new Exception($"Cipher FIPS compliance lookup exception: {ex.Message}", ex)); } }
private void FindAllModules(List <Type> types, Assembly assembly) { Module[] modules = assembly.GetModules(false); foreach (Module module in modules) { try { FindAllTypes(types, module); } catch (Exception ex) { LibraryEvents.OnSuppressedException(this, new Exception($"Static constructor exception: {ex.Message}", ex)); } } }
/// <summary> /// Processes an exception thrown by an operation. /// </summary> /// <param name="ex"><see cref="Exception"/> to be processed.</param> protected void ProcessException(Exception ex) { if (m_exceptionAction == null) { LibraryEvents.OnSuppressedException(this, new Exception($"Synchronized operation exception: {ex.Message}", ex)); } else { try { m_exceptionAction(ex); } catch (Exception handlerEx) { LibraryEvents.OnSuppressedException(this, new Exception($"Synchronized operation exception handler exception: {handlerEx.Message}", new AggregateException(handlerEx, ex))); } } }
/// <summary> /// Gets the default IP stack for this system. /// </summary> /// <returns> /// System's assumed default IP stack. /// </returns> public static IPStack GetDefaultIPStack() { try { IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); // IP's are normally ordered with default IP stack first if (hostEntry.AddressList.Length > 0) { return(hostEntry.AddressList[0].AddressFamily == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6 ? IPStack.IPv6 : IPStack.IPv4); } } catch (Exception ex) { LibraryEvents.OnSuppressedException(typeof(Transport), new InvalidOperationException($"DNS lookup failure for local machine: {ex.Message}", ex)); } // If default stack cannot be determined, assume IPv4 return(IPStack.IPv4); }
private static Task[]? InvokeEventHandlers <TEventHandler, TEventArgs>(TEventHandler?eventHandler, object?eventLock, Action <Exception, Delegate>?exceptionHandler, object sender, TEventArgs args, InvokeMode invokeMode) where TEventHandler : MulticastDelegate where TEventArgs : EventArgs { if (eventHandler is null) { return(null); } Delegate[] handlers; lock (eventLock ?? eventHandler) handlers = eventHandler.GetInvocationList(); void invokeHandler(Delegate handler) { switch (handler) { case EventHandler simpleHandler: try { simpleHandler.Invoke(sender, args); } catch (Exception ex) { if (exceptionHandler is null) { LibraryEvents.OnSuppressedException(typeof(EventHandlerExtensions), new Exception($"SafeInvoke caught exception in {typeof(TEventHandler).FullName} event handler \"{handler.GetHandlerName()}\": {ex.Message}", ex)); } else { exceptionHandler(ex, simpleHandler); } } break; case EventHandler <TEventArgs> typedHandler: try { typedHandler.Invoke(sender, args); } catch (Exception ex) { if (exceptionHandler is null) { LibraryEvents.OnSuppressedException(typeof(EventHandlerExtensions), new Exception($"SafeInvoke caught exception in {typeof(TEventHandler).FullName} event handler \"{handler.GetHandlerName()}\": {ex.Message}", ex)); } else { exceptionHandler(ex, typedHandler); } } break; default: try { handler.DynamicInvoke(sender, args); } catch (Exception ex) { if (exceptionHandler is null) { LibraryEvents.OnSuppressedException(typeof(EventHandlerExtensions), new Exception($"SafeInvoke caught exception in {typeof(TEventHandler).FullName} event handler \"{handler.GetHandlerName()}\": {ex.Message}", ex)); } else { exceptionHandler(ex, handler); } } break; } } // Safely iterate each attached handler, continuing on possible exception, so no handlers are missed switch (invokeMode) { case InvokeMode.InvokeAsync: return(handlers.Select(handler => Task.Run(() => invokeHandler(handler))).ToArray()); case InvokeMode.InvokeParallel when handlers.Length > 1: Parallel.ForEach(handlers, invokeHandler); break; default: foreach (Delegate handler in handlers) { invokeHandler(handler); } break; } return(null); }
private void Callback(object state) { if (m_disposed) { return; } ShortTime fireTime = ShortTime.Now; bool lockTaken = false; try { Monitor.TryEnter(m_syncRunning, 0, ref lockTaken); if (!lockTaken) { lock (m_syncStats) m_skippedIntervals++; return; } DateTime fireTimeDatetime = fireTime.UtcTime; int loopCount = 0; LinkedListNode <WeakAction <DateTime> > timerAction = m_callbacks.First; while (timerAction != null) { if (m_disposed) { return; } // Removing the linked list item will invalidate the "Next" property, so we store it LinkedListNode <WeakAction <DateTime> > nextNode = timerAction.Next; try { if (!timerAction.Value.TryInvoke(fireTimeDatetime)) { m_callbacks.Remove(timerAction); } } catch (Exception ex) { LibraryEvents.OnSuppressedException(this, ex); } loopCount++; timerAction = nextNode; } lock (m_syncStats) { m_sharedTimersCount = m_callbacks.Count; m_sumOfCallbacks += loopCount; m_elapsedIntervals++; m_elapsedWorkerTime += fireTime.ElapsedMilliseconds(); } WeakAction <DateTime> newCallbacks; while (m_additionalQueueItems.TryDequeue(out newCallbacks)) { m_callbacks.AddLast(newCallbacks); } if (m_callbacks.Count == 0) { lock (m_parentTimer.m_syncRoot) { while (m_additionalQueueItems.TryDequeue(out newCallbacks)) { m_parentTimer.RegisterCallback(m_interval, newCallbacks); } if (m_callbacks.Count == 0) { Dispose(); m_parentTimer.m_schedulesByInterval.Remove(m_interval); } } } } finally { if (lockTaken) { Monitor.Exit(m_syncRunning); } } }