Newtonsoft.Json.JsonConvert.SerializeObject(request)
Since .NET Core 3.0 you can use System.Text.Json:
System.Text.Json.JsonSerializer.Serialize(request)
Newtonsoft.Json.JsonConvert.SerializeObject(request)
Since .NET Core 3.0 you can use System.Text.Json:
System.Text.Json.JsonSerializer.Serialize(request)
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
//.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.WithEnvironmentName()
.Enrich.WithProperty("ApplicationNameaaaa", "my application")
.CreateLogger();
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
//.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console(new RenderedCompactJsonFormatter())
.WriteTo.Debug(new RenderedCompactJsonFormatter())
.WriteTo.File(
new RenderedCompactJsonFormatter(),
@"./logs/log-.txt",
fileSizeLimitBytes: 1_000_000,
rollOnFileSizeLimit: true,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(1))
.CreateLogger();
in appsettings.json:
"Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Warning", "System": "Warning", "System.Net.Http.HttpClient": "Warning" } }, "WriteTo": [ { "Name": "Debug", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact" } }, { "Name": "Console", "Args": { "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact" } }, { "Name": "Logger", "Args": { "configureLogger": { "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "Contains(SourceContext, 'nomeapp') and (@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/Error/applog_.json", "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog", "rollingInterval": "Day", "retainedFileCountLimit": 7 } }, { "Name": "MongoDBBson", "Args": { "databaseUrl": "mongodb://user:password@server1,server2,server3/database?authSource=admin&replicaSet=database", "collectionName": "logs", "cappedMaxSizeMb": "1024", "cappedMaxDocuments": "50000" } } ] } } }, { "Name": "Logger", "Args": { "configureLogger": { "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "Contains(SourceContext, 'nomeapp') and @Level = 'Information'" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/Info/applog_.json", "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog", "rollingInterval": "Day", "retainedFileCountLimit": 7 } }, { "Name": "MongoDBBson", "Args": { "databaseUrl": "mongodb://user:password@server1,server2,server3/database?authSource=admin&replicaSet=replicaname", "collectionName": "logs", "cappedMaxSizeMb": "1024", "cappedMaxDocuments": "50000" } } ] } } } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithThreadName" ], "Properties": { "app": "nome", "app_environment": "dev", /*dev,tst,itg,pef,prd*/ "log.level": "", /*error,info,debug,warning*/ "tenant": "nometeam" } }
Front-End-Web-Development-Resources
Lots and lots of freely available programming books, screencasts, podcasts, and even online video tutorials of all sorts. If you are looking for learning materials
https://github.com/RitikPatni/Front-End-Web-Development-Resources
WTFJS
As the name suggests, this repo has a list of WTF examples of JavaScript that should be known by every web developer.
By knowing what they are, you can understand why they occur in the first place and thereby understand JavaScript better.
https://github.com/denysdovhan/wtfjs
Awesome
The most popular repo that curates all topics from software development to hardware to business.
https://github.com/sindresorhus/awesome
List of (Advanced) JavaScript Questions
This repository by Lydia Hallie provides you with a list of JavaScript questions updated regularly by Lydia herself. This repo will definitely help you prepare for your technical JS interview. Also, this repo supports 16 languages.
https://github.com/lydiahallie/javascript-questions
JavaScript Algorithms and Data Structures
We have the trend in the tech world to talk a lot about algorithms and that we have to know them! So, here is this fantastic repo where you can find most of them.
The really cool thing is that every algorithm is written in JavaScript and has been tested. So it is even easier for you to understand!
https://github.com/trekhleb/javascript-algorithms
Clean Code JavaScript
We all know that bad code can work because we all have written bad code. It is normal to write bad code. Having a guide to show you what is bad code can help you to write good code.
https://github.com/ryanmcdermott/clean-code-javascript
Free-for.dev
Developers and open-source authors now have a massive amount of services offering free tiers, but it can be hard to find them all in order to make informed decisions.
This is list of software (SaaS, PaaS, IaaS, etc.) and other offerings that have free tiers for developers.
https://github.com/ripienaar/free-for-dev
List of Free Learning Resources
It offers lots and lots of freely available programming books, screencasts, podcasts, and even online courses of all sorts. If you are looking for learning materials — look no further!
https://github.com/EbookFoundation/free-programming-books
Awesome First PR Opportunities
This repository is a must-visit for web devs, especially newbie devs who have no experience in open-source projects. Contributing to open source allows you to mingle with the lovely community, share knowledge, be a better developer and maybe eventually get a good job.
A common hurdle is that things can get a bit overwhelming in the beginning. This repository lists open-source projects that are known for or currently have beginner-friendly issues that you can tackle.
https://github.com/MunGell/awesome-for-beginners
Daily-Interview-Question
As the name suggests, this GitHub repo gives you an interview question every day. Ultimately allowing you to gain some keen insights on the tech questions thrown at you during interviews.
Although this website is in Chinese, Google translate will help you.
https://github.com/Advanced-Frontend/Daily-Interview-Question
Awesome Learning Resource
this is pretty much a one-stop destination for your learning needs as a developer. This repo contains freely available programming books, podcasts, and even online video tutorials for a variety of software engineering topics and programming languages.
If you are looking to learn a new language or concept in programming, this is a must-visit repo.
https://github.com/lauragift21/awesome-learning-resources
free-programming-books
As the name suggests, this repo contains a list of free programming books for almost any language or concept in programming. The list is quite huge and has 143,000 stars and 34,900 forks. It’s available in many languages and is comprised of mainly programming books.
https://github.com/EbookFoundation/free-programming-books
Best-websites-a-programmer-should-visit
When learning programming, you must be in touch with certain websites in order to learn the technologies better and to learn new things. This repo contains a list of nonexhaustive websites that you should pretty much be in touch with. This contains podcasts, news websites, resources on competitive programming, things to do when you are bored, and much, much more.
https://github.com/sdmg15/Best-websites-a-programmer-should-visit
Project Guidelines
It contains a set of best practices for JS projects. These guidelines help you write and maintain projects with ease and reduce the level of issues that occur in the whole process. This includes some best practices on Git, documentation, environment, dependencies, testing, and more.
If you want to share a best practice or think one of these guidelines should be removed, you can make a PR.
https://github.com/elsewhencode/project-guidelines
App Ideas Collection
Have you ever wanted to build something but you had no idea what to do? Just as authors sometimes have writer’s block, it’s also true for developers. This Repo contains a list of app ideas categorized according to three tiers of programming experience.
These applications help you improve your coding skills as well as allow you to try out new technologies.
https://github.com/florinpop17/app-ideas
Web Developer Road Map
It contains a set visual illustration on career pathways you could take as a web developer. The purpose of these roadmaps is to give you an idea about the landscape and to guide you if you’re confused about what to learn next.
A simpler, more beginner-friendly version of the illustration is under development. This chart gets updated yearly to reflect any new changes, so you never have to be worried about being outdated.
Need to write some description and tags
var collectionName = await _configurationFacade.GetConsumerCollectionArchive(observer.EsbConsumer);
Type collectionType = Type.GetType($"TaxMs.Esb.Infrastructure.Models.{collectionName}");
//_context.TryGetCollection<AccountingTax>().Find(x => x.);
//_context.GetType()
// .GetMethod("TryGetCollection")
// .MakeGenericMethod(propertyInfo.PropertyType)
// .Invoke(mapper, new object[] { "bloggingabout" });
MethodInfo method = _context.GetType().GetMethod(nameof(_context.TryGetCollection));
MethodInfo generic = method.MakeGenericMethod(collectionType);
var mongoCollection = generic.Invoke(this, null);
Your task is to merge two lists of objects. The resulting collection should be without duplicates, based on a certain property on the objects.
The lists are populated with very simple Person objects.
1 2 3 4 5 | class Person { public int Number { get; set; } public string Name { get; set; } } |
C# programmers often turn to LINQ, and they should! With LINQ you could end up with something like this:
1 2 3 | var merged = new List<Person>(list1); merged.AddRange(list2.Where(p2 => list1.All(p1 => p1.Number != p2.Number))); |
It’s not all that obvious how it works and it also has performance problems. This solution has to iterate over list1
for every object in list2
. Not every object every time but on average half of them (if the lists contains no duplicates within themselves). If the lists contains a 1000 objects each there’s a good chance that list1
will be iterated 500.000 times. That kind of work does not come for free.
We need to get rid of this nested looping. I was pretty sure a dictionary based solution would do the trick.
1 2 3 4 5 6 | var dict = list2.ToDictionary(p => p.Number); foreach (var person in list1) { dict[person.Number] = person; } var merged = dict.Values.ToList(); |
This solution converts list2
to a dictionary and then it loops a single time over list1
. It either adds to the dictionary or replaces the value of list2
if it was a duplicate. This seemed to be a much more efficient algorithm.
In C# there’s not just Dictionary<TKey, TValue> but we also have HashSet. A HashSet is a collection that contains no duplicates. It also has the UnionWith
method and that is exactly what we are looking for. The problem is that it compares object to object and we want to compare based on a property.
Fortunately the HashSet methods honors the default equality comparer. Such a beast could look like this.
1 2 3 4 5 6 7 8 9 10 11 12 | class PersonComparer : IEqualityComparer<Person> { public bool Equals(Person p1, Person p2) { return p1.Number == p2.Number; } public int GetHashCode(Person p) { return p.Number; } } |
Then just add it as the second parameter to the constructor.
1 2 3 | var hs = new HashSet<Person>(list1, new PersonComparer()); hs.UnionWith(list2); var merged = hs.ToList(); |
Set theory tells us that this merging is actually a union of the two sets (without duplicates) and LINQ happens to have a Union
method.
var merged = list1.Union(list2, new PersonComparer()); |
By that we’ve come full circle and it’s time to see how the different solutions performs. I wrote a small test program that creates two lists of objects with 1000 objects in each. In each list 500 of the objects property, that we base the merge on, has the same value.
Lists and LINQ merge: 4820ms Dictionary merge: 16ms HashSet and IEqualityComparer: 20ms LINQ Union and IEqualityComparer: 24ms
The first solution is, in this case, 300 times slower than the fastest one!
I prefer LINQ Union because it communicates intent very clearly.
https://alicebobandmallory.com/articles/2012/10/18/merge-collections-without-duplicates-in-c
query.Setup(q => q.Execute(It.Is<QueryRequest>(q => q.Key == key)))
.Returns(new QueryResponse {Customer = customer});
using NLog; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Web.Http.Filters; using TaxMs.DTOs; using TaxMs.Infrastructure.CustomExceptions; using TaxMs.Infrastructure.Extensions; namespace TaxMs.ApiNet.Filters { public class AlertServiceFilter : ExceptionFilterAttribute { private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public HttpStatusCode GetStatusCodeFromException(Exception exc) { if (exc is ArgumentException || exc is FileNotFoundException) return HttpStatusCode.BadRequest; if (exc is InvalidOperationException || exc is NotFoundException) return HttpStatusCode.NotFound; if (exc is FormatException) return HttpStatusCode.ExpectationFailed; return HttpStatusCode.InternalServerError; } private ListGetReasons(Exception exc) { var outList = new List (); if (exc is ArgumentException) { var currExc = exc as ArgumentException; foreach (DictionaryEntry item in currExc.Data) outList.Add(item.Value.ToString()); } else outList.Add(exc.GetInnerMostException().Message); return outList; } public override void OnException(HttpActionExecutedContext cont) { //cont.Response = new HttpResponseMessage(GetStatusCodeFromException(cont.Exception)); var a = new ExceptionStrategy(); cont.Response = new HttpResponseMessage(a.GetStatusCode(cont.Exception.GetType())); cont.Response.Content = new ObjectContent (new ErrorInfo { Date = DateTime.Now, Status = cont.Response.StatusCode.ToInt(), Reasons = GetReasons(cont.Exception), Message = cont.Exception.Message }, new JsonMediaTypeFormatter()); _logger.Error(cont.Exception, cont.Exception.Message); } } ///////////////////////////////////////////////////////////////////////////////////////////////// #region Strategy Interface public interface IHttpResponseMessageStrategy { HttpStatusCode GetStatusCode(); } #endregion #region Concrete Classes public class ExpectationFailedExceptionStrategy : IHttpResponseMessageStrategy { #region IHttpResponseMessageStrategy Members public HttpStatusCode GetStatusCode() { return HttpStatusCode.ExpectationFailed; } #endregion } public class NotFoundExceptionStrategy : IHttpResponseMessageStrategy { #region IHttpResponseMessageStrategy Members public HttpStatusCode GetStatusCode() { return HttpStatusCode.NotFound; } #endregion } public class BadRequestExceptionStrategy : IHttpResponseMessageStrategy { #region IHttpResponseMessageStrategy Members public HttpStatusCode GetStatusCode() { return HttpStatusCode.BadRequest; } #endregion } public class InternalServerErrorExceptionStrategy : IHttpResponseMessageStrategy { #region IHttpResponseMessageStrategy Members public HttpStatusCode GetStatusCode() { return HttpStatusCode.InternalServerError; } #endregion } #endregion #region Context public class ExceptionStrategy { #region Members private readonly Dictionary _strategies = new Dictionary (); #endregion #region Ctor public ExceptionStrategy() { _strategies.Add(typeof(ArgumentException), new BadRequestExceptionStrategy()); _strategies.Add(typeof(FileNotFoundException), new BadRequestExceptionStrategy()); _strategies.Add(typeof(FormatException), new ExpectationFailedExceptionStrategy()); _strategies.Add(typeof(NotFoundException), new NotFoundExceptionStrategy()); _strategies.Add(typeof(InvalidOperationException), new NotFoundExceptionStrategy()); _strategies.Add(typeof(Exception), new InternalServerErrorExceptionStrategy()); } #endregion #region Methods public HttpStatusCode GetStatusCode(Type type) { return _strategies.ContainsKey(type) ? _strategies[type].GetStatusCode() : _strategies[typeof(Exception)].GetStatusCode(); } #endregion } #endregion }
using NUnit.Framework; using System; using System.Linq; using System.Net; using System.Net.Http; using TaxMs.ApiNet.Filters; using TaxMs.DTOs; using TaxMs.Infrastructure.Extensions; namespace TaxMs.ApiNet.Tests.Filters { public class AlertFilterServiceTests { public AlertServiceFilter _sut; public AlertFilterServiceTests() { _sut = new AlertServiceFilter(); } [Test] public void Should_Log_ArgumentException() { var argException = new ArgumentException("Model validation exception !"); argException.Data.Add("Mail", "Mail is required"); argException.Data.Add("Name", "Name is required"); var fakeInput = new System.Web.Http.Filters.HttpActionExecutedContext { Exception = argException, ActionContext = new System.Web.Http.Controllers.HttpActionContext(), Response = new HttpResponseMessage() }; _sut.OnException(fakeInput); var expectdInput = fakeInput.Response.Content as ObjectContent; var expectedBody = expectdInput.Value as ErrorInfo; Assert.IsNotNull(expectdInput); Assert.AreEqual(expectedBody.Status, HttpStatusCode.BadRequest.ToInt()); Assert.AreEqual(expectedBody.Reasons.Count, 2); Assert.AreEqual(expectedBody.Reasons[0], "Mail is required"); Assert.AreEqual(expectedBody.Reasons[1], "Name is required"); } [Test] public void Should_Log_Generic_Exception() { var argException = new Exception("Generic Exception"); var fakeInput = new System.Web.Http.Filters.HttpActionExecutedContext() { Exception = argException, ActionContext = new System.Web.Http.Controllers.HttpActionContext() }; fakeInput.Response = new HttpResponseMessage(); _sut.OnException(fakeInput); var expectdInput = fakeInput.Response.Content as ObjectContent ; var expectedBody = expectdInput.Value as ErrorInfo; Assert.IsNotNull(expectdInput); Assert.AreEqual(expectedBody.Status, HttpStatusCode.InternalServerError.ToInt()); Assert.AreEqual(expectedBody.Reasons.Count, 1); Assert.AreEqual(expectedBody.Reasons.First(),"Generic Exception"); } } }