protected override IEnumerable <object> DoGetAllInstances(Type serviceType)
 {
     if (serviceType is null)
     {
         throw new ArgumentNullException(nameof(serviceType));
     }
     if (disposedValue)
     {
         return(Enumerable.Empty <object>());
     }
     return(_container?.GetExports(serviceType, null, null)?.Select(e => e.Value) ?? Enumerable.Empty <object>());
 }
        public static void OpenApplicationSettingsWindow(CompositionContainer container)
        {
            Messenger <MessengerMessages> .Register(MessengerMessages.OpenApplicationSettings, (args) =>
            {
                var view = container?.GetExports <ViewApplicationSettings>().Single().Value;

                view.ShowDialog();
            });
        }
        public static void ProcessFilePaths(CompositionContainer container)
        {
            Messenger <MessengerMessages> .Register(MessengerMessages.ProcessFilePaths, async (args) =>
            {
                var vm = container?.GetExports <MainViewModel>().Single().Value;

                await vm.ProcessFilePathsAsync(args as IEnumerable <string>);
            });
        }
        public static void OpenMediaPlayerMainWindow(CompositionContainer container)
        {
            Messenger <MessengerMessages> .Register(MessengerMessages.OpenMediaPlayerMainWindow, (args) =>
            {
                var view = container?.GetExports <ViewMediaPlayer>().Single().Value;

                view.Show();
            });
        }
        public static void SaveChangesToDirtyFiles(CompositionContainer container)
        {
            Messenger <MessengerMessages> .Register(MessengerMessages.SaveChangesToDirtyFiles, async (args) =>
            {
                var vm = container?.GetExports <MainViewModel>().Single().Value;

                await vm.SaveChangesAsync();

                var shutdownApplication = (bool)args;

                if (shutdownApplication)
                {
                    Application.Current.Shutdown(0);
                }
            });
        }
Beispiel #6
0
        public void Invoke(CompositionContainer container)
        {
            var traceListener = new ConsolidatedConsoleTraceListener(
                new Dictionary <string, string>
            {
                {
                    "LostDoc.Core.Template",
                    "Template"
                },
                {
                    "LostDoc.Core.Bundle",
                    "Bundle"
                },
                {
                    "LostDoc.Core.Template.AssetResolver",
                    "Resolve"
                }
            });


            TraceSources.TemplateSource.Listeners.Add(traceListener);
            TraceSources.AssetResolverSource.Listeners.Add(traceListener);
            try
            {
                if (this.Quiet.IsPresent)
                {
                    const SourceLevels quietLevel = SourceLevels.Error | SourceLevels.Warning | SourceLevels.Critical;
                    TraceSources.TemplateSource.Switch.Level      = quietLevel;
                    TraceSources.AssetResolverSource.Switch.Level = quietLevel;
                    TraceSources.BundleSource.Listeners.Add(traceListener);
                }
                else if (this.Verbose.IsPresent)
                {
                    const SourceLevels verboseLevel = SourceLevels.All;
                    TraceSources.TemplateSource.Switch.Level      = verboseLevel;
                    TraceSources.AssetResolverSource.Switch.Level = verboseLevel;
                    TraceSources.BundleSource.Listeners.Add(traceListener);
                }
                else
                {
                    const SourceLevels normalLevel = SourceLevels.Information | SourceLevels.Warning | SourceLevels.Error | SourceLevels.ActivityTracing;
                    TraceSources.TemplateSource.Switch.Level      = normalLevel;
                    TraceSources.AssetResolverSource.Switch.Level = normalLevel;
                }

                LinkedList <FileInfo> includedFiles = new LinkedList <FileInfo>();

                if (File.Exists(this.Path))
                {
                    includedFiles.AddLast(new FileInfo(this.Path));
                }
                else if (Directory.Exists(this.Path))
                {
                    Directory.GetFiles(this.Path, "*.ldoc", SearchOption.AllDirectories)
                    .Aggregate(includedFiles,
                               (l, f) => l.AddLast(new FileInfo(f)).List);
                }
                else
                {
                    throw new FileNotFoundException(System.IO.Path.GetFullPath(this.Path));
                }


                Bundle bundle = new Bundle(this.IgnoreVersionComponent);

                TraceSources.TemplateSource.TraceInformation("Merging LostDoc files into bundle.");

                foreach (FileInfo file in includedFiles)
                {
                    TraceSources.TemplateSource.TraceEvent(TraceEventType.Information, 0, "Source: {0}", file.Name);
                    XDocument fileDoc = XDocument.Load(file.FullName);

                    bundle.Add(fileDoc);
                }

                var lazyProviders = container.GetExports <IFileProvider>(ContractNames.TemplateProvider);
                var realProviders = lazyProviders.Select(lazy => lazy.Value);
                TemplateResolver templateResolver = new TemplateResolver(realProviders.ToArray());

                Template template = new Template(container);
                template.Load(templateResolver, this.Template);

                string outputDir = this.Output
                                   ?? (Directory.Exists(this.Path)
                                           ? this.Path
                                           : System.IO.Path.GetDirectoryName(this.Path));
                AssetRedirectCollection assetRedirects;
                XDocument mergedDoc = bundle.Merge(out assetRedirects);

                var templateData = new TemplateData(mergedDoc)
                {
                    AssetRedirects          = assetRedirects,
                    OverwriteExistingFiles  = this.Force.IsPresent,
                    IgnoredVersionComponent = this.IgnoreVersionComponent,
                    Arguments          = this.Arguments,
                    OutputFileProvider = new ScopedFileProvider(new DirectoryFileProvider(), outputDir)
                };

                template.Generate(templateData);
            }
            finally
            {
                TraceSources.TemplateSource.Listeners.Remove(traceListener);
                TraceSources.AssetResolverSource.Listeners.Remove(traceListener);
            }
        }
Beispiel #7
0
        private MockVsTextView CreateTextViewWorker(
            string contentType,
            string content,
            Action <MockVsTextView> onCreate,
            string file = null
            )
        {
            var buffer = new MockTextBuffer(content, ContentTypeRegistry.GetContentType(contentType), file);

            var view = new MockTextView(buffer);
            var res  = new MockVsTextView(_serviceProvider, this, view);

            view.Properties[typeof(MockVsTextView)] = res;
            onCreate?.Invoke(res);

            var classifier = res.Classifier;

            if (classifier != null)
            {
                classifier.GetClassificationSpans(new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length));
            }

            // Initialize code window
            LanguageServiceInfo info;

            if (CachedInfo.LangServicesByName.TryGetValue(contentType, out info))
            {
                var id = info.Attribute.LanguageServiceSid;
                var serviceProvider = Container.GetExportedValue <MockVsServiceProvider>();
                var langInfo        = (IVsLanguageInfo)serviceProvider.GetService(id);
                if (langInfo == null)
                {
                    throw new NotImplementedException("Unable to get IVsLanguageInfo for " + info.Attribute.LanguageName);
                }
                IVsCodeWindowManager mgr;
                var codeWindow = new MockCodeWindow(serviceProvider, view);
                view.Properties[typeof(MockCodeWindow)] = codeWindow;
                if (ErrorHandler.Succeeded(langInfo.GetCodeWindowManager(codeWindow, out mgr)))
                {
                    if (ErrorHandler.Failed(mgr.AddAdornments()))
                    {
                        Console.WriteLine("Failed to add adornments to text view");
                    }
                }
            }

            // Initialize intellisense imports
            var providers = Container.GetExports <IIntellisenseControllerProvider, IContentTypeMetadata>();

            foreach (var provider in providers)
            {
                foreach (var targetContentType in provider.Metadata.ContentTypes)
                {
                    if (buffer.ContentType.IsOfType(targetContentType))
                    {
                        provider.Value.TryCreateIntellisenseController(
                            view,
                            new[] { buffer }
                            );
                        break;
                    }
                }
            }

            // tell the world we have a new view...
            foreach (var listener in Container.GetExports <IVsTextViewCreationListener, IContentTypeMetadata>())
            {
                foreach (var targetContentType in listener.Metadata.ContentTypes)
                {
                    if (buffer.ContentType.IsOfType(targetContentType))
                    {
                        listener.Value.VsTextViewCreated(res);
                    }
                }
            }

            OnDispose(() => res.Close());
            return(res);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            if (args.Length < 0)
            {
                // click once argument data
                args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
            }

            var reset = false;

            if (args.Length <= 0)
            {
                System.Console.Write("R for RESET, Any other key to READ A FILE... ");
                var keyInfo = System.Console.ReadKey(true);
                reset = keyInfo.Key == ConsoleKey.R;
                System.Console.WriteLine();
            }

            if (reset || (args.Length > 0 && args[0] == "RESET"))
            {
                ResetSettings();
            }
            else
            {
                var connection = Authenticate();

                Interaction.Notice("USER: "******"HOST: " + Properties.Settings.Default.Host + ":" + Properties.Settings.Default.Port);

                FileInfo inputFile = null;
                if (args.Length >= 1)
                {
                    inputFile = new FileInfo(args[0]);
                }
                else
                {
                    var inputFileName = Interaction.GetText("Please enter InputFile");
                    inputFile = new FileInfo(inputFileName);
                    inputFile.Refresh();
                }

                var namePart    = Path.Combine(Path.GetDirectoryName(inputFile.FullName), Path.GetFileNameWithoutExtension(inputFile.FullName));
                var logfileName = namePart + ".log";

                Interaction.Notice("LOG : " + logfileName);

                var compositionCatalog   = new DirectoryCatalog("./Plugins", "*.dll");
                var compositionContainer = new CompositionContainer(compositionCatalog);

                var dayFilters = compositionContainer.GetExports <ITrakkrDayFilter>();
                var logFilters = compositionContainer.GetExports <ITrakkrLogFilter>();

                bool failure;
                do
                {
                    var entries = ParseEvents(inputFile);

                    entries = entries
                              .GroupBy(e => e.Timestamp.Date)
                              .SelectMany(dateGroup =>
                    {
                        var result = dateGroup.AsEnumerable();

                        foreach (var dayFilter in dayFilters)
                        {
                            result = dayFilter.Value.Filter(result, dateGroup.Key);
                        }

                        return(result);
                    });

                    foreach (var logFilter in logFilters)
                    {
                        entries = logFilter.Value.Filter(entries);
                    }

                    var logger = new FileAppendLogger(logfileName, $"Updating Workitems : {DateTime.Now:O}");

                    failure = !UpdateWorkItems(connection, entries, logger);
                }while (failure && Interaction.Confirm("Retry?"));

                if (failure)
                {
                    // do not show message when retry was declined
                    return;
                }

                Interaction.Acknowledge("Done (press any key).");
            }
        }
Beispiel #9
0
        public object GetService(Type serviceType)
        {
            var export = container.GetExports(serviceType, null, null).SingleOrDefault();

            return(null != export ? export.Value : null);
        }
Beispiel #10
0
        private IPythonInterpreterFactoryProvider[] LoadProviders(
            SettingsStore store,
            IServiceProvider serviceProvider
            )
        {
            var seen    = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var catalog = new List <ComposablePartCatalog>();

            if (store.CollectionExists(SuppressFactoryProvidersCollection))
            {
                return(new IPythonInterpreterFactoryProvider[0]);
            }

            if (store.CollectionExists(FactoryProvidersCollection))
            {
                foreach (var idStr in store.GetSubCollectionNames(FactoryProvidersCollection))
                {
                    var key = FactoryProvidersCollection + "\\" + idStr;
                    LoadOneProvider(
                        store.GetString(key, FactoryProviderCodeBaseSetting, ""),
                        seen,
                        catalog,
                        _activityLog
                        );
                }
            }

            foreach (var baseKey in new[] { Registry.CurrentUser, Registry.LocalMachine })
            {
                using (var key = baseKey.OpenSubKey(FactoryProvidersRegKey)) {
                    if (key != null)
                    {
                        foreach (var idStr in key.GetSubKeyNames())
                        {
                            using (var subkey = key.OpenSubKey(idStr)) {
                                if (subkey != null)
                                {
                                    LoadOneProvider(
                                        subkey.GetValue(FactoryProviderCodeBaseSetting, "") as string,
                                        seen,
                                        catalog,
                                        _activityLog
                                        );
                                }
                            }
                        }
                    }
                }
            }

            if (!catalog.Any())
            {
                LoadOneProvider(
                    typeof(CPythonInterpreterFactoryConstants).Assembly.Location,
                    seen,
                    catalog,
                    _activityLog
                    );
            }

            const string FailedToImportMessage   = "Failed to import factory providers";
            var          providers               = new List <IPythonInterpreterFactoryProvider>();
            var          serviceProviderProvider = new MockExportProvider();

            if (serviceProvider != null)
            {
                serviceProviderProvider.SetExport(typeof(SVsServiceProvider), () => serviceProvider);
            }

            foreach (var part in catalog)
            {
                var container = new CompositionContainer(part, serviceProviderProvider);
                try {
                    foreach (var provider in container.GetExports <IPythonInterpreterFactoryProvider>())
                    {
                        if (provider.Value != null)
                        {
                            providers.Add(provider.Value);
                        }
                    }
                } catch (CompositionException ex) {
                    LogException(_activityLog, FailedToImportMessage, null, ex, ex.Errors);
                } catch (ReflectionTypeLoadException ex) {
                    LogException(_activityLog, FailedToImportMessage, null, ex, ex.LoaderExceptions);
                } catch (Exception ex) {
                    LogException(_activityLog, FailedToImportMessage, null, ex);
                }
            }

            return(providers.ToArray());
        }
Beispiel #11
0
 protected static IEnumerable <ITechnologyPollingProvider> InitializeMEF(
     ComposablePartCatalog catalog)
 {
     using (CompositionContainer compositionContainer = new CompositionContainer(catalog, Array.Empty <ExportProvider>()))
         return((IEnumerable <ITechnologyPollingProvider>)compositionContainer.GetExports <ITechnologyPollingProvider>().Select <Lazy <ITechnologyPollingProvider>, ITechnologyPollingProvider>((Func <Lazy <ITechnologyPollingProvider>, ITechnologyPollingProvider>)(n => n.Value)).ToList <ITechnologyPollingProvider>());
 }
        private SourceRepository GetSourceRepository(string SourceUrl)
        {
            try
            {
                IEnumerable <Lazy <INuGetResourceProvider, INuGetResourceProviderMetadata> > providers = container.GetExports <INuGetResourceProvider, INuGetResourceProviderMetadata>();

                StringBuilder sb = new StringBuilder();

                foreach (var provider in providers)
                {
                    sb.AppendLine(provider.Metadata.ResourceType.ToString());
                }

                Assert.True(providers.Count() > 0);
                NuGet.Configuration.PackageSource source = new NuGet.Configuration.PackageSource(SourceUrl, "mysource", true);
                SourceRepository repo = new SourceRepository(source, providers);
                return(repo);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
        protected void ImportThread()
        {
            _logger.Log(EErrorType.Info, "ImportThread started");
            if (_compContainer != null)
            {
                // Clearing all errors
                Errors.Clear();

                // validating if there are anything need to be imported
                CurrentState = EImportState.Init;

                var sources = string.IsNullOrEmpty(_impParams.AgencyCode) ? _compContainer.GetExports <IQuotesSource>() : _compContainer.GetExports <IQuotesSource>(_impParams.AgencyCode);

                IQuotesSourceCanImportParams canImportParams = null;

                foreach (var s in sources)
                {
                    // break if stopped
                    if (!_isRunning)
                    {
                        break;
                    }

                    var source = s;

                    if (source != null)
                    {
                        List <string> tickersToImport = new List <string>();

                        //if list of tickers is provided - checking which of them can be imported by the current source
                        if (_impParams.Tickers != null)
                        {
                            // checking which of the given tickers can be imported
                            canImportParams = source.Value.CreateCanImportParams();
                            _impParams.Tickers.ToList().ForEach(x => canImportParams.Tickers.Add(x));

                            IQuotesSourceCanImportResult canImportResult = source.Value.CanImport(canImportParams);
                            if (canImportResult.Success)
                            {
                                tickersToImport.AddRange(canImportResult.Tickers);
                            }
                        }

                        // starting import in two cases: 1) some tickers can be imported by this source OR 2) requested to import all possible tickers by given agency
                        if (tickersToImport.Count > 0 || (_impParams.Tickers == null && !string.IsNullOrEmpty(_impParams.AgencyCode)))
                        {
                            CurrentState = EImportState.ImportSources;

                            IQuotesSourceGetQuotesParams getQuotesParams = source.Value.CreateGetQuotesParams();
                            foreach (var t in tickersToImport)
                            {
                                getQuotesParams.Tickers.Add(t);
                            }
                            try
                            {
                                IQuotesDalSaveTimeseriesValuesParams saveParams = _dal.CreateSaveTimeseriesValuesParams();

                                getQuotesParams.Country = ConfigurationManager.AppSettings["DefaultCountry"];

                                getQuotesParams.PeriodStart = _impParams.DateStart;
                                getQuotesParams.PeriodEnd   = _impParams.DateEnd;
                                getQuotesParams.TimeFrame   = (ETimeFrame)_impParams.TimeFrame;

                                CurrentState = EImportState.ImportSources;

                                IQuotesSourceGetQuotesResult getQuotesResult = source.Value.GetQuotes(getQuotesParams);

                                saveParams.Quotes.AddRange(getQuotesResult.QuotesData);

                                CurrentState = EImportState.Saving;

                                IQuotesDalSaveTimeseriesValuesResult saveResult = _dal.SaveTimeseriesValues(saveParams);

                                if (saveResult.Success)
                                {
                                    foreach (var t in tickersToImport)
                                    {
                                        _tickersProcessed.Add(t);
                                    }

                                    saveResult.TimeSeriesSaved.ToList().ForEach(x => { AddTickerForETL(x); });
                                }

                                _logger.Log(EErrorType.Info, string.Format("Import done"));
                            }
                            catch (Exception ex)
                            {
                                _logger.Log(ex);
                                Errors.Add(new Error()
                                {
                                    Code = EErrorCodes.ImporterError, Type = EErrorType.Error, Message = string.Format("Import failed. Error: {0}", ex.Message)
                                });
                            }
                        }
                    }
                } // foreach
            }
            else
            {
                Errors.Add(new Error()
                {
                    Code = EErrorCodes.ImporterError, Type = EErrorType.Error, Message = "Import failed. Composition comtainer is NULL"
                });
            }

            CurrentState = EImportState.Idle;
            _isRunning   = false;
            _importEnd   = DateTime.UtcNow;

            _logger.Log(EErrorType.Info, string.Format("ImportThread finished. Total errors: {0}, Time: {1}", Errors.Count, _importEnd - _importStart));
        }
        private void HandleAddingPreCompiledPluginInDirectory(AggregateCatalog returnValue, string pluginDirectory)
        {
            List <Assembly> assemblies = new List <Assembly>();

            var assembliesFiles = Directory.GetFiles(pluginDirectory, "*.dll");

            foreach (string assemblyName in assembliesFiles)
            {
                try
                {
                    if (IsAssemblyAlreadyReferenced(assemblyName))
                    {
                        string message = $"Warning: {pluginDirectory} - Skipping over assembly {assemblyName} because it is already loaded by a different plugin";

                        CompileOutput.Add(message);
                    }
                    else
                    {
                        var asm = Assembly.LoadFrom(assemblyName);

                        assemblies.Add(asm);
                    }
                }
                catch (Exception ex)
                {
                    CompileErrors.Add(string.Format("Failed to load {0}: {1}", assemblyName, ex.Message));
                }
            }

            AggregateCatalog catalogToMakeSureStuffIsLinked = new AggregateCatalog();

            foreach (var assembly in assemblies)
            {
                var catalog = new AssemblyCatalog(assembly);
                catalogToMakeSureStuffIsLinked.Catalogs.Add(catalog);
            }

            bool failed = false;

            try
            {
                var container = new CompositionContainer(catalogToMakeSureStuffIsLinked);
                container.GetExports <object>();
            }
            catch (Exception e)
            {
                string message = "";
                message += "Error trying to load plugins from directory:     " + pluginDirectory;

                if (e is ReflectionTypeLoadException)
                {
                    foreach (var innerException in (e as ReflectionTypeLoadException).LoaderExceptions)
                    {
                        message += "\r\n" + innerException.ToString();
                    }
                }
                else
                {
                    message += "\r\n" + e.ToString();
                }
                CompileErrors.Add(message);

                failed = true;
            }

            if (!failed)
            {
                foreach (var assemblyCatalog in catalogToMakeSureStuffIsLinked.Catalogs)
                {
                    returnValue.Catalogs.Add(assemblyCatalog);
                }
            }
        }
Beispiel #15
0
 public IEnumerable <Lazy <T> > GetExports <T>()
 {
     return(_compositionContainer.GetExports <T>());
 }
Beispiel #16
0
        private void InitializeSecurityContext(StubNavigationService navigationService, out IMenuDefinition[] menus, out ISubMenuDefinition[] subMenus, out IServiceBus serviceBus)
        {
            // N'importer que les IMenuDefinition et ISubMenuDefinition

            var menuDeftype = typeof(IMenuDefinition);
            var subMenuDeftype = typeof(ISubMenuDefinition);

            var assembly = typeof(KProcess.Ksmed.Presentation.Shell.Controller).Assembly;

            // Rechercher les types qui les implémentent
            var menuTypes = assembly.GetTypes().Where(t => t.GetInterface(menuDeftype.FullName) != null || t.GetInterface(subMenuDeftype.FullName) != null).ToArray();


            // Composer MEF
            var container = new CompositionContainer(
                new AggregateCatalog(
                    new TypeCatalog(menuTypes),
                    new TypeCatalog(
                        typeof(IServiceBus), typeof(ServiceBus),
                        typeof(IEventBus), typeof(EventBus)
                        )));
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            batch.AddExportedValue<CompositionContainer>(container);
            //IoC.RegisterInstance<CompositionContainer>(_container);
            container.Compose(batch);

            menus = container.GetExports<IMenuDefinition>().Select(l => l.Value).ToArray();
            subMenus = container.GetExports<ISubMenuDefinition>().Select(l => l.Value).ToArray();

            foreach (var menu in menus)
            {
                menu.Initialize();
            }


            var rolesReadAuthorizations = new Dictionary<Type, string[]>();
            var rolesWriteAuthorizations = new Dictionary<Type, string[]>();
            var featuresReadAuthorizations = new Dictionary<Type, short[]>();
            var featuresWriteAuthorizations = new Dictionary<Type, short[]>();
            var customReadAuthorizations = new Dictionary<Type, Func<string, bool>>();
            var customWriteAuthorizations = new Dictionary<Type, Func<string, bool>>();
            var accessProjectContext = new Dictionary<Type, bool>();

            foreach (var subMenu in subMenus)
            {
                subMenu.Initialize();
                rolesReadAuthorizations[subMenu.ViewModelType] = subMenu.RolesCanRead;
                rolesWriteAuthorizations[subMenu.ViewModelType] = subMenu.RolesCanWrite;
                featuresReadAuthorizations[subMenu.ViewModelType] = subMenu.FeaturesCanRead;
                featuresWriteAuthorizations[subMenu.ViewModelType] = subMenu.FeaturesCanWrite;
                customReadAuthorizations[subMenu.ViewModelType] = subMenu.CustomCanRead;
                customWriteAuthorizations[subMenu.ViewModelType] = subMenu.CustomCanWrite;
                accessProjectContext[subMenu.ViewModelType] = subMenu.IsSecurityProjectContext;
            }

            Security.SecurityContext.RegisterAuthorizations(
                rolesReadAuthorizations,
                rolesWriteAuthorizations,
                featuresReadAuthorizations,
                featuresWriteAuthorizations,
                customReadAuthorizations,
                customWriteAuthorizations);

            serviceBus = container.GetExport<IServiceBus>().Value;
            serviceBus.Register<INavigationService>(navigationService);
            serviceBus.Register<IProjectManagerService>(new StubProjectManagerService());

        }
        public void Initialise(Scene scene, IConfigSource config)
        {
            string desiredWindPlugin = DEFAULT_WIND_PLUGIN;

            IConfig windConfig = config.Configs["Wind"];

            if (windConfig != null)
            {
                m_enabled         = windConfig.GetBoolean("enabled", true);
                m_frameUpdateRate = windConfig.GetInt("wind_update_rate", 150);

                // Determine which wind model plugin is desired
                if (windConfig.Contains("wind_plugin"))
                {
                    desiredWindPlugin = windConfig.GetString("wind_plugin");
                }
            }

            if (m_enabled)
            {
                m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);

                m_scene = scene;
                m_frame = 0;

                if (windConfig != null)
                {
                    CompositionContainer moduleContainer = scene.ModuleContainer;
                    IEnumerable <Lazy <object, object> > exportEnumerable = moduleContainer.GetExports(typeof(IPlugin), null, null);

                    foreach (Lazy <object, object> lazyExport in exportEnumerable)
                    {
                        IDictionary <string, object> metadata = (IDictionary <string, object>)lazyExport.Metadata;
                        object nameObj;
                        if (metadata.TryGetValue("Name", out nameObj))
                        {
                            string name = (string)nameObj;
                            if (name.Equals(desiredWindPlugin, StringComparison.InvariantCultureIgnoreCase) && lazyExport.Value is IWindModelPlugin)
                            {
                                m_log.InfoFormat("[WIND] {0} plugin found, initializing.", desiredWindPlugin);

                                m_activeWindPlugin = (IWindModelPlugin)lazyExport.Value;
                                m_activeWindPlugin.Initialise();
                                m_activeWindPlugin.WindConfig(m_scene, windConfig);
                                break;
                            }
                        }
                    }
                }

                // if the plug-in wasn't found, default to no wind.
                if (m_activeWindPlugin == null)
                {
                    m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", desiredWindPlugin);
                    m_log.ErrorFormat("[WIND] Defaulting to no wind.");
                }

                // This one puts an entry in the main help screen
                m_scene.AddCommand(this, String.Empty, "wind", "Usage: wind <param> [value] - Get or Update Wind paramaters", null);

                // This one enables the ability to type just the base command without any parameters
                m_scene.AddCommand(this, "wind", "", "", HandleConsoleCommand);

                // Get a list of the parameters for the plugin
                if (m_activeWindPlugin != null)
                {
                    m_scene.AddCommand(this, String.Format("wind wind_update_rate"), "Change the wind update rate.", "", HandleConsoleBaseCommand);

                    foreach (KeyValuePair <string, string> kvp in m_activeWindPlugin.WindParams())
                    {
                        m_scene.AddCommand(this, String.Format("wind {0} {1}", m_activeWindPlugin.Name, kvp.Key),
                                           String.Format("{0} : {1} - {2}", m_activeWindPlugin.Name, kvp.Key, kvp.Value), "", HandleConsoleParamCommand);
                    }
                }

                // Register event handlers for when Avatars enter the region, and frame ticks
                m_scene.EventManager.OnFrame         += WindUpdate;
                m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion;

                // Register the wind module
                m_scene.RegisterModuleInterface <IWindModule>(this);

                // Generate initial wind values
                GenWindPos();

                // Mark Module Ready for duty
                m_ready = true;
            }
        }
Beispiel #18
0
        public bool LoadModules()
        {
            #region Application Module Whitelist Loading

            // Load the application module whitelist
            List <KeyValuePair <int, string> > whitelist = new List <KeyValuePair <int, string> >();

            IConfig config = Config.Configs["ApplicationModules"];
            if (config != null)
            {
                foreach (string key in config.GetKeys())
                {
                    int runLevel = config.GetInt(key, -1);
                    if (runLevel >= 0)
                    {
                        whitelist.Add(new KeyValuePair <int, string>(runLevel, key));
                    }
                }
            }

            // Sort the list based on runlevel
            whitelist.Sort(delegate(KeyValuePair <int, string> lhs, KeyValuePair <int, string> rhs) { return(lhs.Key.CompareTo(rhs.Key)); });

            #endregion Application Module Whitelist Loading

            #region Module Container Loading

            AggregateCatalog catalog = new AggregateCatalog();

            AssemblyCatalog  assemblyCatalog  = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(".", "Simian.*.dll");

            catalog.Catalogs.Add(assemblyCatalog);
            catalog.Catalogs.Add(directoryCatalog);

            m_moduleContainer = new CompositionContainer(catalog, true);

            try
            {
                m_log.InfoFormat("Found {0} modules in the current assembly and {1} modules in external assemblies",
                                 assemblyCatalog.Parts.Count(), directoryCatalog.Parts.Count());
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder error = new StringBuilder("Error(s) encountered loading extension modules. You may have an incompatible or out of date extension .dll in the current folder.");
                foreach (Exception loaderEx in ex.LoaderExceptions)
                {
                    error.Append("\n " + loaderEx.Message);
                }
                m_log.Error(error.ToString());

                return(false);
            }

            #endregion Module Container Loading

            #region Module Loading

            IEnumerable <Lazy <object, object> >        exportEnumerable = m_moduleContainer.GetExports(typeof(IApplicationModule), null, null);
            Dictionary <string, Lazy <object, object> > exports          = new Dictionary <string, Lazy <object, object> >();
            List <IApplicationModule> imports   = new List <IApplicationModule>();
            List <string>             notLoaded = new List <string>();

            // Reshuffle exportEnumerable into a dictionary mapping module names to their lazy instantiations
            foreach (Lazy <object, object> lazyExport in exportEnumerable)
            {
                IDictionary <string, object> metadata = (IDictionary <string, object>)lazyExport.Metadata;
                object nameObj;
                if (metadata.TryGetValue("Name", out nameObj))
                {
                    string name = (string)nameObj;

                    if (!exports.ContainsKey(name))
                    {
                        exports.Add(name, lazyExport);
                    }
                    else
                    {
                        m_log.Warn("Found an IApplicationModule with a duplicate name: " + name);
                    }
                }
            }

            // Load modules in the order they appear in the whitelist
            foreach (KeyValuePair <int, string> kvp in whitelist)
            {
                string whitelisted = kvp.Value;

                Lazy <object, object> lazyExport;
                if (exports.TryGetValue(whitelisted, out lazyExport))
                {
                    imports.Add((IApplicationModule)lazyExport.Value);
                    exports.Remove(whitelisted);
                }
                else
                {
                    notLoaded.Add(whitelisted);
                }
            }

            // Populate m_applicationModules
            m_applicationModules = imports.ToArray();

            // Start the application modules
            for (int i = 0; i < m_applicationModules.Length; i++)
            {
                IApplicationModule module = m_applicationModules[i];
                if (!(module is ISceneFactory))
                {
                    module.Start(this);
                }
            }

            // ISceneFactory modules are always started last
            for (int i = 0; i < m_applicationModules.Length; i++)
            {
                IApplicationModule module = m_applicationModules[i];
                if (module is ISceneFactory)
                {
                    module.Start(this);
                }
            }

            #endregion Module Loading

            #region Logging

            m_log.InfoFormat("Loaded {0} application modules", m_applicationModules.Length);

            if (exports.Count > 0)
            {
                StringBuilder skippedStr = new StringBuilder("Skipped application modules: ");
                foreach (string exportName in exports.Keys)
                {
                    skippedStr.Append(exportName + " ");
                }
                m_log.Info(skippedStr.ToString());
            }

            if (notLoaded.Count > 0)
            {
                StringBuilder notLoadedStr = new StringBuilder("Did not load whitelisted application modules: ");
                foreach (string entry in notLoaded)
                {
                    notLoadedStr.Append(entry + " ");
                }
                m_log.Warn(notLoadedStr.ToString());
            }

            #endregion Logging

            // Get a reference to the HTTP server if we have one
            m_httpServer = GetAppModule <IHttpServer>();
            if (m_httpServer != null)
            {
                m_capabilityRouter = new CapabilityRouter(m_httpServer.HttpAddress.Combine(CAPABILITY_PATH));
                m_httpServer.AddHandler(null, null, CAPABILITY_PATH, false, false, m_capabilityRouter.RouteCapability);
            }

            // Get a reference to the ISceneFactory if we have one
            m_sceneFactory = GetAppModule <ISceneFactory>();
            if (m_sceneFactory != null)
            {
                AddCommandHandler("scene", SceneHandler);
            }

            return(true);
        }
Beispiel #19
0
        public static Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> > GetRunnableClientSampleMethods(string area = null, string resource = null)
        {
            Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> > results = new Dictionary <ClientSample, IEnumerable <RunnableClientSampleMethod> >();

            CompositionContainer container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            IEnumerable <Lazy <ClientSample> > samples = container.GetExports <ClientSample>();

            foreach (Lazy <ClientSample> cs in samples)
            {
                try
                {
                    Type csType = cs.Value.GetType();
                    ClientSampleAttribute csAttr = csType.GetCustomAttribute <ClientSampleAttribute>();

                    List <RunnableClientSampleMethod> runnableMethods = new List <RunnableClientSampleMethod>();

                    foreach (MethodInfo m in csType.GetMethods())
                    {
                        ClientSampleMethodAttribute[] attrs = (ClientSampleMethodAttribute[])m.GetCustomAttributes(typeof(ClientSampleMethodAttribute), false);
                        foreach (var ma in attrs)
                        {
                            RunnableClientSampleMethod runnableMethod = new RunnableClientSampleMethod();

                            if (string.IsNullOrEmpty(ma.Area))
                            {
                                runnableMethod.Area = csAttr.Area;
                            }
                            else
                            {
                                runnableMethod.Area = ma.Area;
                            }

                            if (string.IsNullOrEmpty(ma.Resource))
                            {
                                runnableMethod.Resource = csAttr.Resource;
                            }
                            else
                            {
                                runnableMethod.Resource = ma.Resource;
                            }

                            if (!string.IsNullOrEmpty(runnableMethod.Area) && !string.IsNullOrEmpty(runnableMethod.Resource))
                            {
                                runnableMethod.MethodBase = m;
                                runnableMethods.Add(runnableMethod);
                            }
                        }
                    }

                    if (runnableMethods.Any())
                    {
                        if (!String.IsNullOrEmpty(area))
                        {
                            runnableMethods = runnableMethods.FindAll(
                                rcsm =>
                            {
                                return(string.Equals(area, rcsm.Area, StringComparison.InvariantCultureIgnoreCase) &&
                                       (resource == null || string.Equals(resource, rcsm.Resource, StringComparison.InvariantCultureIgnoreCase)));
                            }
                                );
                        }

                        results.Add(cs.Value, runnableMethods);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }

            return(results);
        }
Beispiel #20
0
        public SourceRepository GetSourceRepository(NuGet.IPackageRepository legacyRepo)
        {
            V2PackageSource source = new V2PackageSource(@"passed in", () => legacyRepo);

            IEnumerable <Lazy <INuGetResourceProvider, INuGetResourceProviderMetadata> > providers = Container.GetExports <INuGetResourceProvider, INuGetResourceProviderMetadata>();

            Assert.True(providers.Count() > 0);

            SourceRepository repo = new SourceRepository(source, providers);

            return(repo);
        }
        public void ImportAll(out IReadOnlyCollection <ImportedMigration> migrations, out IReadOnlyCollection <ImportedAggregateMigration> aggregateMigrations)
        {
            Log.Info("Importing migrations...");
            DateTime start     = DateTime.Now;
            var      container = new CompositionContainer(_catalog);
            IEnumerable <Lazy <IMigration, IMigrationExportMetadata> >          migrationExports          = container.GetExports <IMigration, IMigrationExportMetadata>();
            IEnumerable <Lazy <IMigration, IAggregateMigrationExportMetadata> > aggregateMigrationExports = container.GetExports <IMigration, IAggregateMigrationExportMetadata>(AggregateMigrationExportAttribute.ContractName);

            migrations = migrationExports
                         .Select(l =>
            {
                var timestamp         = ExtractTimestamp(l.Metadata.ModuleName, l.Value);
                var migrationMetadata = new MigrationMetadata(timestamp, l.Metadata.ModuleName, l.Metadata.Tag);
                return(new ImportedMigration(l.Value, migrationMetadata, l.Metadata.UseModuleNameAsDefaultSchema));
            }).ToList();
            aggregateMigrations = aggregateMigrationExports
                                  .Select(l =>
            {
                var timestamp = ExtractTimestamp(l.Metadata.ModuleName, l.Value);
                var aggregateMigrationMetadata = new AggregateMigrationMetadata(timestamp, l.Metadata.ModuleName);
                return(new ImportedAggregateMigration(l.Value, aggregateMigrationMetadata));
            }).ToList();
            Log.Verbose(LogCategory.Performance, "Importing migrations took {0}s", (DateTime.Now - start).TotalSeconds);
            Log.Info("Found {0} migration(s) and {1} aggregate migration(s)", migrations.Count, aggregateMigrations.Count);
        }
Beispiel #22
0
 void ImportPlugins()
 {
     myPlugins = _container.GetExports <T, TMetadata>();
 }
Beispiel #23
0
        public static object[] GetExportedValues(this CompositionContainer container, Type type, string contractName = null)
        {
            var exports = container.GetExports(type, null, contractName);

            return(exports.Select(it => it.Value).ToArray());
        }
Beispiel #24
0
 static IEnumerable <T> GetAllExports <T>(this CompositionContainer container)
 {
     return(container.GetExports <T>().Select(x => x.Value));
 }
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="configuration">The current configuration in an XML fragment</param>
        /// <param name="container">The composition container user to locate the syntax generators</param>
        public SyntaxComponentConfigDlg(string configuration, CompositionContainer container)
        {
            HashSet <string> generatorIds = new HashSet <string>();
            XElement         node;
            XAttribute       attr;
            bool             value;

            InitializeComponent();

            syntaxGenerators = new List <SyntaxGeneratorSettings>();

            // Get a list of all configurable syntax generators
            try
            {
                var generators = container.GetExports <ISyntaxGeneratorFactory, ISyntaxGeneratorMetadata>().Select(
                    g => g.Metadata).ToList();

                // There may be duplicate generator IDs across the assemblies found.  See
                // BuildComponentManger.GetComponentContainer() for the folder search precedence.  Only the
                // first component for a unique ID will be used.
                foreach (var generator in generators)
                {
                    if (!generatorIds.Contains(generator.Id))
                    {
                        syntaxGenerators.Add(new SyntaxGeneratorSettings
                        {
                            Id                   = generator.Id,
                            SortOrder            = generator.SortOrder,
                            IsConfigurable       = generator.IsConfigurable,
                            DefaultConfiguration = generator.DefaultConfiguration,
                            CurrentConfiguration = generator.DefaultConfiguration
                        });

                        generatorIds.Add(generator.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                syntaxGenerators = new List <SyntaxGeneratorSettings>();
                btnOK.Enabled    = false;

                MessageBox.Show("Unable to obtain a list of syntax generators: " + ex.Message, "Syntax Component",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            // Load the current settings
            config = XElement.Parse(configuration);
            node   = config.Element("syntax");

            if (node != null)
            {
                attr = node.Attribute("renderReferenceLinks");

                if (!Boolean.TryParse(attr.Value, out value))
                {
                    value = false;
                }

                chkRenderReferenceLinks.Checked = value;
            }

            node = config.Element("containerElement");

            if (node != null)
            {
                attr = node.Attribute("addNoExampleTabs");

                if (!Boolean.TryParse(attr.Value, out value))
                {
                    value = false;
                }

                chkAddNoExampleTabs.Checked = value;

                if (value)
                {
                    attr = node.Attribute("includeOnSingleSnippets");

                    if (!Boolean.TryParse(attr.Value, out value))
                    {
                        value = false;
                    }

                    chkIncludeOnSingleSnippets.Checked = value;
                }
            }


            // Configurations are stored separately since the actual syntax filters are added at build time
            node = config.Element("configurations");

            if (node != null)
            {
                int idx = 0;

                foreach (var generator in node.Descendants("generator"))
                {
                    var sg = syntaxGenerators.FirstOrDefault(g => g.Id == generator.Attribute("id").Value);

                    if (sg != null)
                    {
                        var reader = generator.CreateReader();
                        reader.MoveToContent();

                        sg.SortOrder = idx;

                        if (sg.IsConfigurable)
                        {
                            sg.CurrentConfiguration = reader.ReadInnerXml();
                        }
                    }

                    idx++;
                }
            }

            foreach (var generator in syntaxGenerators.OrderBy(g => g.SortOrder))
            {
                tvGenerators.Nodes.Add(generator.Id);
            }

            if (tvGenerators.Nodes.Count != 0)
            {
                tvGenerators.SelectedNode = tvGenerators.Nodes[0];
            }
            else
            {
                btnReset.Enabled = txtConfiguration.Enabled = btnMoveUp.Enabled = btnMoveDown.Enabled = false;
            }
        }
Beispiel #26
0
        protected void Application_Start()
        {
            // TODO maybe put this somewhere else (not in global.asax)
            // TODO maybe move all of this into the App class with "IAppConfig"

            // initialize logger
            TraceListener traceListener =
                new TextWriterTraceListener(Path.Combine(AppConfig.LogPath,
                                                         string.Format("repository_{0:yyyy'-'MM'-'dd__HHmmss}.log",
                                                                       DateTime.Now)));

            // TODO introduce flags/settings for controlling logging levels, but for now include everything
            traceListener.Filter = new EventTypeFilter(SourceLevels.All);

            traceListener.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;

            Web.TraceSources.Content.Listeners.Add(traceListener);
            Web.TraceSources.AddInManager.Listeners.Add(traceListener);
            Repository.TraceSources.ContentManagerSource.Listeners.Add(traceListener);
            Repository.TraceSources.ContentSearcherSource.Listeners.Add(traceListener);

            // this might be stupid, but it fixes things for iisexpress
            Directory.SetCurrentDirectory(HostingEnvironment.ApplicationPhysicalPath);

            // set up add-in system
            AddInSource officalSource = new AddInSource("Official LostDoc repository add-in feed",
                                                        AppConfig.AddInRepository,
                                                        isOfficial: true);

            // intialize MEF

            // core 'add-ins'
            var              currentAssembly    = Assembly.GetExecutingAssembly();
            var              assemblyName       = currentAssembly.GetName();
            string           corePackageId      = assemblyName.Name;
            string           corePackageVersion = assemblyName.Version.ToString();
            AggregateCatalog catalog            = new AggregateCatalog();

            // load other sources from site-settings (not config)
            AddInRepository repository   = new AddInRepository(officalSource);
            AddInManager    addInManager = new AddInManager(repository,
                                                            AppConfig.AddInInstallPath,
                                                            AppConfig.AddInPackagePath);

            // when the catalog changes, discover and route all ApiControllers
            catalog.Changed += (sender, args) => this.UpdateWebApiRegistry(args);

            //// TODO for debugging only
            //Debugger.Break();
            //Debugger.Launch();

            // now register core libs
            catalog.Catalogs.Add(new AddInCatalog(new ApplicationCatalog(), corePackageId, corePackageVersion));

            // hook event so that installed add-ins get registered in the catalog, if composition occurs after this fires
            // or if recomposition is enabled, no restart should be requried
            addInManager.Installed +=
                (sender, args) => catalog.Catalogs.Add(new AddInCatalog(new DirectoryCatalog(args.InstallationPath),
                                                                        args.Package.Id,
                                                                        args.Package.Version));

            // delete and redeploy all installed packages, this will trigger the Installed event ^
            // this acts as a crude "remove/overwrite plugins that were in use when un/installed" hack
            addInManager.Restore();

            // create container
            CompositionContainer container = new CompositionContainer(catalog);

            // set up template resolver
            var lazyProviders = container.GetExports <IFileProvider>(ContractNames.TemplateProvider);
            var realProviders = lazyProviders.Select(lazy => lazy.Value);
            TemplateResolver templateResolver = new TemplateResolver(realProviders.ToArray());

            // load template
            Template template = new Template(container);

            template.Load(templateResolver, AppConfig.Template);

            // set up content manager
            ContentManager contentManager = new ContentManager(new ContentSettings
            {
                ContentPath = AppConfig.ContentPath,
                // TODO make this configurable
                IgnoreVersionComponent = VersionComponent.Patch,
                RepositoryPath         = AppConfig.RepositoryPath,
                Template = template
            });

            // set up notifaction system
            NotificationManager notifications = new NotificationManager();

            // initialize app-singleton
            App.Initialize(container, contentManager, addInManager, notifications, traceListener);

            // MVC init
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            // inject our custom IControllerFactory for the Admin interface
            IControllerFactory oldControllerFactory = ControllerBuilder.Current.GetControllerFactory();
            IControllerFactory newControllerFactory = new AddInControllerFactory(AdministrationAreaRegistration.Name,
                                                                                 container,
                                                                                 oldControllerFactory);

            ControllerBuilder.Current.SetControllerFactory(newControllerFactory);

            // TODO figure out if we actually need this
            // hook in our MEF based IHttpController instead of the default one
            //GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerTypeResolver), new AddInHttpControllerTypeResolver(App.Instance.Container));
        }
Beispiel #27
0
        //=====================================================================

        /// <summary>
        /// Try to load information about all available presentation styles so that their arguments can be loaded
        /// for use in the project.
        /// </summary>
        /// <returns>True on success, false on failure or if no project is loaded</returns>
        private void LoadAvailablePresentationStyles()
        {
            SandcastleProject currentProject       = null;
            HashSet <string>  presentationStyleIds = new HashSet <string>();

            string[] searchFolders;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (componentContainer != null)
                {
                    componentContainer.Dispose();
                    componentContainer = null;
                }

                presentationStyles = new List <Lazy <PresentationStyleSettings, IPresentationStyleMetadata> >();

#if !STANDALONEGUI
                if (base.ProjectMgr != null)
                {
                    currentProject = ((SandcastleBuilderProjectNode)base.ProjectMgr).SandcastleProject;
                }
#else
                currentProject = base.CurrentProject;
#endif
                lastProjectName = currentProject == null ? null : currentProject.Filename;

                if (currentProject != null)
                {
                    searchFolders = new[] { currentProject.ComponentPath, Path.GetDirectoryName(currentProject.Filename) }
                }
                ;
                else
                {
                    searchFolders = new string[] { }
                };

                componentContainer = ComponentUtilities.CreateComponentContainer(searchFolders);

                // There may be duplicate presentation style IDs across the assemblies found.  See
                // BuildComponentManger.GetComponentContainer() for the folder search precedence.  Only the
                // first component for a unique ID will be used.
                foreach (var style in componentContainer.GetExports <PresentationStyleSettings,
                                                                     IPresentationStyleMetadata>())
                {
                    if (!presentationStyleIds.Contains(style.Metadata.Id))
                    {
                        presentationStyles.Add(style);
                        presentationStyleIds.Add(style.Metadata.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());

                MessageBox.Show("Unexpected error loading presentation styles: " + ex.Message, messageBoxTitle,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Beispiel #28
0
        public TDSListener(TDSProxyService service, ListenerElement configuration)
        {
            var insideAddresses = Dns.GetHostAddresses(configuration.ForwardToHost);

            if (0 == insideAddresses.Length)
            {
                log.ErrorFormat("Unable to resolve forwardToHost=\"{0}\" for listener {1}", configuration.ForwardToHost, configuration.Name);
                _stopped = true;
                return;
            }
            ForwardTo = new IPEndPoint(insideAddresses.First(), configuration.ForwardToPort);

            _service = service;

            var bindToEP = new IPEndPoint(configuration.BindToAddress ?? IPAddress.Any, configuration.ListenOnPort);

            try
            {
                var catalog = new AggregateCatalog(from AuthenticatorElement a in configuration.Authenticators
                                                   select new AssemblyCatalog(a.Dll));
                _mefContainer = new CompositionContainer(catalog);

                var  allExports     = _mefContainer.GetExports <IAuthenticator>().ToDictionary(a => a.GetType().GetGenericArguments()[0].FullName);
                var  authenticators = new Lazy <IAuthenticator> [configuration.Authenticators.Count];
                bool die            = false;
                var  used           = new List <Lazy <IAuthenticator> >();
                for (int i = 0; i < configuration.Authenticators.Count; i++)
                {
                    var a = configuration.Authenticators[i];
                    if (!allExports.TryGetValue(a.Class, out var export))
                    {
                        log.ErrorFormat(
                            "For authenticator {0} found dll {1} but not class {2} (exports in catalog: {3})",
                            a.Name,
                            a.Dll,
                            a.Class,
                            string.Join("; ", allExports.Keys));
                        die = true;
                    }

                    used.Add(export);
                    authenticators[i] = export;
                }

                if (die)
                {
                    Dispose();
                    return;
                }

                _authenticators = authenticators;
                _mefContainer.ReleaseExports(allExports.Values.Except(used));
            }
            catch (CompositionException ce)
            {
                log.Error(
                    "Failed to find an authenticator. Composition errors:\r\n\t" +
                    string.Join("\r\n\t", ce.Errors.Select(err => "Element: " + err.Element.DisplayName + ", Error: " + err.Description)),
                    ce);
                Dispose();
                return;
            }
            catch (Exception e)
            {
                log.Error("Failed to find an authenticator", e);
                Dispose();
                return;
            }

            try
            {
                log.DebugFormat("Opening SSL certificate store {0}.{1}", configuration.SslCertStoreLocation, configuration.SslCertStoreName);
                var store = new X509Store(configuration.SslCertStoreName, configuration.SslCertStoreLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var matching = store.Certificates.Find(X509FindType.FindByThumbprint, configuration.SslCertSubjectThumbprint, false);
                if (0 == matching.Count)
                {
                    log.ErrorFormat(
                        "Failed to find SSL certification with thumbprint '{0}' in location {1}, store {2}.",
                        configuration.SslCertSubjectThumbprint,
                        configuration.SslCertStoreLocation,
                        configuration.SslCertStoreName);
                    Dispose();
                    return;
                }
                Certificate = matching[0];
            }
            catch (Exception e)
            {
                log.Error("Failed to load SSL certificate", e);
                Dispose();
                return;
            }

            _tcpListener = new TcpListener(bindToEP);
            _tcpListener.Start();
            _tcpListener.BeginAcceptTcpClient(AcceptConnection, _tcpListener);

            _service.AddListener(this);

            log.InfoFormat(
                "Listening on {0} and forwarding to {1} (SSL cert DN {2}; expires {5} serial {3}; authenticators {4})",
                bindToEP,
                ForwardTo,
                Certificate.Subject,
                Certificate.GetSerialNumberString(),
                string.Join(", ", from a in Authenticators select a.GetType().FullName),
                Certificate.GetExpirationDateString());
        }
Beispiel #29
0
 public void SelectiveImportBySTMThroughCatalog1(CompositionContainer container)
 {
     Assert.NotNull(container.GetExport <IMyExporter, IMetadataView>());
     var result2 = container.GetExports <IMyExporter, IMetadataView>();
 }
Beispiel #30
0
        //=====================================================================

        /// <summary>
        /// Try to load information about all available plug-ins so that they can be added to the project
        /// </summary>
        /// <returns>True on success, false on failure or if no project is loaded</returns>
        private void LoadAvailablePlugInMetadata()
        {
            SandcastleProject currentProject = null;
            HashSet <string>  plugInIds      = new HashSet <string>();

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (componentContainer != null)
                {
                    componentContainer.Dispose();
                    componentContainer = null;
                    availablePlugIns   = null;
                }

#if !STANDALONEGUI
                if (base.ProjectMgr != null)
                {
                    currentProject = ((SandcastleBuilderProjectNode)base.ProjectMgr).SandcastleProject;
                }
#else
                currentProject = base.CurrentProject;
#endif
                lastProjectName = currentProject == null ? null : currentProject.Filename;

                if (currentProject != null)
                {
                    componentContainer = ComponentUtilities.CreateComponentContainer(new[] {
                        currentProject.ComponentPath, Path.GetDirectoryName(currentProject.Filename)
                    });
                }
                else
                {
                    componentContainer = ComponentUtilities.CreateComponentContainer(new string[] { });
                }

                lbProjectPlugIns.Items.Clear();

                availablePlugIns = componentContainer.GetExports <IPlugIn, IPlugInMetadata>().ToList();

                // There may be duplicate component IDs across the assemblies found.  See
                // BuildComponentManger.GetComponentContainer() for the folder search precedence.  Only the first
                // component for a unique ID will be used.  We also ignore hidden plug-ins.
                foreach (var plugIn in availablePlugIns)
                {
                    if (!plugIn.Metadata.IsHidden && !plugInIds.Contains(plugIn.Metadata.Id))
                    {
                        lbAvailablePlugIns.Items.Add(plugIn.Metadata.Id);
                        plugInIds.Add(plugIn.Metadata.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());

                MessageBox.Show("Unexpected error loading plug-ins: " + ex.Message, messageBoxTitle,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            if (lbAvailablePlugIns.Items.Count != 0)
            {
                lbAvailablePlugIns.SelectedIndex = 0;
                gbAvailablePlugIns.Enabled       = gbProjectAddIns.Enabled = true;
            }
            else
            {
                MessageBox.Show("No valid plug-ins found", messageBoxTitle, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                gbAvailablePlugIns.Enabled = gbProjectAddIns.Enabled = false;
            }
        }