public void SatisfyImportsOnce(ComposablePart part)
        {
            if (this.DoNothingOnSatisfyImportsOnce)
            {
                return;
            }

            CompositionBatch batch = new CompositionBatch();

            // We only want to include the standard exports and parts to compose in the first composition
            if (!this.alreadyComposed)
            {
                foreach (object instance in this.PartsToCompose)
                {
                    batch.AddPart(instance);
                }

                foreach (Export export in this.ExportsToCompose)
                {
                    batch.AddExport(export);
                }
            }

            if (part != null)
            {
                batch.AddPart(part);
            }

            this.container.Compose(batch);
            this.alreadyComposed = true;
        }
Example #2
0
        public void Compose(BaseParameters parameters)
        {
            try
            {
                var catalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                                                   new AssemblyCatalog(typeof(Logic.SanityCheck).Assembly));

                LoadPlugins(catalog, parameters);

                var container = new CompositionContainer(catalog);

                var batch = new CompositionBatch();
                batch.AddPart(this);
                batch.AddPart(parameters);

                var config = new Configuration(parameters.FileSystem, parameters.Path);
                config.ReadFromFile();
                batch.AddExportedValue((IConfiguration)config);

                container.Compose(batch);
            }
            catch (ReflectionTypeLoadException ex)
            {
                Console.WriteLine(@"Unable to load: \r\n{0}",
                    string.Join("\r\n", ex.LoaderExceptions.Select(e => e.Message)));

                throw;
            }
        }
Example #3
0
        private static void ComposeBatchTwo(CompositionContainer container)
        {
            var batch = new CompositionBatch();
            batch.RemovePart(a);
            c = batch.AddPart(new PluginC());
            batch.AddPart(logger);

            container.Compose(batch);
        }
Example #4
0
        static void Main() 
        {
            // important to call these before creating application host
            Application.EnableVisualStyles();
            Application.DoEvents(); // see http://www.codeproject.com/buglist/EnableVisualStylesBug.asp?df=100&forumid=25268&exp=0&select=984714

            // Set up localization support early on, so that user-readable strings will be localized
            //  during the initialization phase below. Use XML files that are embedded resources.
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CurrentCulture;
            Localizer.SetStringLocalizer(new EmbeddedResourceStringLocalizer());

            // Create a catalog with all the components that make up the application, except for
            //  our MainForm.
            var catalog = new TypeCatalog(
                typeof(SettingsService),                // persistent settings and user preferences dialog
                typeof(CommandService),                 // handles commands in menus and toolbars
                typeof(AtfUsageLogger),                 // logs computer info to an ATF server
                typeof(CrashLogger),                    // logs unhandled exceptions to an ATF server
                typeof(UnhandledExceptionService),      // catches unhandled exceptions, displays info, and gives user a chance to save
                typeof(StandardFileExitCommand),        // standard File exit menu command
                typeof(HelpAboutCommand),               // Help -> About command
                typeof(FolderViewer),                   // manages TreeControl to display folder hierarchy
                typeof(FileViewer),                     // managed ListView to display last selected folder contents

                typeof(NameDataExtension),              // extension to display file name
                typeof(SizeDataExtension),              // extension to display file size
                typeof(CreationTimeDataExtension),      // extension to display file creation time

                typeof(UserFeedbackService),            // component to send feedback form to SHIP
                typeof(VersionUpdateService),           // component to update to latest version on SHIP

                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );          

            var container = new CompositionContainer(catalog);

            // manually add the MainForm
            var batch = new CompositionBatch();
            var mainForm = new MainForm
            {
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };
            // our custom main Form with SplitContainer
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-File-Explorer-Sample".Localize()));
            container.Compose(batch);

            // initialize all components which require it
            container.InitializeAll();
            
            Application.Run(mainForm);

            container.Dispose();
        }
Example #5
0
        private static void ComposeBatchOne(CompositionContainer container)
        {
            var batch = new CompositionBatch();

            a = batch.AddPart(new PluginA());
            b = batch.AddPart(new PluginB());

            batch.AddPart(bootstrapper);

            container.Compose(batch);
        }
        public void FunctionsFieldsAndProperties2()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new SubtractProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(-1, c.op(c.a, c.b), "1 - 2 == -1");
        }
        public App()
        {
            var catalog = new AggregateCatalog(new DirectoryCatalog(Path.GetDirectoryName(typeof(App).Assembly.Location)), new AssemblyCatalog(typeof(App).Assembly));

            _container = new CompositionContainer(catalog);

            var batch = new CompositionBatch();
            batch.AddPart(ExistingComposablePart.Create<ExportProvider>(_container));
            batch.AddPart(ExistingComposablePart.Create(_container));

            _container.Compose(batch);
        }
        public void PrivateFromPublic()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();
            var importer = new AllPrivateImportOnly();
            batch.AddPart(importer);
            batch.AddPart(new AllPublicExportOnly() { ExportA = 5, ExportB = 10 });
            container.Compose(batch);

            Assert.AreEqual(5, importer.PublicImportA);
            Assert.AreEqual(10, importer.PublicImportB);
        }
        public void ImportSingleToInternal()
        {
            var container = ContainerFactory.Create();
            var importer = new Int32ImporterInternal();
            var exporter = new Int32Exporter(42);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value, "Expecting value to be imported");
        }
        public void ConstructorInjectionCycle()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();

            batch.AddPart(new ConstructorInjectionComposablePart(typeof(AClass)));
            batch.AddPart(new ConstructorInjectionComposablePart(typeof(BClass)));

            CompositionAssert.ThrowsErrors(ErrorId.ImportEngine_PartCannotSetImport,
                                           ErrorId.ImportEngine_PartCannotSetImport, RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });
        }
        public void ImportTest()
        {
            var exporter = new TestExportBinder();
            var importer = new TestImportBinder();

            CompositionContainer container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();

            batch.AddPart(importer);
            batch.AddPart(exporter);
            container.Compose(batch);

            ExportsAssert.AreEqual(importer.SetImports["single"], 42);
            ExportsAssert.AreEqual(importer.SetImports["multi"], 1, 2, 3);
        }
Example #12
0
        public void Compose()
        {
            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            string executionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string generatorsPath = Path.Combine(executionPath, "Generators");
            CreatePathIfRequied(generatorsPath);
            generatorsCatalog = new DirectoryCatalog(generatorsPath);

            string uiPath = Path.Combine(executionPath, "UI");
            CreatePathIfRequied(uiPath);
            UICatalog = new DirectoryCatalog(uiPath);

            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(generatorsCatalog);
            catalog.Catalogs.Add(UICatalog);

            //Set the defaults....
            CatalogExportProvider mainProvider = new CatalogExportProvider(assemblyCatalog);
            CompositionContainer container = new CompositionContainer(catalog, mainProvider);
            mainProvider.SourceProvider = container;

            var batch = new CompositionBatch();
            batch.AddPart(this);

            RefreshCatalog refreshCatalog = new RefreshCatalog(generatorsCatalog, UICatalog);
            container.ComposeParts(refreshCatalog);
            container.Compose(batch);

            Logger.Write("Compose complete");
        }
Example #13
0
        /// <summary>
        /// Initialises a new instance of the <see cref="MainForm"/> class.
        /// </summary>
        public MainForm()
        {
            this.InitializeComponent();

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog("..\\..\\Crypto", "*.dll"));
            var batch = new CompositionBatch();
            batch.AddPart(this);
            this.compositionContainer = new CompositionContainer(catalog);
            ////get all the exports and load them into the appropriate list tagged with the importmany
            this.compositionContainer.Compose(batch);

            this.CryptoAlgorithmComboBox.DataSource = (new List<CryptoAlgorithm> { CryptoAlgorithm.None }).Union(
                this.CryptoProviders.Select(c => c.Metadata.Algorithm).Distinct()).ToList();

            this.JoinedUsers = new BindingList<User>();

            this.ConnectedUsersDataGridView.DataSource = this.JoinedUsers;
            this.userProxy = new UserServiceClient(new InstanceContext(this));

            this.userProxy.Open();
            this.messagingProxy = new MessagingServiceClient(new InstanceContext(this));
            this.messagingProxy.Open();

            this.userProxy.Subscribe();
            foreach (var u in this.userProxy.GetJoinedUsers())
            {
                this.AddUser(u);
            }

            this.uiSyncContext = SynchronizationContext.Current;
        }
Example #14
0
 private void Compose()
 {
     var container = new CompositionContainer(directories);
       var batch = new CompositionBatch();
       batch.AddPart(this);
       container.Compose(batch);
 }
Example #15
0
        public void FunctionsFieldsAndProperties2_WithCatalog()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            ConsumerOfMultiple c = new ConsumerOfMultiple();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(c);
            container.Compose(batch);

            foreach (var export in c.opInfo)
            {
                if ((string)export.Metadata["Var1"] == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if ((string)export.Metadata["Var1"] == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }
Example #16
0
        /// <summary>
        ///     Will satisfy the imports on a object instance based on a <see cref="CompositionContainer"/>
        ///     registered with the <see cref="CompositionHost"/>. By default if no <see cref="CompositionContainer"/>
        ///     is registered the first time this is called it will be initialized to a catalog
        ///     that contains all the assemblies in the entry assembly folder, plus, optionally, an Extensions folder.
        /// </summary>
        /// <param name="attributedPart">
        ///     Object instance that contains <see cref="ImportAttribute"/>s that need to be satisfied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="attributedPart"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="attributedPart"/> contains <see cref="ExportAttribute"/>s applied on its type.
        /// </exception>
        /// <exception cref="ChangeRejectedException">
        ///     One or more of the imports on the object instance could not be satisfied.
        /// </exception>
        /// <exception cref="CompositionException">
        ///     One or more of the imports on the object instance caused an error while composing.
        /// </exception>
        public static void SatisfyImports(object attributedPart)
        {
            if (attributedPart == null)
            {
                throw new ArgumentNullException("attributedPart");
            }

            var batch = new CompositionBatch();

            var part = batch.AddPart(attributedPart);

            if (part.ExportDefinitions.Any())
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ExceptionStrings.ArgumentException_TypeHasExports, attributedPart.GetType().FullName), "attributedPart");
            }

            CompositionContainer container;

            // Ignoring return value because we don't need to know if we created it or not
            CompositionHost.TryGetOrCreateContainer(createContainer, out container);

            lock (locker)
            {
                container.Compose(batch);
            }
        }
Example #17
0
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            //catalog.Catalogs.Add(new AssemblyCatalog(typeof(IEmailService).Assembly));

            _container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();
            batch.AddPart(this);

            #if DEBUG
            _container.Compose(batch);
            #else
            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            #endif
            return true;
        }
        /// <summary>
        ///     Will satisfy the imports on a object instance based on a <see cref="CompositionContainer"/>
        ///     registered with the <see cref="CompositionHost"/>. By default if no <see cref="CompositionContainer"/>
        ///     is registered the first time this is called it will be initialized to a catalog
        ///     that contains all the assemblies loaded by the initial application XAP.
        /// </summary>
        /// <param name="instance">
        ///     Object instance that contains <see cref="ImportAttribute"/>s that need to be satisfied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="instance"/> contains <see cref="ExportAttribute"/>s applied on its type.
        /// </exception>
        /// <exception cref="ChangeRejectedException">
        ///     One or more of the imports on the object instance could not be satisfied.
        /// </exception>
        /// <exception cref="CompositionException">
        ///     One or more of the imports on the object instance caused an error while composing.
        /// </exception>
        public static void SatisfyImports(object instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var batch = new CompositionBatch();

            var attributedPart = batch.AddPart(instance);

            if (attributedPart.ExportDefinitions.Any())
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                        "Cannot call SatisfyImports on a object of type '{0}' because it is marked with one or more ExportAttributes.",
                        instance.GetType().FullName), "instance");
            }

            CompositionContainer container = null;

            // Ignoring return value because we don't need to know if we created it or not
            CompositionHost.TryGetOrCreateContainer(_createContainer, out container);

            container.Compose(batch);
        }
        public void ImportValues()
        {
            var container = ContainerFactory.Create();
            Importer importer = new Importer();
            Exporter exporter42 = new Exporter(42);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter42);

            CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotSetImport,
                                          ErrorId.ReflectionModel_ImportNotAssignableFromExport, RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });            
        }
Example #20
0
        public void GetValuesByType()
        {
            var cat = CatalogFactory.CreateDefaultAttributed();

            var container = new CompositionContainer(cat);

            string itestName = AttributedModelServices.GetContractName(typeof(ITest));

            var e1 = container.GetExportedValues<ITest>();
            var e2 = container.GetExports<ITest, object>(itestName);

            Assert.IsInstanceOfType(e1.First(), typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e1.Skip(1).First(), typeof(T2), "Second should be T2");

            Assert.IsInstanceOfType(e2.First().Value, typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e2.Skip(1).First().Value, typeof(T2), "Second should be T2");

            CompositionContainer childContainer = new CompositionContainer(container);
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new T1());
            container.Compose(batch);
            var t1 = childContainer.GetExportedValue<ITest>();
            var t2 = childContainer.GetExport<ITest, object>(itestName);

            Assert.IsInstanceOfType(t1, typeof(T1), "First (resolved) should be T1");
            Assert.IsInstanceOfType(t2.Value, typeof(T1), "First (resolved) should be T1");
        }
Example #21
0
        public void ConventionCatalog_should_support_type_exports()
        {
            var registry = new PartRegistry();
            registry.TypeScanner = new AssemblyTypeScanner(Assembly.GetExecutingAssembly());

            registry
                .Part()
                .ForType<SampleExport>()
                .Export();

            var catalog =
               new ConventionCatalog(registry);

            var instance =
                new ConventionPart<SampleExport>();

            var batch =
                new CompositionBatch();
            batch.AddPart(instance);

            var container =
                new CompositionContainer(catalog);

            container.Compose(batch);

            instance.Imports.Count().ShouldEqual(1);
        }
Example #22
0
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(IMefShapesGame).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(DefaultDimensions).Assembly));
            var partCreatorEP = new DynamicInstantiationExportProvider();

            this._container = new CompositionContainer(catalog, partCreatorEP);
            partCreatorEP.SourceProvider = this._container;

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            batch.AddExportedValue<ICompositionService>(this._container);
            batch.AddExportedValue<AggregateCatalog>(catalog);

            try
            {
                this._container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            return true;
        }
Example #23
0
 public RestServer(ushort port)
     : base(port)
 {
     this.HttpRequestReceived += new EventHandler<HttpServerEventArgs>(RestServer_RequestReceived);
     batch = new CompositionBatch();
     batch.AddPart(this);
 }
Example #24
0
        public void DualContainers()
        {
            var container1 = new CompositionContainer();
            TypeDescriptorServices dat1 = new TypeDescriptorServices();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(dat1);
            container1.Compose(batch);
            MetadataStore.AddAttribute(
                typeof(DynamicMetadataTestClass),
                ( type, attributes) => 
                    Enumerable.Concat(
                        attributes,
                        new Attribute[] { new TypeConverterAttribute(typeof(DynamicMetadataTestClassConverter)) }
                    ),
                container1
            );


            var container2 = new CompositionContainer();
            CompositionBatch batch2 = new CompositionBatch();
            TypeDescriptorServices dat2 = new TypeDescriptorServices();
            batch2.AddPart(dat2);
            container2.Compose(batch2);

            DynamicMetadataTestClass val = DynamicMetadataTestClass.Get("42");

            var attached1 = dat1.GetConverter(val.GetType());
            Assert.IsTrue(attached1.CanConvertFrom(typeof(string)), "The new type converter for DynamicMetadataTestClass should support round tripping");

            var attached2 = dat2.GetConverter(val.GetType());
            Assert.IsFalse(attached2.CanConvertFrom(typeof(string)), "The default type converter for DynamicMetadataTestClass shouldn't support round tripping");
        }
 private void OnComponentRegistrationOnActivated(object sender, ActivatedEventArgs<object> activation_event)
 {
     // compose by batch to allow for recomposition
     var batch = new CompositionBatch();
     batch.AddPart(activation_event.Instance);
     _mefContainer.Compose(batch);
 }
Example #26
0
        private bool Compose()
        {
            var catalog = new System.ComponentModel.Composition.Hosting.AggregateCatalog();
            //            var catalog = new AggregatingComposablePartCatalog();
            catalog.Catalogs.Add(
                new RubyCatalog(new RubyPartFile("calculator_ops.rb")));
            catalog.Catalogs.Add(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new System.ComponentModel.Composition.Hosting.CompositionContainer(catalog);
            //_container. AddPart(this);
            var batch = new System.ComponentModel.Composition.Hosting.CompositionBatch();
            batch.AddPart(this);
            //_container.AddPart(this);
            //_container.Compose(this);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }
            return true;
        }
Example #27
0
        public void SingleContainerPartReplacement()
        {
            var container = ContainerFactory.Create();
            var importPart = PartFactory.CreateImporter(true, "value1", "value2");

            CompositionBatch batch = new CompositionBatch();
            var export1Key = batch.AddExportedValue("value1", "Hello");
            batch.AddExportedValue("value2", "World");
            batch.AddPart(importPart);
            container.Compose(batch);

            Assert.AreEqual(2, importPart.ImportSatisfiedCount);
            Assert.AreEqual("Hello", importPart.GetImport("value1"));
            Assert.AreEqual("World", importPart.GetImport("value2"));

            importPart.ResetImportSatisfiedCount();

            batch = new CompositionBatch();
            batch.RemovePart(export1Key);
            batch.AddExportedValue("value1", "Goodbye");
            container.Compose(batch);

            Assert.AreEqual(1, importPart.ImportSatisfiedCount);
            Assert.AreEqual("Goodbye", importPart.GetImport("value1"));
            Assert.AreEqual("World", importPart.GetImport("value2"));
        }
Example #28
0
        public Runner Init(IFeedbackProvider feedbackProvider, string[] args)
        {
            var catalog = new AggregateCatalog(new AssemblyCatalog(typeof(Bootstrapper).Assembly));

            var currentDir = Environment.CurrentDirectory;
            var assemblyDir = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath).Directory.FullName;

            var paths = new string[]
            {
                assemblyDir,
                Path.Combine(assemblyDir, "Tasks"),
                currentDir,
                Path.Combine(currentDir, "Tasks")
            }.Unique();

            var dirCatalogs = paths.Where(x => Directory.Exists(x))
                                   .Select(x => new DirectoryCatalog(x, "*.Tasks.dll"));
            dirCatalogs.Apply(x => catalog.Catalogs.Add(x));

            var container = new CompositionContainer(catalog);

            var parsed = new ArgumentParser().Parse(args);
            var runner = new Runner(parsed.ActualArgs.ToArray());

            var batch = new CompositionBatch();
            batch.AddExportedValue<IFeedbackProvider>(feedbackProvider);
            parsed.Options.Apply(x => batch.AddExportedValue<string>(x.Item1, x.Item2));
            parsed.Switches.Apply(x => batch.AddExportedValue<bool>(x, true));
            batch.AddPart(runner);
            container.Compose(batch);

            return runner;
        }
Example #29
0
        public static void Compose(object o)
        {
            var container = new CompositionContainer(new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")));
            var batch = new CompositionBatch();

            batch.AddPart(o);
            container.Compose(batch);
        }
 private void LoadExtensions()
 {
     var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     var catalog = new DirectoryCatalog(location + "\\Extensions\\");
     var container = new CompositionContainer(catalog);
     var batch = new CompositionBatch();
     batch.AddPart(this);
     container.Compose(batch);
 }