void OnMatching(Matching match) { if (match != null) { foreach (var entity in match.blocks) { if (match.IsCharged()) { if (match.blockEntity.destroyVFX > 0) { AttachEffect(match.blockEntity.destroyVFX, entity.Offset, 1); } } else { if (match.blockEntity.destroyVFX > 0) { AttachEffect(match.blockEntity.destroyVFX, entity.Offset, 1); } } } // sound if (match.IsCharged()) { PlaySound(match.blockEntity.destroySFX); } else { int soundId = GetInARowSoundId(match.pattern.Count); PlaySound(soundId); } } }
public override int GetHashCode() { unchecked { var hash = 17; hash = hash * 23 + Matching.GetHashCode(); foreach (var type in types) { if (type != null) { hash = hash * 23 + type.GetHashCode(); } } hash = hash * 23 + Value.GetHashCode(); hash = hash * 23 + Reference.GetHashCode(); hash = hash * 23 + Classes.GetHashCode(); hash = hash * 23 + Interfaces.GetHashCode(); hash = hash * 23 + Structs.GetHashCode(); hash = hash * 23 + Enums.GetHashCode(); hash = hash * 23 + Public.GetHashCode(); hash = hash * 23 + NonPublic.GetHashCode(); hash = hash * 23 + Abstract.GetHashCode(); hash = hash * 23 + Generic.GetHashCode(); hash = hash * 23 + OpenConstructedGeneric.GetHashCode(); hash = hash * 23 + Static.GetHashCode(); hash = hash * 23 + Sealed.GetHashCode(); hash = hash * 23 + Nested.GetHashCode(); hash = hash * 23 + Primitives.GetHashCode(); hash = hash * 23 + Object.GetHashCode(); hash = hash * 23 + NonSerializable.GetHashCode(); hash = hash * 23 + Obsolete.GetHashCode(); return(hash); } }
private static Matching ComputeMatching(SyntaxNode target, SyntaxNode source) { var groups = source.GetSubtrees().GroupBy(t => t.treeHash); var sourceTable = new MultiValueDict <int, SyntaxNode>(groups); var matching = new Matching(); foreach (var tree in target.GetSubtrees()) { foreach (var t in sourceTable.GetValues(tree.treeHash)) // `tree.hash = t.hash` { if (matching.ContainsValue(tree, t)) // Tree `t` has been visited before. { continue; } // Let's check if `tree` and `t` are really identical. if (tree.IdenticalTo(t)) // We find a match! { // Since `tree` is identical to `t`, so are their subtrees. tree.GetSubtrees() .Zip(t.GetSubtrees(), (t1, t2) => (tree: t1, t: t2)) .ToList() .ForEach(pair => matching.Add(pair.tree, pair.t)); } else { Log.Debug("Same hash {0} but different trees:", tree.treeHash); var printer = new IndentPrinter(); tree.PrintTo(printer); printer.PrintLine("<->"); t.PrintTo(printer); } } } return(matching); }
static async Task Start() { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .Enrich.With(new ExceptionMessageEnricher()) .Filter.ByExcluding(Matching.FromSource("NServiceBus.Transport.Msmq.QueuePermissions")) .Filter.ByExcluding(Matching.FromSource("NServiceBus.SubscriptionReceiverBehavior")) .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{ExceptionMessage}{NewLine}") .CreateLogger(); LogManager.Use <SerilogFactory>(); Console.Title = "Orders"; var config = new EndpointConfiguration("ExactlyOnce.Ex1.Orders"); config.UseTransport <LearningTransport>(); config.Recoverability().Immediate(x => x.NumberOfRetries(5)); config.Recoverability().Delayed(x => x.NumberOfRetries(0)); config.Recoverability().AddUnrecoverableException(typeof(DbEntityValidationException)); config.SendFailedMessagesTo("error"); config.EnableInstallers(); config.LimitMessageProcessingConcurrencyTo(10); SqlHelper.EnsureDatabaseExists(ConnectionString); using (var receiverDataContext = new OrdersDataContext(new SqlConnection(ConnectionString))) { receiverDataContext.Database.Initialize(true); } var endpoint = await Endpoint.Start(config).ConfigureAwait(false); Console.WriteLine("Press <enter> to exit."); Console.ReadLine(); await endpoint.Stop().ConfigureAwait(false); }
private static Action <HostBuilderContext, LoggerConfiguration> ConfigureSerilog(string serviceName) { return((hostingContext, loggerConfiguration) => { var logSettings = hostingContext.Configuration.GetSection("Logging").Get <LoggingOptions>(); var enrichedConfiguration = loggerConfiguration .Filter.ByExcluding(Matching.FromSource("Microsoft")) .Filter.ByExcluding(Matching.FromSource("Hangfire")) .Destructure.ToMaximumDepth(3) .Enrich.FromLogContext() .Enrich.WithProperty("Service", serviceName); #if DEBUG enrichedConfiguration.WriteTo.Async(x => x.Console(logSettings.LogLevel)); #else enrichedConfiguration.WriteTo.Async(x => x.Console(new JsonFormatter(), logSettings.LogLevel)); #endif if (!string.IsNullOrEmpty(logSettings.Seq)) { enrichedConfiguration.WriteTo.Seq(logSettings.Seq); } }); }
public async Task <string> GetUrl() { //https://developer.here.com/documentation/route-match/dev_guide/topics/quick-start-gps-trace-route.html string url = string.Empty; Matching matching = await GetMathing(); if (!string.IsNullOrEmpty(matching.AppCode) && !string.IsNullOrEmpty(matching.AppID) && !string.IsNullOrEmpty(matching.Routemode) && listData.Count > 0) { StringBuilder sb = new StringBuilder(); int i = 0; foreach (var data in listData) { sb.Append("&waypoint" + i + "="); sb.Append(data.Latitude); sb.Append(","); sb.Append(data.Longitude); i++; } url = "https://rme.api.here.com/2/calculateroute.json?app_id={" + matching.AppID + "}&app_code={" + matching.AppCode + "}&routeMatch=1&mode=fastest;" + matching.Routemode + ";traffic:disabled" + sb.ToString(); } return(await Task.FromResult(url)); }
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .Filter .ByExcluding(Matching.FromSource("System")) .Enrich.FromLogContext() .MinimumLevel.Information() .WriteTo.File(new CompactJsonFormatter(), "Logs/Neon.homecontrol.log", rollingInterval: RollingInterval.Day) .WriteTo.Console( theme: AnsiConsoleTheme.Literate, outputTemplate: "{Timestamp:HH:mm:ss} [{Level}] [{SourceContext:u3}] {Message}{NewLine}{Exception}") .CreateLogger(); try { CreateWebHostBuilder(args).Build().Run(); } finally { Log.CloseAndFlush(); } }
public static void Main(string[] args) { var logger = new LoggerConfiguration() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .WriteTo.Console(outputTemplate: "{Message}{NewLine}", theme: ConsoleTheme.None) .CreateLogger(); // TODO: Move to bivouac var host = new WebHostBuilder() .ConfigureAppConfiguration((context, configurationBuilder) => { configurationBuilder .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true); }) .UseUrls("http://*:8090/") .UseKestrel() .UseStartup <Startup>() .UseSerilog(logger) .Build(); host.Run(); }
public async Task RequestLoggingMiddlewareShouldEnrich() { var(sink, web) = Setup(options => { options.EnrichDiagnosticContext += (diagnosticContext, httpContext) => { diagnosticContext.Set("SomeInteger", 42); }; }); await web.CreateClient().GetAsync("/resource"); Assert.NotEmpty(sink.Writes); var completionEvent = sink.Writes.First(logEvent => Matching.FromSource <RequestLoggingMiddleware>()(logEvent)); Assert.Equal(42, completionEvent.Properties["SomeInteger"].LiteralValue()); Assert.Equal("string", completionEvent.Properties["SomeString"].LiteralValue()); Assert.Equal("/resource", completionEvent.Properties["RequestPath"].LiteralValue()); Assert.Equal(200, completionEvent.Properties["StatusCode"].LiteralValue()); Assert.Equal("GET", completionEvent.Properties["RequestMethod"].LiteralValue()); Assert.True(completionEvent.Properties.ContainsKey("Elapsed")); }
public static IHostBuilder UseSerilogForLogging(this IHostBuilder hostBuilder) { var assembly = Assembly.GetExecutingAssembly().GetName(); hostBuilder.UseSerilog((hostingContext, services, loggerConfiguration) => { loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration) .Enrich.FromLogContext() .Enrich.WithMachineName() // usefule for distributed/microservice .Enrich.WithProperty(nameof(Assembly), assembly.Name) .Enrich.WithProperty("Version", assembly.Version) .WriteTo.MSSqlServer(hostingContext.Configuration.GetConnectionString("DataContext"), sinkOptions: GetMSSqlServerSinkOptions(), columnOptions: GetColumnOptions()) .WriteTo.Logger(l => l.WriteTo.MSSqlServer(hostingContext.Configuration.GetConnectionString("DataContext"), sinkOptions: GetMSSqlServerSinkOptions2(), columnOptions: GetColumnOptions()) .Filter.ByIncludingOnly(Matching.WithProperty("ErrorId"))) // see ApiExceptionMiddleware for {ErrorId} .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // minimize the logs that we see(we only show logs from MS namespace if warning and above) .WriteTo.File(new JsonFormatter(), Path.Combine(Directory.GetCurrentDirectory(), "logs.json"), shared: true, restrictedToMinimumLevel: LogEventLevel.Warning); // this means any log level below Warning will not be displayed on the file (Warning level and above are shown) if (hostingContext.HostingEnvironment.IsDevelopment()) { // We can only see the logs in the console if we're running in kestrel //loggerConfiguration.WriteTo.Console(new JsonFormatter(),Serilog.Events.LogEventLevel.Verbose); // this means any log level below Information will not be displayed on the Console (information level and above are shown) loggerConfiguration.WriteTo.Console(Serilog.Events.LogEventLevel.Information); // this means any log level below Information will not be displayed on the Debug (information level and above are shown) loggerConfiguration.WriteTo.Debug(Serilog.Events.LogEventLevel.Information); } }); return(hostBuilder); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .WriteTo.Logger(l => l.Filter.ByIncludingOnly(Matching.WithProperty("ModuleName")).WriteTo.MySQL()) .WriteTo.Logger(l => l.Filter.ByIncludingOnly(Matching.WithProperty("Command")).WriteTo.RollingFile(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "log/{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Command} {Level}] {Message}{NewLine}param=>{Parameter}{NewLine}{Exception}{NewLine}")) .CreateLogger(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("SiteCorsPolicy"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseStaticFiles(); //api文档 app.UseSwagger(); app.UseSwaggerUI(c => { c.ShowExtensions(); c.RoutePrefix = "docs"; c.SwaggerEndpoint("/swagger/v1/swagger.json", "sk.core v1.0"); //c.EnableValidator(); c.DocExpansion(DocExpansion.Full); }); //设置公用appsetting ConfigurationUtil.SetConfiguration(Configuration); }
public async void InvokeTest_TestWithSerilogAndCorrelationMiddlewareWithCriticalLogLevel() { var formatter = new CustomJsonFormatter("testapp"); Serilog.Log.Logger = new Serilog.LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Logger(lc => lc .Filter.ByExcluding(Matching.FromSource("performance")) .WriteTo.RollingFile(formatter, Path.Combine(".\\logs\\", "log-{Date}.log")) .WriteTo.Console(formatter)) .WriteTo.Logger(lc => lc .Filter.ByIncludingOnly(Matching.FromSource("performance")) .WriteTo.RollingFile(formatter, Path.Combine(".\\logs\\", "log-perf-{Date}.log")) .WriteTo.Console(formatter)) .CreateLogger(); //Arrange var builder = new WebHostBuilder() .Configure((app) => { var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); loggerFactory.AddSerilog(); app.UseMiddleware <CorrelationIdMiddleware>("X-Correlation-Id"); app.UsePerformanceLog(options => options.Configure() .WithFormat("request to {operation} took {duration}ms") .WithLogLevel(LogLevel.Critical)); app.UseMiddleware <FakeMiddleware>(TimeSpan.FromMilliseconds(20)); }); var server = new TestServer(builder); //Act var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), "/delay/"); requestMessage.Headers.TryAddWithoutValidation("X-Correlation-Id", "jonas"); var responseMessage = await server.CreateClient().SendAsync(requestMessage); }
public static Logger Configure(IConfiguration configuration) { var logLevelSwtich = new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Information }; // Please do not change this format as this format is used by fluentd var template = "{Timestamp:yyyy-MM-ddTHH\\:mm\\:ss.ffzzz} [" + configuration.GetValue <string>("AppSettings:HostName") + "] [{Level}] [{SourceContext}] {Message} {Exception}" + Environment.NewLine; var loggerConfiguration = new LoggerConfiguration() .MinimumLevel.ControlledBy(logLevelSwtich) .WriteTo.Async(b => b.Logger(l => l.Enrich.FromLogContext()) .WriteTo.Async(a => a.FileStaticName("logs/costs.net.incoming.http.log", outputTemplate: template, rollOnFileSizeLimit: true, fileSizeLimitBytes: FileSizeLimitBytes, rollingInterval: DailyRollingInterval, retainedFileCountLimit: RetainedFileCountLimit) .Filter.ByIncludingOnly(Matching.FromSource <SerilogRequestMiddleware>())) .WriteTo.Async(a => a.FileStaticName("logs/costs.net.messaging.log", outputTemplate: template, rollOnFileSizeLimit: true, fileSizeLimitBytes: FileSizeLimitBytes, rollingInterval: DailyRollingInterval, retainedFileCountLimit: RetainedFileCountLimit) .Filter.ByIncludingOnly(c => Matching.FromSource("costs.net.messaging")(c) || Matching.FromSource("costs.net.core.Messaging")(c))) .WriteTo.Async(a => a.FileStaticName("logs/costs.net.application.log", outputTemplate: template, rollOnFileSizeLimit: true, fileSizeLimitBytes: FileSizeLimitBytes, rollingInterval: DailyRollingInterval, retainedFileCountLimit: RetainedFileCountLimit) .Filter.ByIncludingOnly(c => Matching.FromSource("costs.net")(c) || Matching.FromSource <AuthMiddleware>()(c) || Matching.FromSource <Startup>()(c) || Matching.FromSource <GlobalExceptionFilter>()(c)) .Filter.ByExcluding(c => Matching.FromSource("costs.net.core.messaging")(c) || Matching.FromSource("costs.net.messaging")(c) || Matching.FromSource <SerilogRequestMiddleware>()(c))) .ReadFrom.Configuration(configuration)); return(loggerConfiguration.CreateLogger()); }
public static void AddSerilogApi(IConfiguration configuration) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.WithProperty("ApplicationName", $"API Exemplo - {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}") .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithEnvironmentUserName() .Enrich.WithDemystifiedStackTraces() .Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.StaticFiles")) .Filter.ByExcluding(z => z.MessageTemplate.Text.Contains("erro de negócio")) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(configuration["ElasticsearchSettings:uri"])) { AutoRegisterTemplate = true, IndexFormat = "logs", ModifyConnectionSettings = x => x.BasicAuthentication(configuration["ElasticsearchSettings:username"], configuration["ElasticsearchSettings:password"]) }) .WriteTo.Seq(configuration["Seq:uri"]) .WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces) .WriteTo.LiterateConsole() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") .CreateLogger(); }
public void Initialize() { this.menuSession = new MenuLayout(this, 550, 34); this.menuInSessionHosting = new MenuLayout(this, 450, 34); this.menuInSessionClient = new MenuLayout(this, 450, 34); Matching.add_OnCreatedSession(new Messages.EventHandler(this.OnMatchingCreatedSession)); Matching.add_OnFoundSessions(new Messages.EventHandler(this.OnMatchingFoundSessions)); Matching.add_OnJoinedSession(new Messages.EventHandler(this.OnMatchingJoinedSession)); Matching.add_OnJoinInvalidSession(new Messages.EventHandler(this.OnMatchingJoinInvalidSession)); Matching.add_OnUpdatedSession(new Messages.EventHandler(this.OnMatchingUpdatedSession)); Matching.add_OnLeftSession(new Messages.EventHandler(this.OnMatchingLeftSession)); Matching.add_OnSessionDestroyed(new Messages.EventHandler(this.OnMatchingSessionDestroyed)); Matching.add_OnKickedOut(new Messages.EventHandler(this.OnMatchingKickedOut)); Matching.add_OnSessionError(new Messages.EventHandler(this.OnSessionError)); Matching.ClearAttributeDefinitions(); Matching.AddAttributeDefinitionInt("LEVEL", 2); Matching.AddAttributeDefinitionBin("RACE_TRACK", 4, 2); Matching.AddAttributeDefinitionBin("CAR_TYPE", 16, 4); Matching.AddAttributeDefinitionInt("GAME_DETAILS", 8); Matching.AddAttributeDefinitionInt("APP_VERSION", 2); Matching.AddAttributeDefinitionBin("TEST_BIN_SEARCH", 2, 8); Matching.AddAttributeDefinitionBin("PASSWORD", 8, 2); this.ErrorHandler(Matching.RegisterAttributeDefinitions()); }
public void Initialize() { menuSession = new MenuLayout(this, 550, 34); menuInSessionHosting = new MenuLayout(this, 450, 34); menuInSessionClient = new MenuLayout(this, 450, 34); Matching.OnCreatedSession += OnMatchingCreatedSession; Matching.OnFoundSessions += OnMatchingFoundSessions; Matching.OnJoinedSession += OnMatchingJoinedSession; Matching.OnJoinInvalidSession += OnMatchingJoinInvalidSession; Matching.OnUpdatedSession += OnMatchingUpdatedSession; Matching.OnLeftSession += OnMatchingLeftSession; Matching.OnSessionDestroyed += OnMatchingSessionDestroyed; Matching.OnKickedOut += OnMatchingKickedOut; Matching.OnSessionError += OnSessionError; Matching.ClearAttributeDefinitions(); Matching.AddAttributeDefinitionInt("LEVEL", Matching.EnumAttributeType.SESSION_SEARCH_ATTRIBUTE); Matching.AddAttributeDefinitionBin("RACE_TRACK", Matching.EnumAttributeType.SESSION_EXTERNAL_ATTRIBUTE, Matching.EnumAttributeMaxSize.SESSION_ATTRIBUTE_MAX_SIZE_12); Matching.AddAttributeDefinitionBin("CAR_TYPE", Matching.EnumAttributeType.SESSION_MEMBER_ATTRIBUTE, Matching.EnumAttributeMaxSize.SESSION_ATTRIBUTE_MAX_SIZE_28); Matching.AddAttributeDefinitionInt("GAME_DETAILS", Matching.EnumAttributeType.SESSION_INTERNAL_ATTRIBUTE); Matching.AddAttributeDefinitionInt("APP_VERSION", Matching.EnumAttributeType.SESSION_SEARCH_ATTRIBUTE); Matching.AddAttributeDefinitionBin("TEST_BIN_SEARCH", Matching.EnumAttributeType.SESSION_SEARCH_ATTRIBUTE, Matching.EnumAttributeMaxSize.SESSION_ATTRIBUTE_MAX_SIZE_60); Matching.AddAttributeDefinitionBin("PASSWORD", Matching.EnumAttributeType.SESSION_INTERNAL_ATTRIBUTE, Matching.EnumAttributeMaxSize.SESSION_ATTRIBUTE_MAX_SIZE_12); ErrorHandler(Matching.RegisterAttributeDefinitions()); }
/// <summary> /// Filters the list by the matching start string. /// </summary> /// <param name="start">Common start for the completions.</param> /// <param name="includeCommands">Set true to include internal commands.</param> /// <returns>Offset where the completion match or -1 when nothing matches.</returns> public int Match(string start, bool includeCommands = false) { MatchingPath = null; if (String.IsNullOrWhiteSpace(start)) { Reload(".", includeCommands); Matching = All; return(0); } start = CommandLine.Unquote(start); var lastSlashIndex = start.LastIndexOf(Path.DirectorySeparatorChar); if (lastSlashIndex >= 0) { var path = start.Substring(0, lastSlashIndex + 1); start = start.Substring(lastSlashIndex + 1); Reload(MatchingPath = path); Matching = String.IsNullOrEmpty(start) ? All : All.Where(i => i.StartsWith(start, StringComparison.OrdinalIgnoreCase)).ToArray(); return(lastSlashIndex + 1); } Reload(".", includeCommands); Matching = All.Where(i => i.StartsWith(start, StringComparison.OrdinalIgnoreCase)).ToArray(); return(Matching.Any() ? 0 : -1); }
public void Print_GivenMatching_ShouldPrintExpectedStringToConsole() { //arrange var consoleMatchingPrinter = new ConsoleMatchingPrinter(); var hits = new List <Hit>() { new Hit(new Ball(0, 0, 0), new Hole(1, 1, 1)), new Hit(new Ball(2, 1, 0), new Hole(3, 0, 1)) }; var matching = new Matching(hits); //act using (StringWriter sw = new StringWriter()) { Console.SetOut(sw); consoleMatchingPrinter.Print(matching); string expected = $"Solution:{Environment.NewLine}0,1{Environment.NewLine}2,3{Environment.NewLine}"; var output = sw.ToString(); //assert output.Should().Be(expected); } }
public static void SetupLogging() { var logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Particular", "ServiceInsight", "log-{Date}.txt"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() // Turn off some of Caliburn.Micro's chattiness .Filter.ByExcluding(le => Matching.FromSource(typeof(Screen).FullName)(le) && le.Level <= LogEventLevel.Information) .Filter.ByExcluding(le => Matching.FromSource(typeof(Caliburn.Micro.Action).FullName)(le) && le.Level <= LogEventLevel.Information) .Filter.ByExcluding(le => Matching.FromSource(typeof(ActionMessage).FullName)(le) && le.Level <= LogEventLevel.Information) .Filter.ByExcluding(le => Matching.FromSource(typeof(ViewModelBinder).FullName)(le) && le.Level <= LogEventLevel.Information) .WriteTo.RollingFile(logPath, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}") .WriteTo.Trace(outputTemplate: "[{Level}] ({SourceContext}) {Message}{NewLine}{Exception}") .WriteTo.Logger(lc => lc .MinimumLevel.Verbose() .Filter.ByIncludingOnly(Matching.FromSource <IServiceControl>()) .WriteTo.Observers(logEvents => logEvents .ObserveOn(TaskPoolScheduler.Default) .Do(LogWindowViewModel.LogObserver) .Subscribe())) .CreateLogger(); }
public static void WithWiredBrainConfiguration(this LoggerConfiguration loggerConfig, IServiceProvider provider, IConfiguration config) { var elasticsearchUri = config["Logging:ElasticsearchUri"]; var elasticIndexRoot = config["Logging:ElasticIndexFormatRoot"]; var rollingFileName = config["Logging:RollingFileName"]; var elasticBufferRoot = config["Logging:ElasticBufferRoot"]; var assemblyName = Assembly.GetEntryAssembly()?.GetName().Name; loggerConfig .ReadFrom.Configuration(config) // minimum levels defined per project in json files .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithProperty("Assembly", assemblyName) .Enrich.WithAspnetcoreHttpcontext(provider, GetContextInfo) .WriteTo.File(rollingFileName) .WriteTo.Logger(lc => lc.Filter.ByExcluding(Matching.WithProperty <bool>("Security", p => p)) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticsearchUri)) { AutoRegisterTemplate = true, AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, IndexFormat = elasticIndexRoot + "-{0:yyyy.MM.dd}", InlineFields = true })) .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(Matching.WithProperty <bool>("Security", p => p)) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticsearchUri)) { AutoRegisterTemplate = true, AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, IndexFormat = "security-{0:yyyy.MM.dd}", InlineFields = true })); }
public static async Task RunAsync(Application application, string[] args) { var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, }; options.Converters.Add(ReplicaStatus.JsonConverter); using var host = Host.CreateDefaultBuilder(args) .UseSerilog((context, configuration) => { // Logging for this application configuration .MinimumLevel.Verbose() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .Enrich .FromLogContext() .WriteTo .Console(); }) .ConfigureWebHostDefaults(web => { web.ConfigureServices(services => { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddOptions <StaticFileOptions>() .PostConfigure(o => { // Make sure we don't remove the other file providers (blazor needs this) o.FileProvider = new CompositeFileProvider(o.FileProvider, new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot")); }); services.AddSingleton(application); }); web.ConfigureKestrel(options => { var logger = options.ApplicationServices.GetRequiredService <ILogger <MicronetesHost> >(); var config = options.ApplicationServices.GetRequiredService <IConfiguration>(); if (config["port"] != null && int.TryParse(config["port"], out int cpPort)) { // Use the specified port options.Listen(IPAddress.Loopback, cpPort); } else { // This is lame but it allows running multiple versions of this // we should also allow ports to be specified as input options.Listen(IPAddress.Loopback, 0); } foreach (var service in application.Services.Values) { if (service.Description.External) { // We eventually want to proxy everything, this is temporary continue; } static int GetNextPort() { // Let the OS assign the next available port. Unless we cycle through all ports // on a test run, the OS will always increment the port number when making these calls. // This prevents races in parallel test runs where a test is already bound to // a given port, and a new test is able to bind to the same port due to port // reuse being enabled by default by the OS. using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); return(((IPEndPoint)socket.LocalEndPoint).Port); } foreach (var binding in service.Description.Bindings) { if (binding.Port == null) { continue; } if (service.Description.Replicas == 1) { // No need to proxy service.PortMap[binding.Port.Value] = new List <int> { binding.Port.Value }; continue; } var ports = new List <int>(); for (int i = 0; i < service.Description.Replicas; i++) { // Reserve a port for each replica var port = GetNextPort(); ports.Add(port); } logger.LogInformation("Mapping external port {ExternalPort} to internal port(s) {InternalPorts} for {ServiceName}", binding.Port, string.Join(", ", ports.Select(p => p.ToString())), service.Description.Name); service.PortMap[binding.Port.Value] = ports; options.Listen(IPAddress.Loopback, binding.Port.Value, o => { long count = 0; // o.UseConnectionLogging("Micronetes.Proxy"); o.Run(async connection => { var notificationFeature = connection.Features.Get <IConnectionLifetimeNotificationFeature>(); var next = (int)(Interlocked.Increment(ref count) % ports.Count); NetworkStream targetStream = null; try { var target = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; var port = ports[next]; logger.LogDebug("Attempting to connect to {ServiceName} listening on {ExternalPort}:{Port}", service.Description.Name, binding.Port, port); await target.ConnectAsync(IPAddress.Loopback, port); logger.LogDebug("Successfully connected to {ServiceName} listening on {ExternalPort}:{Port}", service.Description.Name, binding.Port, port); targetStream = new NetworkStream(target, ownsSocket: true); } catch (Exception ex) { logger.LogDebug(ex, "Proxy error for service {ServiceName}", service.Description.Name); await targetStream.DisposeAsync(); connection.Abort(); return; } try { logger.LogDebug("Proxying traffic to {ServiceName} {ExternalPort}:{InternalPort}", service.Description.Name, binding.Port, ports[next]); // external -> internal var reading = Task.Run(() => connection.Transport.Input.CopyToAsync(targetStream, notificationFeature.ConnectionClosedRequested)); // internal -> external var writing = Task.Run(() => targetStream.CopyToAsync(connection.Transport.Output, notificationFeature.ConnectionClosedRequested)); await Task.WhenAll(reading, writing); } catch (ConnectionResetException) { // Connection was reset } catch (OperationCanceledException ex) { if (!notificationFeature.ConnectionClosedRequested.IsCancellationRequested) { logger.LogDebug(0, ex, "Proxy error for service {ServiceName}", service.Description.Name); } } catch (Exception ex) { logger.LogDebug(0, ex, "Proxy error for service {ServiceName}", service.Description.Name); } finally { await targetStream.DisposeAsync(); } // This needs to reconnect to the target port(s) until its bound // it has to stop if the service is no longer running }); }); } }
static void Main(string[] args) { Console.Title = "Automatica.Core.Watchdog"; Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console() .MinimumLevel.Verbose() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .CreateLogger(); var logger = CoreLoggerFactory.GetLogger("Watchdog"); logger.LogInformation($"Starting WatchDog...Version {ServerInfo.GetServerVersion()}, Datetime {ServerInfo.StartupTime}"); var fi = new FileInfo(Assembly.GetEntryAssembly().Location); var appName = Path.Combine(fi.DirectoryName, ServerInfo.ServerExecutable); //logger.LogInformation($"Getting all processes by name {ServerInfo.ServerExecutable}..."); //var processes = Process.GetProcessesByName(ServerInfo.ServerExecutable); //logger.LogInformation($"Getting all processes by name {ServerInfo.ServerExecutable}...done"); //foreach (var process in processes) //{ // logger.LogInformation($"Kill {process.ProcessName} - {process.MainWindowTitle}..."); // process.Kill(); //} var tmpPath = Path.Combine(ServerInfo.GetTempPath(), $"Automatica.Core.Update"); if (Directory.Exists(tmpPath)) { Directory.Delete(tmpPath, true); } if (File.Exists(Path.Combine(ServerInfo.GetTempPath(), ServerInfo.UpdateFileName))) { File.Delete(Path.Combine(ServerInfo.GetTempPath(), ServerInfo.UpdateFileName)); } ProcessStartInfo processInfo; if (!File.Exists(appName)) { if (!File.Exists(appName + ".dll")) { logger.LogError($"Could not fine {appName} or {appName}.dll - exiting startup..."); return; } logger.LogInformation($"Starting with dotnet {appName}.dll"); processInfo = new ProcessStartInfo("dotnet", appName + ".dll"); } else { processInfo = new ProcessStartInfo(appName); } processInfo.WorkingDirectory = Environment.CurrentDirectory; Process process = null; try { while (true) { logger.LogInformation($"Starting {appName}"); process = Process.Start(processInfo); process.WaitForExit(); var exitCode = process.ExitCode; logger.LogInformation($"{appName} stopped with exit code {exitCode}"); if (PrepareUpdateIfExists(logger)) { Environment.Exit(2); //restart return; } process = null; Thread.Sleep(500); } } catch (TaskCanceledException) { process?.Kill(); } Console.ReadLine(); //cancelToken.Cancel(); }
public static async Task RunAsync(Application application, string[] args) { var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, }; options.Converters.Add(ReplicaStatus.JsonConverter); using var host = Host.CreateDefaultBuilder(args) .UseSerilog((context, configuration) => { // Logging for this application configuration .MinimumLevel.Verbose() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .Enrich .FromLogContext() .WriteTo .Console(); }) .ConfigureWebHostDefaults(web => { web.ConfigureServices(services => { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddOptions <StaticFileOptions>() .PostConfigure(o => { // Make sure we don't remove the other file providers (blazor needs this) o.FileProvider = new CompositeFileProvider(o.FileProvider, new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot")); }); services.AddSingleton(application); }); web.ConfigureKestrel(options => { var config = options.ApplicationServices.GetRequiredService <IConfiguration>(); if (config["port"] != null && int.TryParse(config["port"], out int cpPort)) { // Use the specified port options.Listen(IPAddress.Loopback, cpPort); } else { // This is lame but it allows running multiple versions of this // we should also allow ports to be specified as input options.Listen(IPAddress.Loopback, 0); } }); web.Configure(app => { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseRouting(); var api = new MicronetesApi(options); app.UseEndpoints(endpoints => { api.MapRoutes(endpoints); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); }); }) .Build(); var logger = host.Services.GetRequiredService <ILogger <MicronetesHost> >(); var lifetime = host.Services.GetRequiredService <IHostApplicationLifetime>(); var configuration = host.Services.GetRequiredService <IConfiguration>(); var serverAddressesFeature = host.Services.GetRequiredService <IServer>().Features.Get <IServerAddressesFeature>(); var diagnosticOptions = DiagnosticOptions.FromConfiguration(configuration); var diagnosticsCollector = new DiagnosticsCollector(logger, diagnosticOptions); var proxyService = new ProxyService(logger); // Print out what providers were selected and their values diagnosticOptions.DumpDiagnostics(logger); var target = new OutOfProcessExecutionTarget(logger, OutOfProcessOptions.FromArgs(args), diagnosticsCollector); await host.StartAsync(); logger.LogInformation("Dashboard running on {Address}", serverAddressesFeature.Addresses.First()); try { await proxyService.StartAsync(application); await target.StartAsync(application); } catch (Exception ex) { logger.LogError(0, ex, "Failed to launch application"); } var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); lifetime.ApplicationStopping.Register(obj => waitForStop.TrySetResult(null), null); await waitForStop.Task; logger.LogInformation("Shutting down..."); try { await target.StopAsync(application); await proxyService.StopAsync(application); } finally { // Stop the host after everything else has been shutdown await host.StopAsync(); } }
public static async Task RunAsync(Application application, string[] args) { var builder = WebApplication.CreateBuilder(args); // Logging for this application builder.Host.UseSerilog((context, configuration) => configuration .MinimumLevel.Verbose() .Filter.ByExcluding(Matching.FromSource("Microsoft")) .Enrich .FromLogContext() .WriteTo .Console() ); builder.Services.AddRazorPages(o => o.RootDirectory = "/Dashboard/Pages"); builder.Services.AddServerSideBlazor(); builder.Services.AddOptions <StaticFileOptions>() .PostConfigure(o => { var fileProvider = new ManifestEmbeddedFileProvider(typeof(MicronetesHost).Assembly, "wwwroot"); // Make sure we don't remove the existing file providers (blazor needs this) o.FileProvider = new CompositeFileProvider(o.FileProvider, fileProvider); }); builder.Services.AddSingleton(application); builder.Services.AddCors( options => { options.AddPolicy( "default", policy => { policy .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); using var app = builder.Build(); var port = app.Configuration["port"] ?? "0"; app.Listen($"http://127.0.0.1:{port}"); app.UseDeveloperExceptionPage(); app.UseCors("default"); app.UseStaticFiles(); app.UseRouting(); var api = new MicronetesApi(); api.MapRoutes(app); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); var logger = app.Logger; logger.LogInformation("Executing application from {Source}", application.Source); var lifetime = app.ApplicationLifetime; var configuration = app.Configuration; var diagnosticOptions = DiagnosticOptions.FromConfiguration(configuration); var diagnosticsCollector = new DiagnosticsCollector(logger, diagnosticOptions); // Print out what providers were selected and their values diagnosticOptions.DumpDiagnostics(logger); var processor = new AggregateApplicationProcessor(new IApplicationProcessor[] { new EventPipeDiagnosticsRunner(logger, diagnosticsCollector), new ProxyService(logger), new DockerRunner(logger), new ProcessRunner(logger, ProcessRunnerOptions.FromArgs(args)), }); await app.StartAsync(); logger.LogInformation("Dashboard running on {Address}", app.Addresses.First()); try { await processor.StartAsync(application); } catch (Exception ex) { logger.LogError(0, ex, "Failed to launch application"); } var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); lifetime.ApplicationStopping.Register(obj => waitForStop.TrySetResult(null), null); await waitForStop.Task; logger.LogInformation("Shutting down..."); try { await processor.StopAsync(application); } finally { // Stop the host after everything else has been shutdown await app.StopAsync(); } }
private static WebApplication BuildWebApplication(Application application, HostOptions options, ILogEventSink?sink) { var args = new List <string>(); if (options.Port.HasValue) { args.Add("--port"); args.Add(options.Port.Value.ToString(CultureInfo.InvariantCulture)); } var builder = WebApplication.CreateBuilder(args.ToArray()); // Logging for this application builder.Host.UseSerilog((context, configuration) => { configuration .MinimumLevel.Verbose() .Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore")) .Filter.ByExcluding(Matching.FromSource("Microsoft.Extensions")) .Filter.ByExcluding(Matching.FromSource("Microsoft.Hosting")) .Enrich .FromLogContext() .WriteTo .Console(); if (sink is object) { configuration.WriteTo.Sink(sink, LogEventLevel.Verbose); } }); builder.Services.AddRazorPages(o => o.RootDirectory = "/Dashboard/Pages"); builder.Services.AddServerSideBlazor(); builder.Services.AddOptions <StaticFileOptions>() .PostConfigure(o => { var fileProvider = new ManifestEmbeddedFileProvider(typeof(TyeHost).Assembly, "wwwroot"); // Make sure we don't remove the existing file providers (blazor needs this) o.FileProvider = new CompositeFileProvider(o.FileProvider, fileProvider); }); builder.Services.AddCors( options => { options.AddPolicy( "default", policy => { policy .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); builder.Services.AddSingleton(application); var app = builder.Build(); return(app); }
/// <summary> /// Provides standardized, centralized Serilog wire-up for a suite of applications. /// </summary> /// <param name="loggerConfig">Provide this value from the UseSerilog method param</param> /// <param name="provider">Provide this value from the UseSerilog method param as well</param> /// <param name="applicationName">Represents the name of YOUR APPLICATION and will be used to segregate your app /// from others in the logging sink(s).</param> /// <param name="config">IConfiguration settings -- generally read this from appsettings.json</param> public static void WithSimpleConfiguration(this LoggerConfiguration loggerConfig, IServiceProvider provider, string applicationName, IConfiguration config) { var name = Assembly.GetEntryAssembly()?.GetName(); loggerConfig .ReadFrom.Configuration(config) // minimum levels defined per project in json files .Enrich.WithAspnetcoreHttpcontext(provider, AddCustomContextDetails) .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithProperty("Assembly", $"{name.Name}") .Enrich.WithProperty("Version", $"{name.Version}") #region UnComment if you want // log into file without formatter //.WriteTo.File(new CompactJsonFormatter(), // $@"C:\temp\Logs\{applicationName}.json"); // if you want use sql server un comment this //notice:create Logging db by yourself //.WriteTo.Logger(lc => lc // .Filter.ByIncludingOnly(Matching.WithProperty("ElapsedMilliseconds")) // .WriteTo.MSSqlServer( // connectionString: @"Server=DESKTOP-SEC6MPT\SQLEXPRESS;Database=Logging;Trusted_Connection=True;", // tableName: "PerfLog", // autoCreateSqlTable: true, // columnOptions: GetSqlColumnOptions())) #endregion .WriteTo.Logger(le => le .Filter.ByIncludingOnly(Matching.WithProperty("ElapsedMilliseconds")) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://*****:*****@"c:\temp\logs\{applicationName}-error.json")); }
public void AcceptCompoundStatement(CompoundStatement stmt) { if (stmt.Statements.Count != 2) { return; } StoreStatement initializer = stmt.Statements[0] as StoreStatement; LoopBlock loop = stmt.Statements[1].AsWhileLoop(); if (initializer == null || loop == null) { return; } IList <Statement> body = loop.Body.AsStatementList(); if (body.Count == 0) { return; } StoreStatement step = body.Last() as StoreStatement; if (step == null) { return; } CompoundStatement newBody = new CompoundStatement(); newBody.Statements.AddRange(body.Take(body.Count - 1)); loop.Initializer = initializer; loop.Body = newBody; loop.Step = step; if (Level == EForLoopLevel.Strict || Level == EForLoopLevel.StrictOneInc) { StoreStatement initStore = initializer; if (initStore.Container == null) { return; } Variable counterVar = initStore.Container as Variable; if (counterVar == null) { return; } loop.CounterVariable = counterVar; Type counterType = counterVar.Type.CILType; if (!counterType.IsEnumerable()) { return; } if (loop.Body.Modifies(counterVar)) { return; } loop.CounterStart = initStore.Value; if (step.Container == null) { return; } if (!step.Container.Equals(counterVar)) { return; } Expression stepExpr = step.Value; Matching x = new Matching(); Matching mctr = (LiteralReference)counterVar; Matching mctrInc = mctr + x; Matching mctrDec = mctr - x; if (((Expression.MatchFunction)mctrInc)(stepExpr)) { loop.CounterStep = x.Result; loop.CounterDirection = LoopBlock.ECounterDirection.Increment; } else if (((Expression.MatchFunction)mctrDec)(stepExpr)) { loop.CounterStep = x.Result; loop.CounterDirection = LoopBlock.ECounterDirection.Decrement; } else { return; } BinOp cmp = loop.HeadCondition as BinOp; if (cmp == null) { return; } LiteralReference lhs = cmp.Children[0] as LiteralReference; if (lhs == null) { return; } if (!lhs.ReferencedObject.Equals(counterVar)) { return; } loop.CounterStop = cmp.Children[1]; switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Decrement: switch (cmp.Operation) { case BinOp.Kind.Gt: case BinOp.Kind.NEq: loop.CounterLimitKind = LoopBlock.ELimitKind.ExcludingStopValue; break; case BinOp.Kind.GtEq: loop.CounterLimitKind = LoopBlock.ELimitKind.IncludingStopValue; break; default: return; } break; case LoopBlock.ECounterDirection.Increment: switch (cmp.Operation) { case BinOp.Kind.Lt: case BinOp.Kind.NEq: loop.CounterLimitKind = LoopBlock.ELimitKind.ExcludingStopValue; break; case BinOp.Kind.LtEq: loop.CounterLimitKind = LoopBlock.ELimitKind.IncludingStopValue; break; default: return; } break; } if (Level == EForLoopLevel.StrictOneInc) { object inc; try { inc = loop.CounterStep.Eval(new DefaultEvaluator()); } catch (BreakEvaluationException) { return; } if (inc == null) { return; } long stepValue = TypeConversions.ToLong(inc); if (stepValue == 1) { switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Increment: loop.CounterDirection = LoopBlock.ECounterDirection.IncrementOne; break; case LoopBlock.ECounterDirection.Decrement: loop.CounterDirection = LoopBlock.ECounterDirection.DecrementOne; break; } } else if (stepValue == -1) { switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Increment: loop.CounterDirection = LoopBlock.ECounterDirection.DecrementOne; break; case LoopBlock.ECounterDirection.Decrement: loop.CounterDirection = LoopBlock.ECounterDirection.IncrementOne; break; } } else { return; } } } Result = loop; }
/// <summary> /// Froms the specified page. /// </summary> /// <param name="page">The page.</param> /// <returns></returns> public static MatchingConfigScript Initialize(Matching page) { MatchingConfigScript matchingConfigScript = new MatchingConfigScript(); matchingConfigScript.Id = page.ID; matchingConfigScript.ClientId = page.ClientID; return matchingConfigScript; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true) .AddEnvironmentVariables() .Build(); var logLevelSwitch = new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Information }; // Please do not change this format as this format is used by fluentd var template = "{Timestamp:yyyy-MM-ddTHH\\:mm\\:ss.ffzzz} [" + config.GetValue <string>("AppSettings:HostName") + "] [{Level}] [{SourceContext}] {Message} {Exception}" + Environment.NewLine; Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(logLevelSwitch) .WriteTo.Async(a => a.File("logs/costs.net.scheduler.log", outputTemplate: template) .Filter.ByIncludingOnly(c => Matching.FromSource("costs.net")(c))) .ReadFrom.Configuration(config) .CreateLogger(); Logger.Information("Starting costs.net.scheduler.host..."); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = new List <JsonConverter> { new StringEnumConverter() }, TypeNameHandling = TypeNameHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Serialize }; var services = new ServiceCollection(); services.AddOptions(); services.AddMemoryCache(); services.AddLogging(); services.Configure <AppSettings>(options => config.GetSection("AppSettings").Bind(options)); services.Configure <AclSettings>(options => config.GetSection("AclSettings").Bind(options)); services.Configure <AmqSettings>(options => config.GetSection("AmqSettings").Bind(options)); services.Configure <ElasticSearchSettings>(options => config.GetSection("ElasticSearch").Bind(options)); services.Configure <PaperpusherSettings>(options => config.GetSection(nameof(PaperpusherSettings)).Bind(options)); services.Configure <CacheSettings>(options => config.GetSection("CacheSettings").Bind(options)); var builder = new ContainerBuilder(); builder.RegisterLogger(); builder.RegisterInstance <IConfiguration>(config); builder.RegisterModule <AclModule>(); builder.RegisterModule <SchedulerModule>(); builder.RegisterModule <plugins.Modules.PluginModule>(); builder.RegisterModule <MessagingModule>(); builder.RegisterModule <ServiceModule>(); RegisterDataAccess(config, builder); loggerFactory.AddSerilog(); builder.Populate(services); var applicationContainer = builder.Build(); PrintSettings(applicationContainer); //The FluentScheduler SetupJobManager(applicationContainer); }
public void AcceptCompoundStatement(CompoundStatement stmt) { if (stmt.Statements.Count != 2) return; StoreStatement initializer = stmt.Statements[0] as StoreStatement; LoopBlock loop = stmt.Statements[1].AsWhileLoop(); if (initializer == null || loop == null) return; IList<Statement> body = loop.Body.AsStatementList(); if (body.Count == 0) return; StoreStatement step = body.Last() as StoreStatement; if (step == null) return; CompoundStatement newBody = new CompoundStatement(); newBody.Statements.AddRange(body.Take(body.Count - 1)); loop.Initializer = initializer; loop.Body = newBody; loop.Step = step; if (Level == EForLoopLevel.Strict || Level == EForLoopLevel.StrictOneInc) { StoreStatement initStore = initializer; if (initStore.Container == null) return; Variable counterVar = initStore.Container as Variable; if (counterVar == null) return; loop.CounterVariable = counterVar; Type counterType = counterVar.Type.CILType; if (!counterType.IsEnumerable()) return; if (loop.Body.Modifies(counterVar)) return; loop.CounterStart = initStore.Value; if (step.Container == null) return; if (!step.Container.Equals(counterVar)) return; Expression stepExpr = step.Value; Matching x = new Matching(); Matching mctr = (LiteralReference)counterVar; Matching mctrInc = mctr + x; Matching mctrDec = mctr - x; if (((Expression.MatchFunction)mctrInc)(stepExpr)) { loop.CounterStep = x.Result; loop.CounterDirection = LoopBlock.ECounterDirection.Increment; } else if (((Expression.MatchFunction)mctrDec)(stepExpr)) { loop.CounterStep = x.Result; loop.CounterDirection = LoopBlock.ECounterDirection.Decrement; } else return; BinOp cmp = loop.HeadCondition as BinOp; if (cmp == null) return; LiteralReference lhs = cmp.Children[0] as LiteralReference; if (lhs == null) return; if (!lhs.ReferencedObject.Equals(counterVar)) return; loop.CounterStop = cmp.Children[1]; switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Decrement: switch (cmp.Operation) { case BinOp.Kind.Gt: case BinOp.Kind.NEq: loop.CounterLimitKind = LoopBlock.ELimitKind.ExcludingStopValue; break; case BinOp.Kind.GtEq: loop.CounterLimitKind = LoopBlock.ELimitKind.IncludingStopValue; break; default: return; } break; case LoopBlock.ECounterDirection.Increment: switch (cmp.Operation) { case BinOp.Kind.Lt: case BinOp.Kind.NEq: loop.CounterLimitKind = LoopBlock.ELimitKind.ExcludingStopValue; break; case BinOp.Kind.LtEq: loop.CounterLimitKind = LoopBlock.ELimitKind.IncludingStopValue; break; default: return; } break; } if (Level == EForLoopLevel.StrictOneInc) { object inc; try { inc = loop.CounterStep.Eval(new DefaultEvaluator()); } catch (BreakEvaluationException) { return; } if (inc == null) return; long stepValue = TypeConversions.ToLong(inc); if (stepValue == 1) { switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Increment: loop.CounterDirection = LoopBlock.ECounterDirection.IncrementOne; break; case LoopBlock.ECounterDirection.Decrement: loop.CounterDirection = LoopBlock.ECounterDirection.DecrementOne; break; } } else if (stepValue == -1) { switch (loop.CounterDirection) { case LoopBlock.ECounterDirection.Increment: loop.CounterDirection = LoopBlock.ECounterDirection.DecrementOne; break; case LoopBlock.ECounterDirection.Decrement: loop.CounterDirection = LoopBlock.ECounterDirection.IncrementOne; break; } } else return; } } Result = loop; }
/// <summary> /// Filter log events to include only those that has specified property /// </summary> /// <param name="configuration">configuration</param> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Expected property value</param> /// <returns>LoggerConfiguration</returns> public static LoggerConfiguration FilterByHasProperty(this LoggerFilterConfiguration configuration, string propertyName) { return(configuration.ByIncludingOnly(Matching.WithProperty(propertyName))); //return configuration.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey(propertyName)); }
protected void Application_Start() { //Init logger InitAppInsights(); InitSiteNames(); System.Net.ServicePointManager.DefaultConnectionLimit = 12 * SimpleSettings.NUMBER_OF_PROCESSORS; var config = GlobalConfiguration.Configuration; config.Services.Add(typeof(IExceptionLogger), new TelemetryExceptionLogger()); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; //Analytics logger if (new[] { SimpleSettings.EmailPassword, SimpleSettings.EmailServer, SimpleSettings.EmailUserName, SimpleSettings.FromEmail, SimpleSettings.ToEmails }.All(s => !string.IsNullOrEmpty(s))) { var analyticsLogger = new LoggerConfiguration() .Enrich.With(new UserNameEnricher()) .Destructure.JsonNetTypes() .WriteTo.ApplicationInsightsEvents(AppInsights.TelemetryClient) .CreateLogger(); SimpleTrace.Analytics = analyticsLogger; //Diagnostics Logger var diagnosticsLogger = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.With(new UserNameEnricher()) .WriteTo.ApplicationInsightsTraces(AppInsights.TelemetryClient) .WriteTo.Logger(lc => lc .Filter.ByIncludingOnly(Matching.WithProperty <int>("Count", p => p % 10 == 0)) .WriteTo.Email(new EmailConnectionInfo { EmailSubject = "TryAppService Alert", EnableSsl = true, FromEmail = SimpleSettings.FromEmail, MailServer = SimpleSettings.EmailServer, NetworkCredentials = new NetworkCredential(SimpleSettings.EmailUserName, SimpleSettings.EmailPassword), Port = 587, ToEmail = SimpleSettings.ToEmails }, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Fatal)) .CreateLogger(); SimpleTrace.Diagnostics = diagnosticsLogger; } else { var logger = new LoggerConfiguration().CreateLogger(); SimpleTrace.Diagnostics = logger; SimpleTrace.Analytics = logger; } SimpleTrace.Diagnostics.Information("Application started"); //Configure Json formatter GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Error = (sender, args) => { SimpleTrace.Diagnostics.Error(args.ErrorContext.Error.Message); args.ErrorContext.Handled = true; }; //Templates Routes RouteTable.Routes.MapHttpRoute("templates", "api/templates", new { controller = "Templates", action = "Get", authenticated = false }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("arm-template", "api/armtemplate/{templateName}", new { controller = "Templates", action = "GetARMTemplate", authenticated = false }, new { verb = new HttpMethodConstraint("GET") }); //Telemetry Routes RouteTable.Routes.MapHttpRoute("post-telemetry-event", "api/telemetry/{telemetryEvent}", new { controller = "Telemetry", action = "LogEvent", authenticated = false }, new { verb = new HttpMethodConstraint("POST") }); RouteTable.Routes.MapHttpRoute("post-feedback-comment", "api/feedback", new { controller = "Telemetry", action = "LogFeedback", authenticated = false }, new { verb = new HttpMethodConstraint("POST") }); //Resources Api Routes RouteTable.Routes.MapHttpRoute("get-resource", "api/resource", new { controller = "Resource", action = "GetResource", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-username", "api/resource/user", new { controller = "Resource", action = "GetUserIdentityName", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("create-resource", "api/resource", new { controller = "Resource", action = "CreateResource", authenticated = true }, new { verb = new HttpMethodConstraint("POST") }); RouteTable.Routes.MapHttpRoute("get-webapp-publishing-profile", "api/resource/getpublishingprofile", new { controller = "Resource", action = "GetWebAppPublishingProfile", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-vscode-url", "api/resource/getvscodeurl", new { controller = "Resource", action = "GetVSCodeUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-vscodeinsiders-url", "api/resource/getvscodeinsidersurl", new { controller = "Resource", action = "GetVSCodeInsidersUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-gitclone-url", "api/resource/getgitcloneurl", new { controller = "Resource", action = "GetGitCloneUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-vscode-url-1", "api/resource/vscodeurl", new { controller = "Resource", action = "GetVSCodeUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-vscodeinsiders-url-1", "api/resource/vscodeinsidersurl", new { controller = "Resource", action = "GetVSCodeInsidersUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-app-gitclone-url-1", "api/resource/gitcloneurl", new { controller = "Resource", action = "GetGitCloneUrl", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-webapp-content", "api/resource/getwebappcontent/{siteName}", new { controller = "Resource", action = "GetWebAppContent", authenticated = false }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("get-mobile-client-app", "api/resource/mobileclient/{platformString}", new { controller = "Resource", action = "GetMobileClientZip", authenticated = false }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("delete-resource", "api/resource", new { controller = "Resource", action = "DeleteResource", authenticated = true }, new { verb = new HttpMethodConstraint("DELETE") }); RouteTable.Routes.MapHttpRoute("get-resource-status", "api/resource/status", new { controller = "Resource", action = "GetResourceStatus", authenticated = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("extend-resource-expiration-time", "api/resource/extend", new { controller = "Resource", action = "ExtendResourceExpirationTime", authenticated = true }, new { verb = new HttpMethodConstraint("POST") }); //Admin Only Routes RouteTable.Routes.MapHttpRoute("get-all-resources", "api/resource/all/{showFreeResources}", new { controller = "Resource", action = "All", authenticated = true, adminOnly = true, showFreeResources = RouteParameter.Optional }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("reset-all-free-resources", "api/resource/reset", new { controller = "Resource", action = "Reset", authenticated = true, adminOnly = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("reload-all-free-resources", "api/resource/reload", new { controller = "Resource", action = "DropAndReloadFromAzure", authenticated = true, adminOnly = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("delete-users-resource", "api/resource/delete/{userIdentity}", new { controller = "Resource", action = "DeleteUserResource", authenticated = true, adminOnly = true }, new { verb = new HttpMethodConstraint("GET") }); RouteTable.Routes.MapHttpRoute("cleanup-subscriptions", "api/resource/runcleanup", new { controller = "Resource", action = "RunCleanupSubscriptions", authenticated = true, adminOnly = true }, new { verb = new HttpMethodConstraint("GET") }); //Register auth provider SecurityManager.InitAuthProviders(); ResourcesManager.GetInstanceAsync().ConfigureAwait(false).GetAwaiter().GetResult(); }
// Saves question to test protected void btnSaveQuestion_Click(object sender, EventArgs e) { // Multiple choice question checked and saved if(rblChooseQuestion.SelectedValue == "Multiple Choice") if(txtMCQuestion.Text != String.Empty) if (txtMC1.Text != String.Empty || txtMC2.Text != String.Empty || txtMC3.Text != String.Empty || txtMC4.Text != String.Empty) { Question newQuestion = new Question(questionCounter, Int32.Parse(ddlPointValue.SelectedValue), "Multiple Choice"); if(rdbMC1.Checked == true) { MultipleChoice newMCQuestion = new MultipleChoice(questionCounter, txtMCQuestion.Text, "A"); } else if (rdbMC2.Checked == true) { MultipleChoice newMCQuestion = new MultipleChoice(questionCounter, txtMCQuestion.Text, "B"); } else if (rdbMC3.Checked == true) { MultipleChoice newMCQuestion = new MultipleChoice(questionCounter, txtMCQuestion.Text, "C"); } else { MultipleChoice newMCQuestion = new MultipleChoice(questionCounter, txtMCQuestion.Text, "D"); } MultipleChoiceChoice MCOption1 = new MultipleChoiceChoice(questionCounter, 'A', txtMC1.Text); MultipleChoiceChoice MCOption2 = new MultipleChoiceChoice(questionCounter, 'A', txtMC2.Text); MultipleChoiceChoice MCOption3 = new MultipleChoiceChoice(questionCounter, 'A', txtMC3.Text); MultipleChoiceChoice MCOption4 = new MultipleChoiceChoice(questionCounter, 'A', txtMC4.Text); questionList.Add(newQuestion); } // True False Question checked and saved if(rblChooseQuestion.SelectedValue == "True False") if(txtTFQuestion.Text != String.Empty) { Question newQuestion = new Question(questionCounter,Int32.Parse(ddlPointValue.SelectedValue), "True/False"); TrueFalse newTFQuestion = new TrueFalse(questionCounter, txtTFQuestion.Text, rblTrueFalse.SelectedValue.ToString()); questionList.Add(newQuestion); } // Fill in the Blank question checked and saved if (rblChooseQuestion.SelectedValue == "Short Answer") if (txtFBAnswer.Text != String.Empty) { Question newQuestion = new Question(questionCounter, Int32.Parse(ddlPointValue.SelectedValue), "Short Answer"); if (txtFBStatementBegin.Text != String.Empty && txtFBStatementEnd.Text != String.Empty) { ShortAnswer newSAQuestion = new ShortAnswer(questionCounter, txtFBStatementBegin.Text, txtFBAnswer.Text, txtFBStatementEnd.Text); } else if(txtFBStatementBegin.Text != String.Empty) { ShortAnswer newSAQuestion = new ShortAnswer(questionCounter, String.Empty, txtFBAnswer.Text, txtFBStatementEnd.Text); } else { ShortAnswer newSAQuestion = new ShortAnswer(questionCounter, txtFBStatementBegin.Text, txtFBAnswer.Text, String.Empty); } questionList.Add(newQuestion); } // Matching question checked and saved if(rblChooseQuestion.SelectedValue == "Matching") { if (txtSectionName.Text != String.Empty) { Question newQuestion = new Question(questionCounter, Int32.Parse(ddlPointValue.SelectedValue), "Matching"); Matching newMatching = new Matching(questionCounter, txtSectionName.Text); if (txtMQuestion1.Text != String.Empty && txtMAnswer1.Text != String.Empty) { MatchingQuestions newChoice1 = new MatchingQuestions(4, txtMQuestion1.Text, txtMAnswer1.Text); } if (txtMQuestion2.Text != String.Empty && txtMAnswer2.Text != String.Empty) { MatchingQuestions newChoice2 = new MatchingQuestions(4, txtMQuestion2.Text, txtMAnswer2.Text); } if (txtMQuestion3.Text != String.Empty && txtMAnswer3.Text != String.Empty) { MatchingQuestions newChoice3 = new MatchingQuestions(4, txtMQuestion3.Text, txtMAnswer3.Text); } if (txtMQuestion4.Text != String.Empty && txtMAnswer4.Text != String.Empty) { MatchingQuestions newChoice4 = new MatchingQuestions(4, txtMQuestion4.Text, txtMAnswer4.Text); } questionList.Add(newQuestion); } } // Essay question checked and saved if (rblChooseQuestion.SelectedValue == "Essay") if (txtEQuestion.Text != String.Empty) { Question newQuestion = new Question(questionCounter, Int32.Parse(ddlPointValue.SelectedValue), "Essay"); Essay newEssayQuestion = new Essay(questionCounter, txtEQuestion.Text); questionList.Add(newQuestion); } // tentative way to have unique questionIds questionCounter++; }
public override void AcceptIf(IfStatement stmt) { if (stmt.Conditions.Count == 1 && stmt.Branches.Count == 2 && stmt.Branches[0].IsEmpty()) { /* This case models the following situation: * * if (someCondition) * { * // empty * } * else * { * someActions(); * } * * Thus, it is rewritten to the following statement: * * if (!someCondition) * { * someActions(); * } * */ If((!stmt.Conditions[0]).Simplify()); { stmt.Branches[1].Accept(this); } EndIf(); } else { Expression c0 = stmt.Conditions[0].Simplify(); Matching x = new Matching(); Matching not_x = !x; if (c0.Match(not_x) == c0 && stmt.Conditions.Count == 1 && stmt.Branches.Count == 2) { /* This case models the following situation: * * if (!someCondition) * { * someThenAction(); * } * else * { * someElseAction(); * } * * Thus, it is rewritten to the following statement: * * if (someCondition) * { * someElseAction(); * } * else * { * someThenAction(); * } * */ If(c0.Children[0]); { stmt.Branches[1].Accept(this); } Else(); { stmt.Branches[0].Accept(this); } EndIf(); } else { If(c0); { stmt.Branches[0].Accept(this); } for (int i = 1; i < stmt.Conditions.Count; i++) { ElseIf(stmt.Conditions[i].Simplify()); { stmt.Branches[i].Accept(this); } } if (stmt.Branches.Count > stmt.Conditions.Count) { Else(); { stmt.Branches.Last().Accept(this); } } EndIf(); } } CopyAttributesToLastStatement(stmt); }
public override void Read(string sFolderPath, Matching matching) { this.matching = matching; }
void OnMatching(Matching match) { if (match != null) { foreach (var entity in match.blocks) { if (match.blockCommandEntity.destroyVFX > 0) { AttachEffect(match.blockCommandEntity.destroyVFX, entity.Offset, 1); } if (match.blockEntity.symbolVFX > 0) { AttachEffect(match.blockEntity.symbolVFX, entity.Offset, 1); } } // sound if (match.blockCommandEntity.destroySFX > 0) { PlaySound(match.blockCommandEntity.destroySFX); } } }