Example #1
0
        private static void Setup()
        {
            LogLog.InternalDebugging = true;

            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternString patternString = new PatternString();

            patternString.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternString.ActivateOptions();

            FileAppender fileAppender = new FileAppender
            {
                Name         = "XmlAppender",
                AppendToFile = true,
                Layout       = new XmlLayoutSchemaLog4j(),
                Encoding     = Encoding.UTF8,
                File         = BaseDirectory + LogFileName
            };

            fileAppender.ActivateOptions();

            hierarchy.Root.AddAppender(fileAppender);
            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
        /// <summary>
        /// Create a named instance from a <see cref="PatternConverter"/>
        /// </summary>
        /// <param name="name">conversion name</param>
        /// <param name="pattern">pattern string</param>
        public RawCallLayout(string name, PatternString pattern)
        {
            Name = name;

            pattern.ActivateOptions();

            m_getter = (e) => pattern.Format();
        }
    public Object ConvertFrom(Object source)
    {
        String        pattern       = (String)source;
        PatternString patternString = new PatternString(pattern);
        String        value         = patternString.Format();

        return(Int32.Parse(value));
    }
        /// <summary>
        /// Converts the given value object to the specified type, using the arguments
        /// </summary>
        /// <param name="source">the object to convert</param>
        /// <param name="targetType">The Type to convert the value parameter to</param>
        /// <returns>the converted object</returns>
        /// <remarks>
        /// <para>
        /// Uses the <see cref="PatternString.Format()"/> method to convert the
        /// <see cref="PatternString"/> argument to a <see cref="String"/>.
        /// </para>
        /// </remarks>
        /// <exception cref="ConversionNotSupportedException">
        /// The <paramref name="source"/> object cannot be converted to the
        /// <paramref name="targetType"/>. To check for this condition use the
        /// <see cref="CanConvertTo"/> method.
        /// </exception>
        public object ConvertTo(object source, Type targetType)
        {
            PatternString patternString = source as PatternString;

            if (patternString != null && CanConvertTo(targetType))
            {
                return(patternString.Format());
            }
            throw ConversionNotSupportedException.Create(targetType, source);
        }
Example #5
0
        public object ConvertTo(object source, Type targetType)
        {
            PatternString str = source as PatternString;

            if ((str == null) || !this.CanConvertTo(targetType))
            {
                throw ConversionNotSupportedException.Create(targetType, source);
            }
            return(str.Format());
        }
        public void GenericInvocationTest(string expression, string expected)
        {
            var actual = PatternString.TransformPattern(expected, new TestClass {
                IntField = 1, StringProperty = "2", Other = new TestClass {
                    IntField = 3, StringProperty = "4"
                }
            });

            output.WriteLine("Transformed: " + actual);

            Assert.Equal(expected, actual);
        }
Example #7
0
        /// <summary>
        /// 测试AppSetting路径转换器(在配置的应用程序域中)
        /// </summary>
        public void TestAppSettingPathConverterInConfiguredDomain()
        {
            string        pattern          = "%appSetting{TestKey}";
            PatternString patternString    = new PatternString(pattern);
            string        evaluatedPattern = patternString.Format();
            string        appSettingValue  = ConfigurationManager.AppSettings["TestKey"];

            Assert.AreEqual("TestValue", appSettingValue, "Expected configuration file to contain a key TestKey with the value TestValue");
            Assert.AreEqual(appSettingValue, evaluatedPattern, "Evaluated pattern expected to be identical to appSetting value");

            string badPattern = "%appSetting{UnknownKey}";

            patternString    = new PatternString(badPattern);
            evaluatedPattern = patternString.Format();
            Assert.AreEqual("(null)", evaluatedPattern, "Evaluated pattern expected to be \"(null)\" for non-existent appSettings key");
        }
        public void TestEnvironmentFolderPathPatternConverter()
        {
            string[] specialFolderNames = Enum.GetNames(typeof(Environment.SpecialFolder));

            foreach (string specialFolderName in specialFolderNames)
            {
                string pattern = "%envFolderPath{" + specialFolderName + "}";

                PatternString patternString = new PatternString(pattern);

                string evaluatedPattern = patternString.Format();

                Environment.SpecialFolder specialFolder =
                    (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), specialFolderName);

                Assert.AreEqual(Environment.GetFolderPath(specialFolder), evaluatedPattern);
            }
        }
 public PatternDetails(SourceFileContext ctx, ResourceDetails.Definition def, ResourceDetails.Definition.Pattern pattern)
 {
     PatternString = pattern.PatternString;
     PathSegments  = pattern.Template.Segments.Select(x => new PathSegment(ctx, def, x)).ToList();
     if (pattern.Template.ParameterNames.Count() == 0)
     {
         // Path-template contains no parameters, special naming required.
         UpperName = PatternString.ToUpperCamelCase();
         LowerName = PatternString.ToLowerCamelCase();
     }
     else
     {
         // Standard naming, concat all parameter names.
         UpperName = string.Join("", PathElements.Select(x => x.UpperCamel));
         LowerName = string.Join("", PathElements.Take(1).Select(x => x.LowerCamel).Concat(PathElements.Skip(1).Select(x => x.UpperCamel)));
     }
     PathTemplateField = Field(Private | Static, ctx.Type <PathTemplate>(), $"s_{LowerName}").WithInitializer(New(ctx.Type <PathTemplate>())(pattern.Template.PathTemplateString));
 }
Example #10
0
        public void ToStringTest()
        {
            const string file_name = "TestFile";
            const string ext       = "log";
            var          now       = DateTime.Now;
            var          processor = new PatternString("{FileName}[{date:yyy-MM-ddTHH-mm-ss}].{ext}")
            {
                //{ "FileName", () => "TestFile" },
                //["FileName"] = () => "TestFile",
                //["date"] = () => DateTime.Now,
                //["ext"] = () => ext,
                { "FileName", "TestFile" },
                { "date", () => now },
                { "ext", ext }
            };

            var result = processor.ToString();

            Assert.That.Value(result).IsEqual($"{file_name}[{now:yyy-MM-ddTHH-mm-ss}].{ext}");
        }
Example #11
0
        public void ChangePatternTest()
        {
            const string file_name = "TestFile";
            const string ext       = "log";
            var          now       = DateTime.Now;
            var          processor = new PatternString("[[FileName]][[[date:yyy-MM-ddTHH-mm-ss]]].[[ext]]")
            {
                //{ "FileName", () => "TestFile" },
                //["FileName"] = () => "TestFile",
                //["date"] = () => DateTime.Now,
                //["ext"] = () => ext,
                { "FileName", "TestFile" },
                { "date", () => now },
                { "ext", ext },
            };

            processor.Pattern = @"\[\[(?<name>\w+)(:(?<format>.*?))?\]\]";

            var result = processor.ToString();

            Debug.WriteLine(result);

            Assert.That.Value(result).IsEqual($"{file_name}[{now:yyy-MM-ddTHH-mm-ss}].{ext}");
        }
 public DynamicPatternLayout(string pattern) : base(pattern)
 {
     this.m_headerPatternString = new PatternString(string.Empty);
     this.m_footerPatternString = new PatternString(string.Empty);
 }
Example #13
0
 /// <summary>
 /// This function is validate the phne string format of pattern and return true if valid else  return false.
 /// This method also validate the phone string pattern according to country. By default it's validate universe phone string formate.
 /// </summary>
 /// <param name="phone"> (PatternType enum) value.</param>
 /// <param name="patternType"></param>
 /// <returns></returns>
 public static bool PhonePatternIsValid(this string phone, PatternType patternType = PatternType.Universal)
 {
     return(PatternString.GetRegexInstance(patternType).IsMatch(phone));
 }
        public CommandVoidResult Help(
            CommandEvaluationContext context,
            [Option("s", "short", "short display: decrase output details")] bool shortView,
            [Option("v", "verbose", "set verbose view: increase output details")] bool verboseView,
            [Option("a", "all", "list all commands")] bool all,
            [Option("n", "namespace", "filter commands list by namespace value or wildcard or regex (wildcard have ?,* , regex starts with \\)", true, true)] PatternString @namespace,
            [Option("t", "type", "filter commands list on command declaring type name value or wildcard or regex", true, true)] PatternString type,
            [Option("m", "module", "filter commands list by module name value or wildcard or regex ", true, true)] PatternString module,
            [Option("l", "list", "if one of -n|-t|-m is set, output list of filtered values")] bool listFilter,
            [Parameter("output help for the command having the name 'commandName'", true)] string commandName
            )
        {
            var hascn      = !string.IsNullOrWhiteSpace(commandName);
            var list       = !all && !hascn;
            var cmds       = context.CommandLineProcessor.ModuleManager.ModuleCommandManager.AllCommands.AsQueryable();
            var namespaces = cmds.Select(x => x.Namespace).Distinct().ToList();

            namespaces.Sort();
            bool ignoreCase = true;

            if (hascn)
            {
                cmds = cmds.Where(x => x.Name.Equals(commandName, CommandLineParser.SyntaxMatchingRule));
            }

            if (cmds.Count() > 0)
            {
                #region filter on declaring type

                if (!string.IsNullOrWhiteSpace(type))
                {
                    var typenames = context.CommandLineProcessor.ModuleManager.ModuleCommandManager.CommandDeclaringTypesAssemblyQualifiedNames.ToList();
                    var typelst   = typenames
                                    .Select(x => Type.GetType(x))
                                    .Where(x => type.Match(x.Name))
                                    .ToList();
                    typelst.Sort((x, y) => x.Name.CompareTo(y.Name));
                    shortView = !verboseView;

                    if (!listFilter)
                    {
                        cmds = cmds.Where(x => type.Match(x.DeclaringTypeShortName, ignoreCase));
                    }
                    else
                    {
                        var sfx = "Commands";
                        string TypeName(Type type)
                        {
                            var s = shortView ? type.Name : type.FullName;

                            if (shortView && s.EndsWith(sfx))
                            {
                                s = s.Substring(0, s.Length - sfx.Length);
                            }
                            return(s);
                        }

                        if (typelst.Count > 0)
                        {
                            var maxtl = typelst.Select(x => TypeName(x).Length).Max();

                            foreach (var typ in typelst)
                            {
                                var cmdattr = typ.GetCustomAttribute <CommandsAttribute>();
                                context.Out.Echoln(Darkcyan + TypeName(typ).PadRight(maxtl) + Tab + DefaultForegroundCmd + cmdattr.Description);
                            }
                        }
                        return(new CommandVoidResult());
                    }
                }

                #endregion

                #region filter on module

                if (cmds.Count() > 0 && !string.IsNullOrWhiteSpace(module))
                {
                    var mods     = context.CommandLineProcessor.ModuleManager.Modules;
                    var modnames = mods.Values.Where(x => module.Match(x.Name)).Select(x => x.Name).ToList();
                    modnames.Sort();
                    shortView = !verboseView;

                    if (!listFilter)
                    {
                        cmds = cmds.Where(x => module.Match(x.ModuleName, ignoreCase));
                    }
                    else
                    {
                        if (modnames.Count > 0)
                        {
                            var maxml = modnames.Select(x => x.Length).Max();
                            foreach (var modname in modnames)
                            {
                                context.Out.Echoln(Darkcyan + modname.PadRight(maxml) + Tab + DefaultForegroundCmd + mods[modname].Description);
                            }
                        }
                        return(new CommandVoidResult());
                    }
                }

                #endregion

                #region filter on namespace

                if (cmds.Count() > 0 && !string.IsNullOrWhiteSpace(@namespace))
                {
                    var nslst = namespaces.Where(x => @namespace.Match(x));
                    shortView = !verboseView;

                    if (!listFilter)
                    {
                        cmds = cmds.Where(x => @namespace.Match(x.Namespace, ignoreCase));
                    }
                    else
                    {
                        foreach (var ns in nslst)
                        {
                            context.Out.Echoln(Darkcyan + ns);
                        }
                        return(new CommandVoidResult());
                    }
                }

                #endregion

                var ncmds = cmds.ToList();
                ncmds.Sort(new Comparison <CommandSpecification>((x, y) => x.Name.CompareTo(y.Name)));
                cmds = ncmds.AsQueryable();
                if (cmds.Count() > 0)
                {
                    var maxcmdlength     = cmds.Select(x => x.Name.Length).Max() + 1;
                    var maxcmdtypelength = cmds.Select(x => x.DeclaringTypeShortName.Length).Max() + 1;
                    var maxmodlength     = cmds.Select(x => Path.GetFileNameWithoutExtension(x.MethodInfo.DeclaringType.Assembly.Location).Length).Max() + 1;
                    var maxnslength      = cmds.Select(x => x.Namespace.Length).Max() + 1;

                    if (list)
                    {
                        shortView = !verboseView;
                    }

                    var groupByNs = list;
                    if (groupByNs)
                    {
                        // get all fs
                        var cmdByNs = cmds.GroupBy((x) => x.Namespace).ToList(); // ordered
                        cmdByNs.Sort((x, y) => x.Key.CompareTo(y.Key));
                        int g = 0;
                        foreach (var grouping in cmdByNs)
                        {
                            if (grouping.Count() > 0)
                            {
                                if (g > 0)
                                {
                                    context.Out.Echoln();
                                }
                                context.Out.Echoln($"{ANSI.SGR_Underline}{context.ShellEnv.Colors.Label}{grouping.Key}{ANSI.SGR_UnderlineOff}{context.ShellEnv.Colors.Default}{ANSI.CRLF}");
                                foreach (var item in grouping)
                                {
                                    _PrintCommandHelp(context, item, shortView, verboseView, list, maxnslength, maxcmdlength, maxcmdtypelength, maxmodlength, !string.IsNullOrWhiteSpace(commandName));
                                }
                                g++;
                            }
                        }
                    }
                    else
                    {
                        int n = 0;
                        foreach (var cmd in cmds)
                        {
                            if (!list && n > 0)
                            {
                                context.Out.Echoln();
                            }
                            _PrintCommandHelp(context, cmd, shortView, verboseView, list, maxnslength, maxcmdlength, maxcmdtypelength, maxmodlength, !string.IsNullOrWhiteSpace(commandName));
                            n++;
                        }
                    }
                }
            }
            else
            {
                context.Errorln($"Command not found: '{commandName}'");
                return(new CommandVoidResult(ReturnCode.Error));
            }
            return(new CommandVoidResult());
        }