Esempio n. 1
0
 public void SetSourceSwitchTest()
 {
     var trace = new TraceSource("TestTraceSource");
     var @switch = new SourceSwitch("TestTraceSwitch");
     trace.Switch = @switch;
     Assert.Equal(@switch, trace.Switch);
 }
Esempio n. 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true; //Add this line

            ISharedConfiguration SharedConfiguration = services.RegisterSharedConfiguration();

            string     appName    = SharedConfiguration.GetValue("Tracing:appName");
            string     traceFile  = SharedConfiguration.GetTraceFilePath();
            TraceLevel traceLevel = (TraceLevel)System.Enum.Parse(typeof(TraceLevel), SharedConfiguration.GetValue("Tracing:traceLevel"));

            Fs.Core.Trace.Init(appName, traceLevel, traceFile);
            Fs.Core.Trace.Write("ConfigureServices()", "Started", TraceLevel.Info);

            SourceSwitch sourceSwitch = new SourceSwitch("POCTraceSwitch", "Verbose");

            AppLoggerFactory = LoggerFactory.Create(builder => { builder.AddTraceSource(sourceSwitch, Fs.Core.Trace.TraceListener); });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseLoggerFactory(AppLoggerFactory).
                                                         UseSqlServer(SharedConfiguration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <LoggerContext>(options =>
                                                  options.UseLoggerFactory(AppLoggerFactory).
                                                  UseSqlServer(SharedConfiguration.GetConnectionString("LoggerConnection")));
            services.AddDbContext <OrderingContext>(options =>
                                                    options.UseLoggerFactory(AppLoggerFactory).
                                                    UseSqlServer(SharedConfiguration.GetConnectionString("DefaultConnection")));

            services.AddLogging(config => config.ClearProviders())
            .AddLogging(config => config.AddTraceSource(sourceSwitch, Fs.Core.Trace.TraceListener));

            services.RegisterServices(SharedConfiguration, AppLoggerFactory);
            services.AddHttpContextAccessor();

            /*services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
             *  .AddEntityFrameworkStores<ApplicationDbContext>();
             *
             * services.AddIdentityServer()
             * .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
             * {
             *  options.Clients.Add(new IdentityServer4.Models.Client
             *  {
             *      ClientId = "ClientPOC2",
             *      AllowedGrantTypes = GrantTypes.ClientCredentials,
             *      AllowedScopes = { "WebAPI" },
             *      ClientSecrets = { new IdentityServer4.Models.Secret("secret".Sha256()) }
             *  });
             *  options.Clients.Add(new IdentityServer4.Models.Client
             *  {
             *      ClientId = "Fs.Blazor.Client",
             *      ClientSecrets = { new IdentityServer4.Models.Secret("secret".Sha256()) },
             *
             *      AllowedGrantTypes = GrantTypes.Code,
             *      RequireConsent = false,
             *      RequirePkce = true,
             *
             *      AllowedScopes =
             *      {
             *          IdentityServerConstants.StandardScopes.OpenId,
             *          IdentityServerConstants.StandardScopes.Profile
             *      },
             *
             *      // where to redirect to after login
             *      RedirectUris = { "https://fs-blazor-client.netpoc.com/signin-oidc" },
             *
             *      // where to redirect to after logout
             *      PostLogoutRedirectUris = { "https://fs-blazor-client.netpoc.com/signout-callback-oidc" },
             *
             *      AllowedCorsOrigins = { "https://fs-blazor-client.netpoc.com" },
             *  });
             *  options.Clients.AddSPA(
             *          "Fs.Angular.Is4.Client", spa =>
             *          spa.WithRedirectUri("https://fs-angular-is4-client.netpoc.com/signin-oidc")
             *             .WithLogoutRedirectUri("https://fs-angular-is4-client.netpoc.com/signout-callback-oidc"));
             *  options.Clients.AddSPA(
             *          "Fs.Blazor.Is4.Wasm.Client", spa =>
             *          spa.WithRedirectUri("https://fs-blazor-is4-wasm-client.netpoc.com/signin-oidc")
             *             .WithLogoutRedirectUri("https://fs-blazor-is4-wasm-client.netpoc.com/signout-callback-oidc"));
             *  options.Clients.AddSPA(
             *          "Fs.Angular.Client", spa =>
             *          spa.WithRedirectUri("https://fs-angular-client.netpoc.com/authentication/login-callback")
             *             .WithLogoutRedirectUri("https://fs-angular-client.netpoc.com/authentication/logout-callback")
             *             .WithScopes(new string[]
             *              {
             *                  IdentityServerConstants.StandardScopes.OpenId
             *              }));
             *  options.Clients.AddSPA(
             *          "Fs.Blazor.Wasm.Client", spa =>
             *          spa.WithRedirectUri("https://fs-blazor-wasm-client.netpoc.com/authentication/login-callback")
             *             .WithLogoutRedirectUri("https://fs-blazor-wasm-client.netpoc.com/authentication/logout-callback")
             *             //.WithoutClientSecrets()
             *             .WithScopes(new string[]
             *              {
             *                  IdentityServerConstants.StandardScopes.OpenId,
             *                  IdentityServerConstants.StandardScopes.Profile
             *              }));
             *
             *  options.Clients["Fs.Angular.Client"].AllowedCorsOrigins.Add("https://fs-angular-client.netpoc.com");
             *  options.Clients["Fs.Angular.Client"].RedirectUris.Add("https://fs-angular-client.netpoc.com/signin-oidc");
             *
             *  options.Clients["Fs.Blazor.Wasm.Client"].AllowedCorsOrigins.Add("https://fs-blazor-wasm-client.netpoc.com");
             *  options.Clients["Fs.Blazor.Wasm.Client"].RedirectUris.Add("https://fs-blazor-wasm-client.netpoc.com/signin-oidc");
             * });
             *
             * services.AddAuthentication()
             *  .AddIdentityServerJwt();*/

            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(Config.Ids)
                          //.AddInMemoryApiResources(Config.Apis)
                          .AddInMemoryClients(Config.Clients)
                          .AddTestUsers(TestUsers.Users);

            builder.AddDeveloperSigningCredential();

            /*services.AddAuthentication()
             *  .AddGoogle("Google", options =>
             *  {
             *      options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
             *
             *      options.ClientId = "<insert here>";
             *      options.ClientSecret = "<insert here>";
             *  })
             * .AddOpenIdConnect("oidc", "Demo IdentityServer", options =>
             * {
             *  options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
             *  options.SignOutScheme = IdentityServerConstants.SignoutScheme;
             *  options.SaveTokens = true;
             *
             *  options.Authority = "https://demo.identityserver.io/";
             *  //options.RequireHttpsMetadata = false;
             *  options.ClientId = "native.code";
             *  options.ClientSecret = "secret";
             *  options.ResponseType = "code";
             *  options.TokenValidationParameters = new TokenValidationParameters
             *  {
             *      NameClaimType = "name",
             *      RoleClaimType = "role"
             *  };
             * });*/

            //services.AddRazorPages();
            services.AddControllersWithViews();
            services.AddAutoMapper(typeof(Fs.Business.Mappings.MappingProfile).Assembly);
        }
Esempio n. 3
0
 public TraceManager()
 {
     Switch = new SourceSwitch("SignalRSwitch");
 }
        public void ConstructorNullName()
        {
            SourceSwitch s = new SourceSwitch(null);

            Assert.IsNull(s.DisplayName);
        }
Esempio n. 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TraceSourceLoggerProvider"/> class.
 /// </summary>
 /// <param name="rootSourceSwitch"></param>
 public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch)
     : this(rootSourceSwitch, null)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiagnosticsLoggerProvider"/> class.
 /// </summary>
 /// <summary>
 /// Creates a factory named "Microsoft.Owin".
 /// </summary>
 public DiagnosticsLoggerProvider()
 {
     _rootSourceSwitch  = new SourceSwitch(RootTraceName);
     _rootTraceListener = null;
 }
        /// <summary>
        /// Run the demo.
        /// </summary>
        public static void Run()
        {
            // in debugging mode, the default trace listner write logs to debug console.
            Console.WriteLine($"Is debugging: {Debugger.IsAttached}");
            Console.WriteLine();

            // create file based logger factory
            string logFilePath =
                Path.Combine(AppContext.BaseDirectory, "TraceSourceLogDemo.log");
            Stream logStream = File.Create(logFilePath);
            TextWriterTraceListener fileListener =
                new TextWriterTraceListener(logStream);

            // Information, Warning, Error, Critical, Verbose (Trace/Debug)
            SourceSwitch   fileSwitch        = new SourceSwitch("FileSwtich", "Verbose");
            ILoggerFactory fileLoggerFactory = new LoggerFactory();

            fileLoggerFactory.AddTraceSource(fileSwitch, fileListener);

            // create console based logger factory
            TextWriterTraceListener consoleListener =
                new TextWriterTraceListener(Console.Out);
            SourceSwitch   consoleSwitch        = new SourceSwitch("ConsoleSwitch", "Warning");
            ILoggerFactory consoleLoggerFactory = new LoggerFactory();

            consoleLoggerFactory.AddTraceSource(consoleSwitch, consoleListener);

            EventId eventId = new EventId(1003, "TraceSourceLogDemoEvent");

            IEnumerable <LogLevel> logLevels =
                Enum.GetValues(typeof(LogLevel))
                .Cast <LogLevel>()
                .Except(new[] { LogLevel.None });

            Action <ILoggerFactory, string> loggerDemoAction =
                (factory, loggerName) =>
            {
                Console.WriteLine($"Logger name: {loggerName}");

                // also support factory.CreateLogger<T>();
                ILogger logger = factory.CreateLogger(loggerName);

                foreach (var logLevel in logLevels)
                {
                    bool isEnabled = logger.IsEnabled(logLevel);
                    Console.WriteLine($"\t[{(int)logLevel}]{logLevel} is enabled: ".PadRight(30, ' ') + isEnabled);
                }

                // file and console linster not support scopes
                using (logger.BeginScope("[{LOGGER}]TraceSourceLogDemoScope", loggerName))
                {
                    logger.LogTrace(eventId, "LogTrace from {LOGGER}", loggerName);
                    logger.LogDebug(eventId, "LogDebug from {LOGGER}", loggerName);
                    logger.LogInformation(eventId, "LogInformation from {LOGGER}", loggerName);
                    logger.LogWarning(eventId, "LogWarning from {LOGGER}", loggerName);
                    logger.LogError(eventId, "LogError from {LOGGER}", loggerName);
                    logger.LogCritical(eventId, "LogCritical from {LOGGER}", loggerName);
                }

                Console.WriteLine();
            };

            // console log level: >= Warning,
            loggerDemoAction(consoleLoggerFactory, "ConsoleLogger");

            // file log level: >= Verbose,
            loggerDemoAction(fileLoggerFactory, "FileLogger");

            // dispose file logger factory to release the log file handler.
            fileLoggerFactory.Dispose();

            // print log file.
            Console.WriteLine($"[Trace] log file path: {logFilePath}");
            Console.WriteLine(File.ReadAllText(logFilePath, Encoding.UTF8));
        }
Esempio n. 8
0
 // This constructor sets verbosity level to HDACLient instance
 public HDAClient(SourceSwitch sw)
 {
     _trace        = new TraceSource("HDAClientTraceSource");
     _trace.Switch = sw;
     _trace.TraceEvent(TraceEventType.Verbose, 0, "Created HDAClient");
 }
Esempio n. 9
0
        static void Main()
        //</Snippet2>
        {
            try
            {
                // Initialize trace switches.
                //<Snippet7>
#if (!ConfigFile)
                SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
                ts.Switch = sourceSwitch;
                int idxConsole = ts.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
                ts.Listeners[idxConsole].Name = "console";
#endif
                //</Snippet7>
                DisplayProperties(ts);
                //<Snippet16>
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.Callstack;
                //</Snippet16>
                //<Snippet17>
                ts.TraceEvent(TraceEventType.Warning, 1);
                //</Snippet17>
                ts.Listeners["console"].TraceOutputOptions = TraceOptions.DateTime;
                //<Snippet18>
                // Issue file not found message as a warning.
                ts.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
                //</Snippet18>
                //<Snippet24>
                // Issue file not found message as a verbose event using a formatted string.
                ts.TraceEvent(TraceEventType.Verbose, 3, "File {0} not found.", "test");
                //</Snippet24>
                // Issue file not found message as information.
                ts.TraceInformation("File {0} not found.", "test");
                //<Snippet26>
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.LogicalOperationStack;
                //</Snippet26>
                // Issue file not found message as an error event.
                ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test");
                //<Snippet28>
                // Test the filter on the ConsoleTraceListener.
                ts.Listeners["console"].Filter = new SourceFilter("No match");
                ts.TraceData(TraceEventType.Error, 5,
                             "SourceFilter should reject this message for the console trace listener.");
                ts.Listeners["console"].Filter = new SourceFilter("TraceTest");
                ts.TraceData(TraceEventType.Error, 6,
                             "SourceFilter should let this message through on the console trace listener.");
                //</Snippet28>
                ts.Listeners["console"].Filter = null;
                // Use the TraceData method.
                //<Snippet30>
                ts.TraceData(TraceEventType.Warning, 7, new object());
                //</Snippet30>
                //<Snippet31>
                ts.TraceData(TraceEventType.Warning, 8, new object[] { "Message 1", "Message 2" });
                //</Snippet31>
                // Activity tests.
                //<Snippet32>
                ts.TraceEvent(TraceEventType.Start, 9, "Will not appear until the switch is changed.");
                ts.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Critical;
                ts.TraceEvent(TraceEventType.Suspend, 10, "Switch includes ActivityTracing, this should appear");
                ts.TraceEvent(TraceEventType.Critical, 11, "Switch includes Critical, this should appear");
                //</Snippet32>
                //<Snippet33>
                ts.Flush();
                ts.Close();
                //</Snippet33>
                Console.WriteLine("Press any key to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                // Catch any unexpected exception.
                Console.WriteLine("Unexpected exception: " + e.ToString());
                Console.Read();
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TraceSourceLoggerProvider"/> class.
 /// </summary>
 /// <param name="rootSourceSwitch">The <see cref="SourceSwitch"/> to use.</param>
 /// <param name="rootTraceListener">The <see cref="TraceListener"/> to use.</param>
 public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch !!, TraceListener?rootTraceListener)
Esempio n. 11
0
        public void ConstructorNullName()
        {
            SourceSwitch s = new SourceSwitch(null);

            AssertHelper.IsEmpty(s.DisplayName);
        }
Esempio n. 12
0
        /// <summary>
        /// 配置中间件
        /// </summary>
        /// <param name="app"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.AddConsole();
            loggerFactory.AddDebug();
            var testSwitch = new SourceSwitch("sourceSwitch", "Logging Sample");

            testSwitch.Level = SourceLevels.Warning;
            loggerFactory.AddTraceSource(testSwitch, new TextWriterTraceListener(writer: Console.Out));
            app.UseRequestIP();            //自定义的middleware
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseSession();
            //set up custom content types-associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();

            //add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"]  = "text/html";
            provider.Mappings[".image"] = "image/png";
            //replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            //remove mp4 videos
            provider.Mappings.Remove(".mp4");
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
                RequestPath         = "/MyImages",
                ContentTypeProvider = provider
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
                RequestPath = "/MyStaticFiles"
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/MyImages")
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute",
                                template: "{area:exists}/{controller=Home}/{action=Index}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            //app.UseMvcWithDefaultRoute();
            ConfigureMapping(app);
            ConfigurationMapWhen(app);
        }
 public TraceSource(string name)
 {
     Switch = new SourceSwitch();
 }
Esempio n. 14
0
File: test.cs Progetto: mono/gert
	static int Test1 ()
	{
		TraceSwitch testSwitch1 = new TraceSwitch ("testSwitch1", null);
		if (testSwitch1.Level != TraceLevel.Verbose)
			return 1;

		TraceSwitch testSwitch2 = new TraceSwitch ("testSwitch2", null);
		if (testSwitch2.Level != TraceLevel.Off)
			return 2;

		TraceSwitch testSwitch3 = new TraceSwitch ("testSwitch3", null);
		if (testSwitch3.Level != TraceLevel.Warning)
			return 3;

		TraceSwitch testSwitch4 = new TraceSwitch ("testSwitch4", null);
		if (testSwitch4.Level != TraceLevel.Info)
			return 4;

		TraceSwitch testSwitch5 = new TraceSwitch ("testSwitch5", null);
		if (testSwitch5.Level != TraceLevel.Verbose)
			return 5;

		TraceSwitch testSwitch6 = new TraceSwitch ("testSwitch6", null);
		if (testSwitch6.Level != TraceLevel.Off)
			return 6;

#if NET_2_0
		TraceSwitch testSwitch7 = new TraceSwitch ("testSwitch7", null);
		if (testSwitch7.Level != TraceLevel.Info)
			return 7;

		TraceSwitch testSwitch8 = new TraceSwitch ("testSwitch8", null);
		if (testSwitch8.Level != TraceLevel.Warning)
			return 8;
#endif

		TraceSwitch testSwitch9 = new TraceSwitch ("testSwitch9", null);
		if (testSwitch9.Level != TraceLevel.Off)
			return 9;

		BooleanSwitch boolSwitch1 = new BooleanSwitch ("boolSwitch1", null);
		if (boolSwitch1.Enabled)
			return 10;

		BooleanSwitch boolSwitch2 = new BooleanSwitch ("boolSwitch2", null);
		if (!boolSwitch2.Enabled)
			return 11;

		BooleanSwitch boolSwitch3 = new BooleanSwitch ("boolSwitch3", null);
		if (!boolSwitch3.Enabled)
			return 12;

		BooleanSwitch boolSwitch4 = new BooleanSwitch ("boolSwitch4", null);
		if (boolSwitch4.Enabled)
			return 13;

#if NET_2_0
		BooleanSwitch boolSwitch5 = new BooleanSwitch ("boolSwitch5", null);
		if (!boolSwitch5.Enabled)
			return 14;

		BooleanSwitch boolSwitch6 = new BooleanSwitch ("boolSwitch6", null);
		if (boolSwitch6.Enabled)
			return 15;

		SourceSwitch sourceSwitch1 = new SourceSwitch ("sourceSwitch1");
		if ((sourceSwitch1.Level & SourceLevels.Critical) == 0)
			return 16;

		SourceSwitch sourceSwitch2 = new SourceSwitch ("sourceSwitch2");
		if ((sourceSwitch2.Level & SourceLevels.Warning) == 0)
			return 17;
		if ((sourceSwitch2.Level & SourceLevels.Error) == 0)
			return 18;

		SourceSwitch sourceSwitch3 = new SourceSwitch ("sourceSwitch3");
		if (sourceSwitch3.Level != SourceLevels.Off)
			return 19;
#endif

		return 0;
	}
Esempio n. 15
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public Tracer()
 {
     _traceSource        = new TraceSource(SOURCE_NAME);
     _traceSwitch        = new SourceSwitch(SWITCH_NAME);
     _traceSource.Switch = _traceSwitch;
 }
Esempio n. 16
0
 public TraceSource(string name)
 {
     Switch = new SourceSwitch();
 }
Esempio n. 17
0
        /// <summary>
        /// Run the demo.
        /// </summary>
        public static void Run()
        {
            // define a trace source logger with file listener.
            string logFilePath =
                Path.Combine(AppContext.BaseDirectory, "UnityDemo.log");
            Stream logStream = File.Create(logFilePath);
            TextWriterTraceListener traceListener =
                new TextWriterTraceListener(logStream);
            SourceSwitch verboseSwitch =
                new SourceSwitch("VerboseSwitch", "Verbose");
            ILoggerFactory loggerFactory =
                new LoggerFactory().AddTraceSource(verboseSwitch, traceListener);

            // define a local logger instance.
            ILogger logger = loggerFactory.CreateLogger <UnityDemo>();

            // create unity container instance.
            UnityContainer container = new UnityContainer();

            logger.LogDebug("Unity Container created.");

            // add logging extension to the unity container.
            container.AddExtension(new LoggingExtension(loggerFactory));
            logger.LogDebug("Logging extension added.");

            // load unity config file
            ExeConfigurationFileMap fileMap =
                new ExeConfigurationFileMap
            {
                ExeConfigFilename = "UnityDemo.unity.config"
            };
            Configuration configuration =
                ConfigurationManager.OpenMappedExeConfiguration(
                    fileMap,
                    ConfigurationUserLevel.None);
            UnityConfigurationSection unitySection =
                (UnityConfigurationSection)configuration.GetSection("unity");

            // load design-time configuration to the unity container.
            container.LoadConfiguration(unitySection);
            logger.LogDebug("Design-time configuration loaded.");

            // add runtime registration to the unity container.
            container.RegisterType <IDemoClass, DemoClass>(
                "runtime_register",
                new InjectionConstructor(
                    new ResolvedParameter(typeof(ILogger <DemoClass>), "logger"),
                    new ResolvedParameter(typeof(string), "name"),
                    new ResolvedParameter(typeof(string), "value")));
            logger.LogDebug("Runtime type mapping registered.");

            // define parameter overrides for design time resolving.
            ParameterOverride designTimeNameOverride =
                new ParameterOverride("name", "design_time_demo_1");
            ParameterOverride designTimeValueOverride =
                new ParameterOverride("value", "demo_value_1");

            // resolve demo class instance from design time registration with parameter overrides.
            IDemoClass designTimeDemoClass =
                container.Resolve <IDemoClass>(
                    "design_time_register",
                    designTimeNameOverride,
                    designTimeValueOverride);

            Console.WriteLine($"Resolved design time demo class: {designTimeDemoClass}");
            designTimeDemoClass.DemoMethod();

            // define parameter overrides for runtime time resolving.
            ParameterOverride runtimeNameOverride =
                new ParameterOverride("name", "runtime_demo_2");
            ParameterOverride runtimeValueOverride =
                new ParameterOverride("value", "demo_value_2");

            // resolve demo class instance from runtime registration with parameter overrides.
            IDemoClass runtimeDemoClass =
                container.Resolve <IDemoClass>(
                    "runtime_register",
                    runtimeNameOverride,
                    runtimeValueOverride);

            Console.WriteLine($"Resolved runtime demo class: {runtimeDemoClass}");
            runtimeDemoClass.DemoMethod();

            // release the log file handler.
            loggerFactory.Dispose();

            // print unity config file
            Console.WriteLine();
            string configFilePath =
                Path.Combine(AppContext.BaseDirectory, fileMap.ExeConfigFilename);

            Console.WriteLine($"[Trace] unity config file: {configFilePath}");
            Console.WriteLine(File.ReadAllText(configFilePath, Encoding.UTF8));

            // print log file
            Console.WriteLine();
            Console.WriteLine($"[Trace] log file: {logFilePath}");
            Console.WriteLine(File.ReadAllText(logFilePath, Encoding.UTF8));
        }
        /// <summary>
        /// Run the demo.
        /// </summary>
        public static void Run()
        {
            // create entities to be inserted.
            DemoNestedEntity nestedEntity =
                new DemoNestedEntity {
                Name = "nested_entity_1"
            };
            List <DemoEntity> subEntities = new List <DemoEntity>
            {
                new DemoEntity {
                    SubName = "sub_entity_1", ParentEntity = nestedEntity
                },
                new DemoEntity {
                    SubName = "sub_entity_2", ParentEntity = nestedEntity
                },
                new DemoEntity {
                    SubName = "sub_entity_3", ParentEntity = nestedEntity
                },
            };

            nestedEntity.SubEntities = subEntities;

            // write verbose logs to file in debug mode.
            ILoggerFactory loggerFactory = null;

            if (!Debugger.IsAttached)
            {
                string logFilePath =
                    Path.Combine(AppContext.BaseDirectory, "EntityFrameworkInMemoryDemo.log");
                Stream logStream = File.Create(logFilePath);
                TextWriterTraceListener traceListener = new TextWriterTraceListener(logStream);
                SourceSwitch            verboseSwitch = new SourceSwitch("VerboseSwitch", "Verbose");
                loggerFactory =
                    new LoggerFactory().AddTraceSource(verboseSwitch, traceListener);
            }

            try
            {
                using (DemoContext db = new DemoContext(loggerFactory))
                {
                    Console.WriteLine($"Is In-Memory database: {db.Database.IsInMemory()}");

                    // insert entities and save changes to database.
                    db.NestedEntities.Add(nestedEntity);
                    int count = db.SaveChanges();
                    Console.WriteLine($"{count} records saved to database");

                    // query all nested entities data.
                    Console.WriteLine();
                    Console.WriteLine("All nested entities in database:");
                    foreach (DemoNestedEntity entity in db.NestedEntities)
                    {
                        Console.WriteLine($" - id: '{entity.Id}', name '{entity.Name}'");
                    }

                    // query all sub entities data.
                    Console.WriteLine();
                    Console.WriteLine("All sub entities in database:");
                    foreach (DemoEntity entity in db.Entities)
                    {
                        Console.WriteLine($" - id: '{entity.SubId}', name '{entity.SubName}'");
                    }
                }
            }
            finally
            {
                // release log file handler
                if (loggerFactory != null)
                {
                    loggerFactory.Dispose();
                }
            }
        }
Esempio n. 19
0
        private static void Main(string[] args)
        {
            string            dt  = $"{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}";
            FileSystemHandler fsh = new FileSystemHandler(new FSHandlerOptions("c:\\Temp\\votalot\\dummy" + dt + ".log"));

            fsh.SetFormatter(new FlimFlamV2Formatter());
            Bilge.AddMessageHandler(new ConsoleHandler());
            Bilge.AddMessageHandler(new TCPHandler("127.0.0.1", 9060));
            Bilge.AddMessageHandler(fsh);
            Bilge.Alert.Online("TestClient");

#if CORE
            // Due to the dependency on configurations and the different ways that you can configure a core service this is not
            // implemented within Bilge even as a default but is documented instead.
            Bilge.SetConfigurationResolver((s, lvl) => {
                var configuration = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", false, true)
                                    .Build();

                SourceLevels result            = lvl;
                string defaultValue            = configuration["logging:loglevel:default"];
                string specificForThisInstance = configuration[$"logging:loglevel:{s}"];

                if (Enum.TryParse <SourceLevels>(specificForThisInstance, out SourceLevels slSpecific))
                {
                    result = slSpecific;
                }
                else
                {
                    if (Enum.TryParse <SourceLevels>(defaultValue, out SourceLevels slDefault))
                    {
                        result = slDefault;
                    }
                }

                return(result);
            });
#else
            Bilge.SetConfigurationResolver((instanceName, lvl) => {
                // Logic -> Try Source Switch, Failing that Trace Switch, failing that SourceSwitch + Switch, Failing that TraceSwitch+Switch.

                SourceLevels result   = lvl;
                bool tryTraceSwitches = true;

                try {
                    SourceSwitch ss = new SourceSwitch(instanceName);
                    if (ss.Level == SourceLevels.Off)
                    {
                        ss = new SourceSwitch($"{instanceName}Switch");
                        if (ss.Level == SourceLevels.Off)
                        {
                        }
                        else
                        {
                            tryTraceSwitches = false;
                            result           = ss.Level;
                        }
                    }
                    else
                    {
                        tryTraceSwitches = false;
                        result           = ss.Level;
                    }
                } catch (SystemException) {
                    // This is the higher level exception of a ConfigurationErrorsException but that one requires a separate reference
                    // This occurs when a TraceSwitch has the same name as the source switch with a value that is not supported by source switch e.g. Info
                }

                if (tryTraceSwitches)
                {
                    TraceSwitch ts = new TraceSwitch(instanceName, "");
                    if (ts.Level == TraceLevel.Off)
                    {
                        ts = new TraceSwitch($"{instanceName}Switch", "");
                        if (ts.Level != TraceLevel.Off)
                        {
                            result = Bilge.ConvertTraceLevel(ts.Level);
                        }
                    }
                    else
                    {
                        result = Bilge.ConvertTraceLevel(ts.Level);
                    }
                }

                return(result);
            });
#endif

            Bilge b = new Bilge("PliskyConsoleTestApp");
            b.ActiveTraceLevel = SourceLevels.Verbose;

            b.Verbose.Log("Hello Cruel World");

            bool traceSwitchTests   = false;
            bool bulkFileWriteTests = false;
            bool perfTests          = false;
            bool basicWriteAllTest  = true;
            bool actionTest         = true;

            if (actionTest)
            {
                int acCount = 0;


                b.Action.RegisterHandler((m) => {
                    if (m.Success)
                    {
                        acCount++;
                    }
                }, "bob");

                b.Action.Occured("Event", "Data");


                if (acCount == 0)
                {
                    throw new InvalidOperationException("didnt work");
                }
            }


            if (basicWriteAllTest)
            {
                Bilge.SetConfigurationResolver((instanceName, lvl) => {
                    return(SourceLevels.Verbose);
                });

                ModularWriting mw = new ModularWriting();
                mw.DoWrite();
            }
            if (bulkFileWriteTests)
            {
                ProductionLoggingTest(b);
            }
            b.Flush();

            if (perfTests)
            {
                PerformanceTest p = new PerformanceTest();
                p.AnalysisBatchVsNoBatch();
                //p.ExecuteTest();
                p.WriteOutput();

                Bilge.ForceFlush();
            }
            Console.ReadLine();
            return;

            b.AddHandler(new SimpleTraceFileHandler(@"c:\temp\"));
            if (traceSwitchTests)
            {
                Console.WriteLine("Actual Trace Level : " + b.ActiveTraceLevel.ToString());

                try {
                    TraceSource ts = new TraceSource("monkeySwitch", SourceLevels.Off);
                    TraceSwitch tx = new TraceSwitch("monkey2Switch", "test", "Off");

                    SourceSwitch sw = new SourceSwitch("boner", "off");

                    Console.WriteLine($"{ts.Switch.Level} >> {tx.Level} >> {sw.Level}");

                    Console.ReadLine();
                } catch (Exception ex) {
                }
            }

            bool doDirectWriting = false;

            if (args.Length > 0)
            {
                if (args[0] == "direct")
                {
                    doDirectWriting = true;
                }
            }

            if (doDirectWriting)
            {
                var dr = new DirectWriting(b);
                dr.DoDirectWrites();
            }

            ModularWriting mr = new ModularWriting();
            mr.DoWrite();
            b.Flush();
            Console.WriteLine("Readline");
            Console.ReadLine();
        }
Esempio n. 20
0
 public TraceManager(TextWriterTraceListener hostTraceListener)
 {
     Switch             = new SourceSwitch("SignalRSwitch");
     _hostTraceListener = hostTraceListener;
 }
Esempio n. 21
0
        static void Main(string[] args)
        {
            // use 'w', 'a', 's', 'd' to move and generate debug and trace

            // comment next line for assert error
            GameState.Map = new Map(30, 25);

            GameState.Character = new Character(10, 10);
            GameState.Map.Draw();

            #region Trace listeners

            // console output
            TraceListener consoleListener = new ConsoleTraceListener();
            // delimited records by a ';', can be used for xls for example
            TraceListener delimitexListTraceListener = new DelimitedListTraceListener("logs_D-Limitor5000.txt");
            // event log requires you to run visual studio in administrator mode and create a new or use an exisitng event log.
            //EventLogTraceListener eventLogTraceListener = new EventLogTraceListener("EventSource");
            // windows event schema
            TraceListener eventSchemaTraceListener = new EventSchemaTraceListener("logs_SchemingEvent.xsd");
            // any text file
            TraceListener textWriterTraceListener = new TextWriterTraceListener("logs_Writ0r.txt");
            // xml
            TraceListener xmlWriterTraceListener = new XmlWriterTraceListener("logs_Xmlol.xml");

            // Add trace listeners to regular traces
            Trace.Listeners.Add(consoleListener);
            Trace.Listeners.Add(delimitexListTraceListener);
            Trace.Listeners.Add(eventSchemaTraceListener);
            Trace.Listeners.Add(textWriterTraceListener);
            Trace.Listeners.Add(xmlWriterTraceListener);

            #endregion

            #region Trace source and switch

            // switch trace level of the custom tracesource
            var control = new SourceSwitch("control", "Controls the tracing")
            {
                Level = SourceLevels.All
            };

            var trace = new TraceSource("Tray-zor", SourceLevels.All)
            {
                Switch = control
            };

            // switch trace level of the static "Trace"
            var traceSwitch = new TraceSwitch("General", "The entire application");
            traceSwitch.Level = TraceLevel.Verbose;

            // Add trace listeners to custom trace source
            trace.Listeners.Add(consoleListener);
            trace.Listeners.Add(delimitexListTraceListener);
            trace.Listeners.Add(eventSchemaTraceListener);
            trace.Listeners.Add(textWriterTraceListener);
            trace.Listeners.Add(xmlWriterTraceListener);

            // trace some events
            trace.TraceEvent(TraceEventType.Verbose, 1, "Using Trace Source");
            trace.TraceEvent(TraceEventType.Start, 10000, "Start of logical operation");
            trace.TraceEvent(TraceEventType.Warning, 20000, "Warning");
            trace.TraceEvent(TraceEventType.Verbose, 30000, "Debug");
            trace.TraceData(TraceEventType.Information, 1003, GameState.Character.Position);

            #endregion

            #region Trace through config

            EventTypeFilter configFilter =
                (EventTypeFilter)configSource.Listeners["console"].Filter;
            configSource.Switch.Level = SourceLevels.All;
            configSource.TraceEvent(TraceEventType.Verbose, 1, "Using config trace");

            #endregion

            #region Performance

            Stopwatch stopwatch = new Stopwatch();

            // this needs adminisrator rights
            if (!PerformanceCounterCategory.Exists("AverageCount64NewCounterOfMineCategory"))
            {
                CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();

                // Add the counter.
                CounterCreationData newCounterOfMine = new CounterCreationData();
                newCounterOfMine.CounterType = PerformanceCounterType.AverageCount64;
                newCounterOfMine.CounterName = "NewCounterOfMine";
                counterDataCollection.Add(newCounterOfMine);

                // Add another counter.
                CounterCreationData newerCounterOfMine = new CounterCreationData();
                newerCounterOfMine.CounterType = PerformanceCounterType.AverageBase;
                newerCounterOfMine.CounterName = "NewerCounterOfMine";
                counterDataCollection.Add(newerCounterOfMine);

                // Create the category.
                PerformanceCounterCategory.Create("AverageCount64NewCounterOfMineCategory",
                                                  "Demonstrates usage of the NewCounterCategory performance counter type.",
                                                  PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
                Trace.WriteLine("Created loopCounter");
            }

            var loopCounter = new PerformanceCounter("AverageCount64NewCounterOfMineCategory",
                                                     "NewerCounterOfMine",
                                                     false)
            {
                RawValue = 0
            };

            var performance = new PerformanceCounter("Processor Information",
                                                     "% Processor Time",
                                                     "_Total");

            #endregion

            #region EventLog

            // Create the source, if it does not already exist.
            if (!EventLog.SourceExists("MySource"))
            {
                //An event log source should not be created and immediately used.
                //There is a latency time to enable the source, it should be created
                //prior to executing the application that uses the source.
                //Execute this sample a second time to use the new source.
                EventLog.CreateEventSource("MySource", "MyNewLog");
                Console.WriteLine("CreatedEventSource");
                Console.WriteLine("Exiting, execute the application a second time to use the source.");
                // The source is created.  Exit the application to allow it to be registered.
                return;
            }

            // Create an EventLog instance and assign its source.
            EventLog myLog = new EventLog();
            myLog.Source = "MySource";

            // Write an informational entry to the event log.
            myLog.WriteEntry("Writing to event log.");

            Console.ForegroundColor = ConsoleColor.Green;
            foreach (EventLogEntry entry in myLog.Entries)
            {
                Console.WriteLine("Source: {0}, Type: {1}, Time: {2}, Message: {3}", entry.Source, entry.EntryType, entry.TimeWritten, entry.Message);
            }
            Console.ForegroundColor = ConsoleColor.White;

            #endregion

            for (; ;)
            {
                // trace
                configSource.TraceEvent(TraceEventType.Verbose, 191919, "Start of iteration of the eternal loop");
                trace.TraceEvent(TraceEventType.Verbose, 10000, "Start of iteration of the eternal loop");
                Trace.WriteLine("Iteration of the eternal input loop");

                // logic
                var read = Console.ReadKey().KeyChar;
                Console.Clear();
                stopwatch.Restart();
                GameState.Character.ProcessInput(read);
                GameState.Map.Draw();

                // stopwatch
                stopwatch.Stop();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("\tms after processing input: {0}", stopwatch.ElapsedMilliseconds);
                Console.WriteLine("\tTicks after processing input: {0}", stopwatch.ElapsedTicks);
                Console.WriteLine("\tTime after processing input: {0}", stopwatch.Elapsed);
                Console.ForegroundColor = ConsoleColor.White;
                stopwatch.Start();

                // trace
                Trace.WriteLine("Drawn the map");
                Trace.WriteLine("End of the iteration of the eternal loop");
                trace.TraceEvent(TraceEventType.Verbose, 10001, "End of iteration of the eternal loop");
                configSource.TraceEvent(TraceEventType.Verbose, 191920, "End of iteration of the eternal loop");

                // stopwatch
                stopwatch.Stop();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("\tCumulative ms after 4 trace calls: {0}", stopwatch.ElapsedMilliseconds);
                Console.WriteLine("\tCumulative ticks after 4 trace calls: {0}", stopwatch.ElapsedTicks);
                Console.WriteLine("\tCumulative time after 4 trace calls: {0}", stopwatch.Elapsed);
                Console.ForegroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Yellow;

                // counters
                loopCounter.IncrementBy(20);
                Console.WriteLine("% of processor time: {0}", performance.NextValue());
                Console.WriteLine("Our own counter: {0}", loopCounter.NextValue());
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiagnosticsLoggerProvider"/> class.
 /// </summary>
 /// <param name="rootSourceSwitch"></param>
 /// <param name="rootTraceListener"></param>
 public DiagnosticsLoggerProvider(SourceSwitch rootSourceSwitch, TraceListener rootTraceListener)
 {
     _rootSourceSwitch  = rootSourceSwitch ?? new SourceSwitch(RootTraceName);
     _rootTraceListener = rootTraceListener;
 }
Esempio n. 23
0
        static void Main(string[] args)
        {
            var host = new HostBuilder();
            // 環境パスのDOTNETCORE_ENVIRONMENTを取得
            var environment = Environment.GetEnvironmentVariable("DOTNETCORE_ENVIRONMENT") ?? "Development";

            // 環境の設定
            host.UseEnvironment(environment);
            // ホストの構成
            host.ConfigureHostConfiguration(config =>
            {
                // Microsoft.Extensions.Configuration
                config.SetBasePath(Directory.GetCurrentDirectory());

                // Microsoft.Extensions.Configuration.EnvironmentVariables
                // 環境変数の先頭文字列"EnvironmentSettingModel_"の変数を取り込む.
                // 取り込んだ環境変数の名前は"EnvironmentSettingModel_"の部分がトリミングされる
                config.AddEnvironmentVariables(prefix: "EnvironmentSettingModel_");

                // Microsoft.Extensions.Configuration.JSON
                config.AddJsonFile($"Settings/setting.json");
                // 環境変数DOTNETCORE_ENVIRONMENTの設定値を使用する。
                config.AddJsonFile($"Settings/setting.{environment}.json");
                config.AddJsonFile($"Settings/loggingSetting.json");

                // Microsoft.Extensions.Configuration.Ini
                config.AddIniFile("Settings/setting.ini");

                // Microsoft.Extensions.Configuration.XML
                config.AddXmlFile("Settings/setting.xml");

                // Microsoft.Extensions.Configuration.Memory
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "InMemoryMessage", "Hello InMemoryCollection!" }
                });

                // Microsoft.Extensions.Configuration.CommandLine
                config.AddCommandLine(args);
            });
            // アプリケーションの構成
            host.ConfigureAppConfiguration((hostContext, config) =>
            {
                var env = hostContext.HostingEnvironment;
                if (env.IsDevelopment())
                {
                    // Microsoft.Extensions.Configuration.UserSecrets
                    config.AddUserSecrets <Program>();
                }
            });
            // サービスの構成
            host.ConfigureServices((hostContext, config) =>
            {
                // Microsoft.Extensions.Configuration
                config.Configure <IniSettingModel>(hostContext.Configuration.GetSection("IniSettingModel"));
                config.Configure <JsonSettingModel>(hostContext.Configuration.GetSection("JsonSettingModel"));
                config.Configure <XmlSettingModel>(hostContext.Configuration.GetSection("XmlSettingModel"));
                config.Configure <UserSecretSettingModel>(hostContext.Configuration.GetSection("UserSecretSettingModel"));
                config.Configure <CommandLineSettingModel>(hostContext.Configuration.GetSection("CommandLineSettingModel"));

                // こういった方法でも使用可能
                var message       = hostContext.Configuration.GetValue <String>("UserSecretSettingModel:Message");
                var messageModel1 = hostContext.Configuration.GetSection("UserSecretSettingModel").Get <BaseSettingModel>();
                var messageModel2 = hostContext.Configuration.GetValue <UserSecretSettingModel>("UserSecretSettingModel");
                var messageModel3 = new BaseSettingModel();
                hostContext.Configuration.GetSection("UserSecretSettingModel").Bind(messageModel3);

                // ConnectionStringだけは別途関数がある
                // var connectionString = hostContext.Configuration.GetConnectionString ("DefaultConnection");

                // Microsoft.Extensions.DependencyInjection
                config.AddHostedService <SampleService>();
                // BackgroundServiceの場合
                // config.AddHostedService<SampleBackgroundService> ();

                // その他サービスのDI
                config.AddTransient <IHoge, LoudHoge>();
            });
            // ロギングの構成
            host.ConfigureLogging((hostContext, config) =>
            {
                // config系の設定を初期化
                config.ClearProviders();
                // appsettings.jsonに記載した設定を反映
                config.AddConfiguration(hostContext.Configuration.GetSection("Logging"));

                // 今回は上記ファイルで指定してるのでコメントアウト.
                // 出力するLogの最低レベルを指定
                // config.SetMinimumLevel (LogLevel.Trace);
                // Microsofot系のLogはInformation以下のレベルは出力しない
                // config.AddFilter ("Microsoft", LogLevel.Information);

                // Microsoft.Extensions.Logging.Console
                config.AddConsole();

                // Microsoft.Extensions.Logging.Debug
                config.AddDebug();

                // Microsoft.Extensions.Logging.EventLog
                config.AddEventLog();

                // Microsoft.Extensions.Logging.EventSource
                // これはEvent Tracing for Windows (ETW)によるLoggin.
                config.AddEventSourceLogger();

                //Microsoft.Extensions.Logging.TraceSource
                Trace.AutoFlush  = true;
                var sourceSwitch = new SourceSwitch("sample")
                {
                    Level = SourceLevels.All
                };
                var listener = new TextWriterTraceListener("Trace.log");
                config.AddTraceSource(sourceSwitch, listener);
            });
            host.UseConsoleLifetime();

            // 起動方法
            // host.RunConsoleAsync();
            // host.Start();
            host.Build().Run();
            // host.Build().Start();
            // host.Build().StartAsync();
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TraceSourceLoggerProvider"/> class.
 /// </summary>
 /// <param name="rootSourceSwitch"></param>
 /// <param name="rootTraceListener"></param>
 public TraceSourceLoggerProvider([NotNull] SourceSwitch rootSourceSwitch, [NotNull] TraceListener rootTraceListener)
 {
     _rootSourceSwitch  = rootSourceSwitch;
     _rootTraceListener = rootTraceListener;
 }
Esempio n. 25
0
        //</Snippet2>
        static void Main()
        {
            try
            {
                // Initialize trace switches.
                //<Snippet3>
#if (!ConfigFile)
                TraceSwitch traceSwitch = new TraceSwitch("TraceSwitch", "Verbose");
#endif
                //</Snippet3>
                //<Snippet4>
                Console.WriteLine(traceSwitch.Level);
                //</Snippet4>
                //<Snippet5>
#if (!ConfigFile)
                BooleanSwitch boolSwitch = new BooleanSwitch("BoolSwitch", "True");
#endif
                //</Snippet5>
                //<Snippet6>
                Console.WriteLine(boolSwitch.Enabled);
                //</Snippet6>
                //<Snippet7>
#if (!ConfigFile)
                SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
#endif
                //</Snippet7>
                //<Snippet8>
                Console.WriteLine(sourceSwitch.Level);
                //</Snippet8>
                // Initialize trace source.
                //<Snippet9>
                MyTraceSource ts = new MyTraceSource("TraceTest");
                //</Snippet9>
                //<Snippet10>
                Console.WriteLine(ts.Switch.DisplayName);
                //</Snippet10>
                //<Snippet11>
                Console.WriteLine(ts.Switch.Level);
                //</Snippet11>
                //<Snippet12>
                SwitchAttribute[] switches = SwitchAttribute.GetAll(typeof(TraceTest).Assembly);
                for (int i = 0; i < switches.Length; i++)
                {
                    Console.Write(switches[i].SwitchName);
                    Console.Write("\t");
                    Console.WriteLine(switches[i].SwitchType);
                }
                //</Snippet12>
                //<Snippet13>
                // Display the SwitchLevelAttribute for the BooleanSwitch.
                Object[] attribs = typeof(BooleanSwitch).GetCustomAttributes(typeof(SwitchLevelAttribute), false);
                if (attribs.Length == 0)
                {
                    Console.WriteLine("Error, couldn't find SwitchLevelAttribute on BooleanSwitch.");
                }
                else
                {
                    Console.WriteLine(((SwitchLevelAttribute)attribs[0]).SwitchLevelType.ToString());
                }
                //</Snippet13>
#if (ConfigFile)
                //<Snippet14>
                // Get the custom attributes for the TraceSource.
                Console.WriteLine(ts.Attributes.Count);
                foreach (DictionaryEntry de in ts.Attributes)
                {
                    Console.WriteLine(de.Key + "  " + de.Value);
                }
                //</Snippet14>
                //<Snippet15>
                // Get the custom attributes for the trace source switch.
                foreach (DictionaryEntry de in ts.Switch.Attributes)
                {
                    Console.WriteLine(de.Key + "  " + de.Value);
                }
                //</Snippet15>
#endif
                //<Snippet16>
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.Callstack;
                //</Snippet16>
                //<Snippet17>
                ts.TraceEvent(TraceEventType.Warning, 1);
                //</Snippet17>
                ts.Listeners["console"].TraceOutputOptions = TraceOptions.DateTime;
                //<Snippet18>
                // Issue file not found message as a warning.
                ts.TraceEvent(TraceEventType.Warning, 1, "File Test not found");
                //</Snippet18>
                System.Threading.Thread.Sleep(1000);
                //<Snippet19>
                Console.WriteLine(ts.Listeners.Count);
                //</Snippet19>
                //<Snippet20>
                ts.Listeners.Add(new TestListener(TESTLISTENERFILE, "TestListener"));
                //</Snippet20>
                Console.WriteLine(ts.Listeners.Count);
                //<Snippet22>
                foreach (TraceListener traceListener in ts.Listeners)
                {
                    Console.Write(traceListener.Name + "\t");
                    // The following output can be used to update the configuration file.
                    Console.WriteLine((traceListener.GetType().AssemblyQualifiedName));
                }
                //</Snippet22>
                //<Snippet23>
                // Show correlation and output options.
                Trace.CorrelationManager.StartLogicalOperation("abc");
                //</Snippet23>
                //<Snippet24>
                // Issue file not found message as a verbose event using a formatted string.
                ts.TraceEvent(TraceEventType.Verbose, 2, "File {0} not found.", "test");
                //</Snippet24>
                Trace.CorrelationManager.StartLogicalOperation("def");
                // Issue file not found message as information.
                ts.TraceEvent(TraceEventType.Information, 3, "File {0} not found.", "test");
                //<Snippet25>
                Trace.CorrelationManager.StopLogicalOperation();
                //</Snippet25>
                //<Snippet26>
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.LogicalOperationStack;
                //</Snippet26>
                // Issue file not found message as an error event.
                ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test");
                Trace.CorrelationManager.StopLogicalOperation();
                // Write simple message from trace.
                //<Snippet27>
                Trace.TraceWarning("Warning from Trace.");
                //</Snippet27>
                //<Snippet28>
                // Test the filter on the ConsoleTraceListener.
                ts.Listeners["console"].Filter = new SourceFilter("No match");
                ts.TraceData(TraceEventType.Information, 5,
                             "SourceFilter should reject this message for the console trace listener.");
                ts.Listeners["console"].Filter = new SourceFilter("TraceTest");
                ts.TraceData(TraceEventType.Information, 6,
                             "SourceFilter should let this message through on the console trace listener.");
                //</Snippet28>
                ts.Listeners["console"].Filter = null;
                // Use the TraceData method.
                //<Snippet30>
                ts.TraceData(TraceEventType.Warning, 9, new object());
                //</Snippet30>
                //<Snippet31>
                ts.TraceData(TraceEventType.Warning, 10, new object[] { "Message 1", "Message 2" });
                //</Snippet31>
                // Activity tests.
                //<Snippet32>
                ts.TraceEvent(TraceEventType.Start, 11, "Will not appear until the switch is changed.");
                ts.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Critical;
                ts.TraceEvent(TraceEventType.Suspend, 12, "Switch includes ActivityTracing, this should appear");
                ts.TraceEvent(TraceEventType.Critical, 13, "Switch includes Critical, this should appear");
                //</Snippet32>

                Trace.Flush();
                ((TextWriterTraceListener)Trace.Listeners["file"]).Close();
                ((TextWriterTraceListener)Trace.Listeners["fileBuilder"]).Close();

                System.Threading.Thread.Sleep(1000);


                // Examine the contents of the log file.
                Console.WriteLine("\n\n\n");
                // Use try/catch in case the file hasn't been defined.
                try
                {
                    Console.WriteLine("Examining " + TEXTFILE);
                    StreamReader logfile = new StreamReader(TEXTFILE);
                    while (!logfile.EndOfStream)
                    {
                        Console.WriteLine(logfile.ReadLine());
                    }

                    logfile.Close();

                    File.Delete(TEXTFILE);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error tying to read the text log file. " + e.Message);
                }

                // Display the contents of the log file builder.
                Console.WriteLine("\n\n\n");
                // Use try/catch in case the file hasn't been defined.
                try
                {
                    Console.WriteLine("Examining " + DELIMITEDFILE);
                    StreamReader logfile = new StreamReader(DELIMITEDFILE);
                    while (!logfile.EndOfStream)
                    {
                        Console.WriteLine(logfile.ReadLine());
                    }
                    logfile.Close();
                    File.Delete(DELIMITEDFILE);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error tying to read the delimited text file. " + e.Message);
                }

                Console.WriteLine("Press any key to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                // Catch any unexpected exception.
                Console.WriteLine("Unexpected exception: " + e.ToString());
                Console.Read();
            }
        }
 public void ConstructorNullDefaultValue()
 {
     SourceSwitch s = new SourceSwitch("foo", null);
 }
Esempio n. 27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime life)
        {
            life.ApplicationStarted.Register(OnStarted);
            life.ApplicationStopping.Register(OnStopping);
            life.ApplicationStopped.Register(OnStopped);
            //life.StopApplication();
            StaticFiles(app);
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                //The Windows EventLog provider
                //loggerFactory.AddEventSourceLogger();
                // add Trace Source logging
                var testSwitch = new SourceSwitch("sourceSwitch", "Logging Sample");
                testSwitch.Level = SourceLevels.Warning;
                loggerFactory.AddTraceSource(testSwitch,
                                             new TextWriterTraceListener(writer: Console.Out));
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            //app.Run delegate terminates the pipeline
            //app.Run(async context =>
            //{
            //    await context.Response.WriteAsync("hello word . short cirquit!");
            //}
            //);
            app.Use(async(context, next) =>
            {
                // Do work that doesn't write to the Response.
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });
            app.Map("/map1", appctx => appctx.Run(async ctx => await ctx.Response.WriteAsync("request filter")));
            app.UseRequestCulture();
            app.UseAuthentication();

            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "ENNumber",
                    template: "en-Us/Number/{id}",
                    defaults: new { controller = "Home", action = "Number" },
                    constraints: new { id = new IntRouteConstraint() },
                    dataTokens: new { locale = "en-US" }
                    );
            });
            CustomeRouteHandler(app);
            //It's often a good idea for production error pages to consist of purely static content
            app.UseStatusCodePages();
            //Sende Status Code to Route
            //app.UseStatusCodePagesWithRedirects("/error/{0}");
            //app.UseStatusCodePagesWithReExecute("/error/{0}");
        }
 static void \u202B‮‪​‎‍​‍‎‪‬‫‎‌‪‬‮‫‌​‪‫‫‮‬‌‮([In] TraceSource obj0, [In] SourceSwitch obj1)
 {
     // ISSUE: unable to decompile the method.
 }
Esempio n. 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var sect = Configuration.GetSection("AppSets");

            SettingsManager.UserName         = sect["UserName"];
            SettingsManager.Pass             = sect["Pas"];
            SettingsManager.ConnectionString = sect["ConnStr"];
            SettingsManager.CacheTimeSpan    = sect["CacheTimeSpan"];
            SettingsManager.LogFileName      = sect["LogFileName"];
            SettingsManager.mailsmpt         = sect["mailsmpt"];
            SettingsManager.mailport         = sect["mailport"];
            SettingsManager.mailadress       = sect["mailadress"];
            SettingsManager.mailpass         = sect["mailpass"];
            SettingsManager.validurl         = sect["validurl"];
            SettingsManager.mailmesstext     = sect["mailmesstext"];
            SettingsManager.mailpassmesstext = sect["mailpassmesstext"];
            SettingsManager.robocassaid      = sect["robocassaid"];
            SettingsManager.robopass         = sect["robopass"];
            SettingsManager.robopass2        = sect["robopass2"];
            SettingsManager.robotest         = sect["robotest"];
            SettingsManager.showconloyer     = sect["showconloyer"];
            SettingsManager.stimulpath       = sect["StimulLicens"];



            SourceSwitch sw   = new SourceSwitch("mys", sect["LogLevel"]);
            CoreLogic    core = new CoreLogic();

            var cultureInfo = new CultureInfo(sect["CultureVal"]);

            CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;


            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddTraceSource(sw, new LogTraceListener(SettingsManager.LogFileName));

            CoreLogic.logger = loggerFactory.CreateLogger("AppLogger");
            //lg.LogInformation("Старт приложения", null);
            CoreLogic.logger.LogCritical("Старт приложения, уровень логирования - " + sect["LogLevel"]);

            Stimulsoft.Base.StiLicense.LoadFromFile(SettingsManager.stimulpath);

            CoreLogic.logger.LogCritical("Лицензия отчетов загружена  ");

            app.UseSession();
            //app.Run(async (context) =>
            //{
            //    if (context.Session.Keys.Contains("name"))
            //        await context.Response.WriteAsync($"Hello {context.Session.GetString("name")}!");
            //    else
            //    {
            //        context.Session.SetString("name", "Tom");
            //        await context.Response.WriteAsync("Hello World!");
            //    }
            //});



            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            /*
             * app.UseCookieAuthentication(new CookieAuthenticationOptions
             * {
             *  AuthenticationScheme = "Cookies",
             * //  LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Register"),
             *  AutomaticAuthenticate = true,
             *  AutomaticChallenge = true
             *
             * });
             */
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}");
                routes.MapRoute(
                    name: "Api",
                    template: "api/{controller}/{action}"
                    );
            });


            //app.UseEsiaAuthentication(new EsiaAuthenticationOptions(Esia.GetOptions())
            //{
            //    VerifyTokenSignature = true,    // Будем проверять подпись маркера доступа
            //    Provider = new EsiaAuthenticationProvider
            //    {
            //        OnAuthenticated = context =>    // Сохраним после авторизации маркер доступа в сессии для будущего использования в приложении (HomeController/EsiaPage)
            //        {
            //            HttpContext.Current.Session["esiaToken"] = context.Token;

            //            return Task.FromResult<object>(null);
            //        }
            //    }
            //});
        }