Exemple #1
0
        public static bool TryInject(
            IServiceRegistrationProvider serviceProvider,
            object target,
            Type attributeType,
            ITrace logger = null,
            Func <Type, object> instanceProvider = null,
            bool tryConstructArguments           = false,
            bool?requireConstructorAttributes    = null,
            IReadOnlyCollection <Type> constructorAttributeTypes = null)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (attributeType == null)
            {
                throw new ArgumentNullException(nameof(attributeType));
            }
            if ((constructorAttributeTypes == null) ||
                (constructorAttributeTypes.Count == 0))
            {
                constructorAttributeTypes = new[] { typeof(ServiceProviderConstructorAttribute) }
            }
            ;
            ServiceConstructorRequest request
                = new ServiceConstructorRequest(logger ?? TraceSources.For(typeof(ServiceConstructorMethods)));

            request.Logger.Verbose(
                "Injecting '{0}' on '{1}'.",
                attributeType.GetFriendlyFullName(),
                target.GetType().GetFriendlyFullName());
            if (ServiceConstructorMethods.invokeMember(
                    ServiceConstructorMethods.findMethods(target, attributeType, request.TraceStack),
                    true,
                    target,
                    out _,
                    request,
                    serviceProvider,
                    instanceProvider,
                    tryConstructArguments,
                    requireConstructorAttributes,
                    constructorAttributeTypes,
                    false))
            {
                request.Logger.Verbose(
                    "Inject result for '{0}' on '{1}' is true.",
                    attributeType.GetFriendlyFullName(),
                    target.GetType().GetFriendlyFullName());
                return(true);
            }
            request.Logger.Info(
                "Inject result for '{0}' on '{1}' is false.",
                attributeType.GetFriendlyFullName(),
                target.GetType().GetFriendlyFullName());
            return(false);
        }
Exemple #2
0
 public void RegisterExport(Type importType, Type exportType)
 {
     if (importType == null)
     {
         throw new ArgumentNullException(nameof(importType));
     }
     if (exportType == null)
     {
         throw new ArgumentNullException(nameof(exportType));
     }
     if (!typeof(TExport).IsAssignableFrom(exportType))
     {
         throw new ArgumentException(typeof(TExport).GetFriendlyFullName(), nameof(exportType));
     }
     lock (Registrations) {
         if (Registrations.ContainsKey(importType))
         {
             throw new InvalidOperationException(
                       $"Cannot add duplicate registration for '{importType.GetFriendlyFullName()}'.");
         }
         if (!OnRegisterExport(importType, exportType))
         {
             return;
         }
         TraceSources.For(GetType())
         .Verbose(
             $"{nameof(ExportRegistry<TExport>.RegisterExport)}:"
             + " '{0}' for '{1}'.",
             exportType.GetFriendlyFullName(),
             importType.GetFriendlyFullName());
         Registrations[importType] = exportType;
     }
 }
Exemple #3
0
        private void refresh(FileSystemEventArgs fileSystemEventArgs)
        {
            Exception exception;

            lock (syncLock) {
                if (isDisposed)
                {
                    if (fileSystemEventArgs == null)
                    {
                        throw new ObjectDisposedException(ToString());
                    }
                    return;
                }
                disposeFileSystemWatcher();
                tryCreateFileSystemWatcher(out exception);
                if (exception != null)
                {
                    TraceSources.For <DirectoryWatcher>()
                    .Error("Local Error for {0}: {1}.", exception, this, exception.Message);
                }
                else if ((fileSystemEventArgs == null) ||
                         !IsWatchingPath)
                {
                    return;
                }
            }
            Changed?.Invoke(this, new DirectoryWatcherEventArgs(fileSystemEventArgs, exception));
        }
Exemple #4
0
        /// <summary>
        /// Invokes the <see cref="TraceSources"/> factory method with a delegate
        /// that adds a verbose console trace listener to all sources.
        /// </summary>
        /// <returns>Dispose to reset the default factory.</returns>
        public static IDisposable TraceAllVerbose()
        {
            void Configure(SimpleTraceSource traceSource)
            {
                traceSource.TraceSource.TryAdd(
                    new Diagnostics.ConsoleTraceListener
                {
                    Filter = new EventTypeFilter(SourceLevels.All),
                });
                traceSource.TraceSource.Switch.Level = SourceLevels.All;
            }

            void Remove(SimpleTraceSource traceSource)
            => traceSource.TraceSource.Listeners.Remove(Diagnostics.ConsoleTraceListener.DefaultName);

            DelegateTraceSourceSelector selector = new DelegateTraceSourceSelector(Configure, Remove);

            TraceSources.AddSelector(selector);
            TraceSources.For(typeof(TestHelper))
            .Verbose("TraceSources are verbose.");
            void Dispose()
            => TraceSources.RemoveSelector(selector);

            return(DelegateDisposable.With(Dispose));
        }
Exemple #5
0
 /// <summary>
 /// This method is virtual and implements
 /// <see cref="IHandleComposed{TTarget}.HandleComposed{T}"/>.
 /// This implementation invokes all participants added here.
 /// Notice that each is invoked in a catch block, and this will trace exceptions,
 /// AND re-throw a new <see cref="AggregateException"/> if there are
 /// any exceptions.
 /// </summary>
 /// <param name="eventArgs"><see cref="IHandleComposed{TTarget}"/> argument.</param>
 /// <exception cref="AggregateException"></exception>
 public void HandleComposed <T>(ComposerEventArgs <T> eventArgs)
     where T : TTarget
 {
     lock (Participants) {
         checkDisposed();
         List <Exception> exceptions = new List <Exception>(Participants.Count);
         foreach (IHandleComposed <TTarget> participant
                  in Participants.OfType <IHandleComposed <TTarget> >())
         {
             try {
                 participant.HandleComposed(eventArgs);
             } catch (Exception exception) {
                 TraceSources.For(GetType())
                 .Error(
                     exception,
                     "Participant exception invoking HandleComposed: {0}, '{1}'.",
                     participant,
                     exception.Message);
                 exceptions.Add(exception);
             }
         }
         if (exceptions.Count != 0)
         {
             throw new AggregateException(
                       $"One or more exceptions was raised by a {GetType().GetFriendlyName()} participant in"
                       + $" {nameof(IHandleComposed<TTarget>.HandleComposed)}.",
                       exceptions.EnumerateInReverse());
         }
     }
 }
Exemple #6
0
        protected sealed override void WithAllParts(ContainerConfiguration target)
        {
            Action Mutate(MultiDictionary <CompositionHost, object> exportsList)
            {
                try {
                    CompositionHost compositionHost = target.CreateContainer();
                    List <object>   newExports      = new List <object>();
                    foreach (Type compositionContract in ExportTypes)
                    {
                        newExports.AddRange(compositionHost.GetExports(compositionContract));
                    }
                    Action OnMutate(List <object> list)
                    => handleNewExports(list, newExports);

                    return(handleMutate(exportsList, OnMutate, compositionHost));
                } catch (Exception exception) {
                    TraceSources.For <MefSingletonComposer>()
                    .Error(
                        exception,
                        "Catching exception refreshing Exports: {0}",
                        exception.Message);
                    throw;
                }
            }

            exports.Mutate(Mutate)
            ?.Invoke();
        }
Exemple #7
0
        /// <summary>
        /// This virtual method provides the implementation for
        /// <see cref="IProvideParts{TTarget}"/>.
        /// This enumerates the files on the <see cref="DirectoryWatcher"/> with the
        /// <see cref="SearchOption"/>, and loads each path with <see cref="TryLoadAssembly"/>.
        /// This method catches and traces all exceptions; and also provides support for
        /// <see cref="ProvideAssembliesOneTimeOnly"/>.
        /// </summary>
        public virtual void ProvideParts <T>(ProvidePartsEventArgs <T> eventArgs)
            where T : ContainerConfiguration
        {
            List <Assembly> assemblies = new List <Assembly>();

            if (DirectoryWatcher.PathExists)
            {
                try {
                    foreach (string filePath in Directory.EnumerateFiles(
                                 DirectoryWatcher.Path,
                                 DirectoryWatcher.Filter,
                                 SearchOption))
                    {
                        if (TryLoadAssembly(filePath, out Assembly assembly))
                        {
                            assemblies.Add(assembly);
                        }
                    }
                } catch (Exception exception) {
                    TraceSources.For <MefDirectoryPartWatcher>()
                    .Warning(
                        exception,
                        "Catching exception enumerating files in the watched directory: '{0}'.",
                        exception.Message);
                }
            }
            if (assemblies.Count == 0)
            {
                return;
            }
            lock (ComposedAssemblies) {
                if (ProvideAssembliesOneTimeOnly)
                {
                    foreach (Assembly assembly in new List <Assembly>(assemblies))
                    {
                        if (!ComposedAssemblies.Contains(assembly))
                        {
                            ComposedAssemblies.Add(assembly);
                        }
                        else
                        {
                            assemblies.Remove(assembly);
                        }
                    }
                    if (assemblies.Count == 0)
                    {
                        return;
                    }
                }
            }
            if (Conventions != null)
            {
                eventArgs.Target.WithAssemblies(assemblies, Conventions);
            }
            else
            {
                eventArgs.Target.WithAssemblies(assemblies);
            }
        }
Exemple #8
0
        private void trySetPropertiesFromConfigFile()
        {
            string configFilePath = GetConfigFileFullPath();

            if (File.Exists(configFilePath))
            {
                try {
                    LogFileFactoryConfig newLogFileFactoryConfig
                        = LogFileFactoryConfig.LoadFromFile(configFilePath);
                    bool resetIsInitializing = false;
                    try {
                        lock (SyncLock) {
                            resetIsInitializing = !isInitializing;
                            isInitializing      = true;
                        }
                        newLogFileFactoryConfig.SetPropertiesOn(this);
                    } finally {
                        lock (SyncLock) {
                            logFileFactoryConfig = newLogFileFactoryConfig;
                            if (resetIsInitializing)
                            {
                                isInitializing = false;
                            }
                        }
                    }
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Info(
                        "Found {0} file found at '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        logFileFactoryConfig);
                } catch (Exception exception) {
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Error(
                        exception,
                        "Invalid {0} file found at '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        exception.Message);
                }
            }
            else
            {
                try {
                    Directory.CreateDirectory(GetLogFolderPath());
                    LogFileFactoryConfig.CreateFrom(this, out XmlDocument xmlDocument);
                    File.WriteAllText(configFilePath, xmlDocument.InnerXml);
                } catch (Exception exception) {
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Error(
                        exception,
                        "Error writing {0} file to '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        exception.Message);
                }
            }
        }
Exemple #9
0
 private void handleConfigWatcherError(object sender, ErrorEventArgs e)
 => TraceSources.For <LogFileFactory>()
 .Error(
     e.GetException(),
     "{0} error for config file watcher at '{1}' - '{2}'.",
     nameof(FileSystemWatcher),
     Path.Combine(GetLogFolderPath(), GetConfigFileName()),
     e.GetException()
     .Message);
Exemple #10
0
 private void traceAction(string message)
 {
     TraceSources.For(TraceFileFactoryAssembly)
     .Warning($"##########    ####    {message}    ####    ##########");
     Trace.TraceWarning(
         "##########    ####    "
         + $"{message} For: {TraceFileFactoryAssembly.GetName().Name}."
         + "    ####    ##########");
     FlushAll();
 }
Exemple #11
0
        private void handleFileSystemWatcherError(object sender, ErrorEventArgs errorEventArgs)
        {
            Exception exception = errorEventArgs.GetException();

            TraceSources.For <DirectoryWatcher>()
            .Warning(
                exception,
                $"{nameof(FileSystemWatcher)} Error for {{0}}: {{1}}.",
                this,
                exception.Message);
            FileSystemWatcherError?.Invoke(this, errorEventArgs);
        }
Exemple #12
0
 private void tryCreateFileSystemWatcher(out Exception exception)
 {
     try {
         string path = Path;
         do
         {
             if (Directory.Exists(path))
             {
                 break;
             }
             path = System.IO.Path.GetDirectoryName(PathHelper.RemoveTrailingSeparators(path));
             if (!string.IsNullOrWhiteSpace(path))
             {
                 continue;
             }
             throw new NotSupportedException($"Failed to create {nameof(FileSystemWatcher)} for {this}.");
         } while (true);
         fileSystemWatcher = PathHelper.IsSameFullPath(Path, path)
                                         ? new FileSystemWatcher
         {
             Path   = Path,
             Filter = Filter,
             IncludeSubdirectories = IncludeSubdirectories,
             NotifyFilter          = NotifyFilter,
             EnableRaisingEvents   = true
         }
                                         : new FileSystemWatcher
         {
             Path   = path,
             Filter = "*",
             IncludeSubdirectories = true,
             NotifyFilter          = NotifyFilters.LastWrite
                                     | NotifyFilters.DirectoryName,
             EnableRaisingEvents = true
         };
         fileSystemWatcher.Changed += handleFileSystemWatcherChanged;
         fileSystemWatcher.Created += handleFileSystemWatcherChanged;
         fileSystemWatcher.Deleted += handleFileSystemWatcherChanged;
         fileSystemWatcher.Renamed += handleFileSystemWatcherChanged;
         fileSystemWatcher.Error   += handleFileSystemWatcherError;
         exception = null;
     } catch (Exception error) {
         TraceSources.For <DirectoryWatcher>()
         .Error(
             error,
             "Failed to refresh {0}: {1}. Not watching any folder.",
             this,
             error.Message);
         fileSystemWatcher?.Dispose();
         fileSystemWatcher = null;
         exception         = error;
     }
 }
Exemple #13
0
 /// <summary>
 /// This protected virtual method loads each Assembly. If a delegate was provided, that
 /// is invoked here; and otherwise, this loads the Assembly with <c>Assembly.LoadFrom</c>.
 /// This is invoked in <see cref="ProvideParts{T}"/>. This method catches and traces all
 /// exceptions.
 /// </summary>
 /// <param name="filePath">Not null.</param>
 /// <param name="assembly">Not null if the method returns true.</param>
 /// <returns>True if the out argument is not null.</returns>
 protected virtual bool TryLoadAssembly(string filePath, out Assembly assembly)
 {
     try {
         assembly = loadAssembly != null
                                         ? loadAssembly(filePath)
                                         : Assembly.LoadFrom(filePath);
     } catch (Exception exception) {
         TraceSources.For <MefDirectoryPartWatcher>()
         .Warning(
             exception,
             "Failed to load Assembly from '{0}': {1}.",
             filePath,
             exception.Message);
         assembly = null;
     }
     return(assembly != null);
 }
Exemple #14
0
        private void setupTracingUnsafe()
        {
            bool resetIsInitializing = false;

            try {
                lock (SyncLock) {
                    if (!isInitialized ||
                        isInitializing)
                    {
                        return;
                    }
                    isInitializing      = true;
                    resetIsInitializing = true;
                }
                TraceSources.For(TraceFileFactoryAssembly)
                .Info("Configure tracing.");
                HandleBeginSetupTracing();
                disposeResources();
                if (ToggleLogFile)
                {
                    lock (SyncLock) {
                        logFileListener = CreateFileLogTraceListener();
                    }
                }
                setupConfigFileWatcher();
                if (addToTraceSources)
                {
                    TraceSources.AddSelector(this);
                }
                traceAction(
                    LogFileListener != null
                                                                ? $"{nameof(LogFileFactory)} Trace File Initialized."
                                                                : $"{nameof(LogFileFactory)} Reset With No Trace File.");
            } finally {
                if (resetIsInitializing)
                {
                    lock (SyncLock) {
                        isInitializing = false;
                    }
                }
            }
            HandleEndSetupTracing();
        }
Exemple #15
0
        private object tryGetService(
            Type serviceType,
            ServiceConstructorRequest serviceConstructorRequest)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }
            object service = serviceProvider.GetService(serviceType);

            return(serviceType.IsInstanceOfType(service)
                                        ? service
                                        : parentServiceRegistrationProvider != null
                                                        ? parentServiceRegistrationProvider.GetService(
                       serviceType,
                       serviceConstructorRequest
                       ?? new ServiceConstructorRequest(
                           TraceSources.For <ServiceRegistrationProviderWrapper>()))
                                                        : ParentServiceProvider?.GetService(serviceType));
        }
Exemple #16
0
 private void setupConfigFileWatcher()
 {
     lock (SyncLock) {
         if (!isInitialized)
         {
             return;
         }
         disposeConfigFileWatcher();
         if (!WatchConfigFileChanges)
         {
             return;
         }
         try {
             Directory.CreateDirectory(GetLogFolderPath());
             configFileWatcher
                 = new FileSystemWatcher(
                       GetLogFolderPath(),
                       GetConfigFileName())
                 {
                 IncludeSubdirectories = false,
                 NotifyFilter          = NotifyFilters.CreationTime
                                         | NotifyFilters.FileName
                                         | NotifyFilters.LastWrite,
                 EnableRaisingEvents = true,
                 };
             configFileWatcher.Changed += handleConfigWatcherChangeEvent;
             configFileWatcher.Created += handleConfigWatcherChangeEvent;
             configFileWatcher.Deleted += handleConfigWatcherChangeEvent;
             configFileWatcher.Error   += handleConfigWatcherError;
         } catch (Exception exception) {
             disposeConfigFileWatcher();
             TraceSources.For(TraceFileFactoryAssembly)
             .Error(
                 exception,
                 "Exception trying to watch for {0} config file changes at '{1}' - '{2}'.",
                 nameof(LogFileFactoryConfig),
                 GetConfigFileFullPath(),
                 exception.Message);
         }
     }
 }
Exemple #17
0
        /// <summary>
        /// Static helper method is used to configure optional verbose tracing.
        /// </summary>
        private static void configureTracing()
        {
            Console.WriteLine("Verbose Tracing? (Y for Yes)");
            ConsoleKey consoleKey = Console.ReadKey().Key;

            Console.WriteLine();
            if (consoleKey != ConsoleKey.Y)
            {
                return;
            }
            void Configure(SimpleTraceSource traceSource)
            {
                traceSource.TraceSource.TryAdd(
                    new Sc.Diagnostics.ConsoleTraceListener
                {
                    Filter = new EventTypeFilter(SourceLevels.All),
                });
                traceSource.TraceSource.Switch.Level = SourceLevels.All;
            }

            TraceSources.AddSelector(new DelegateTraceSourceSelector(Configure));
            TraceSources.For(typeof(Program))
            .Verbose("TraceSources are verbose.");
        }
Exemple #18
0
 private ServiceConstructorRequest newServiceConstructorRequest()
 => new ServiceConstructorRequest(TraceSources.For <BasicContainer>());
Exemple #19
0
 private void handleFileSystemWatcherChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
 {
     TraceSources.For <DirectoryWatcher>()
     .Verbose("Refreshing {0}.", this);
     refresh(fileSystemEventArgs);
 }