public void ShouldSetALogger()
        {
            IPluginCreator tested    = PluginCreator.GetCreator();
            ILogWriter     logwriter = tested as ILogWriter;

            Assert.IsNotNull(logwriter.Log);
        }
示例#2
0
        private void QueryAndRunPlugins()
        {
            Console.WriteLine("Creating AppDomain PluginDomain");
            AppDomain pluginDomain = AppDomain.CreateDomain("PluginDomain");

            pluginDomain.AssemblyLoad += (s, e) => Console.WriteLine("{0} loaded {1}", AppDomain.CurrentDomain.FriendlyName, e.LoadedAssembly.FullName);
            IPluginCreator pluginCreator = PluginCreator.GetCreator(pluginDomain);

            try
            {
                ITestPlugin plugin;
                Dictionary <string, object> settings = new Dictionary <string, object>();
                settings.Add("Name", "SettingName");

                PluginFilter filter = PluginFilter.Create.Implements(typeof(ITestPlugin)).HasMinVersion("1.0");
                Console.WriteLine("Querying for plugins satisfying {0}", filter);
                PluginDescriptor[] foundPlugins = this.pluginRepository.Plugins(filter).ToArray();
                Console.WriteLine(string.Format("{0} plugins found", foundPlugins.Length));

                foreach (var pluginDescriptor in foundPlugins)
                {
                    Console.WriteLine(string.Format("Creating plugin {0} inside {1}", pluginDescriptor.QualifiedName.TypeFullName, pluginDomain.FriendlyName));
                    plugin = pluginCreator.Create(pluginDescriptor, this.assemblyRepository, settings) as ITestPlugin;
                    Console.WriteLine("Say hello plugin...");
                    plugin.SayHello();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Unloading {0}", pluginDomain.FriendlyName);
            AppDomain.Unload(pluginDomain);
        }
 public void GetCreatorCanReturnCreatorInsideAnotherAppDomain()
 {
     using (MockDomain otherDomain = new MockDomain())
     {
         IPluginCreator tested = PluginCreator.GetCreator(otherDomain);
         Assert.IsNotNull(tested);
     }
 }
        public void CreateRequiresPluginDescriptor()
        {
            IAssemblyRepository         repository = new MockAssemblyRepository();
            Dictionary <string, object> settings   = new Dictionary <string, object>();
            IPluginCreator tested = PluginCreator.GetCreator();

            DoAssert.Throws <ArgumentNullException>(() => tested.Create(null, repository, settings));
        }
        public void CreateShouldThrowIfMissingRequiredSettings()
        {
            MockAssemblyRepository repository = new MockAssemblyRepository();
            IPluginCreator         tested     = PluginCreator.GetCreator();
            PluginDescriptor       descriptor = MockPluginDescriptor.For <MockPlugin2>();

            DoAssert.Throws <PluginSettingException>(() => tested.Create(descriptor, repository, null));
        }
        public void CreateRequiresAssemblyRepository()
        {
            PluginDescriptor            descriptor = MockPluginDescriptor.For <MockPlugin1>();
            Dictionary <string, object> settings   = new Dictionary <string, object>();
            IPluginCreator tested = PluginCreator.GetCreator();

            DoAssert.Throws <ArgumentNullException>(() => tested.Create(descriptor, null, settings));
        }
 public void GetCreatorShouldReturnSameInstanceForSameDomain()
 {
     using (MockDomain otherDomain = new MockDomain())
     {
         IPluginCreator first  = PluginCreator.GetCreator(otherDomain);
         IPluginCreator tested = PluginCreator.GetCreator(otherDomain);
         Assert.AreSame(first, tested);
     }
 }
        public void CreateShouldCreatePluginInstance()
        {
            IAssemblyRepository repository = new MockAssemblyRepository();
            IPluginCreator      tested     = PluginCreator.GetCreator();
            PluginDescriptor    descriptor = MockPluginDescriptor.For <MockPlugin1>();
            object plugin = tested.Create(descriptor, repository, null);

            Assert.IsNotNull(plugin);
        }
        public void CreateShouldLogCatchedPluginExceptionAsError()
        {
            MockAssemblyRepository repository = new MockAssemblyRepository();
            IPluginCreator         tested     = PluginCreator.GetCreator();
            MockLog          mocklog          = new MockLog((ILogWriter)tested);
            PluginDescriptor descriptor       = MockPluginDescriptor.For <MockPlugin2>();
            Exception        ex = DoAssert.Throws <PluginSettingException>(() => tested.Create(descriptor, repository, null));

            Assert.IsTrue(mocklog.Any(x => x.Level == MockLog.Level.Error && x.Message.Contains(ex.Message)));
        }
 public void GetCreatorShouldReturnDifferentInstanceForDifferentDomain()
 {
     using (MockDomain domain1 = new MockDomain())
         using (MockDomain domain2 = new MockDomain())
         {
             IPluginCreator tested1 = PluginCreator.GetCreator(domain1);
             IPluginCreator tested2 = PluginCreator.GetCreator(domain2);
             Assert.AreNotSame(tested1, tested2);
         }
 }
 public void ShouldLogInfoEventWithDomainNameOnNewPluginCreator()
 {
     using (MockDomain domain = new MockDomain())
     {
         MockAssemblyRepository repository = new MockAssemblyRepository();
         MockLog mocklog        = new MockLog(typeof(PluginCreator));
         var     mockLogFactory = new Mock <ILoggerFactory>();
         mockLogFactory.Setup(x => x.GetLog(typeof(PluginCreator).FullName)).Returns(mocklog);
         PluginCreator.GetCreator(domain, mockLogFactory.Object);
         Assert.IsTrue(mocklog.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains(domain.Domain.FriendlyName)));
     }
 }
 public void ShouldLogInfoMessageWhenPluginIsCreated()
 {
     using (MockDomain domain = new MockDomain())
     {
         MockAssemblyRepository repository = new MockAssemblyRepository();
         var     creator    = PluginCreator.GetCreator(domain);
         MockLog mocklog    = new MockLog(creator as ILogWriter);
         var     descriptor = MockPluginDescriptor.For <MockPlugin1>();
         creator.Create(descriptor, repository, null);
         Assert.IsTrue(mocklog.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains(typeof(MockPlugin1).FullName)));
     }
 }
 public void CreateShouldResolveMissingAssemblies()
 {
     using (MockDomain domain = new MockDomain())
     {
         MockAssemblyRepository repository = new MockAssemblyRepository();
         IPluginCreator         tested     = PluginCreator.GetCreator(domain);
         PluginDescriptor       descriptor = MockPluginDescriptor.For <MockPlugin1>();
         object instance = tested.Create(descriptor, repository, null);
         Assert.IsNotNull(instance);
         Assert.IsTrue(repository.Fetched.Keys.Contains(typeof(MockPlugin1).Assembly.FullName));
     }
 }
        public void CreateShouldThrowIfSettingIsWrongType()
        {
            MockAssemblyRepository repository = new MockAssemblyRepository();
            IPluginCreator         tested     = PluginCreator.GetCreator();
            PluginDescriptor       descriptor = MockPluginDescriptor.For <MockPlugin2>();

            Dictionary <string, object> settings = new Dictionary <string, object>()
            {
                { "NamedSetting", "not int" }
            };

            DoAssert.Throws <PluginSettingException>(() => tested.Create(descriptor, repository, settings));
        }
        public void CreateShouldApplySettings()
        {
            MockAssemblyRepository repository = new MockAssemblyRepository();
            IPluginCreator         tested     = PluginCreator.GetCreator();
            PluginDescriptor       descriptor = MockPluginDescriptor.For <MockPlugin2>();

            Dictionary <string, object> settings = new Dictionary <string, object>()
            {
                { "NamedSetting", 42 }
            };

            MockPlugin2 plugin = tested.Create(descriptor, repository, settings) as MockPlugin2;

            Assert.AreEqual(42, plugin.Setting);
        }
        public void CreateShouldLogCatchedExceptionAsError()
        {
            using (MockDomain domain = new MockDomain())
            {
                MockAssemblyRepository repository = new MockAssemblyRepository();
                QualifiedName          fakeName   = new QualifiedName(
                    typeof(string).FullName.Replace("mscorlib", "NonExistingAssemblyName"),
                    typeof(string).Assembly.FullName.Replace("mscorlib", "NonExistingAssemblyName"));

                IPluginCreator   tested     = PluginCreator.GetCreator(domain);
                MockLog          mocklog    = new MockLog((ILogWriter)tested);
                PluginDescriptor descriptor = MockPluginDescriptor.For(fakeName);
                Exception        ex         = DoAssert.Throws <PluginException>(() => tested.Create(descriptor, repository, null));
                Assert.IsTrue(mocklog.Any(x => x.Level == MockLog.Level.Error && x.Message.Contains(ex.Message)));
            }
        }
        public void CreateShouldThrowOnUnresolvedAssembly()
        {
            using (MockDomain domain = new MockDomain())
            {
                MockAssemblyRepository repository = new MockAssemblyRepository();
                IPluginCreator         tested     = PluginCreator.GetCreator(domain);
                QualifiedName          fakeName   = new QualifiedName(
                    typeof(string).FullName.Replace("mscorlib", "NonExistingAssemblyName"),
                    typeof(string).Assembly.FullName.Replace("mscorlib", "NonExistingAssemblyName"));

                PluginDescriptor descriptor = MockPluginDescriptor.For(fakeName);

                PluginException ex = DoAssert.Throws <PluginException>(() => tested.Create(descriptor, repository, null));
                Assert.IsNotNull(ex.InnerException);
                Assert.IsInstanceOfType(ex.InnerException, typeof(FileNotFoundException));
            }
        }
示例#18
0
        internal void LoadPlugins(Assembly ass)
        {
            var allOfThemTypes = ass.GetTypes();

            foreach (var type in allOfThemTypes)
            {
                if (typeof(IPlugin).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
                {
                    logger.Info($"Loading Plugin {type.Name} from Assembly {ass.FullName}");
                    plugins.Add(PluginCreator <IPlugin> .GetInstance(type));
                }
                else if (typeof(BaseController).IsAssignableFrom(type))
                {
                    ControllerTypes.Add(type);
                }
                else if (typeof(IDbUpdater).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
                {
                    var updater = PluginCreator <IDbUpdater> .GetInstance(type);

                    DbUpdater.Add(updater);
                }
            }
        }
        /// <summary>
        /// Generates proxy classes
        /// </summary>
        /// <param name="generatorParams"></param>
        public void GenerateClientProxyClasses(GeneratorParams generatorParams)
        {
            _logger.LogInformation(Resources.Generating_Client_Proxy____);

            try
            {
                var edmxTmpFile = GetMetadata(generatorParams, out var version);

                if (version == Constants.EdmxVersion4)
                {
                    throw new ArgumentException(string.Format(Resources.Wrong_edx_version, version));
                }

                var generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode)
                {
                    UseDataServiceCollection = true,
                    Version = DataServiceCodeVersion.V3
                };

                // Set up XML secure resolver
                var xmlUrlResolver = new XmlUrlResolver
                {
                    Credentials = CredentialCache.DefaultNetworkCredentials
                };

                var permissionSet = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);

                var settings = new XmlReaderSettings
                {
                    XmlResolver = new XmlSecureResolver(xmlUrlResolver, permissionSet)
                };

                var fileHandler = new FilesHandler();

                using (var reader = XmlReader.Create(generatorParams.MetadataUri, settings))
                {
                    var tempFile = Path.GetTempFileName();
                    var noErrors = true;

                    using (StreamWriter writer = File.CreateText(tempFile))
                    {
                        var errors = generator.GenerateCode(reader, writer, generatorParams.NamespacePrefix);
                        writer.Flush();

                        if (errors != null && errors.Any())
                        {
                            noErrors = false;

                            foreach (var err in errors)
                            {
                                _logger.LogError(err.Message);
                            }
                            _logger.LogError(Resources.Client_Proxy_for_OData_V3_was_not_generated_);
                        }
                    }

                    if (noErrors)
                    {
                        var csFile = new FileInfo(Path.Combine(generatorParams.OutputDir, generatorParams.OutputFilename + ".cs"));
                        _logger.LogInformation(string.Format(Resources.Writing_file__0_, csFile.FullName));
                        fileHandler.AddFileAsync(tempFile, csFile.FullName).ConfigureAwait(true);

                        var edmxFile = new FileInfo(Path.Combine(generatorParams.OutputDir, generatorParams.OutputFilename + ".edmx"));
                        _logger.LogInformation(string.Format(Resources.Writing_file__0_, edmxFile.FullName));
                        fileHandler.AddFileAsync(edmxTmpFile, edmxFile.FullName).ConfigureAwait(true);

                        foreach (var pluginCommand in generatorParams.Plugins)
                        {
                            var plugin = PluginCreator.Create(_logger, generatorParams, pluginCommand);
                            plugin.Execute();
                        }
                    }
                }

                _logger.LogInformation(Resources.Client_Proxy_for_OData_V3_was_generated_);
            }
            catch (Exception e)
            {
                _logger.LogCritical(Resources.Errors_during_generation_Client_Proxy_for_OData_V3, e);
                throw;
            }
        }
        public void GetCreatorCanReturnCreatorInsideCurrentAppDomain()
        {
            IPluginCreator tested = PluginCreator.GetCreator();

            Assert.IsNotNull(tested);
        }
 public void InternalGetCreatorRequiresDomain()
 {
     DoAssert.Throws <ArgumentNullException>(() => PluginCreator.GetCreator(null, Logger.Singleton.LoggerFactory));
 }
 public void InternalGetCreatorRequiresILoggerFactory()
 {
     DoAssert.Throws <ArgumentNullException>(() => PluginCreator.GetCreator(AppDomain.CurrentDomain, null));
 }
 public void GetCreatorRequiresArgument()
 {
     DoAssert.Throws <ArgumentNullException>(() => PluginCreator.GetCreator(null));
 }
        /// <summary>
        /// Generates proxy classes
        /// </summary>
        /// <param name="configuration"></param>
        public void GenerateClientProxyClasses(GeneratorParams configuration)
        {
            _logger.LogInformation(Resources.Generating_Client_Proxy____);

            if (string.IsNullOrWhiteSpace(configuration.MetadataDocumentUri))
            {
                throw new ArgumentNullException(nameof(configuration.MetadataDocumentUri));
            }

            var version = GetMetadataVersion(configuration);

            if (version != Constants.EdmxVersion4)
            {
                throw new ArgumentException(string.Format(Resources.Wrong_edx_version, version));
            }

            ODataT4CodeGenerator t4CodeGenerator = new ODataT4CodeGenerator();

            t4CodeGenerator.MetadataDocumentUri      = configuration.MetadataDocumentUri;
            t4CodeGenerator.UseDataServiceCollection = configuration.UseDataServiceCollection;
            t4CodeGenerator.TargetLanguage           = ODataT4CodeGenerator.LanguageOption.CSharp;
            t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = configuration.IgnoreUnexpectedElementsAndAttributes;
            t4CodeGenerator.EnableNamingAlias                  = configuration.EnableNamingAlias;
            t4CodeGenerator.NamespacePrefix                    = configuration.NamespacePrefix;
            t4CodeGenerator.MakeTypesInternal                  = configuration.MakeTypesInternal;
            t4CodeGenerator.GenerateMultipleFiles              = configuration.GenerateMultipleFiles;
            t4CodeGenerator.ExcludedOperationImports           = configuration.ExcludedOperationImports;
            t4CodeGenerator.ExcludedBoundOperations            = configuration.ExcludedBoundOperations;
            t4CodeGenerator.ExcludedSchemaTypes                = configuration.ExcludedSchemaTypes;
            t4CodeGenerator.CustomHttpHeaders                  = configuration.CustomHttpHeaders;
            t4CodeGenerator.IncludeWebProxy                    = configuration.IncludeWebProxy;
            t4CodeGenerator.WebProxyHost                       = configuration.WebProxyHost;
            t4CodeGenerator.IncludeWebProxyNetworkCredentials  = configuration.IncludeWebProxyNetworkCredentials;
            t4CodeGenerator.WebProxyNetworkCredentialsUsername = configuration.WebProxyNetworkCredentialsUsername;
            t4CodeGenerator.WebProxyNetworkCredentialsPassword = configuration.WebProxyNetworkCredentialsPassword;
            t4CodeGenerator.WebProxyNetworkCredentialsDomain   = configuration.WebProxyNetworkCredentialsDomain;
            t4CodeGenerator.CustomContainerName                = configuration.CustomContainerName;

            var tempFile        = Path.GetTempFileName();
            var referenceFolder = configuration.OutputDirectory;

            var fileHandler = new FilesHandler(_logger);

            fileHandler.TokenReplacementValues.Add("#VersionNumber#", Constants.GeneratorVersion);

            var serviceFilename = Constants.DefaultServiceFilename;

            if (!string.IsNullOrWhiteSpace(configuration.CustomContainerName))
            {
                serviceFilename = configuration.CustomContainerName;
            }

            var csdlFileName = string.Concat(serviceFilename, Constants.CsdlFileNameSuffix);
            var metadataFile = Path.Combine(referenceFolder, csdlFileName);

            fileHandler.AddFileAsync(tempFile, metadataFile).ConfigureAwait(true);

            t4CodeGenerator.EmitContainerPropertyAttribute = false;
            t4CodeGenerator.MetadataFilePath         = metadataFile;
            t4CodeGenerator.MetadataFileRelativePath = csdlFileName;

            try
            {
                using (StreamWriter writer = File.CreateText(tempFile))
                {
                    writer.Write(t4CodeGenerator.TransformText());
                    writer.Flush();
                    if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0)
                    {
                        foreach (var err in t4CodeGenerator.Errors)
                        {
                            _logger?.LogError(err.ToString());
                        }
                        _logger.LogError(Resources.Client_Proxy_for_OData_V4_was_not_generated_);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(Resources.Generators_error, e);
                throw;
            }

            var outputFile = Path.Combine(referenceFolder, string.IsNullOrWhiteSpace(configuration.CustomContainerName) ? $"{Constants.DefaultServiceFilename}.cs" : $"{configuration.CustomContainerName}.cs");

            fileHandler.AddFileAsync(tempFile, outputFile).ConfigureAwait(true);
            t4CodeGenerator.MultipleFilesManager?.GenerateFiles(true, fileHandler, referenceFolder, true, false);

            foreach (var pluginCommand in configuration.Plugins)
            {
                var plugin = PluginCreator.Create(_logger, configuration, pluginCommand);
                plugin.Execute();
            }

            _logger?.LogInformation(Resources.Client_Proxy_for_OData_V4_was_generated_);
        }