예제 #1
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(ContainerBuilder builder
                                      , IContainer Container
                                      , ITypeFinder typeFinder
                                      , IConfigurationSectionHandler config
                                      , IConfigOptions options)
        {
            //we cache presentation models between requests

            builder
            .RegisterGeneric(typeof(EfRepository <>))
            .As(typeof(IRepository <>))
            .InstancePerLifetimeScope();

            var lconfig = (ReposConfig)config;


            if (!Container.IsRegistered <IDbContext>())
            {
                builder
                .Register <IDbContext>(c => new ReposContext(lconfig.ContextName))
                .InstancePerLifetimeScope();
            }

            builder
            .RegisterType <PerRequestCacheManager>()
            .As <ICacheManager>()
            .Named <ICacheManager>("repos_cache_per_request")
            .InstancePerLifetimeScope();
        }
        /// <summary>
        /// Gets the handler for a config section
        /// </summary>
        /// <param name="sectionName">Name of the handler</param>
        /// <param name="parentHandler">Handler of the parent section</param>
        /// <param name="xmlDoc">XML document containing the config</param>
        /// <returns>Handler for a config section</returns>
        private static object GetAppSettingsFileHandler(string sectionName, IConfigurationSectionHandler parentHandler, XmlDocument xmlDoc)
        {
            object       handler = null;
            XmlNode      node    = xmlDoc.SelectSingleNode("//" + sectionName);
            XmlAttribute att     = (XmlAttribute)node.Attributes.RemoveNamedItem("file");

            if (att == null || att.Value == null || att.Value.Length == 0)
            {
                return(parentHandler.Create(null, null, node));
            }
            else
            {
                string      fileName = att.Value;
                string      dir      = Path.GetDirectoryName(fileName);
                string      fullName = Path.Combine(dir, fileName);
                XmlDocument xmlDoc2  = new XmlDocument();
                xmlDoc2.Load(fullName);

                object parent = parentHandler.Create(null, null, node);
                IConfigurationSectionHandler h = new NameValueSectionHandler();
                handler = h.Create(parent, null, xmlDoc2.DocumentElement);
            }

            return(handler);
        }
        /// <summary>
        /// Gets the handler for a config section
        /// </summary>
        /// <param name="sectionName">Name of the section</param>
        /// <param name="xmlDoc">XML document containing the config</param>
        /// <returns>Handler for a config section</returns>
        private static IConfigurationSectionHandler GetHandler(string sectionName, XmlDocument xmlDoc)
        {
            IConfigurationSectionHandler handler = null;

            handler = new NameValueSectionHandler();
            return(handler);
        }
예제 #4
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(

#if DI_UNITY
#else
            ContainerBuilder builder
          , IContainer Container
#endif
         , ITypeFinder typeFinder
         , IConfigurationSectionHandler config
         , IConfigOptions options)
        {




           // var appConfig = ConfigurationManager.OpenExeConfiguration("C:\\VSProjects\\Repos\\bin\\ReposServiceConfigures.dll");

           // var local = appConfig.Sections.Cast<ConfigurationSection>().Where(s => s.SectionInformation.Name == "ServiceConfig");
           var appConfig = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);

            //Assembly.GetExecutingAssembly().Location);

            var localconfig = appConfig.GetSection("ServiceConfig") as IConfigurationSectionHandler;


            //if (options.Contains( enumConfigOpts.RegAll))
            //    SetResolveNameFlag(ResolveDepName.YES);
            
        }
예제 #5
0
        internal IConfigurationSectionHandler GetSectionHandler(string configKey)
        {
            if ((this.sectionHandlers == null) || !(this.sectionHandlers.Contains(configKey)))
            {
                if (!this.shouldInheritSections && this.parent != null)
                {
                    return(this.parent.GetSectionHandler(configKey));
                }
                return(null);
            }
            object obj = this.sectionHandlers[configKey];

            if (obj == removedSectionObj)
            {
                return(null);
            }
            IConfigurationSectionHandler sectionHandler = obj as IConfigurationSectionHandler;

            if (sectionHandler != null)
            {
                return(sectionHandler);
            }
            sectionHandler = CreateSectionHandler(obj);
            lock (this.sectionHandlers.SyncRoot)
            {
                this.sectionHandlers[configKey] = sectionHandler;
            }
            return(sectionHandler);
        }
예제 #6
0
        object GetConfigInternal(string sectionName)
        {
            object handler = GetHandler(sectionName);
            IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;

            if (iconf == null)
            {
                return(handler);
            }

            object parentConfig = null;

            if (parent != null)
            {
                parentConfig = parent.GetConfig(sectionName);
            }

            XmlDocument doc = GetDocumentForSection(sectionName);

            if (doc == null || doc.DocumentElement == null)
            {
                return(parentConfig);
            }

            return(iconf.Create(parentConfig, fileName, doc.DocumentElement));
        }
예제 #7
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(ContainerBuilder builder
         , IContainer Container
         , ITypeFinder typeFinder
         , IConfigurationSectionHandler config
         , IConfigOptions options)
        {

            if (!Container.IsRegistered<IRule>())
                builder
                .RegisterType<DefaultDomainRule>()
                .As<IRule>()
                .InstancePerLifetimeScope();

            if (!Container.IsRegistered<IDomainEdit>())
                builder
                  .RegisterType<DefaultServiceEntityEdit>()
                  .As<IDomainEdit>()
                  .InstancePerLifetimeScope();

            if (!Container.IsRegistered<ICacheService>())
                builder
                .RegisterType<CacheService>()
                .As<ICacheService>()
                .InstancePerLifetimeScope();
        }
예제 #8
0
        protected virtual void RegisterDependencies(IConfigurationSectionHandler config)
        {
            var builder   = new ContainerBuilder();
            var container = builder.Build();

            this._containerManager = new ContainerManager(container);

            //dependencies
            var typeFinder = new WebAppTypeFinder();

            builder = new ContainerBuilder();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
            builder.Update(container);



            foreach (var dependencyRegistrar
                     in new Type[] {
                typeof(DependencyRegistrar)
                , typeof(Repos.DomainModel.Interface.DependencyRegistrar)
                , typeof(FilterDependencyRegistrar)
                , typeof(ReposDomain.Handlers.DependencyRegistrar)
                , typeof(ReposDomain.Filters.DependencyRegistrar)
                //          ,typeof(ValidationDependencyRegistrar)
                //        ,typeof(ReposAdmin.ValidationDependencyRegistrar)
            })

            {
                var dep = (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar);
                builder = new ContainerBuilder();
                dep.Register(builder, container, null, config, new TestClassConfigOptions());
                builder.Update(container);
            }
        }
예제 #9
0
            private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
            {
                // Get the type of the factory
                Type type = TypeUtil.GetType(configRecord.Host, factoryRecord.FactoryTypeName,
                                             true);

                // If the type is a ConfigurationSection, that's the type.
                if (typeof(ConfigurationSection).IsAssignableFrom(type))
                {
                    _sectionCtor = TypeUtil.GetConstructor(type, typeof(ConfigurationSection),
                                                           true);
                }
                else
                {
                    // Note: in v1, IConfigurationSectionHandler is in effect a factory that has a Create method
                    // that creates the real section object.

                    // throws if type does not implement IConfigurationSectionHandler
                    TypeUtil.VerifyAssignableType(typeof(IConfigurationSectionHandler), type, true);

                    // Create an instance of the handler
                    _sectionHandler =
                        (IConfigurationSectionHandler)TypeUtil.CreateInstance(type);
                }
            }
        /// <summary>
        /// Configures the <seealso cref="FrameworkEnvironment"/>
        /// </summary>
        public static FrameworkEnvironment Configure(IConfigurationSectionHandler configuration = null)
        {
            if (Instance == null)
            {
                lock (typeof(FrameworkEnvironment))
                {
                    try
                    {
                        //Load configuration from config file if not provided
                        configuration = configuration ?? (FrameworkConfiguration)ConfigurationManager.GetSection("Framework");

                        //Create environment and configure it.
                        var env = new FrameworkEnvironment((IFrameworkConfiguration)configuration);
                        env.ConfigureContainer();
                        return(env);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine("Error configuring Environment: {0}", exception);
                        throw;
                    }
                }
            }

            return(Instance);
        }
예제 #11
0
        public static object ReadSection(Configuration conf, string sectionname)
        {
            ConfigurationSection section = null;

            if (conf == null || (section = conf.GetSection(sectionname)) == null)
            {
                return(null);
            }

            string xml  = section.SectionInformation.GetRawXml();
            Type   type = Type.GetType(section.SectionInformation.Type);

            if (typeof(IConfigurationSectionHandler).IsAssignableFrom(type))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(XmlReader.Create(new StringReader(xml)));

                IConfigurationSectionHandler configSectionHandlerHandle = Activator.CreateInstance(type) as IConfigurationSectionHandler;
                if (configSectionHandlerHandle != null)
                {
                    return(configSectionHandlerHandle.Create(null, null, doc));
                }
            }
            return(xml);
        }
예제 #12
0
        private object EvaluateRecursive(IConfigurationSectionHandler sectionHandler, object config, string[] keys, int keyIndex, XmlTextReader reader)
        {
            string name  = keys[keyIndex];
            int    depth = reader.Depth;

            while (reader.Read() && reader.NodeType != XmlNodeType.Element)
            {
                ;
            }
            while (reader.Depth == depth + 1)
            {
                if (reader.Name == name)
                {
                    if (keyIndex < keys.Length - 1)
                    {
                        config = EvaluateRecursive(sectionHandler, config, keys, keyIndex + 1, reader);
                    }
                    else
                    {
                        XmlDocument doc     = new XmlDocument();
                        XmlNode     section = doc.ReadNode(reader);
                        config = sectionHandler.Create(config, null, section);
                    }
                    continue;
                }
                SkipToNextElement(reader);
            }
            return(config);
        }
예제 #13
0
        // Get a configuration object, using a particular handler.
        // This is for internal use, to provide a fallback handler
        // if the section is not mentioned in "machine.default".
        internal static Object GetConfig
            (String sectionName, IConfigurationSectionHandler handler)
        {
            // Make sure that the configuration system is initialized.
            BuiltinConfigurationSystem system;

            lock (typeof(ConfigurationSettings))
            {
                if (configSystem != null)
                {
                    system = configSystem;
                }
                else if (configError != null)
                {
                    throw configError;
                }
                else
                {
                    configSystem = new BuiltinConfigurationSystem();
                    try
                    {
                        configSystem.Init();
                    }
                    catch (Exception e)
                    {
                        configError = e;
                        throw;
                    }
                    system = configSystem;
                }
            }

            // Look up the specified configuration item.
            return(system.GetConfig(sectionName, handler));
        }
예제 #14
0
        protected virtual void RegisterDependencies(IConfigurationSectionHandler config)
        {
            var builder   = new ContainerBuilder();
            var container = builder.Build();

            this._containerManager = new ContainerManager(container);

            //dependencies
            var typeFinder = new WebAppTypeFinder();

            builder = new ContainerBuilder();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
            builder.Update(container);



            //foreach (var dependencyRegistrar
            //               in new Type[]{
            //                   typeof(DependencyRegistrar)
            //                  ,typeof(Repos.DomainModel.Interface.DependencyRegistrar)
            //                  ,typeof(ReposDomain.Handlers.DependencyRegistrar)
            //               })

            //{
            //    var dep = (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar);
            //    builder = new ContainerBuilder();
            //    dep.Register(builder, container, null, config, new DefaultConfOptions());
            //    builder.Update(container);
            //}

            ReqisterDependencies.DependencyRegister(container, config, new DefaultConfOptions());
        }
예제 #15
0
        private object Evaluate(string configKey)
        {
            IConfigurationSectionHandler sectionHandler = GetSectionHandler(configKey);
            object parentResult = this.parent != null?this.parent.GetConfig(configKey) : null;

            string[]      keys   = configKey.Split(new char[] { '/' });
            XmlTextReader reader = null;
            object        result = null;

            try
            {
                reader = OpenXmlTextReader(this.configurationFile);
                result = EvaluateRecursive(sectionHandler, parentResult, keys, 0, reader);
            }
            catch (XmlException e)
            {
                throw new ConfigurationException(e.Message, e, this.configurationFile, e.LineNumber);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            RemoveUnresolvedConfig(configKey);
            return(result);
        }
예제 #16
0
        /// <summary>
        /// Reads the specified configuration section from the given <see cref="XmlDocument"/>
        /// </summary>
        /// <param name="document"></param>
        /// <param name="configSectionName"></param>
        /// <param name="defaultConfigurationSectionHandlerType"></param>
        /// <returns></returns>
        public static object GetSectionFromXmlDocument(XmlDocument document, string configSectionName, Type defaultConfigurationSectionHandlerType)
        {
            Type handlerType = GetSectionHandlerType(document, configSectionName, defaultConfigurationSectionHandlerType);

            // obtain Xml node with section content
            XmlNode sectionContent = document.SelectSingleNode(string.Format("//{0}/{1}", ConfigurationElement, configSectionName));

            if (sectionContent == null)
            {
                // TODO: review if we shouldn't better simply return null here to match the ConfigurationManager's behaviour?
                throw ConfigurationUtils.CreateConfigurationException("Cannot read config section '" + configSectionName + "' - section not found.");
            }

            // IConfigurationSectionHandler
            if (typeof(IConfigurationSectionHandler).IsAssignableFrom(handlerType))
            {
                IConfigurationSectionHandler handler = (IConfigurationSectionHandler)ObjectUtils.InstantiateType(handlerType);
                return(handler.Create(null, null, sectionContent));
            }

            // NET 2.0 ConfigurationSection
            if (typeof(ConfigurationSection).IsAssignableFrom(handlerType))
            {
                ConfigurationSection section = CreateConfigurationSection(handlerType, new XmlNodeReader(sectionContent));
                return(section);
            }

            // Not supported
            throw ConfigurationUtils.CreateConfigurationException("Configuration section '" + configSectionName + "' is neither of type IConfigurationSectionHandler nor ConfigurationSection.");
        }
예제 #17
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(ContainerBuilder builder
                                      , IContainer Container
                                      , ITypeFinder typeFinder
                                      , IConfigurationSectionHandler config
                                      , IConfigOptions options)
        {
            ValidAssmPrefix(config);


            if (!Container.IsRegistered <IRule>())
            {
                builder
                .RegisterType <DomainRule>()
                .As <IRule>()
                .InstancePerLifetimeScope();
            }


            SetDependency <IEntityRule, IModelRule>(
                builder
                , Container
                , this
                .GetType()
                .Assembly
                .GetTypes()
                , EnumServiceTypes.Rules
                , options
                );
        }
예제 #18
0
        object GetConfigInternal(string sectionName, HttpContext context, bool useLoc)
        {
            object handler = GetHandler(sectionName);
            IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;

            if (iconf == null)
            {
                return(handler);
            }

            object parentConfig = null;

            if (parent != null)
            {
                if (useLoc)
                {
                    parentConfig = parent.GetConfig(sectionName, context);
                }
                else
                {
                    parentConfig = parent.GetConfigOptLocation(sectionName, context, false);
                }
            }

            XmlDocument doc = GetDocumentForSection(sectionName);

            if (doc == null || doc.DocumentElement == null)
            {
                return(parentConfig);
            }

            return(iconf.Create(parentConfig, fileName, doc.DocumentElement));
        }
예제 #19
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(ContainerBuilder builder
                                      , IContainer Container
                                      , ITypeFinder typeFinder
                                      , IConfigurationSectionHandler config
                                      , IConfigOptions options)
        {
            if (!CallBaseResolver)
            {
                return;
            }


            var RegTypes = ResolveTypes <IBaseService>(typeFinder, options);

            SetDependency <IBaseService, INullResolver, INullResolver>(
                builder
                , Container
                , RegTypes
                , EnumServiceTypes.None //, "Handlers"
                , options

                );


            //var services = this.GetType().Assembly.GetTypes()
            //              .Where(t => typeof(IBaseService).IsAssignableFrom(t)
            //                          && !t.IsAbstract)
            //              .Where(i => i.GetInterfaces()
            //              .Any(g => g.IsGenericType
            //                    && g.GetType().GetInterfaces().Any()))
            //              .Select(map => new
            //              {
            //                  target = map
            //              });

            //IHttpContextAccessor



            builder
            .RegisterType <HttpContextAccessor>()
            .As <IHttpContextAccessor>()
            .AsImplementedInterfaces()
            .InstancePerDependency();


            //ICacheService
            //foreach (var service in services)
            //{
            //    var serviceName = SetResolveName(service.target);

            //    if (!Container.IsRegisteredWithName<IBaseService>(serviceName))
            //        builder
            //            .RegisterType(service.target)
            //            .Named<IBaseService>(serviceName)
            //            .AsImplementedInterfaces()
            //            .InstancePerDependency();
            //}
        }
예제 #20
0
 /// <summary>
 /// Register services and interfaces
 /// </summary>
 /// <param name="builder">Container builder</param>
 /// <param name="typeFinder">Type finder</param>
 /// <param name="config">Config</param>
 public override void Register(ContainerBuilder builder
                               , IContainer Container
                               , ITypeFinder typeFinder
                               , IConfigurationSectionHandler config
                               , IConfigOptions options)
 {
     base.Register(builder, Container, typeFinder, config, options);
 }
예제 #21
0
 /// <summary>
 /// Register services and interfaces
 /// </summary>
 /// <param name="builder">Container builder</param>
 /// <param name="typeFinder">Type finder</param>
 /// <param name="config">Config</param>
 public override void Register(ContainerBuilder builder
                               , IContainer Container
                               , ITypeFinder typeFinder
                               , IConfigurationSectionHandler config
                               , IConfigOptions options)
 {
     //we cache presentation models between requests
 }
예제 #22
0
        //public static IEngine Initialize(IEngine Engine)
        //{
        //    Singleton<IEngine>.Instance = Engine;
        //     var config = ConfigurationManager.GetSection("ReposConfig")  as IConfigurationSectionHandler;
        //     Singleton<IEngine>.Instance.Initialize(config);

        //    return Singleton<IEngine>.Instance;
        //}

        public static IEngine Initialize(IEngine Engine, IConfigurationSectionHandler config)
        {
            Singleton <IEngine> .Instance = Engine;
            //  var config = ConfigurationManager.GetSection("ReposConfig") as IConfigurationSectionHandler;
            Singleton <IEngine> .Instance.Initialize(config);

            return(Singleton <IEngine> .Instance);
        }
예제 #23
0
        private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string [] keys, int iKey, XmlTextReader reader)
        {
            string name = keys[iKey];

            TraceVerbose("  EvaluateRecursive " + iKey + " " + name);

            int depth = reader.Depth;

            while (reader.Read() && reader.NodeType != XmlNodeType.Element)
            {
                ;
            }

            while (reader.Depth == depth + 1)
            {
                TraceVerbose("  EvaluateRecursive " + iKey + " " + name + " Name:" + reader.Name);
                if (reader.Name == name)
                {
                    if (iKey < keys.Length - 1)
                    {
                        config = EvaluateRecursive(factory, config, keys, iKey + 1, reader);
                    }
                    else
                    {
                        TraceVerbose("  EvaluateRecursive " + iKey + " calling Create()");
                        Debug.Assert(iKey == keys.Length - 1);

                        //
                        // Call configuration section handler
                        //
                        // - try-catch is necessary to insulate config system from exceptions in user config handlers.
                        //   - bubble ConfigurationExceptions & XmlException
                        //   - wrap all others in ConfigurationException
                        //
                        int line = reader.LineNumber;
                        try {
                            ConfigXmlDocument doc = new ConfigXmlDocument();
                            doc.LoadSingleElement(_filename, reader);
                            config = factory.Create(config, null, doc.DocumentElement);
                        }
                        catch (ConfigurationException) {
                            throw;
                        }
                        catch (XmlException) {
                            throw;
                        }
                        catch (Exception ex) {
                            throw new ConfigurationException(
                                      SR.GetString(SR.Exception_in_config_section_handler),
                                      ex, _filename, line);
                        }
                    }
                    continue;
                }
                StrictSkipToNextElement(reader);
            }
            return(config);
        }
예제 #24
0
        public static T OpenCreate <T>(this IConfigurationSectionHandler <T> configurationLocation)
        {
            if (!configurationLocation.Exists())
            {
                return(configurationLocation.Create());
            }

            return(configurationLocation.Open());
        }
예제 #25
0
        /// <summary>
        /// Initialize components and plugins in the nop environment.
        /// </summary>
        /// <param name="config">Config</param>
        public void Initialize(IConfigurationSectionHandler configHandler)
        {
            ConfOptions options = new DefaultConfOptions();


            //register dependencies
            RegisterDependencies((ReposConfig)configHandler, options);
            RunStartupTasks();
        }
        public object Create(object parent, object configContext, XmlNode section)
        {
            Type configReaderBaseType = Type.GetType(((XmlElement)section)?.GetAttribute("configReaderBaseType"));

            ValidateBaseType(configReaderBaseType);

            BaseConfig = CreateDynamicConfigReader(configReaderBaseType);

            return(BaseConfig.Create(parent, configContext, section));
        }
예제 #27
0
        public void Initialize(IConfigurationSectionHandler config
                               , TestClassConfigOptions opts = null)
        {
            if (opts == null)
            {
                opts = new TestClassConfigOptions();
            }

            RegisterDependencies(config, opts);
        }
예제 #28
0
    public DefaultConfiguration(IConfigurationSectionHandler configurationSectionHandler)
    {
      MerchantId = configurationSectionHandler.MerchantId;
      MerchantSubId = configurationSectionHandler.MerchantSubId;
      AcquirerUrl = configurationSectionHandler.AcquirerUrl;

      // Retrieve acceptant's certificate
      if (!configurationSectionHandler.AcceptantCertificateFilename.IsNullEmptyOrWhiteSpace())
      {
        // Retrieve certificate from file
        if (configurationSectionHandler.AcceptantCertificatePassword.IsNullEmptyOrWhiteSpace())
          throw new ConfigurationErrorsException("Password is required when acceptant's certificate is loaded from filesystem");

        AcceptantCertificate = GetCertificateFromFile(configurationSectionHandler.AcceptantCertificateFilename, configurationSectionHandler.AcceptantCertificatePassword);
      }
      else if (configurationSectionHandler.AcceptantCertificateStoreLocation != null)
      {
        // Retrieve certificate from certificate store
        if (configurationSectionHandler.AcceptantCertificateStoreName.IsNullEmptyOrWhiteSpace())
          throw new ConfigurationErrorsException("Acceptant's certificate store name is required when loading certificate from the certificate store");

        if (configurationSectionHandler.AcceptantCertificateThumbprint.IsNullEmptyOrWhiteSpace())
          throw new ConfigurationErrorsException("Acceptant's certificate thumbprint is required when loading certificate from the certificate store");

        AcceptantCertificate = GetCertificateFromStore(configurationSectionHandler.AcceptantCertificateStoreLocation.Value, configurationSectionHandler.AcceptantCertificateStoreName, configurationSectionHandler.AcceptantCertificateThumbprint);
      }
      else
      {
        // Neither filename nor store location is specified
        throw new ConfigurationErrorsException("You should either specify a filename or a certificate store location to specify the acceptant's certificate.");
      }

      // Retrieve acquirer's certificate
      if (!configurationSectionHandler.AcquirerCertificateFilename.IsNullEmptyOrWhiteSpace())
      {
        // Retrieve certificate from file
        AcquirerCertificate = GetCertificateFromFile(configurationSectionHandler.AcquirerCertificateFilename, null);
      }
      else if (configurationSectionHandler.AcquirerCertificateStoreLocation != null)
      {
        // Retrieve certificate from certificate store
        if (configurationSectionHandler.AcquirerCertificateStoreName.IsNullEmptyOrWhiteSpace())
          throw new ConfigurationErrorsException("Acquirer's certificate store name is required when loading certificate from the certificate store");

        if (configurationSectionHandler.AcquirerCertificateThumbprint.IsNullEmptyOrWhiteSpace())
          throw new ConfigurationErrorsException("Acquirer's certificate thumbprint is required when loading certificate from the certificate store");

        AcquirerCertificate = GetCertificateFromStore(configurationSectionHandler.AcquirerCertificateStoreLocation.Value, configurationSectionHandler.AcquirerCertificateStoreName, configurationSectionHandler.AcquirerCertificateThumbprint);
      }
      else
      {
        // Neither filename nor store location is specified
        throw new ConfigurationErrorsException("You should either specify a filename or a certificate store location to specify the acquirer's certificate.");
      }
    }
예제 #29
0
        public static object DeserializeXmlNode(
            IConfigurationSectionHandler caller,
            string sectionName,
            XmlNode node,
            string typeName,
            bool shouldNodeNameMatchTypeName = true)
        {
            Type typeToDeserialize = Type.GetType(typeName);

            if (typeToDeserialize == null)
            {
                throw NewConfigurationErrorsException(sectionName, $"\"{typeName}\" is not a recognized type name.");
            }

            string xmlString     = node.OuterXml;
            string nodeName      = node.Name;
            string shortTypeName = typeToDeserialize.Name;

            if (shouldNodeNameMatchTypeName && nodeName != shortTypeName)
            {
                xmlString = xmlString
                            .Replace($"<{nodeName}>", $"<{shortTypeName}>")
                            .Replace($"<{nodeName} ", $"<{shortTypeName} ")
                            .Replace($"</{nodeName}>", $"</{shortTypeName}>");
            }

            var xmlSerializer = new XmlSerializer(typeToDeserialize);

            try
            {
                using (var sr = new StringReader(xmlString))
                {
                    return(xmlSerializer.Deserialize(sr));
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "There is an error in the XML document.")
                {
                    Exception inner = ex.InnerException;
                    if (inner != null && inner.Message.ToLowerInvariant().Contains(sectionName.ToLowerInvariant()))
                    {
                        throw new ConfigurationErrorsException(
                                  $"Unable to load from the \"{sectionName} .config section using {caller.GetType().FullName}."
                                  + " Please check the \"configSections\" definition for this section.",
                                  ex
                                  );
                    }
                }

                throw;
            }
        }
예제 #30
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public override void Register(ContainerBuilder builder
                                      , IContainer Container
                                      , ITypeFinder typeFinder
                                      , IConfigurationSectionHandler config
                                      , IConfigOptions options)
        {
            base.Register(builder, Container, typeFinder, config, options);

            //ValidAssmPrefix(config);

            //if (!CallBaseResolver)
            //    return;

            //var RegTypes = ResolveTypes<IHandler>(typeFinder, options);



            //if (!Container.IsRegistered<ClientRefInfoHandler>())
            // builder
            //   .RegisterType<ClientRefInfoHandler>()
            //   .As<IClientRefInfoHandler>()
            //   .InstancePerLifetimeScope();

            //var sup = RegTypes
            //           .Where(w => !w.GetCustomAttributes(typeof(ServiceNoResolveAttribute), true)
            //                               .Any()).ToList<Type>();


            //SetDependency<IEditFilter, INullResolver>(
            //    builder
            //    , Container
            //     , sup
            //     , EnumServiceTypes.None
            //     , options
            //   );

            //SetDependency<IHandler, IServiceHandler, INullResolver>(
            //    builder
            //    , Container
            //     , sup
            //     , EnumServiceTypes.Handlers //, "Handlers"
            //     , options

            //   );

            //SetDependency<IGenericHandler, INullResolver>(
            //    builder
            //    , Container
            //     , sup
            //     , EnumServiceTypes.None
            //     , options
            //   );
        }
예제 #31
0
        private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string[] keys, int iKey, XmlTextReader reader, object context)
        {
            string name  = keys[iKey];
            int    depth = reader.Depth;

            while (reader.Read() && reader.NodeType != XmlNodeType.Element)
            {
                ;
            }

            while (reader.Depth == depth + 1)
            {
                if (reader.Name == name)
                {
                    if (iKey < keys.Length - 1)
                    {
                        config = EvaluateRecursive(factory, config, keys, iKey + 1, reader, context);
                    }
                    else
                    {
                        // Call configuration section handler
                        int line = reader.LineNumber;

                        // Try-catch is necessary to protect from exceptions in user config handlers
                        try
                        {
                            ConfigXmlDocument doc = new ConfigXmlDocument();
                            doc.LoadSingleElement(filename, reader);
                            config = factory.Create(config, context, doc.DocumentElement);
                        }
                        catch (ConfigurationException)
                        {
                            // Bubble ConfigurationExceptions
                            throw;
                        }
                        catch (XmlException)
                        {
                            // Bubble XmlExceptions
                            throw;
                        }
                        catch (Exception ex)
                        {
                            // Wrap all others as ConfigurationExceptions
                            throw new ConfigurationException("Exception in ConfigSectionHandler", ex, filename, line);
                        }
                    }
                    continue;
                }
                StrictSkipToNextElement(reader);
            }
            return(config);
        }
예제 #32
0
        private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string [] keys, int iKey, XmlTextReader reader) {
            string name = keys[iKey];
            TraceVerbose("  EvaluateRecursive " + iKey + " " + name);

            int depth = reader.Depth;

            while (reader.Read() && reader.NodeType != XmlNodeType.Element);

            while (reader.Depth == depth + 1) {
                TraceVerbose("  EvaluateRecursive " + iKey + " " + name + " Name:" + reader.Name);
                if (reader.Name == name) {
                    if (iKey < keys.Length - 1) {
                        config = EvaluateRecursive(factory, config, keys, iKey + 1, reader);
                    }
                    else {
                        TraceVerbose("  EvaluateRecursive " + iKey + " calling Create()");
                        Debug.Assert(iKey == keys.Length - 1);

                        // 
                        // Call configuration section handler
                        // 
                        // - try-catch is necessary to insulate config system from exceptions in user config handlers.
                        //   - bubble ConfigurationExceptions & XmlException
                        //   - wrap all others in ConfigurationException
                        //
                        int line = reader.LineNumber;
                        try {
                            ConfigXmlDocument doc = new ConfigXmlDocument();
                            doc.LoadSingleElement(_filename, reader);
                            config = factory.Create(config, null, doc.DocumentElement);
                        }
                        catch (ConfigurationException) {
                            throw;
                        }
                        catch (XmlException) {
                            throw;
                        }
                        catch (Exception ex) {
                            throw new ConfigurationException(
                                        SR.GetString(SR.Exception_in_config_section_handler),
                                        ex, _filename, line);
                        }

                    }
                    continue;
                }
                StrictSkipToNextElement(reader);
            }
            return config;
        }
예제 #33
0
 private object EvaluateRecursive(IConfigurationSectionHandler sectionHandler, object config, string[] keys, int keyIndex, XmlTextReader reader)
 {
     string name = keys[keyIndex];
     int depth = reader.Depth;
     while (reader.Read() && reader.NodeType != XmlNodeType.Element)
     {
         ;
     }
     while (reader.Depth == depth + 1)
     {
         if (reader.Name == name)
         {
             if (keyIndex < keys.Length - 1)
             {
                 config = EvaluateRecursive(sectionHandler, config, keys, keyIndex + 1, reader);
             }
             else
             {
                 XmlDocument doc = new XmlDocument();
                 XmlNode section = doc.ReadNode(reader);
                 config = sectionHandler.Create(config, null, section);
             }
             continue;
         }
         SkipToNextElement(reader);
     }
     return config;
 }
		// Get the object for a specific configuration key and handler.
		public Object GetConfig
					(String configKey, IConfigurationSectionHandler handler)
				{
				#if SECOND_PASS
					// Bail out if the configuration key is invalid.
					if(configKey == null || configKey.Length == 0)
					{
						return null;
					}

					// See if we have cached information from last time.
					if(cachedInfo.Contains(configKey))
					{
						return cachedInfo[configKey];
					}

					// Get the section handler, if necessary.
					if(handler == null)
					{
						Object schema = sectionSchema[configKey];
						if(schema == null)
						{
							// We don't know how to handle the section.
							cachedInfo[configKey] = null;
							return null;
						}
						else if(schema == groupMarker)
						{
							// This section is a group.
							cachedInfo[configKey] = null;
							return null;
						}
						else
						{
							// Create an instance of the specified handler.
							Type handlerType = Type.GetType((String)schema);
							if(handlerType == null)
							{
								cachedInfo[configKey] = null;
								return null;
							}
							handler = Activator.CreateInstance(handlerType)
										as IConfigurationSectionHandler;
							if(handler == null)
							{
								cachedInfo[configKey] = null;
								return null;
							}
						}
					}

					// Scan all documents, and collect up the data.
					Object data = null;
					int posn;
					XmlNode section;
					for(posn = 0; posn < numDocuments; ++posn)
					{
						section = FindSectionByName
							(documents[posn].DocumentElement, configKey);
						if(section != null)
						{
							data = handler.Create(data, null, section);
						}
					}

					// Cache the data for next time and then return it.
					cachedInfo[configKey] = data;
					return data;
				#else
					// Configuration data is not available, so bail out.
					return null;
				#endif
				}
        protected static object GetAppSettingsFileHandler(string sectionName, IConfigurationSectionHandler parentHandler, XmlDocument xmlDoc)
        {
            object handler = null;
            XmlNode node = xmlDoc.SelectSingleNode("//" + sectionName);
            XmlAttribute att = (XmlAttribute)node.Attributes.RemoveNamedItem("file");

            if (att == null || att.Value == null || att.Value.Length == 0)
            {
                return parentHandler.Create(null, null, node);
            }
            else
            {
                string fileName = att.Value;
                string dir = Path.GetDirectoryName(fileName);
                string fullName = Path.Combine(dir, fileName);
                XmlDocument xmlDoc2 = new XmlDocument();
                xmlDoc2.Load(fullName);

                object parent = parentHandler.Create(null, null, node);
                IConfigurationSectionHandler h = new NameValueSectionHandler();
                handler = h.Create(parent, null, xmlDoc2.DocumentElement);
            }

            return handler;
        }
	// Get a configuration object, using a particular handler.
	// This is for internal use, to provide a fallback handler
	// if the section is not mentioned in "machine.default".
	internal static Object GetConfig
				(String sectionName, IConfigurationSectionHandler handler)
			{
				// Make sure that the configuration system is initialized.
				BuiltinConfigurationSystem system;
				lock(typeof(ConfigurationSettings))
				{
					if(configSystem != null)
					{
						system = configSystem;
					}
					else if(configError != null)
					{
						throw configError;
					}
					else
					{
						configSystem = new BuiltinConfigurationSystem();
						try
						{
							configSystem.Init();
						}
						catch(Exception e)
						{
							configError = e;
							throw;
						}
						system = configSystem;
					}
				}

				// Look up the specified configuration item.
				return system.GetConfig(sectionName, handler);
			}
 private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
 {
     Type c = System.Configuration.TypeUtil.GetTypeWithReflectionPermission(configRecord.Host, factoryRecord.FactoryTypeName, true);
     if (typeof(ConfigurationSection).IsAssignableFrom(c))
     {
         this._sectionCtor = System.Configuration.TypeUtil.GetConstructorWithReflectionPermission(c, typeof(ConfigurationSection), true);
     }
     else
     {
         System.Configuration.TypeUtil.VerifyAssignableType(typeof(IConfigurationSectionHandler), c, true);
         this._sectionHandler = (IConfigurationSectionHandler) System.Configuration.TypeUtil.CreateInstanceWithReflectionPermission(c);
     }
 }
            private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) {
                // Get the type of the factory
                Type type = TypeUtil.GetTypeWithReflectionPermission(configRecord.Host, factoryRecord.FactoryTypeName, true);

                // If the type is a ConfigurationSection, that's the type.
                if (typeof(ConfigurationSection).IsAssignableFrom(type)) {
                    _sectionCtor = TypeUtil.GetConstructorWithReflectionPermission(type, typeof(ConfigurationSection), true);
                }
                else {
                    // Note: in v1, IConfigurationSectionHandler is in effect a factory that has a Create method
                    // that creates the real section object.

                    // throws if type does not implement IConfigurationSectionHandler
                    TypeUtil.VerifyAssignableType(typeof(IConfigurationSectionHandler), type, true);

                    // Create an instance of the handler
                    _sectionHandler = (IConfigurationSectionHandler) TypeUtil.CreateInstanceWithReflectionPermission(type);
                }
            }
		private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string[] keys, int iKey, XmlTextReader reader)
		{
			string name = keys[iKey];
			int depth = reader.Depth;
			
			while(reader.Read() && reader.NodeType != XmlNodeType.Element);

			while (reader.Depth == depth + 1)
			{
				if (reader.Name == name)
				{
					if (iKey < keys.Length - 1)
					{
						config = EvaluateRecursive(factory, config, keys, iKey + 1, reader);
					}
					else 
					{
						// Call configuration section handler
						int line = reader.LineNumber;

						// Try-catch is necessary to protect from exceptions in user config handlers
						try
						{
							ConfigXmlDocument doc = new ConfigXmlDocument();
							doc.LoadSingleElement(filename, reader);
							config = factory.Create(config, null, doc.DocumentElement);
						}
						catch(ConfigurationException)
						{
							// Bubble ConfigurationExceptions
							throw;
						}
						catch (XmlException)
						{
							// Bubble XmlExceptions
							throw;
						}
						catch(Exception ex)
						{
							// Wrap all others as ConfigurationExceptions
							throw new ConfigurationException("Exception in ConfigSectionHandler", ex, filename, line);
						}
					}
					continue;
				}
				StrictSkipToNextElement(reader);
			}
			return config;
		}