public Fingers10Context(CommandsConnectionString connectionString, ConsoleLogging consoleLogging, EventDispatcher eventDispatcher, IHttpContextAccessor httpContextAccessor) { _connectionString = connectionString?.Value ?? throw new ArgumentNullException(nameof(connectionString)); _useConsoleLogger = consoleLogging?.Enable ?? throw new ArgumentNullException(nameof(consoleLogging)); _eventDispatcher = eventDispatcher; _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); }
private static IHostBuilder AddLogging(this IHostBuilder hostBuilder, bool isAppLogging) { return(hostBuilder.ConfigureLogging((context, loggingBuilder) => { var loggerConfiguration = new LoggerConfiguration(); loggerConfiguration.ReadFrom.Configuration(context.Configuration); if (ConsoleLogging.GetIsEnabled()) { AddConsoleLogging(loggerConfiguration); } if (FileLogging.GetIsEnabled()) { AddFileLogging(loggerConfiguration, FileLogging.GetLogFilePath(isAppLogging)); } var logger = loggerConfiguration.CreateLogger(); if (isAppLogging) { // The logs coming from Uno will be sent to the app logger and not the host logger. LogExtensionPoint.AmbientLoggerFactory.AddSerilog(logger); } loggingBuilder.AddSerilog(logger); })); }
public FakeDatabase(ConsoleLogging consoleLogging, EventDispatcher eventDispatcher, IHttpContextAccessor httpContextAccessor, DbContextOptions options) : base(options) { _useConsoleLogger = consoleLogging?.Enable ?? throw new ArgumentNullException(nameof(consoleLogging)); _eventDispatcher = eventDispatcher; _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); }
public async Task ProcessItemsAsync() { IList <Task> indexTaskList = new List <Task>(); IList <SearchIndex> searchIndices = await this._kpiService.GetSearchIndicesAsync(); foreach (SearchIndex searchIndex in searchIndices) { Task indexPushOperation = ProcessIndexAsync(searchIndex); indexTaskList.Add(indexPushOperation); } await Task.WhenAll(indexTaskList); ConsoleLogging.LogLine($"KPI Process done for {searchIndices.Count} indices", ConsoleLogging.LogSeverity.Info); }
public Task LogProcessAsync() { ConsoleLogging.LogLine("{{{PULSE}}} Log Queue Process", severity: ConsoleLogging.LogSeverity.Info); if (notIsLoggingLocked) { notIsLoggingLocked = false; CommonFunctions.LogManager.ProcessLogQueue(); notIsLoggingLocked = true; } else { ConsoleLogging.LogLine("[[[BYPASS]]] Log Queue Process is locked and in progress!", severity: ConsoleLogging.LogSeverity.Warning); } return(Task.CompletedTask); }
public async Task KPIProcessAsync() { ConsoleLogging.LogLine("{{{PULSE}}} KPI Process", severity: ConsoleLogging.LogSeverity.Info); if (notIsProcessLocked) { notIsProcessLocked = false; ServiceManager.Initialize(); await context.ProcessItemsAsync(); notIsProcessLocked = true; } else { ConsoleLogging.LogLine("[[[BYPASS]]] KPI Process is locked and in progress!", severity: ConsoleLogging.LogSeverity.Warning); } }
static void Main(string[] args) { ShowWindow(ThisConsole, MAXIMIZE); Console.Clear(); ConsoleLogging.PrintAsciiArt(); ScoreRetriever retriever = new ScoreRetriever(); retriever.ExecuteOrder66(); ConsoleLogging.PrintUserData(); Console.ReadLine(); }
public void PrintHtml(ILogging logging) { if (logging == null) { logging = new ConsoleLogging(); } logging.WriteLine("Updated {0} rows.", Updated.Count); foreach (var kvp in Updated) { logging.WriteLine("K: {0}\n Old: {1} \n New: {2}", KeySelector(kvp.Value), ContentSelector(Orig[kvp.Key]), ContentSelector(kvp.Value)); } logging.WriteLine("Added {0} rows.", New.Count); foreach (var kvp in New) { logging.WriteLine("{0}", kvp.Key); } }
/// <summary> /// Runs the specified arguments. /// </summary> /// <typeparam name="TStitcher">The type of the stitcher.</typeparam> /// <param name="args">The arguments.</param> /// <returns></returns> public static int Run <TStitcher>(string[] args) where TStitcher : IStitcher, new() { var logging = new ConsoleLogging(); try { var stitcher = new TStitcher { Logging = logging }; var arguments = args.ParseArguments(); stitcher.Inject(arguments); return(stitcher.Process(arguments, Assembly.GetEntryAssembly().Location) ? 0 : 1); } catch (Exception e) { logging.Write("Unhandled exception: {0}", e); } return(2); }
private async Task ProcessIndexAsync(SearchIndex searchIndex) { DateTime startDate = this._kpiService.GetSearchRange(searchIndex.IndexId); // Get last log insertion date int fragmentCount = CalculateLoopCount(startDate); // Calculate fragment count DateTime searchRange = startDate; for (int i = 0; i < fragmentCount; i++) { searchRange = searchRange.AddMinutes(CommonFunctions.UnifyingConstant); // add 15 min for each iteration. string requestBody = ElasticSearchRESTAdapter.GetRequestBody(start: searchRange); string fullIndexName = ElasticSearchRESTAdapter.GetFullIndexName(index: searchIndex.IndexName, indexPattern: searchIndex.IndexPattern, indexPatternValue: searchRange); Root responseRoot = await ElasticSearchRESTAdapter.GetResponseFromElasticUrlAsync(urlAddress : searchIndex.UrlAddress, index : fullIndexName, requestBody : requestBody); if (responseRoot == null) { // Root is null for current search range // Check for next day of search range > today // Example: searchRange: 05.01.2020 -> 06.01.2020 > 10.01.2020 ? double checkForNextDay = (DateTime.Now - searchRange.AddDays(1)).TotalMilliseconds; if (checkForNextDay < 0) { break; // it became greater than current date. } searchRange = searchRange.AddDays(1); // Increase search range by one day // then increase the current loop iterator for increment above to prevent out of range exception. // 24 Hour * 60 Min / fragmentation by minute) - 1 for current iteration i += (24 * 60 / CommonFunctions.UnifyingConstant) - 1; ConsoleLogging.LogLine($"{searchIndex.UrlAddress}-> {searchIndex.IndexName} is expired, skipped to [{i + 1}/{fragmentCount}]."); continue; } InsertDataToDatabase(aggregation: responseRoot.Aggregation, indexId: searchIndex.IndexId, logDate: searchRange); ConsoleLogging.LogLine($"{searchIndex.UrlAddress}-> {searchIndex.IndexName} [{i + 1}/{fragmentCount}] added."); } }
/// <summary> /// This method has to be invoked from application Main. /// </summary> /// <param name="args">The arguments.</param> protected void Run(string[] args) { Logging = new ConsoleLogging(); // arguments foreach (var arg in args) { var trimmedArg = arg.StartsWith("\"") && arg.EndsWith("\"") ? arg.Substring(1, arg.Length - 2) : arg; var equalIndex = trimmedArg.IndexOf('='); if (equalIndex < 0) { continue; } var propertyName = trimmedArg.Substring(0, equalIndex); var propertyValue = trimmedArg.Substring(equalIndex + 1); var property = GetType().GetProperty(propertyName); if (property == null) { continue; } property.SetValue(this, propertyValue); } // and now, run Run(); }
static void Main(string[] args) { #region configuration var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); string connString = config.GetConnectionString("DefaultConnection"); // Check DB connection // Console.WriteLine(connString); IDbConnection conn = new MySqlConnection(connString); #endregion //Select the SQL Departments Table and load it into the IEnumerable depos DapperDepartmentRepository deptrepo = new DapperDepartmentRepository(conn); var depos = deptrepo.GetAllDepartments(); //Select the SQL Products Table and load it into the IEnumerable products DapperProductRepository productrepo = new DapperProductRepository(conn); var products = productrepo.GetAllProducts(); //Dispaly the menu and ask the user to select an option string userSelection; bool stopAppliction = false; while (stopAppliction == false) { ConsoleLogging.DisplayMenu(); Console.WriteLine(); Console.Write("Please enter your selection: "); userSelection = Console.ReadLine(); switch (userSelection) { case "1": //Print All Departments depos = deptrepo.GetAllDepartments(); ConsoleLogging.PrintDept(depos); break; case "2": //Add a New Department Console.Write("Enter the Department Name: "); deptrepo.InsertDepartment(Console.ReadLine()); break; case "3": //Print All Products products = productrepo.GetAllProducts(); ConsoleLogging.PrintProducts(products); break; case "4": //Add a New Product Console.Write("Enter the Product Name: "); string pName = Console.ReadLine(); Console.Write("Enter the Product Price: "); decimal pprice = Decimal.Parse(Console.ReadLine()); Console.Write("Enter the Product CategoryID: "); int pCategoryID = int.Parse(Console.ReadLine()); Console.Write("Enter 1 if OnSale or 0 if Not: "); int pOnSale = int.Parse(Console.ReadLine()); Console.Write("Enter Stock Level: "); int pStockLevel = int.Parse(Console.ReadLine()); productrepo.InsertProduct(pName, pprice, pCategoryID, pOnSale, pStockLevel); break; case "5": stopAppliction = true; break; } } Console.WriteLine("Ending Best Buy Database Application"); }
public static void Main(string[] args) { var army1 = new Unit[] { new Unit { Name = "Воин 1", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 2", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 3", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Magical, Value = 7 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Magical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 4", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 }, new Power { Type = PowerType.Magical, Value = 7 }, }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 }, new Power { Type = PowerType.Magical, Value = 14 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.15f, }, new Unit { Name = "Воин 5", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, }; var army2 = new Unit[] { new Unit { Name = "Воин 11", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 12", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 13", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Magical, Value = 7 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Magical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, new Unit { Name = "Воин 14", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 }, new Power { Type = PowerType.Magical, Value = 7 }, }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 }, new Power { Type = PowerType.Magical, Value = 14 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.15f, }, new Unit { Name = "Воин 15", Health = 100, Fury = 0, Damage = new Power[] { new Power { Type = PowerType.Physical, Value = 5 } }, ActiveDamage = new Power[] { new Power { Type = PowerType.Physical, Value = 10 } }, Resistance = new Power[] { new Power { Type = PowerType.Physical, Value = 0.1f }, new Power { Type = PowerType.Magical, Value = 0.2f } }, Dodge = 0.09f, }, }; var cl = new ConsoleLogging(); var bm = new BattleManager(cl); bm.Battle(army1, army2); Console.ReadLine(); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddHttpCacheHeaders((expirationModelOptions) => { expirationModelOptions.MaxAge = 60; expirationModelOptions.CacheLocation = Marvin.Cache.Headers.CacheLocation.Private; }, (validationModelOptions) => { validationModelOptions.MustRevalidate = true; }); services.AddResponseCaching(); services.AddResponseCompression(); services.AddControllers(options => { //options.Filters.Add(new AuthorizeFilter()); options.Filters.Add(new ProducesDefaultResponseTypeAttribute()); options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status400BadRequest)); options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status401Unauthorized)); options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status406NotAcceptable)); options.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status500InternalServerError)); options.ReturnHttpNotAcceptable = true; options.CacheProfiles.Add("240SecondsCacheProfile", new CacheProfile() { Duration = 240 }); //options.InputFormatters.Insert(0, GetJsonPatchInputFormatter()); }) .AddNewtonsoftJson(setupAction => { setupAction.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) //.AddJsonOptions(options => //{ // options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; //}) .AddXmlDataContractSerializerFormatters() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { // create a problem details object var problemDetailsFactory = context.HttpContext.RequestServices .GetRequiredService <ProblemDetailsFactory>(); var problemDetails = problemDetailsFactory.CreateValidationProblemDetails( context.HttpContext, context.ModelState); // add additional info not added by default problemDetails.Detail = "See the errors field for details."; problemDetails.Instance = context.HttpContext.Request.Path; // find out which status code to use var actionExecutingContext = context as Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext; // if there are modelstate errors & all keys were correctly // found/parsed we're dealing with validation errors // // if the context couldn't be cast to an ActionExecutingContext // because it's a ControllerContext, we're dealing with an issue // that happened after the initial input was correctly parsed. // This happens, for example, when manually validating an object inside // of a controller action. That means that by then all keys // WERE correctly found and parsed. In that case, we're // thus also dealing with a validation error. if (context.ModelState.ErrorCount > 0 && (context is ControllerContext || actionExecutingContext?.ActionArguments.Count == context.ActionDescriptor.Parameters.Count)) { problemDetails.Type = "https://enterprisearchitecture.com/modelvalidationproblem"; problemDetails.Status = StatusCodes.Status422UnprocessableEntity; problemDetails.Title = "One or more validation errors occurred."; return(new UnprocessableEntityObjectResult(problemDetails) { ContentTypes = { "application/problem+json" } }); } // if one of the keys wasn't correctly found / couldn't be parsed // we're dealing with null/unparsable input problemDetails.Status = StatusCodes.Status400BadRequest; problemDetails.Title = "One or more errors on input occurred."; return(new BadRequestObjectResult(problemDetails) { ContentTypes = { "application/problem+json" } }); }; }); services.Configure <MvcOptions>(config => { var newtonsoftJsonOutputFormatter = config.OutputFormatters .OfType <NewtonsoftJsonOutputFormatter>()?.FirstOrDefault(); if (newtonsoftJsonOutputFormatter != null) { newtonsoftJsonOutputFormatter.SupportedMediaTypes.Add("application/vnd.fingers10.hateoas+json"); } }); services.AddVersionedApiExplorer(options => { options.GroupNameFormat = "'v'VV"; //options.SubstituteApiVersionInUrl = true; }); services.AddApiVersioning(options => { options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); options.ReportApiVersions = true; options.ApiVersionReader = new HeaderApiVersionReader("api-version"); //options.ApiVersionReader = new MediaTypeApiVersionReader(); }); IApiVersionDescriptionProvider apiVersionDescriptionProvider = GetApiVersionDescriptionProvider(services); services.AddSwaggerGen(options => { foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) { options.SwaggerDoc( $"EnterpriseArchitectureOpenAPISpecification{description.GroupName}", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "EnterpriseArchitecture API", Version = description.ApiVersion.ToString(), Description = "Through this API you can access architecture reference and knowledge", Contact = new Microsoft.OpenApi.Models.OpenApiContact { Email = "*****@*****.**", Name = "Abdul Rahman", Url = new Uri("https://www.linkedin.com/in/fingers10") }, // Need to change the license in future License = new Microsoft.OpenApi.Models.OpenApiLicense { Name = "MIT License", Url = new Uri("https://opensource.org/licenses/MIT") }, //TermsOfService = new Uri("") }); } //options.AddSecurityDefinition("token", new OpenApiSecurityScheme //{ // Type = SecuritySchemeType.OpenIdConnect, // OpenIdConnectUrl = new Uri(Configuration.GetValue<string>("IDP")) //}); //options.AddSecurityRequirement(new OpenApiSecurityRequirement //{ // { // new OpenApiSecurityScheme // { // Reference = new OpenApiReference { // Type = ReferenceType.SecurityScheme, // Id = "token" } // }, Array.Empty<string>() // } // }); //options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() //{ // Type = SecuritySchemeType.Http, // Scheme = "Bearer", // Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"" //}); //options.AddSecurityRequirement(new OpenApiSecurityRequirement //{ // { // new OpenApiSecurityScheme // { // Reference = new OpenApiReference { // Type = ReferenceType.SecurityScheme, // Id = "Bearer" } // }, new List<string>() } //}); options.DocInclusionPredicate((documentName, apiDescription) => { var actionApiVersionModel = apiDescription.ActionDescriptor .GetApiVersionModel(ApiVersionMapping.Explicit | ApiVersionMapping.Implicit); if (actionApiVersionModel == null) { return(true); } if (actionApiVersionModel.DeclaredApiVersions.Count > 0) { return(actionApiVersionModel.DeclaredApiVersions.Any(v => $"EnterpriseArchitectureOpenAPISpecificationv{v}" == documentName)); } return(actionApiVersionModel.ImplementedApiVersions.Any(v => $"EnterpriseArchitectureOpenAPISpecificationv{v}" == documentName)); }); options.OperationFilter <GetBookOperationFilter>(); options.OperationFilter <CreateAuthorOperationFilter>(); var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile); options.IncludeXmlComments(xmlCommentsFullPath); }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddHttpContextAccessor(); var config = new Config(Configuration.GetValue <int>("DatabaseConnectRetryAttempts")); services.AddSingleton(config); var consoleLogging = new ConsoleLogging(Configuration.GetValue <bool>("EnableConsoleLogging")); services.AddSingleton(consoleLogging); var commandsConnectionString = new CommandsConnectionString(Configuration["ConnectionString"]); var queriesConnectionString = new QueriesConnectionString(Configuration["ConnectionString"]); services.AddSingleton(commandsConnectionString); services.AddSingleton(queriesConnectionString); services.AddTransient <IPropertyCheckerService, PropertyCheckerService>(); services.AddTransient <IBus, Bus>(); services.AddTransient <MessageBus>(); services.AddTransient <EventDispatcher>(); services.AddTransient <Messages>(); services.AddTransient <Fingers10Context>(); services.AddTransient <IAsyncRepository <Student>, StudentRepository>(); services.AddTransient <IStudentReadonlyRepository, StudentReadonlyRepository>(); services.AddTransient <IAuthorReadonlyRepository, AuthorReadonlyRepository>(); services.AddTransient <IUnitOfWork, UnitOfWork>(); services.AddHandlers(); }