コード例 #1
0
        public void Configure(ConfigSource config)
        {
            consumerRequests = config.GetBoolean("consumerRequests");

            ConfigSource child = config.GetChild("accessVerifier");
            if (child != null) {
                string typeString = child.GetString("type");
                if (String.IsNullOrEmpty(typeString))
                    throw new ConfigurationException("The 'accessVerifier' type was not specified.", child, "type");

                Type type = Type.GetType(typeString, false, true);
                if (type == null)
                    throw new ConfigurationException("The type '" + typeString + "' could not be found.", child, "type");

                if (!typeof (IPathAccessVerifier).IsAssignableFrom(type))
                    throw new ConfigurationException(
                        "The type '" + type + "' cannot be is not an implementation of '" + typeof (IPathAccessVerifier) + "'.", child,
                        "type");

                try {
                    accessVerifier = (IPathAccessVerifier) Activator.CreateInstance(type);
                    accessVerifier.Context = OAuthProvider.Current;
                    accessVerifier.Configure(child);
                } catch (ConfigurationException) {
                    throw;
                } catch (Exception e) {
                    throw new ConfigurationException("Error while initializing the type '" + type + "': " + e.Message, e);
                }
            }
        }
コード例 #2
0
        public void TestInt64()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("key", 64L);

            Assert.AreEqual(64L, config.GetInt32("key"));
        }
コード例 #3
0
ファイル: GetConfig.cs プロジェクト: jeanmahai/28helpmate
 /// <summary>
 /// 从XML文件中读取节点值
 /// </summary>
 /// <param name="source">数据源</param>
 /// <param name="nodeName">节点名称</param>
 /// <returns></returns>
 public static string GetXMLValue(ConfigSource source, string nodeName)
 {
     string nodeValue = string.Empty;
     XmlDocument xmlDoc = new XmlDocument();
     try
     {
         string path = AppDomain.CurrentDomain.BaseDirectory + "\\SvcConfig{0}.xml";
         switch (source)
         {
             case ConfigSource.Beijing:
                 path = string.Format(path, "Beijing");
                 break;
             case ConfigSource.Canadan:
                 path = string.Format(path, "Canadan");
                 break;
             default:
                 path = string.Format(path, "");
                 break;
         }
         xmlDoc.Load(path);
         XmlNode xn = xmlDoc.SelectSingleNode("config");
         nodeValue = xn.SelectNodes(nodeName).Item(0).InnerText;
     }
     catch
     {
         throw;
     }
     return nodeValue;
 }
コード例 #4
0
        public void TestIn32()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("key", 32);

            Assert.AreEqual(32, config.GetInt32("key"));
        }
コード例 #5
0
ファイル: Help.cs プロジェクト: mikey179/reference
        /// <summary>Initialize this command</summary>
        public override void Initialize(CommandLine cmd, ConfigSource configuration)
        {
            var arg = cmd.Arguments.FirstOrDefault();
            if (null == arg)
            {
                arguments = new string[] { HELP, Topic("xp/runtime", "xp") };
                modules = new string[] { };
                return;
            }
            else if (arg.StartsWith("/"))
            {
                arguments = new string[] { HELP, Topic("xp/runtime", arg.Substring(1)) };
                modules = new string[] { };
                return;
            }
            else
            {
                var topic = arg.Split(new char[] { '/' }, 2);
                if (null == Type.GetType("Xp.Runners.Commands." + topic[0].UpperCaseFirst()))
                {
                    var plugin = new Plugin(topic[0]);
                    plugin.Initialize(cmd, configuration);

                    arguments = new string[] { HELP, topic.Length > 1 ? Topic(plugin.EntryPoint.Package.Replace('.', '/'), topic[0] + '/' + topic[1]) : plugin.EntryPoint.Type };
                    modules = plugin.Modules;
                }
                else
                {
                    arguments = new string[] { HELP, Topic("xp/runtime", topic.Length > 1 ? topic[0] + '/' + topic[1] : topic[0]) };
                    modules = new string[] { };
                }
            }
        }
コード例 #6
0
 public void AddChild()
 {
     ConfigSource config = new ConfigSource();
     ConfigSource child = config.AddChild("test");
     Assert.IsNotNull(child);
     Assert.AreEqual(1, config.ChildCount);
     Assert.AreEqual("test", child.Name);
 }
コード例 #7
0
ファイル: Logger.cs プロジェクト: ikvm/cloudb
        internal Logger(string name, ILogger logger, ConfigSource config)
        {
            this.name = name;
            this.logger = logger;
            this.config = config;

            logDelegate = new LogDelegate(Log);
        }
コード例 #8
0
ファイル: LoggerTest.cs プロジェクト: erpframework/cloudb
        public void ConfigureNetworkLogger()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("logger.network.type", "simple-console");

            Logger.Init(config);
            Logger logger = Logger.Network;
            Assert.IsInstanceOf(typeof(SimpleConsoleLogger), logger.BaseLogger);
        }
コード例 #9
0
ファイル: LoggerTest.cs プロジェクト: erpframework/cloudb
        public void ConfigureDefaultDebugger()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("logger.foo.type", "default");

            Logger.Init(config);
            Logger logger = Logger.GetLogger("foo");
            Assert.IsInstanceOf(typeof(DefaultLogger), logger.BaseLogger);
        }
コード例 #10
0
        protected override void Config(ConfigSource config)
        {
            base.Config(config);

            NetworkConfigSource networkConfig = (NetworkConfigSource) config;
            networkConfig.AddAllowedIp("localhost");
            networkConfig.AddAllowedIp("127.0.0.1");
            networkConfig.AddAllowedIp("::1");
        }
コード例 #11
0
        public void GetChildValue()
        {
            ConfigSource config = new ConfigSource();
            ConfigSource child = config.AddChild("test.child");
            child.SetValue("value", 32);

            int value = config.GetInt32("test.child.value");
            Assert.AreEqual(32, value);
        }
コード例 #12
0
        public void Save(ConfigSource config, Stream output)
        {
            if (!output.CanWrite)
                throw new ArgumentException("The output stream cannot be written.", "output");

            Util.Properties properties = new Util.Properties();
            SetChildValues(properties, "", config);
            properties.Store(output, null);
        }
コード例 #13
0
ファイル: LoggerTest.cs プロジェクト: erpframework/cloudb
        public void DefaultWithoutExplicitSpec()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("logger.format", "[{Time}] - {Source} - {Message]");

            Logger.Init(config);
            Logger logger = Logger.GetLogger();
            Assert.IsInstanceOf(typeof(DefaultLogger), logger.BaseLogger);
            Assert.AreEqual("[{Time}] - {Source} - {Message]", logger.Config.GetString("format"));
        }
コード例 #14
0
 public void Configure(ConfigSource configSource)
 {
     format = configSource.GetString("format");
     if (String.IsNullOrEmpty(format)) {
         format = DefaultFormat;
     } else if (String.Compare(format, "N", true) != 0 &&
         String.Compare(format, "D", true) != 0) {
         throw new ConfigurationException("Invalid or not supported GUID format specified", configSource, "format");
     }
 }
コード例 #15
0
ファイル: LoggerTest.cs プロジェクト: erpframework/cloudb
        public void ConfigureSimpleConsoleLogger()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("logger.foo.type", "simple-console");

            Logger.Init(config);
            Logger logger = Logger.GetLogger("foo");
            Assert.IsInstanceOf(typeof(SimpleConsoleLogger), logger.BaseLogger);

            logger.Info("Printing a log message");
        }
コード例 #16
0
        public void Load(ConfigSource config, Stream input)
        {
            if (!input.CanRead)
                throw new ArgumentException("Cannot read from the stream.", "input");

            Util.Properties properties = new Util.Properties();
            properties.Load(input);
            foreach(KeyValuePair<object, object> pair in properties) {
                config.SetValue((string)pair.Key, (string)pair.Value);
            }
        }
コード例 #17
0
ファイル: GetTime.cs プロジェクト: jeanmahai/28helpmate
 /// <summary>
 /// 获取当前时间
 /// </summary>
 /// <param name="source">配置的源类型</param>
 /// <returns></returns>
 public DateTime NowTime(ConfigSource source)
 {
     switch (source)
     {
         case ConfigSource.Beijing:
             return DateTime.Now;
         case ConfigSource.Canadan:
             return DateTime.Now;
         default:
             return DateTime.Now;
     }
 }
コード例 #18
0
ファイル: ConfigurationException.cs プロジェクト: ikvm/cloudb
        private static string CreateMessage(ConfigSource config, string key)
        {
            string message;

            if (!String.IsNullOrEmpty(key)) {
                message = "A configuration error occurred at source '" + config.FullName + "' on key '" + key + "'.";
            } else {
                message = "A configuration error occurred at source '" + config.FullName + "'";
            }

            return message;
        }
コード例 #19
0
ファイル: LoggerTest.cs プロジェクト: erpframework/cloudb
        public void CompositeConsoleLogger()
        {
            ConfigSource config = new ConfigSource();
            config.SetValue("logger.composite.type", "composite");
            config.SetValue("logger.composite.1.type", "simple-console");
            config.SetValue("logger.composite.2.type", "simple-console");

            Logger.Init(config);
            Logger logger = Logger.GetLogger("composite");
            Assert.IsInstanceOf(typeof(CompositeLogger), logger.BaseLogger);

            logger.Info("Print a simple message that must be written in the console twice");
        }
コード例 #20
0
        public void AddMessageAddsConfigSourceTitle()
        {
            var source = new ConfigSource();

            source.Title = "foo";

            sut = new ValidationResult(source);
            sut.AddMessage(ErrorLevel.Info, "message");

            var createdText = sut.Messages.First().Message;

            Assert.StartsWith("foo", createdText);
            Assert.EndsWith("message", createdText);
        }
コード例 #21
0
        public void TransformToSourceTable_ProducesCorrectTable()
        {
            using (var scenario = MultiLevelTableScenario.Setup())
            {
                // Act
                var src         = new ConfigSource("test");
                var sourceTable = scenario.Table.TransformToSourceTable(new ConfigSource("test"));

                // Assert
                sourceTable.Get <IConfigSource>(nameof(scenario.Clr.X)).Should().Be(src);
                var sub = sourceTable.Get <TomlTable>(nameof(scenario.Clr.Sub));
                sub.Get <IConfigSource>(nameof(scenario.Clr.Sub.Y)).Should().Be(src);
            }
        }
コード例 #22
0
        public void StructuredProperties()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("test.me = pass");
            sb.AppendLine("test.two = ed");
            sb.AppendLine("stress.it.to.the.max = 200");
            sb.AppendLine("stress.it.again = 23d");

            ConfigSource source = new ConfigSource();
            source.LoadProperties(GetStream(sb));

            Assert.AreEqual(2, source.GetChild("test").Keys.Length);
            Assert.AreEqual("ed", source.GetChild("test").GetString("two"));
        }
コード例 #23
0
        public void SimpleProperties()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("test=passed");
            sb.AppendLine("me=spaced value");

            ConfigSource source = new ConfigSource();
            source.LoadProperties(GetStream(sb));

            Assert.AreEqual("test", source.Keys[0]);
            Assert.AreEqual("me", source.Keys[1]);
            Assert.AreEqual("passed", source.GetString("test"));
            Assert.AreEqual("spaced value", source.GetString("me"));
        }
コード例 #24
0
        public void CompositeConsoleLogger()
        {
            ConfigSource config = new ConfigSource();

            config.SetValue("logger.composite.type", "composite");
            config.SetValue("logger.composite.1.type", "simple-console");
            config.SetValue("logger.composite.2.type", "simple-console");

            Logger.Init(config);
            Logger logger = Logger.GetLogger("composite");

            Assert.IsInstanceOf(typeof(CompositeLogger), logger.BaseLogger);

            logger.Info("Print a simple message that must be written in the console twice");
        }
コード例 #25
0
ファイル: FakeAdminService.cs プロジェクト: yuexiaoyun/cloudb
            public void Init(AdminService adminService)
            {
                if (storeType == StoreType.FileSystem)
                {
                    ConfigSource config   = adminService.Config;
                    string       basePath = config.GetString("node_directory", "./base");
                    factory = new FileSystemServiceFactory(basePath);
                }
                else
                {
                    factory = new MemoryServiceFactory();
                }

                factory.Init(adminService);
            }
コード例 #26
0
        public void GetRepositoryList_PaginationWorks()
        {
            // Name and AuthName must be equal for all of the currently supported hosters, so this test must be without authentication
            // TODO: make authentication for this test configurable when a new hoster without this limitation is added
            Skip.If(this.SkipUnauthenticatedTests);

            var source = new ConfigSource();

            source.Hoster = this.ConfigHoster;
            source.Type   = "user";
            source.Name   = this.HosterPaginationUser;

            var repoList = sut.GetRepositoryList(source);

            Assert.True(repoList.Count > this.Pagination_MinNumberOfRepos);
        }
コード例 #27
0
        public void SetUp()
        {
            source1  = new LambdaConfigurationAction(g => { });
            theLog   = new ConfigLog(null);
            theChain = new BehaviorChain();

            node = new TracedNode();
            node.Trace("something");
            node.Trace("else");

            node2 = new TracedNode();

            theConfigSource = theLog.StartSource(new FubuRegistry(), source1);
            theLog.RecordEvents(theChain, node);
            theLog.RecordEvents(theChain, node2);
        }
コード例 #28
0
        public void SetDefaultFakeConfig()
        {
            var config = new Config();

            config.LocalFolder        = "foo";
            config.WaitSecondsOnError = 0;

            var source = new ConfigSource();

            source.Title  = "title";
            source.Hoster = "fake";

            config.Sources.Add(source);

            this.FakeConfig = config;
        }
コード例 #29
0
        private static void SetChildValues(Util.Properties properties, string prefix, ConfigSource config)
        {
            prefix += config.Name;

            foreach(string key in config.Keys) {
                string value = config.GetString(key, null);
                if (String.IsNullOrEmpty(value))
                    continue;

                properties.SetProperty(prefix + "." + key, value);
            }

            foreach(ConfigSource child in config.Children) {
                SetChildValues(properties, prefix, child);
            }
        }
コード例 #30
0
        public IgnoringHosterApiCallerTests()
        {
            this.source = new ConfigSource {
                Title = "foo"
            };

            var repos = new List <HosterRepository>();

            repos.Add(new HosterRepository("foo.bar", "bar", "http://clone", ScmType.Git));
            repos.Add(new HosterRepository("foo.baz", "baz", "http://clone", ScmType.Git));

            var caller = new FakeHosterApiCaller();

            caller.Lists.Add(this.source, repos);

            this.sut = new IgnoringHosterApiCaller(caller);
        }
コード例 #31
0
ファイル: Logger.cs プロジェクト: yuexiaoyun/cloudb
        public static void Init(ConfigSource config)
        {
            lock (logSyncLock) {
                InspectLoggers();

                ConfigSource loggerConfig = config;
                // if it is a root configuration, get the 'logger' child
                if (loggerConfig.Parent == null)
                {
                    loggerConfig = config.GetChild("logger");
                }

                // if we haven't found any 'logger' or if the element has no
                // children, simply return and get empty loggers ...
                if (loggerConfig == null)
                {
                    return;
                }

                // this means there's just one logger and its children are config...
                if (loggerConfig.ChildCount == 0)
                {
                    DoInit(String.Empty, loggerConfig, null);
                }
                else
                {
                    List <ILogger> composites = new List <ILogger>();
                    foreach (ConfigSource child in loggerConfig.Children)
                    {
                        DoInit(child.Name, child, composites);
                    }

                    // let's late process the composite loggers found
                    if (composites.Count > 0)
                    {
                        for (int i = 0; i < composites.Count; i++)
                        {
                            composites[i].Init(config);
                        }
                    }
                }


                initid = true;
            }
        }
コード例 #32
0
        public void Init()
        {
            nullableLogger = NullLogger.Instance;
            config         = new EnvConfig(nullableLogger);

            Environment.SetEnvironmentVariable("kumuluzee-name", "test-service", EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("kumuluzee-server-http-port", "9000", EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("kumuluzee.name.dot", "test-service_dot", EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("kumuluzee.server.http.port.dot", "9000_dot", EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("kumuluzee_name_underscore", "test-service_underscore", EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("kumuluzee_server_http_port_underscore", "9000_underscore", EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("KUMULUZEE_NAME_UPPERCASE", "test-service_uppercase", EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("KUMULUZEE_SERVER_HTTP_PORT_UPPERCASE", "9000_uppercase", EnvironmentVariableTarget.Process);
        }
コード例 #33
0
ファイル: Command.cs プロジェクト: mikey179/reference
        /// <summary>Entry point</summary>
        public int Execute(CommandLine cmd, ConfigSource configuration)
        {
            Initialize(cmd, configuration);

            var proc    = new Process();
            var runtime = configuration.GetRuntime();
            var ini     = new Dictionary <string, IEnumerable <string> >()
            {
                { "magic_quotes_gpc", new string[] { "0" } },
                { "date.timezone", new string[] { TimeZoneInfo.Local.Olson() ?? "UTC" } },
                { "extension", configuration.GetExtensions(runtime) }
            };
            var use = configuration.GetUse() ?? UseComposer();

            Encoding encoding;
            Func <string, string> args;
            var main = Paths.TryLocate(use, new string[] { Paths.Compose("tools", MainFor(cmd) + ".php") }).FirstOrDefault();

            if (null == main)
            {
                main     = Paths.Locate(new string[] { Paths.Binary().DirName() }, new string[] { MainFor(cmd) + "-main.php" }).First();
                encoding = Encoding.UTF8;

                // Arguments are encoded in utf-7, which is binary-safe
                args = Arguments.Encode;
            }
            else
            {
                args     = Arguments.Escape;
                encoding = Encoding.GetEncoding("iso-8859-1");
            }

            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.FileName        = configuration.GetExecutable(runtime) ?? "php";
            proc.StartInfo.Arguments       = string.Format(
                "-C -q -d include_path=\".{0}{1}{0}{0}.{0}{2}\" {3} {4} {5}",
                Paths.Separator,
                string.Join(Paths.Separator, use.Concat(cmd.Options["modules"].Concat(ModulesFor(cmd)))),
                string.Join(Paths.Separator, cmd.Options["classpath"].Concat(ClassPathFor(cmd))),
                string.Join(" ", IniSettings(ini.Concat(configuration.GetArgs(runtime)))),
                main,
                string.Join(" ", ArgumentsFor(cmd).Select(args))
                );

            return(cmd.ExecutionModel.Execute(proc, encoding));
        }
コード例 #34
0
 public SpecFlowConfiguration(ConfigSource configSource,
                              CultureInfo featureLanguage,
                              CultureInfo bindingCulture,
                              List <string> additionalStepAssemblies,
                              StepDefinitionSkeletonStyle stepDefinitionSkeletonStyle,
                              bool usesPlugins,
                              string generatorPath
                              )
 {
     ConfigSource                = configSource;
     FeatureLanguage             = featureLanguage;
     BindingCulture              = bindingCulture;
     AdditionalStepAssemblies    = additionalStepAssemblies;
     StepDefinitionSkeletonStyle = stepDefinitionSkeletonStyle;
     UsesPlugins   = usesPlugins;
     GeneratorPath = generatorPath;
 }
コード例 #35
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Microsoft.Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (ConfigSource != null)
     {
         ConfigSource.Validate();
     }
     if (Taints != null)
     {
         foreach (var element in Taints)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
 }
コード例 #36
0
        public void GetRepositoryList_DoesntReturnMercurialRepos()
        {
            // #60: 2 months after Bitbucket's HG deprecation, their API still returns HG repos but cloning/pulling them fails -> ignore them
            var source = new ConfigSource();

            source.Hoster   = this.ConfigHoster;
            source.Type     = "user";
            source.Name     = this.HosterUser;
            source.AuthName = TestHelper.EnvVar(this.EnvVarPrefix, "Name");
            source.Password = TestHelper.EnvVar(this.EnvVarPrefix, "PW");

            var repoList = sut.GetRepositoryList(source);

            var hgrepos = repoList.Where(x => x.Scm == ScmType.Mercurial);

            Assert.Empty(hgrepos);
        }
コード例 #37
0
ファイル: Command.cs プロジェクト: mikey179/reference
        /// <summary>Entry point</summary>
        public int Execute(CommandLine cmd, ConfigSource configuration)
        {
            Initialize(cmd, configuration);

            var proc = new Process();
            var runtime = configuration.GetRuntime();
            var ini = new Dictionary<string, IEnumerable<string>>()
            {
                { "magic_quotes_gpc", new string[] { "0" } },
                { "date.timezone", new string[] { TimeZoneInfo.Local.Olson() ?? "UTC" } },
                { "extension", configuration.GetExtensions(runtime) }
            };
            var use = configuration.GetUse() ?? UseComposer();

            Encoding encoding;
            Func<string, string> args;
            var main = Paths.TryLocate(use, new string[] { Paths.Compose("tools", MainFor(cmd) + ".php") }).FirstOrDefault();
            if (null == main)
            {
                main = Paths.Locate(new string[] { Paths.Binary().DirName() }, new string[] { MainFor(cmd) + "-main.php" }).First();
                encoding = Encoding.UTF8;

                // Arguments are encoded in utf-7, which is binary-safe
                args = Arguments.Encode;
            }
            else
            {
                args = Arguments.Escape;
                encoding = Encoding.GetEncoding("iso-8859-1");
            }

            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.FileName = configuration.GetExecutable(runtime) ?? "php";
            proc.StartInfo.Arguments = string.Format(
                "-C -q -d include_path=\".{0}{1}{0}{0}.{0}{2}\" {3} {4} {5}",
                Paths.Separator,
                string.Join(Paths.Separator, use.Concat(cmd.Options["modules"].Concat(ModulesFor(cmd)))),
                string.Join(Paths.Separator, cmd.Options["classpath"].Concat(ClassPathFor(cmd))),
                string.Join(" ", IniSettings(ini.Concat(configuration.GetArgs(runtime)))),
                main,
                string.Join(" ", ArgumentsFor(cmd).Select(args))
            );

            return cmd.ExecutionModel.Execute(proc, encoding);
        }
コード例 #38
0
        protected virtual void Config(ConfigSource config)
        {
            if (storeType == StoreType.FileSystem)
            {
                if (Directory.Exists(TestPath))
                {
                    Directory.Delete(TestPath, true);
                }

                Directory.CreateDirectory(path);

                config.SetValue("node_directory", path);
            }

            config.SetValue("logger." + Logger.NetworkLoggerName + ".type", "simple-console");
            Logger.Init(config);
            Assert.IsInstanceOf(typeof(SimpleConsoleLogger), Logger.Network.BaseLogger);
        }
コード例 #39
0
                public override int GetHashCode()
                {
                    int hash = 1;

                    if (configSource_ != null)
                    {
                        hash ^= ConfigSource.GetHashCode();
                    }
                    if (Name.Length != 0)
                    {
                        hash ^= Name.GetHashCode();
                    }
                    if (_unknownFields != null)
                    {
                        hash ^= _unknownFields.GetHashCode();
                    }
                    return(hash);
                }
コード例 #40
0
        /// <summary>
        /// basic validation rules which are always the same
        /// </summary>
        public ValidationResult Validate(ConfigSource source)
        {
            var result = new ValidationResult(source);

            if (source.Hoster != this.HosterName)
            {
                result.AddMessage(ErrorLevel.Error, string.Format(Resource.WrongHoster, source.Hoster), ValidationMessageType.WrongHoster);
            }

            if (source.Type != "user" && source.Type != "org")
            {
                result.AddMessage(ErrorLevel.Error, string.Format(Resource.WrongType, source.Type), ValidationMessageType.WrongType);
            }

            if (string.IsNullOrWhiteSpace(source.Name))
            {
                result.AddMessage(ErrorLevel.Error, Resource.NameEmpty, ValidationMessageType.NameEmpty);
            }

            bool authNameEmpty = string.IsNullOrWhiteSpace(source.AuthName);
            bool passwordEmpty = string.IsNullOrWhiteSpace(source.Password);

            if (authNameEmpty != passwordEmpty)
            {
                result.AddMessage(ErrorLevel.Error, Resource.AuthNameOrPasswortEmpty, ValidationMessageType.AuthNameOrPasswortEmpty);
            }
            else if (authNameEmpty && passwordEmpty)
            {
                result.AddMessage(ErrorLevel.Warn, Resource.AuthNameAndPasswortEmpty, ValidationMessageType.AuthNameAndPasswortEmpty);
            }

            if (this.AuthNameAndNameMustBeEqual)
            {
                if (source.Type != "org" && source.Name != source.AuthName)
                {
                    result.AddMessage(ErrorLevel.Warn, string.Format(Resource.AuthNameAndNameNotEqual, source.Hoster), ValidationMessageType.AuthNameAndNameNotEqual);
                }
            }

            this.ValidateSpecific(result, source);

            return(result);
        }
コード例 #41
0
        public void LoadProperties()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("test=23");
            sb.AppendLine("test.foo=12");
            sb.AppendLine("test.bar=test");
            Stream input = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

            ConfigSource config = new ConfigSource();
            config.LoadProperties(input);

            Assert.AreEqual(1, config.Keys.Length);
            Assert.AreEqual("test", config.Keys[0]);
            Assert.AreEqual(2, config.GetChild("test").Keys.Length);
            Assert.AreEqual("foo", config.GetChild("test").Keys[0]);
            Assert.AreEqual("bar", config.GetChild("test").Keys[1]);
            Assert.AreEqual(12, config.GetChild("test").GetInt32("foo"));
            Assert.AreEqual("test", config.GetChild("test").GetString("bar"));
        }
コード例 #42
0
ファイル: ConfigBase.cs プロジェクト: 15831944/NFramework
        public virtual void Set(string key, object value)
        {
            value.ShouldNotBeNull("value");

            if (Get(key) == null)
            {
                Add(key, value.ToString());
            }
            else
            {
                keys[key] = value.ToString();
            }

            if (ConfigSource.AutoSave)
            {
                ConfigSource.Save();
            }

            OnKeySet(new ConfigKeyEventArgs(key, value.ToString()));
        }
コード例 #43
0
 public void MergeFrom(TapDSConfig other)
 {
     if (other == null)
     {
         return;
     }
     if (other.configSource_ != null)
     {
         if (configSource_ == null)
         {
             ConfigSource = new global::Envoy.Api.V2.Core.ConfigSource();
         }
         ConfigSource.MergeFrom(other.ConfigSource);
     }
     if (other.Name.Length != 0)
     {
         Name = other.Name;
     }
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
コード例 #44
0
        public static Cluster CreateCluster(string clusterName)
        {
            var edsSource = new ConfigSource
            {
                Ads = new AggregatedConfigSource()
            };


            return(new Cluster
            {
                Name = clusterName,
                ConnectTimeout = Duration.FromTimeSpan(TimeSpan.FromSeconds(5)),
                EdsClusterConfig = new EdsClusterConfig
                {
                    EdsConfig = edsSource,
                    ServiceName = clusterName,
                },
                Type = DiscoveryType.Eds
            });
        }
コード例 #45
0
ファイル: Plugin.cs プロジェクト: mikey179/reference
        /// <summary>Initialize this command. Searches modules passed via command line, current directory
        /// and locally as well as globally installed locations for subcommands, in this order.</summary>
        public override void Initialize(CommandLine cmd, ConfigSource configuration)
        {
            foreach (var dir in cmd.Options["modules"].Concat(new string[] { "." }))
            {
                if (null == (entry = FindEntryPoint(dir, name))) continue;

                modules = new string[] { };
                return;
            }

            foreach (var dir in ComposerLocations())
            {
                if (null == (entry = FindEntryPoint(dir, name))) continue;

                modules = DependenciesAndSelf(dir, entry.Module, new HashSet<string>());
                return;
            }

            throw new NotImplementedException(name);
        }
コード例 #46
0
        public void GetReposForSourceReturnsList()
        {
            var source = new ConfigSource();

            source.Title = "title";

            var list = new List <HosterRepository>();

            list.Add(new HosterRepository("bar", "bar", "http://bar", ScmType.Git));
            list.Add(new HosterRepository("foo", "foo", "http://foo", ScmType.Git));

            var sut = new ApiRepositories();

            sut.AddItem(source, list);

            var result = sut.GetReposForSource(source);

            Assert.Equal(2, result.Count());
            Assert.Equal("bar", result.First().FullName);
        }
コード例 #47
0
        public void Init(ConfigSource config)
        {
            if (config.ChildCount == 0)
                return;

            foreach(ConfigSource child in config.Children) {
                string childName = child.Name;

                int offset = -1;
                if (!Int32.TryParse(childName, out offset))
                    continue;

                if (offset < 1)
                    continue;

                offset = offset -1;

                string refLogger = child.GetString("ref", null);
                if (!String.IsNullOrEmpty(refLogger)) {
                    loggers.Insert(offset, Logger.GetLogger(refLogger));
                } else {
                    string loggerTypeString = child.GetString("type", null);
                    if (String.IsNullOrEmpty(loggerTypeString))
                        loggerTypeString = "default";

                    Type loggerType = Logger.GetLoggerType(loggerTypeString);
                    if (loggerType == null || !typeof(ILogger).IsAssignableFrom(loggerType))
                        continue;

                    try {
                        ILogger logger = (ILogger) Activator.CreateInstance(loggerType, true);
                        logger.Init(child);

                        EnsureListCapacity(offset);
                        loggers.Insert(offset, new Logger(child.Name, logger, child));
                    } catch {
                        continue;
                    }
                }
            }
        }
コード例 #48
0
ファイル: MachineNode.cs プロジェクト: yuexiaoyun/cloudb
        private static IServiceFactory GetServiceFactory(string storage, ConfigSource nodeConfigSource)
        {
            if (storage == "file")
            {
                string nodeDir = nodeConfigSource.GetString("node_directory", Environment.CurrentDirectory);
                return(new FileSystemServiceFactory(nodeDir));
            }
            if (storage == "memory")
            {
                return(new MemoryServiceFactory());
            }

            if (String.IsNullOrEmpty(storage) &&
                nodeConfigSource != null)
            {
                storage = nodeConfigSource.GetString("storage", "file");
                return(GetServiceFactory(storage, nodeConfigSource));
            }

            return(null);
        }
コード例 #49
0
        public void LogsErrorWhenConfigSourceTitlesContainDuplicates()
        {
            reader = new FakeConfigReader();
            reader.SetDefaultFakeConfig();
            var source = new ConfigSource();

            source.Title = "title";
            source.Type  = "fake";

            reader.FakeConfig.Sources.Add(source);

            logger    = new FakeLogger();
            validator = new FakeHosterValidator();

            sut = new ValidatingConfigReader(reader, logger, validator);
            var result = sut.ReadConfig();

            Assert.True(logger.LoggedSomething);
            Assert.Equal(ErrorLevel.Error, logger.LastErrorLevel);
            Assert.Null(result);
        }
コード例 #50
0
 public SpecFlowConfiguration(ConfigSource configSource,
                              ContainerRegistrationCollection customDependencies,
                              ContainerRegistrationCollection generatorCustomDependencies,
                              CultureInfo featureLanguage,
                              CultureInfo bindingCulture,
                              string unitTestProvider,
                              bool stopAtFirstError,
                              MissingOrPendingStepsOutcome missingOrPendingStepsOutcome,
                              bool traceSuccessfulSteps,
                              bool traceTimings,
                              TimeSpan minTracedDuration,
                              StepDefinitionSkeletonStyle stepDefinitionSkeletonStyle,
                              List <string> additionalStepAssemblies,
                              List <PluginDescriptor> pluginDescriptors,
                              bool allowDebugGeneratedFiles,
                              bool allowRowTests,
                              bool markFeaturesParallelizable,
                              string[] skipParallelizableMarkerForTags,
                              ObsoleteBehavior obsoleteBehavior)
 {
     ConfigSource                 = configSource;
     CustomDependencies           = customDependencies;
     GeneratorCustomDependencies  = generatorCustomDependencies;
     FeatureLanguage              = featureLanguage;
     BindingCulture               = bindingCulture;
     UnitTestProvider             = unitTestProvider;
     StopAtFirstError             = stopAtFirstError;
     MissingOrPendingStepsOutcome = missingOrPendingStepsOutcome;
     TraceSuccessfulSteps         = traceSuccessfulSteps;
     TraceTimings                 = traceTimings;
     MinTracedDuration            = minTracedDuration;
     StepDefinitionSkeletonStyle  = stepDefinitionSkeletonStyle;
     AdditionalStepAssemblies     = additionalStepAssemblies;
     Plugins = pluginDescriptors;
     AllowDebugGeneratedFiles        = allowDebugGeneratedFiles;
     AllowRowTests                   = allowRowTests;
     MarkFeaturesParallelizable      = markFeaturesParallelizable;
     SkipParallelizableMarkerForTags = skipParallelizableMarkerForTags;
     ObsoleteBehavior                = obsoleteBehavior;
 }
コード例 #51
0
        public void GetReposForSourceReturnsAlphabeticallySorted()
        {
            var source = new ConfigSource();

            source.Title = "title";

            var list = new List <HosterRepository>();

            list.Add(new HosterRepository("ccc", "ccc", "http://ccc", ScmType.Git));
            list.Add(new HosterRepository("aaa", "aaa", "http://aaa", ScmType.Git));
            list.Add(new HosterRepository("bbb", "bbb", "http://bbb", ScmType.Git));

            var sut = new ApiRepositories();

            sut.AddItem(source, list);

            var result = sut.GetReposForSource(source).ToList();

            Assert.Equal("aaa", result[0].FullName);
            Assert.Equal("bbb", result[1].FullName);
            Assert.Equal("ccc", result[2].FullName);
        }
コード例 #52
0
        public void SetsWikiToFalseWhenWikiDoesntExist()
        {
            // issue #13: the GitHub API only returns whether it's *possible* to create a wiki, but not if the repo actually *has* a wiki.

            // This is a test repo without wiki, but with the "wiki" checkbox set:
            string username = "******";
            string reponame = "wiki-doesnt-exist";

            // We always use this repo, but authenticate with the user from the config to avoid hitting rate limits:
            var source = new ConfigSource();

            source.Hoster   = this.ConfigHoster;
            source.Type     = "user";
            source.Name     = username;
            source.AuthName = TestHelper.EnvVar(this.EnvVarPrefix, "Name");
            source.Password = TestHelper.EnvVar(this.EnvVarPrefix, "PW");

            var repoList = sut.GetRepositoryList(source);
            var repo     = repoList.First(r => r.ShortName == reponame);

            Assert.False(repo.HasWiki);
        }
コード例 #53
0
ファイル: List.cs プロジェクト: xp-runners/reference
        /// <summary>Entry point</summary>
        public override int Execute(CommandLine cmd, ConfigSource configuration)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var output   = new Output(Console.Out)
                           .Origin(Paths.Binary())
                           .Header("XP Subcommands")
                           .Section("Builtin @ " + assembly.GetName().Version, new Output()
                                    .Line()
                                    .Each(BuiltinsIn(assembly), (self, type) => self.Line("$ xp " + type.Name.ToLower()))
                                    )
            ;

            if (File.Exists(ComposerFile.NAME))
            {
                using (var composer = new ComposerFile(ComposerFile.NAME))
                {
                    if (composer.Definitions.Scripts.Count > 0)
                    {
                        output.Section("Defined via scripts in @ " + composer.SourceUri, new Output()
                                       .Line()
                                       .Each(composer.Definitions.Scripts, (self, script) => self.Line("$ xp " + script.Key))
                                       );
                    }
                }
            }

            foreach (var dir in cmd.Path["modules"])
            {
                AppendCommands(output, "Module", Paths.Resolve(dir));
            }

            AppendCommands(output, "Local", Directory.GetCurrentDirectory());

            foreach (var dir in ComposerLocations())
            {
                AppendCommands(output, "Installed", Paths.Compose(dir, "vendor"));
            }
            return(0);
        }
コード例 #54
0
        public void UpsertKey(string profileName, string key, string value, ConfigSource configSource)
        {
            if (!ConfigKey.IsValid(key))
            {
                throw new ArgumentException($"Not a valid credential key: {key}");
            }
            var credentialProfile = _credentialProfileList.FirstOrDefault(cp => cp.ProfileName.Equals(profileName));

            if (credentialProfile == null)
            {
                credentialProfile = new CredentialProfile()
                {
                    ProfileName = profileName
                };
                _credentialProfileList.Add(credentialProfile);
            }
            credentialProfile.Items[key] = new CredentialItem
            {
                Source = configSource,
                Value  = value
            };
        }
コード例 #55
0
ファイル: AspNetProvider.cs プロジェクト: ruleechen/DQueue
        public void Enqueue(string queueName, object message)
        {
            if (string.IsNullOrWhiteSpace(queueName) || message == null)
            {
                return;
            }

            var json  = message.Serialize();
            var queue = GetQueue(queueName);

            string           hash    = null;
            HashSet <string> hashSet = null;

            if (!IgnoreHash)
            {
                hash    = json.GetMD5();
                hashSet = GetHashSet(queueName);
                if (hashSet.Contains(hash))
                {
                    return;
                }
            }

            var hostId        = ConfigSource.GetAppSetting("DQueue.HostId");
            var dequeueLocker = ReceptionAssistant.GetLocker(queueName + string.Format(Constants.DequeueLockerFlag, hostId));

            lock (dequeueLocker)
            {
                queue.Add(json.AddEnqueueTime());

                if (!IgnoreHash)
                {
                    hashSet.Add(hash);
                }

                Monitor.Pulse(dequeueLocker);
            }
        }
コード例 #56
0
        public void Configure(ConfigSource config)
        {
            consumerRequests = config.GetBoolean("consumerRequests");

            ConfigSource child = config.GetChild("accessVerifier");

            if (child != null)
            {
                string typeString = child.GetString("type");
                if (String.IsNullOrEmpty(typeString))
                {
                    throw new ConfigurationException("The 'accessVerifier' type was not specified.", child, "type");
                }

                Type type = Type.GetType(typeString, false, true);
                if (type == null)
                {
                    throw new ConfigurationException("The type '" + typeString + "' could not be found.", child, "type");
                }

                if (!typeof(IPathAccessVerifier).IsAssignableFrom(type))
                {
                    throw new ConfigurationException(
                              "The type '" + type + "' cannot be is not an implementation of '" + typeof(IPathAccessVerifier) + "'.", child,
                              "type");
                }

                try {
                    accessVerifier         = (IPathAccessVerifier)Activator.CreateInstance(type);
                    accessVerifier.Context = OAuthProvider.Current;
                    accessVerifier.Configure(child);
                } catch (ConfigurationException) {
                    throw;
                } catch (Exception e) {
                    throw new ConfigurationException("Error while initializing the type '" + type + "': " + e.Message, e);
                }
            }
        }
コード例 #57
0
ファイル: Command.cs プロジェクト: mikey179/reference
 /// <summary>Initialize this command</summary>
 public virtual void Initialize(CommandLine cmd, ConfigSource configuration)
 {
     // NOOP
 }
コード例 #58
0
ファイル: OAuthProvider.cs プロジェクト: deveel/cloudb-oauth
        private object ConfigureComponent(ConfigSource config, Type componentType, Type defaultType)
        {
            object obj = null;
            if (config != null) {
                string typeString = config.GetString("type");
                if (String.IsNullOrEmpty(typeString)) {
                    if (defaultType != null)
                        obj = Activator.CreateInstance(defaultType);
                } else {
                    Type type = Type.GetType(typeString, false, true);
                    if (type == null)
                        throw new ConfigurationException("The type '" + typeString + "' was not found in the current context.", config, "type");

                    if (!componentType.IsAssignableFrom(type))
                        throw new ConfigurationException("The type '" + type + "' is not an instance of '" + typeof(ITokenStore) + "'.");

                    try {
                        obj = Activator.CreateInstance(type, null);
                    } catch (Exception e) {
                        throw new ConfigurationException("Unable to instantiate the type '" + type + "': " + e.Message, config, "type");
                    }
                }
            } else {
                if (defaultType != null)
                    obj = Activator.CreateInstance(defaultType);
            }

            if (obj == null)
                return null;

            if (obj is IRequiresProviderContext)
                ((IRequiresProviderContext)obj).Context = this;
            if (obj is IConfigurable)
                ((IConfigurable)obj).Configure(config);

            return obj;
        }
コード例 #59
0
 public void Configure(ConfigSource configSource)
 {
     long timeWindow = configSource.GetInt64("timeWindow");
     SetupTimer(timeWindow);
 }
コード例 #60
0
ファイル: EmptyLogger.cs プロジェクト: ikvm/cloudb
 public void Init(ConfigSource config)
 {
 }