Inheritance: Layout, ISupportsLazyParameters
コード例 #1
0
 public void SimpleLayoutCachingTest()
 {
     var l = new SimpleLayout("xx${level}yy");
     var ev = LogEventInfo.CreateNullEvent();
     string output1 = l.Render(ev);
     string output2 = l.Render(ev);
     Assert.AreSame(output1, output2);
 }
コード例 #2
0
        public void SimpleLayoutToStringTest()
        {
            var l = new SimpleLayout("xx${level}yy");
            Assert.AreEqual("'xx${level}yy'", l.ToString());

            var l2 = new SimpleLayout(new LayoutRenderer[0], "someFakeText", ConfigurationItemFactory.Default);
            Assert.AreEqual("'someFakeText'", l2.ToString());
        }
コード例 #3
0
 public void LayoutRendererThrows()
 {
     ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory();
     configurationItemFactory.LayoutRenderers.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));
     
     SimpleLayout l = new SimpleLayout("xx${throwsException}yy", configurationItemFactory);
     string output = l.Render(LogEventInfo.CreateNullEvent());
     Assert.AreEqual("xxyy", output);
 }
コード例 #4
0
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            if (!_isCached)
            {
                _cachedValue = GetValue();
            }

            var layout = new SimpleLayout(_cachedValue);
            builder.Append(layout.Render(logEvent));
        }
コード例 #5
0
        public void TestConstructor()
        {
            const string name = "SomeName!";
            var layout = new SimpleLayout
                             {
                                 Text = "SomeText"
                             };

            var field = new MongoDBTargetField(name, layout);

            field.Name
                .Should().Be(name);
            field.Layout
                .Should().Be(layout);
        }
コード例 #6
0
        public void ConfigureLogger()
        {
            var layout = new SimpleLayout("${date} [${threadid}] ${level} ${logger} ${ndc} - ${message}${newline}");

            var channelFactory = Substitute.For<ChannelFactory>();
            _channel = Substitute.For<IEventChannel>();
            channelFactory.Create("localhost", 8765, 1).Returns(_channel);
            _target = new BrowserConsoleTarget(channelFactory)
            {
                Host = "localhost",
                Port = 8765,
                Layout = layout,
                Buffer = 1,
                Name = "ConsoleTest"
            };
        }
コード例 #7
0
        static void ConfigureLogging()
        {
            if (LogManager.Configuration != null)
            {
                return;
            }

            var nlogConfig = new LoggingConfiguration();
            var simpleLayout = new SimpleLayout("${longdate}|${threadid}|${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}");
            
            var fileTarget = new FileTarget
            {
                ArchiveEvery = FileArchivePeriod.Day,
                FileName = Path.Combine(Settings.LogPath, "logfile.txt"),
                ArchiveFileName = Path.Combine(Settings.LogPath, "log.{#}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                Layout = simpleLayout,
                MaxArchiveFiles = 14,
            };
            var consoleTarget = new ColoredConsoleTarget
            {
                Layout = simpleLayout,
                UseDefaultRowHighlightingRules = true,
            };

            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, consoleTarget) { Final = true });
            nlogConfig.LoggingRules.Add(new LoggingRule("NServiceBus.Licensing.*", LogLevel.Error, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("NServiceBus.Licensing.*", LogLevel.Error, consoleTarget) { Final = true });

            nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Warn, fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); 
            
            nlogConfig.AddTarget("debugger", fileTarget);
            nlogConfig.AddTarget("console", consoleTarget);
            NLogConfigurator.Configure(new object[] { fileTarget, consoleTarget }, "Info");
            LogManager.Configuration = nlogConfig;
        }
コード例 #8
0
ファイル: FilePathLayout.cs プロジェクト: rosj91/NLog
        /// <summary>
        /// Is this (templated/invalid) path an absolute, relative or unknown?
        /// </summary>
        private static FilePathKind DetectFilePathKind(SimpleLayout pathLayout)
        {
            var isFixedText = pathLayout.IsFixedText;

            //nb: ${basedir} has already been rewritten in the SimpleLayout.compile
            var path = isFixedText ? pathLayout.FixedText : pathLayout.Text;

            if (path != null)
            {
                path = path.TrimStart();

                int length = path.Length;
                if (length >= 1)
                {
                    var firstChar = path[0];
                    if (firstChar == Path.DirectorySeparatorChar || firstChar == Path.AltDirectorySeparatorChar)
                        return FilePathKind.Absolute;
                    if (firstChar == '.') //. and ..
                    {
                        return FilePathKind.Relative;
                    }


                    if (length >= 2)
                    {
                        var secondChar = path[1];
                        //on unix VolumeSeparatorChar == DirectorySeparatorChar
                        if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar && secondChar == Path.VolumeSeparatorChar)
                            return FilePathKind.Absolute;

                    }
                    if (!isFixedText && path.StartsWith("${", StringComparison.OrdinalIgnoreCase))
                    {
                        //if first part is a layout, then unknown
                        return FilePathKind.Unknown;
                    }


                    //not a layout renderer, but text
                    return FilePathKind.Relative;
                }
            }
            return FilePathKind.Unknown;
        }
コード例 #9
0
        /// <summary>
        /// Try get the 
        /// </summary>
        /// <param name="layout"></param>
        /// <returns></returns>
        private bool TryGetLayout(out SimpleLayout layout)
        {
            if (this.Name != null)
            {
                //don't use LogManager (locking, recursion)
                var loggingConfiguration = LoggingConfiguration; //?? LogManager.Configuration;
                var vars = loggingConfiguration != null ? loggingConfiguration.Variables : null;
                if (vars != null && vars.TryGetValue(Name, out layout))
                {
                    return true;
                }

            }
            layout = null;
            return false;
        }
コード例 #10
0
ファイル: SdId.cs プロジェクト: graffen/NLog.Targets.Syslog
 public SdId(SimpleLayout sdIdConfig, EnforcementConfig enforcementConfig)
 {
     layout = sdIdConfig;
     sdIdPolicySet = new SdIdPolicySet(enforcementConfig);
 }
コード例 #11
0
 public void WrapperOverAgnostic()
 {
     Layout l = new SimpleLayout("${rot13:${message}}");
     l.Initialize(null);
     Assert.True(l.IsThreadAgnostic);
 }
コード例 #12
0
ファイル: DatabaseTarget.cs プロジェクト: ExM/NLog
        void ISupportsLazyParameters.CreateParameters(LoggingConfiguration cfg)
        {
            bool foundProvider = false;

            if (!string.IsNullOrEmpty(ConnectionStringName))
            {
                // read connection string and provider factory from the configuration file
                var cs = ConnectionStringsSettings[ConnectionStringName];
                if (cs == null)
                {
                    throw new NLogConfigurationException("Connection string '" + ConnectionStringName + "' is not declared in <connectionStrings /> section.");
                }

                ConnectionString = new SimpleLayout(SimpleLayout.Escape(cs.ConnectionString), cfg);
                ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName);
                foundProvider = true;
            }

            if (!foundProvider)
            {
                foreach(DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
                {
                    if ((string)row["InvariantName"] == DBProvider)
                    {
                        ProviderFactory = DbProviderFactories.GetFactory(DBProvider);
                        foundProvider = true;
                    }
                }
            }

            if (!foundProvider)
            {
                switch (DBProvider.ToUpper(CultureInfo.InvariantCulture))
                {
                    case "SQLSERVER":
                    case "MSSQL":
                    case "MICROSOFT":
                    case "MSDE":
                        ConnectionType = systemDataAssembly.GetType("System.Data.SqlClient.SqlConnection", true);
                        break;

                    case "OLEDB":
                        ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true);
                        break;

                    case "ODBC":
                        ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true);
                        break;

                    default:
                        ConnectionType = Type.GetType(DBProvider, true);
                        break;
                }
            }
        }
コード例 #13
0
ファイル: ThreadAgnosticTests.cs プロジェクト: ExM/NLog
        public void CustomNotAgnosticTests()
        {
            var cif = new ConfigurationItemFactory();
            cif.RegisterType(typeof(CustomRendererNonAgnostic), string.Empty);
            var cfg = new LoggingConfiguration(cif);
            Layout l = new SimpleLayout("${customNotAgnostic}", cfg);

            l.Initialize(cfg);
            Assert.IsFalse(l.IsThreadAgnostic);
        }
コード例 #14
0
ファイル: SimpleLayoutOutputTests.cs プロジェクト: ExM/NLog
        public void SimpleLayoutToStringTest()
        {
            var l = new SimpleLayout("xx${level}yy");
            Assert.AreEqual("'xx${level}yy'", l.ToString());

            var l2 = new SimpleLayout("someFakeText", new LayoutRenderer[0]);
            Assert.AreEqual("'someFakeText'", l2.ToString());
        }
コード例 #15
0
        public void LayoutRendererThrows2()
        {
            string internalLogOutput = RunAndCaptureInternalLog(
                () => 
                    {
                        ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory();
                        configurationItemFactory.LayoutRenderers.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));

                        SimpleLayout l = new SimpleLayout("xx${throwsException:msg1}yy${throwsException:msg2}zz", configurationItemFactory);
                        string output = l.Render(LogEventInfo.CreateNullEvent());
                        Assert.AreEqual("xxyyzz", output);
                    }, 
                    LogLevel.Warn);

            Assert.IsTrue(internalLogOutput.IndexOf("msg1") >= 0, internalLogOutput);
            Assert.IsTrue(internalLogOutput.IndexOf("msg2") >= 0, internalLogOutput);
        }
コード例 #16
0
        public void CustomAgnosticTests()
        {
            var cif = new ConfigurationItemFactory();
            cif.RegisterType(typeof(CustomRendererAgnostic), string.Empty);

            Layout l = new SimpleLayout("${customAgnostic}", cif);

            l.Initialize(null);
            Assert.True(l.IsThreadAgnostic);
        }
コード例 #17
0
 public void TripleWrapperOverNonAgnostic()
 {
     Layout l = new SimpleLayout("${uppercase:${lowercase:${rot13:${message}${threadname}}}}");
     l.Initialize(null);
     Assert.False(l.IsThreadAgnostic);
 }
コード例 #18
0
        public void LayoutRendererThrows()
        {
            NLogFactories nlogFactories = new NLogFactories();
            nlogFactories.LayoutRendererFactory.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));

            SimpleLayout l = new SimpleLayout("xx${throwsException}yy", nlogFactories);
            string output = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreEqual("xxyy", output);
        }
コード例 #19
0
ファイル: LogglyTarget.cs プロジェクト: BO45/NzbDrone
 public LogglyTarget()
 {
     Layout = new SimpleLayout("${callsite:className=false:fileName=false:includeSourcePath=false:methodName=true}");
     
 }
コード例 #20
0
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, Tokenizer sr)
        {
            int ch = sr.Read();

            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string         name = ParseLayoutRendererName(sr);
            LayoutRenderer lr   = configurationItemFactory.LayoutRenderers.CreateInstance(name);

            var wrappers        = new Dictionary <Type, LayoutRenderer>();
            var orderedWrappers = new List <LayoutRenderer>();

            ch = sr.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(sr).Trim();
                if (sr.Peek() == '=')
                {
                    sr.Read(); // skip the '='
                    PropertyInfo   pi;
                    LayoutRenderer parameterTarget = lr;

                    if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi))
                    {
                        Type wrapperType;

                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType))
                        {
                            LayoutRenderer wrapperRenderer;

                            if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
                            {
                                wrapperRenderer       = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi))
                            {
                                pi = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (pi == null)
                    {
                        ParseParameterValue(sr);
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(pi.PropertyType))
                        {
                            var              nestedLayout = new SimpleLayout();
                            string           txt;
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt);

                            nestedLayout.SetRenderers(renderers, txt);
                            pi.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(sr);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value);
                        }
                    }
                }
                else
                {
                    // what we've just read is not a parameterName, but a value
                    // assign it to a default property (denoted by empty string)
                    PropertyInfo pi;

                    if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi))
                    {
                        if (typeof(SimpleLayout) == pi.PropertyType)
                        {
                            pi.SetValue(lr, new SimpleLayout(parameterName), null);
                        }
                        else
                        {
                            string value = parameterName;
                            PropertyHelper.SetPropertyFromString(lr, pi.Name, value);
                        }
                    }
                    else
                    {
                        InternalLogger.Warn("{0} has no default property", lr.GetType().FullName);
                    }
                }

                ch = sr.Read();
            }

            lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers);

            return(lr);
        }
コード例 #21
0
ファイル: LayoutParser.cs プロジェクト: njannink/sonarlint-vs
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr)
        {
            int ch = sr.Read();
            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name = ParseLayoutRendererName(sr);
            LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name);

            var wrappers = new Dictionary<Type, LayoutRenderer>();
            var orderedWrappers = new List<LayoutRenderer>();

            ch = sr.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(sr).Trim();
                if (sr.Peek() == '=')
                {
                    sr.Read(); // skip the '='
                    PropertyInfo pi;
                    LayoutRenderer parameterTarget = lr;

                    if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi))
                    {
                        Type wrapperType;

                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType))
                        {
                            LayoutRenderer wrapperRenderer;

                            if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
                            {
                                wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi))
                            {
                                pi = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (pi == null)
                    {
                        ParseParameterValue(sr);
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(pi.PropertyType))
                        {
                            var nestedLayout = new SimpleLayout();
                            string txt;
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt);

                            nestedLayout.SetRenderers(renderers, txt);
                            pi.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType))
                        {
                            var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory);
                            pi.SetValue(parameterTarget, conditionExpression, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(sr);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
                        }
                    }
                }
                else
                {
                    // what we've just read is not a parameterName, but a value
                    // assign it to a default property (denoted by empty string)
                    PropertyInfo pi;

                    if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi))
                    {
                        if (typeof(SimpleLayout) == pi.PropertyType)
                        {
                            pi.SetValue(lr, new SimpleLayout(parameterName), null);
                        }
                        else
                        {
                            string value = parameterName;
                            PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory);
                        }
                    }
                    else
                    {
                        InternalLogger.Warn("{0} has no default property", lr.GetType().FullName);
                    }
                }

                ch = sr.Read();
            }

            lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers);

            return lr;
        }
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool?throwConfigExceptions)
        {
            int ch = stringReader.Read();

            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name           = ParseLayoutRendererName(stringReader);
            var    layoutRenderer = GetLayoutRenderer(configurationItemFactory, name, throwConfigExceptions);

            Dictionary <Type, LayoutRenderer> wrappers        = null;
            List <LayoutRenderer>             orderedWrappers = null;

            ch = stringReader.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(stringReader).Trim();
                if (stringReader.Peek() == '=')
                {
                    stringReader.Read(); // skip the '='
                    PropertyInfo   propertyInfo;
                    LayoutRenderer parameterTarget = layoutRenderer;

                    if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo))
                    {
                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out var wrapperType))
                        {
                            wrappers        = wrappers ?? new Dictionary <Type, LayoutRenderer>();
                            orderedWrappers = orderedWrappers ?? new List <LayoutRenderer>();
                            if (!wrappers.TryGetValue(wrapperType, out var wrapperRenderer))
                            {
                                wrapperRenderer       = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo))
                            {
                                propertyInfo = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (propertyInfo == null)
                    {
                        var value = ParseParameterValue(stringReader);
                        if (!string.IsNullOrEmpty(parameterName) || !StringHelpers.IsNullOrWhiteSpace(value))
                        {
                            // TODO NLog 5.0 Should throw exception when invalid configuration (Check throwConfigExceptions)
                            InternalLogger.Warn("Skipping unrecognized property '{0}={1}` for ${{{2}}} ({3})", parameterName, value, name, layoutRenderer?.GetType());
                        }
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out var txt);

                            var nestedLayout = new SimpleLayout(renderers, txt, configurationItemFactory);
                            propertyInfo.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory);
                            propertyInfo.SetValue(parameterTarget, conditionExpression, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(stringReader);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
                        }
                    }
                }
                else
                {
                    SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName);
                }

                ch = stringReader.Read();
            }

            if (orderedWrappers != null)
            {
                layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers);
            }

            return(layoutRenderer);
        }
コード例 #23
0
ファイル: SimpleLayout.cs プロジェクト: semirs/CellAO
 /// <summary>
 /// Evaluates the specified text by expadinging all layout renderers.
 /// </summary>
 /// <param name="text">The text to be evaluated.</param>
 /// <param name="logEvent">Log event to be used for evaluation.</param>
 /// <returns>The input text with all occurences of ${} replaced with
 /// values provided by the appropriate layout renderers.</returns>
 public static string Evaluate(string text, LogEventInfo logEvent)
 {
     var l = new SimpleLayout(text);
     return l.Render(logEvent);
 }
コード例 #24
0
ファイル: ThreadAgnosticTests.cs プロジェクト: ExM/NLog
 public void TripleWrapperOverAgnostic()
 {
     Layout l = new SimpleLayout("${uppercase:${lowercase:${rot13:${message}}}}");
     l.Initialize(CommonCfg);
     Assert.IsTrue(l.IsThreadAgnostic);
 }
コード例 #25
0
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool?throwConfigExceptions)
        {
            int ch = stringReader.Read();

            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name           = ParseLayoutRendererName(stringReader);
            var    layoutRenderer = GetLayoutRenderer(configurationItemFactory, name, throwConfigExceptions);

            var wrappers        = new Dictionary <Type, LayoutRenderer>();
            var orderedWrappers = new List <LayoutRenderer>();

            ch = stringReader.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(stringReader).Trim();
                if (stringReader.Peek() == '=')
                {
                    stringReader.Read(); // skip the '='
                    PropertyInfo   propertyInfo;
                    LayoutRenderer parameterTarget = layoutRenderer;

                    if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo))
                    {
                        Type wrapperType;

                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType))
                        {
                            LayoutRenderer wrapperRenderer;

                            if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
                            {
                                wrapperRenderer       = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo))
                            {
                                propertyInfo = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (propertyInfo == null)
                    {
                        ParseParameterValue(stringReader);
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            var              nestedLayout = new SimpleLayout();
                            string           txt;
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, true, out txt);

                            nestedLayout.SetRenderers(renderers, txt);
                            propertyInfo.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType))
                        {
                            var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory);
                            propertyInfo.SetValue(parameterTarget, conditionExpression, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(stringReader);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
                        }
                    }
                }
                else
                {
                    SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName);
                }

                ch = stringReader.Read();
            }

            layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers);

            return(layoutRenderer);
        }
コード例 #26
0
 public void ThreadAgnosticTest()
 {
     Layout l = new SimpleLayout("${message}");
     l.Initialize(null);
     Assert.True(l.IsThreadAgnostic);
 }
コード例 #27
0
ファイル: Program.cs プロジェクト: rexxar-tc/SEServerExtender
        private static void Start( string[ ] args )
        {
            // SE_VERSION is a private constant. Need to use reflection to get it.
            FieldInfo field = typeof(SpaceEngineersGame).GetField("SE_VERSION", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            SeVersion = new Version(new MyVersion((int)field.GetValue(null)).FormattedText.ToString().Replace("_", "."));

            bool stableBuild = (bool)typeof(MyFinalBuildConstants).GetField("IS_STABLE").GetValue(null);

            ApplicationLog.BaseLog.Info($"SE version: {SeVersion}");
            ApplicationLog.BaseLog.Info( $"Extender version: {Assembly.GetExecutingAssembly().GetName().Version}" );
            if (stableBuild)
            {
                BaseLog.Info("Detected \"Stable\" branch!");
                IsStable = true;
                PluginManager.IsStable = true;

                //hide the block limit config, since it will crash in stable
                HideConfigs();
            }
            else
                BaseLog.Info("Detected \"Development\" branch!");

            InitSandbox(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + @"..\Content"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode( UnhandledExceptionMode.CatchException );

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info( "Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join( "\r\n\t", args ) );

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
                              {
                                  ConsoleTitle = string.Empty,
                                  AutoStart = false,
                                  WorldName = string.Empty,
                                  InstanceName = string.Empty,
                                  NoGui = false,
                                  NoConsole = false,
                                  Debug = false,
                                  GamePath = new DirectoryInfo( PathManager.BasePath ).Parent.FullName,
                                  //TODO: turn noWFC back to off by default whenever WCF gets fixed
                                  NoWcf = true,
                                  Autosave = 0,
                                  InstancePath = string.Empty,
                                  CloseOnCrash = false,
                                  RestartOnCrash = false,
                                  NoProfiler = false,
                                  Args = string.Join( " ", args.Select( x => string.Format( "\"{0}\"", x ) ) )
                              };

            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ], out _maxChatHistoryMessageAge ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryAge", "3600" );
                }
            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ], out _maxChatHistoryMessageCount ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryCount", "100" );
                }

            bool logPathSet = false;
            //Process the args
            foreach ( string arg in args )
            {
                string[ ] splitAtEquals = arg.Split( '=' );
                if ( splitAtEquals.Length > 1 )
                {
                    string argName = splitAtEquals[ 0 ];
                    string argValue = splitAtEquals[ 1 ];

                    string lowerCaseArgument = argName.ToLower( );
                    if ( lowerCaseArgument.Equals( "instance" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        //sanitize input because stupid people put full paths for this argument
                        extenderArgs.InstanceName = argValue.Replace( @"\", "-" ).Replace( @":", "-" );

                        //Only let this override log path if the log path wasn't already explicitly set
                        if ( !logPathSet )
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                            if ( baseLogTarget != null )
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                            if ( chatLogTarget != null )
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                            if ( pluginLogTarget != null )
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render(new LogEventInfo { TimeStamp = DateTime.Now }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                        }
                    }
                    else if ( lowerCaseArgument.Equals( "gamepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.GamePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "autosave" ) )
                    {
                        if ( !int.TryParse( argValue, out extenderArgs.Autosave ) )
                            BaseLog.Warn( "Autosave parameter was not a valid integer." );
                    }
                    else if ( lowerCaseArgument.Equals( "path" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "instancepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title") )
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if ( lowerCaseArgument == "logpath" )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                        if ( baseLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "SEServerExtenderLog-${shortdate}.log" ) );
                            baseLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                        if ( chatLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "ChatLog-${shortdate}.log" ) );
                            chatLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                        if ( pluginLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "PluginLog-${shortdate}.log" ) );
                            pluginLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }

                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if ( lowerCaseArgument.Equals( "autostart" ) )
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nogui" ) )
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "noconsole" ) )
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "debug" ) )
                    {
                        extenderArgs.Debug = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nowcf" ) )
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wcfon" ) )
                    {
                        extenderArgs.NoWcf = false;
                    }
                    else if ( lowerCaseArgument.Equals( "closeoncrash" ) )
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "autosaveasync" ) )
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if ( lowerCaseArgument.Equals( "autosavesync" ) )
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if ( lowerCaseArgument.Equals( "restartoncrash" ) )
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    else if (lowerCaseArgument.Equals("noprofiler") && !IsStable)
                    {
                        extenderArgs.NoProfiler = true;
                        Server.DisableProfiler = true;
                    }
                    //these things are legacy and don't work anyway
                    /*
                    else if ( lowerCaseArgument.Equals( "wrr" ) )
                    {
                        extenderArgs.WorldRequestReplace = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrm" ) )
                    {
                        extenderArgs.WorldDataModify = true;
                    }
                    else if (lowerCaseArgument.Equals("wvm"))
                    {
                        extenderArgs.WorldVoxelModify = true;
                    }
                    */
                }
            }

            if ( !Environment.UserInteractive )
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui = true;
                extenderArgs.AutoStart = true;
            }

            if ( extenderArgs.Debug )
                ExtenderOptions.IsDebugging = true;

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if ( !unitTestResult )
                    ExtenderOptions.IsInSafeMode = true;

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled = !extenderArgs.NoWcf;
                Server.Init( );

                //if(!DedicatedServerAssemblyWrapper.IsStable)
                //    InitSandbox(Path.Combine( GameInstallationInfo.GamePath, @"..\Content"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand( "gui", ChatCommand_GUI, false );
                ChatManager.Instance.RegisterChatCommand( guiCommand );

                if (!CommandLineArgs.NoConsole)
                {
                    if (string.IsNullOrEmpty(extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                    {
                        Console.Title = "SESE";
                    }
                    else
                    {
                        Console.Title = extenderArgs.ConsoleTitle;
                    }
                }

                if ( extenderArgs.AutoStart )
                {
                    Server.StartServer( );
                }

                if ( !extenderArgs.NoWcf )
                {
                    string uriString = string.Format( "{0}{1}", ConfigurationManager.AppSettings[ "WCFServerServiceBaseAddress" ], CommandLineArgs.InstanceName );
                    BaseLog.Info( "Opening up WCF service listener at {0}", uriString );
                    ServerServiceHost = new ServiceHost( typeof( ServerService.ServerService ), new Uri( uriString, UriKind.Absolute ) );
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if ( !extenderArgs.NoGui )
                {
                    Thread uiThread = new Thread( StartGui );
                    uiThread.SetApartmentState( ApartmentState.STA );
                    uiThread.Start( );
                }
                else if ( Environment.UserInteractive )
                    Console.ReadLine( );

            }
            catch ( AutoException eEx )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw eEx.GetBaseException( );
            }
            catch ( TargetInvocationException ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", ex, ex.InnerException ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
            catch ( Exception ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( ex, "Exception - {0}", ex );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
        }
コード例 #28
0
        /// <summary>
        /// Evaluates the specified text by expanding all layout renderers.
        /// </summary>
        /// <param name="text">The text to be evaluated.</param>
        /// <param name="logEvent">Log event to be used for evaluation.</param>
        /// <returns>The input text with all occurrences of ${} replaced with
        /// values provided by the appropriate layout renderers.</returns>
        public static string Evaluate(string text, LogEventInfo logEvent)
        {
            var l = new SimpleLayout(text);

            return(l.Render(logEvent));
        }
コード例 #29
0
 public void NonThreadAgnosticTest()
 {
     Layout l = new SimpleLayout("${threadname}");
     l.Initialize(null);
     Assert.False(l.IsThreadAgnostic);
 }
コード例 #30
0
ファイル: Program.cs プロジェクト: stansan/SEServerExtender
        private static void Start( string[ ] args )
        {
            //register object builder assembly
            string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "SpaceEngineers.ObjectBuilders.DLL" );
            VRage.Plugins.MyPlugins.RegisterGameObjectBuildersAssemblyFile( path );

            MyObjectBuilderType.RegisterAssemblies( );

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode( UnhandledExceptionMode.CatchException );

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info( "Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join( "\r\n\t", args ) );

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
                              {
                                  ConsoleTitle = string.Empty,
                                  AutoStart = false,
                                  WorldName = string.Empty,
                                  InstanceName = string.Empty,
                                  NoGui = false,
                                  NoConsole = false,
                                  Debug = false,
                                  GamePath = new DirectoryInfo( PathManager.BasePath ).Parent.FullName,
                                  NoWcf = false,
                                  Autosave = 0,
                                  InstancePath = string.Empty,
                                  CloseOnCrash = false,
                                  RestartOnCrash = false,
                                  Args = string.Join( " ", args.Select( x => string.Format( "\"{0}\"", x ) ) )
                              };

            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryAge" ], out _maxChatHistoryMessageAge ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryAge", "3600" );
                }
            if ( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ] != null )
                if ( !int.TryParse( ConfigurationManager.AppSettings[ "WCFChatMaxMessageHistoryCount" ], out _maxChatHistoryMessageCount ) )
                {
                    ConfigurationManager.AppSettings.Add( "WCFChatMaxMessageHistoryCount", "100" );
                }

            bool logPathSet = false;
            //Process the args
            foreach ( string arg in args )
            {
                string[ ] splitAtEquals = arg.Split( '=' );
                if ( splitAtEquals.Length > 1 )
                {
                    string argName = splitAtEquals[ 0 ];
                    string argValue = splitAtEquals[ 1 ];

                    string lowerCaseArgument = argName.ToLower( );
                    if ( lowerCaseArgument.Equals( "instance" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstanceName = argValue;

                        //Only let this override log path if the log path wasn't already explicitly set
                        if ( !logPathSet )
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                            if ( baseLogTarget != null )
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                            if ( chatLogTarget != null )
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                            if ( pluginLogTarget != null )
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render( new LogEventInfo { TimeStamp = DateTime.Now } ).Replace( "NoInstance", argValue );
                            }
                        }
                    }
                    else if ( lowerCaseArgument.Equals( "gamepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.GamePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "autosave" ) )
                    {
                        if ( !int.TryParse( argValue, out extenderArgs.Autosave ) )
                            BaseLog.Warn( "Autosave parameter was not a valid integer." );
                    }
                    else if ( lowerCaseArgument.Equals( "path" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if ( lowerCaseArgument.Equals( "instancepath" ) )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title") )
                    {
                        if (argValue[argValue.Length - 1] == '"')
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if ( lowerCaseArgument == "logpath" )
                    {
                        if ( argValue[ argValue.Length - 1 ] == '"' )
                            argValue = argValue.Substring( 1, argValue.Length - 2 );

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName( "BaseLog" ) as FileTarget;
                        if ( baseLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "SEServerExtenderLog-${shortdate}.log" ) );
                            baseLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName( "ChatLog" ) as FileTarget;
                        if ( chatLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "ChatLog-${shortdate}.log" ) );
                            chatLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName( "PluginLog" ) as FileTarget;
                        if ( pluginLogTarget != null )
                        {
                            Layout l = new SimpleLayout( Path.Combine( argValue, "PluginLog-${shortdate}.log" ) );
                            pluginLogTarget.FileName = l.Render( new LogEventInfo { TimeStamp = DateTime.Now } );
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }

                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if ( lowerCaseArgument.Equals( "autostart" ) )
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nogui" ) )
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "noconsole" ) )
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if ( lowerCaseArgument.Equals( "debug" ) )
                    {
                        extenderArgs.Debug = true;
                    }
                    else if ( lowerCaseArgument.Equals( "nowcf" ) )
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if ( lowerCaseArgument.Equals( "closeoncrash" ) )
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "autosaveasync" ) )
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if ( lowerCaseArgument.Equals( "autosavesync" ) )
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if ( lowerCaseArgument.Equals( "restartoncrash" ) )
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrr" ) )
                    {
                        extenderArgs.WorldRequestReplace = true;
                    }
                    else if ( lowerCaseArgument.Equals( "wrm" ) )
                    {
                        extenderArgs.WorldDataModify = true;
                    }
                    else if (lowerCaseArgument.Equals("wvm"))
                    {
                        extenderArgs.WorldVoxelModify = true;
                    }
                }
            }

            if ( !Environment.UserInteractive )
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui = true;
                extenderArgs.AutoStart = true;
            }

            if ( extenderArgs.Debug )
                ExtenderOptions.IsDebugging = true;

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if ( !unitTestResult )
                    ExtenderOptions.IsInSafeMode = true;

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled = !extenderArgs.NoWcf;
                Server.Init( );

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand( "gui", ChatCommand_GUI, false );
                ChatManager.Instance.RegisterChatCommand( guiCommand );

                if (string.IsNullOrEmpty (extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                {
                    Console.Title = "SESE";
                }
                else
                {
                    Console.Title = extenderArgs.ConsoleTitle;
                }

                if ( extenderArgs.AutoStart )
                {
                    Server.StartServer( );
                }

                if ( !extenderArgs.NoWcf )
                {
                    string uriString = string.Format( "{0}{1}", ConfigurationManager.AppSettings[ "WCFServerServiceBaseAddress" ], CommandLineArgs.InstanceName );
                    BaseLog.Info( "Opening up WCF service listener at {0}", uriString );
                    ServerServiceHost = new ServiceHost( typeof( ServerService.ServerService ), new Uri( uriString, UriKind.Absolute ) );
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if ( !extenderArgs.NoGui )
                {
                    Thread uiThread = new Thread( StartGui );
                    uiThread.SetApartmentState( ApartmentState.STA );
                    uiThread.Start( );
                }
                else if ( Environment.UserInteractive )
                    Console.ReadLine( );

            }
            catch ( AutoException eEx )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ) ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw eEx.GetBaseException( );
            }
            catch ( TargetInvocationException ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( "TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( string.Format( "{0}\n\r{1}", ex, ex.InnerException ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
            catch ( Exception ex )
            {
                if ( !extenderArgs.NoConsole )
                    BaseLog.Info( ex, "Exception - {0}", ex );
                if ( !extenderArgs.NoGui )
                    MessageBox.Show( ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error );

                if ( extenderArgs.NoConsole && extenderArgs.NoGui )
                    throw;
            }
        }
コード例 #31
0
 public void AgnosticPlusNonAgnostic()
 {
     Layout l = new SimpleLayout("${message}${threadname}");
     l.Initialize(null);
     Assert.False(l.IsThreadAgnostic);
 }
コード例 #32
0
ファイル: PropertyHelper.cs プロジェクト: nvpeskov/NLog
        private static bool TryNLogSpecificConversion(Type propertyType, string value, out object newValue, ConfigurationItemFactory configurationItemFactory)
        {
            if (propertyType == typeof(Layout) || propertyType == typeof(SimpleLayout))
            {
                newValue = new SimpleLayout(value, configurationItemFactory);
                return true;
            }

            if (propertyType == typeof(ConditionExpression))
            {
                newValue = ConditionParser.ParseExpression(value, configurationItemFactory);
                return true;
            }

            newValue = null;
            return false;
        }
コード例 #33
0
 public void AgnosticPlusAgnostic()
 {
     Layout l = new SimpleLayout("${message}${level}${logger}");
     l.Initialize(null);
     Assert.True(l.IsThreadAgnostic);
 }