Reset stored git password

To fix this on macOS, you can use

git config --global credential.helper osxkeychain

A username and password prompt will appear with your next Git action (pull, clone, push, etc.).

For Windows, it’s the same command with a different argument:

git config --global credential.helper wincred

C# Web API client Authentication with X-API-KEY

The Web API can authenticate the client through an API key with a middleware or an action filter.

Here’s how you can implement a middleware that does that:

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string ApiKeyHeaderName = "X-API-KEY";

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApiKey))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
            return;
        }

        var configuration = context.RequestServices.GetRequiredService<IConfiguration>();
        var validApiKey = configuration.GetValue<string>("ApiKey");

        if (potentialApiKey != validApiKey)
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Forbidden");
            return;
        }

        await _next(context);
    }
}

This middleware checks each incoming request for an "X-API-KEY" header. If the header is absent or the key is invalid, it rejects the request with an HTTP 401 or 403 status.

You can use this middleware in your Startup.cs like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseMiddleware<ApiKeyMiddleware>();

    // ...
}

In appsettings.json:

{
    "ApiKey": "your-valid-api-key",
    // ...
}

To Add ApiKey in Swagger:

public void ConfigureServices(IServiceCollection services)
{
    // ... other services

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

        // Define the BearerAuth scheme
        c.AddSecurityDefinition("BearerAuth", new OpenApiSecurityScheme
        {
            Description = "Input your Bearer token in the following format - Bearer {your token here}",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "BearerAuth"
        });

        c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "BearerAuth"
                    },
                    Scheme = "oauth2",
                    Name = "BearerAuth",
                    In = ParameterLocation.Header
                },
                new List<string>()
            }
        });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middleware

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");
        c.RoutePrefix = string.Empty;
    });
}

In order to receive other custom headers like X-UserName:

public class UserNameMiddleware
{
    private readonly RequestDelegate _next;
    private const string UserNameHeaderName = "X-AUTH-USERNAME";

    public UserNameMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (context.Request.Headers.TryGetValue(UserNameHeaderName, out var userName))
        {
            context.Items[UserNameHeaderName] = userName.ToString();
        }

        await _next(context);
    }
}

And then, in startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseMiddleware<UserNameMiddleware>();

    // ...
}

Access SQL queries Generated By Entity Framework Core 3

Create a class EntityFrameworkSqlLogger.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Extensions.Logging;

namespace MyApp.Logging
{
    /// <summary>
    /// ILogger implementation
    /// </summary>
    public class EntityFrameworkSqlLogger : ILogger
    {
        #region Fields
        Action<EntityFrameworkSqlLogMessage> _logMessage;
        #endregion

        #region Constructor
        public EntityFrameworkSqlLogger(Action<EntityFrameworkSqlLogMessage> logMessage)
        {
            _logMessage = logMessage;
        }
        #endregion

        #region Implementation
        public IDisposable BeginScope<TState>(TState state)
        {
            return default;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (eventId.Id != 20101)
            {
                //Filter messages that aren't relevant.
                //There may be other types of messages that are relevant for other database platforms...

                return;
            }

            if (state is IReadOnlyList<KeyValuePair<string, object>> keyValuePairList)
            {
                var entityFrameworkSqlLogMessage = new EntityFrameworkSqlLogMessage
                (
                    eventId,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "commandText").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "parameters").Value,
                    (CommandType)keyValuePairList.FirstOrDefault(k => k.Key == "commandType").Value,
                    (int)keyValuePairList.FirstOrDefault(k => k.Key == "commandTimeout").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "elapsed").Value
                );

                _logMessage(entityFrameworkSqlLogMessage);
            }
        }
        #endregion
    }
    
    /// <summary>
    /// Data model
    /// </summary>
    public class EntityFrameworkSqlLogMessage
    {
        public EntityFrameworkSqlLogMessage(
            EventId eventId,
            string commandText,
            string parameters,
            CommandType commandType,
            int commandTimeout,
            string elapsed
        )
        {
            EventId = eventId;
            CommandText = commandText;
            Parameters = parameters;
            CommandType = commandType;
            Elapsed = elapsed;
            CommandTimeout = commandTimeout;
        }

        public string Elapsed { get; }
        public int CommandTimeout { get; }
        public EventId EventId { get; }
        public string CommandText { get; }
        public string Parameters { get; }
        public CommandType CommandType { get; }
    }
    
    /// <summary>
    /// ILogger provider
    /// </summary>
    public class SingletonLoggerProvider : ILoggerProvider
    {
        #region Fields
        ILogger _logger;
        #endregion

        #region Constructor
        public SingletonLoggerProvider(ILogger logger)
        {
            _logger = logger;
        }
        #endregion

        #region Implementation
        public ILogger CreateLogger(string categoryName)
        {
            return _logger;
        }

        public void Dispose()
        {
        }
        #endregion
    }
}

Add Logger to DbContext OnConfiguring Met

public class CartServiceDbContext : DbContext
{
...

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
      var entityFrameworkSqlLogger = new EntityFrameworkSqlLogger((m) =>
      {
          System.Console.WriteLine($"SQL Query:\r\n{m.CommandText}\r\nElapsed:{m.Elapsed} millisecods\r\n\r\n");
      });

      var myLoggerFactory = LoggerFactory.Create(builder =>
      {
          builder
              .AddFilter((category, level) =>
                  category == DbLoggerCategory.Database.Command.Name
                  && level == LogLevel.Information);
      });

      myLoggerFactory.AddProvider(new SingletonLoggerProvider(entityFrameworkSqlLogger));
      optionsBuilder.UseLoggerFactory(myLoggerFactory);
      DbConnectorUtils.ConfigureOptionsBuilder(optionsBuilder);
  }

...
}

References

ssh Github

Mac from Terminal

ssh-keygen -t ed25519 -C "yourmail@domain.com"

output:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/<xxxxx>/.ssh/<yyyy>): /Users/<xxxxx>/.ssh/github_id 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/<xxxxx>/.ssh/github_id
Your public key has been saved in /Users/<xxxxx>/.ssh/github_id.pub
The key fingerprint is:
.....
The key's randomart image is:
+--[ED25519 256]--+
|    ..   .=..    |
|     .o  ..S..   |
|     ..  ..o. . .|
|  . o. ..o . . o |
|   =+...S = . +  |
|  oS.++  o + .   |
|    o+.+    . o  |
|      o..    . . |
|       o..E      |
+----[SHA256]-----+

go to https://github.com/settings/keys

click to New SSH Key

write a title, select Authentication Key, copy content of <yyyy>.pub file to the Key area

Serilog

            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" 
    }
  }

Useful GitHub Repos for developers

Useful Resources for Front-End Developers

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

Useful Resources for Front-End Developers

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.

https://github.com/kamranahmedse/developer-roadmap

Generic method with reflection

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);

Merge collections without duplicates in C#

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 UnionWithmethod 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