May 7, 2020

RePost Link to learning resources from Stackoverflow

https://stackoverflow.blog/2020/04/27/build-your-technical-skills-at-home-with-online-learning/?utm_source=Iterable&utm_medium=email&utm_campaign=the_overflow_newsletter

May 28, 2019

RePost: Serilog with StructureMap - ASP.Net Core 2.1


https://andydote.co.uk/2017/07/28/serilog-context-with-structuremap-and-simpleinjector/

https://carlos.mendible.com/2019/01/14/updated-step-step-serilog-asp-net-core/

https://stackify.com/serilog-tutorial-net-logging/


Required NuGet:

Serilog.AspNetCore
Serilog.Extensions.Logging
Serilog.Sinks.File

Example of Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                            .Enrich.FromLogContext()
                            .MinimumLevel.Error()
                            .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day,rollOnFileSizeLimit:true,fileSizeLimitBytes:10000000)
                            .CreateLogger();
            try
            {
                BuildWebHost(args).Run();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseSerilog()
                .UseStartup<Startup>()
                .Build();
    }

 Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
        {
         
            ....
            return ConfigureIoc(services);
        }
public IServiceProvider ConfigureIoc(IServiceCollection services)
        {
            var container = new Container(config =>
            {
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.AssembliesAndExecutablesFromApplicationBaseDirectory();
                    _.WithDefaultConventions();
                });
                config.For<ILogger>().Use(context => Log.ForContext(context.ParentType));     
                config.Populate(services);
            });
            return container.GetInstance<IServiceProvider>();
        }

How to use:


private readonly ILogger<MyClass> _logger = null;     
        public MyClass(
            ILogger<MyClass> logger         
            )
        {
            _logger = logger; 

Apr 19, 2019

Bootstrap 4 checkbox change jquery javascript

        isCreditCardPaymentSelector: "input[name = 'IsCreditCardPayment']",
        isCreditCardPaymentIdSelector: "input[name='IsCreditCardPayment'][type='hidden']",

form.find(options.isCreditCardPaymentSelector).removeAttr('checked');        form.find(options.isCreditCardPaymentSelector).parent('label').removeClass('active');
form.find(options.isCreditCardPaymentIdSelector).val(false);

Feb 8, 2019

RePost: Git concepts

Very good point about Git architecture.

https://stackoverflow.com/questions/292357/what-is-the-difference-between-git-pull-and-git-fetch

Git was designed to support a more distributed model with no need for a central repository (though you can certainly use one if you like). Also git was designed so that the client and the "server" don't need to be online at the same time. Git was designed so that people on an unreliable link could exchange code via email, even. It is possible to work completely disconnected and burn a CD to exchange code via git.
In order to support this model git maintains a local repository with your code and also an additional local repository that mirrors the state of the remote repository. By keeping a copy of the remote repository locally, git can figure out the changes needed even when the remote repository is not reachable. Later when you need to send the changes to someone else, git can transfer them as a set of changes from a point in time known to the remote repository.
git fetch is the command that says "bring my local copy of the remote repository up to date."
git pull says "bring the changes in the remote repository to where I keep my own code."
Normally git pull does this by doing a git fetch to bring the local copy of the remote repository up to date, and then merging the changes into your own code repository and possibly your working copy.
The take away is to keep in mind that there are often at least three copies of a project on your workstation. One copy is your own repository with your own commit history. The second copy is your working copy where you are editing and building. The third copy is your local "cached" copy of a remote repository.

Dec 17, 2018

Javascript OOP - Example of inheritance with closure (module pattern)

//This is just wrapper function! Not a constructor! It's sole purpose is to provide
//closure for hiding private members. Module?
function Vehicle(type, registration){
//Private members
var defaultType = 'car';
var calcRegistration = function (registration){
return registration ? 'REG-'+registration : 'REG-UNKNOWN';
}
//(Public) Constructor
function Vehicle(type, registration){
this.Type = type || defaultType;
this.Registration = calcRegistration(registration);
}
//Public method
Vehicle.prototype.DumpData = function(){
console.log(this.Type,' ',this.Registration);
}
//object instantiation using constructor and provided params
return new Vehicle(type, registration);
}
function Bus(type, registration, passengers){
function Bus(type, registration, passengers){
//Call base constructor with params
Vehicle.call(this,type,registration);
this.Passengers = passengers;
this.Driver = "";
}
//Inherit methods from prototype of Parent
Bus.prototype = new Vehicle(type, registration, passengers);
//Revert to child constructor
Bus.prototype.constructor = Bus;
//Create new method on child prototype
//Note! Parent method DumpData is inheried/exists on child->prototype->prototoype
Bus.prototype.AssignDriver = function(){
if (this.Passengers>30)
{
this.Driver= "Jack";
}
else
{
this.Driver = "Jenny";
}
}
return new Bus(type, registration, passengers);
}

//new is not needed since Bus function is used to create instance.
var cityBus = new Bus('bus','ZZX23-1',10);
cityBus.AssignDriver();
console.log(cityBus);
var fordTransit = Vehicle('van','');
console.log(fordTransit);
fordTransit.DumpData();

Nov 6, 2018

JavaScript - How to get request url parts (segments)

 Extracting url parts:

var urlParts = window.location.pathname.split('/');
var lastSegment = urlParts.pop() || urlParts.pop();

window.location.href = window.location.pathname.replace(lastSegment, myQueryPath);

Oct 26, 2018

RePost: .NET Architecture guides - DDD, CQRS, Clean, Onion etc.



Set of really good (and free) e-books related to modern and distributed architectures:

Here is a interesting component to investigate (by the author of Automapper):



Here is a list of recommended code samples to look and digest:

Metrics:
https://www.app-metrics.io/






Oct 19, 2018

ASP.NET Core 2.1 - NuGet - Blocked by project issue - AspnetCore.App

Some NuGet packages are added by default as part of framework.

https://docs.microsoft.com/en-us/nuget/tools/package-manager-ui#updating-a-package

For example : Microsoft.ASPNetCore.App.

If you get error that you can not update them to newest version with something like:
"Blocked by project. Update SDK"
; this could help.

Opet CSPROJ file and manually add this line under <PropertyGroup>:

<RuntimeFrameworkVersion>2.1.4</RuntimeFrameworkVersion>



Oct 15, 2018

IoC - Dependecy injection - StructureMap - ASP.NET Core 2.1 - Using factory to inject all type implementations


There are different implementations of IApplicationContext:
- MyContext1
- MyContext2
Also in future we may add new implementations.
We want to use this context in generic class repository like this:

class MyRepository<T, C> : IRepository<T, C> where T : Entity<T> where C : IApplicationContext

So far everything is straightforward. Repository will know two dependencies - entity and repository.
Consumer classes will reference repository like this:

private IRepository<MyEntity, MyContext1> myRepo1;

But how to obtain instance of MyContext1 inside our MyRepository ?

We could write something like:

var context = new C();

It would work but we could not write unit tests for such class since we create explicit instance inside our method which breaks dependecy injection effort.

Alternative is quite elegant and supported by StructureMap IoC container.

First step is to explicitly scan for all instances of our context like this:

Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.WithDefaultConventions();
scan.AddAllTypesOf<IApplicationContext>();
});

Then comes the magic touch :)
We create new Factory class. 

Array of contexts is populated with all known implementations of IApplicationContext.

And lastly the requested one is selected from that list through simple generic method:

public class ApplicationContextFactory : IApplicationContextFactory

{

private readonly IApplicationContext[] _applicationContexts;

public ApplicationContextFactory(IApplicationContext[] applicationContexts)
{
_applicationContexts = applicationContexts ?? throw new ArgumentNullException(nameof(applicationContexts));

}

public IApplicationContext GetContext<T>() where T : IApplicationContext
{

return _applicationContexts.SingleOrDefault(c => c is T);

}
}

Factory is then used in our repository generic class to resolve in simple way our instance required by type that called repository:

_applicationContext = _applicationContextFactory.GetContext<C>();

Oct 5, 2018

JQuery Validation on dynamic form (ASP.NET MVC unobtrusive)

Update

Just add this line in your injected form or in success callback:

              $.validator.unobtrusive.parse("form");              

Bellow code is not needed but it may be useful for its context...

For some reason I've could only make it work on explicit input event binding.

    $(document).off('change', 'input', onInputChange);
        $(document).on('change', 'input', onInputChange);
 function onInputChange() {   
        //Manually initiate unobtrusive validation so error messages are shown
        $(this).closest("form").valid();     
    }

If you are saving using Ajax then prevent saving something like this:

    function SaveItemCallback(e) {
        e.preventDefault();
        if ($(this).closest('form').valid() === false) {
            return;
        }
 var postBody = $(this).closest('form').serialize();
        $.post(options.urlSave, postBody, function (id) {
            loadDetails(id);
        })
            .fail(function () {
                toastr.error(myErrorText);
            });

Sep 25, 2018

RePost: Naming convention - How to avoid calling everything with suffix "Manager"

https://stackoverflow.com/questions/1866794/naming-classes-how-to-avoid-calling-everything-a-whatevermanager?rq=1

Visul Studio Snippets - JavaScript revealing modul template

Here is snippet for revealing modul template explained among other here:

https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

For some reason only way to register is to create custom folder and use "Add" instead of "Import".
Bad part is that it doesn't get copied but just keeps reference to your folder.


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>JS revealing module pattern</Title>
              <Shortcut>jsmodule</Shortcut>
        </Header>
        <Snippet>
            <Declarations>           
            <Object>
                <ID>Namespace</ID>
                <Type>object</Type>
                <ToolTip>Namespace</ToolTip>
                <Default>Namespace</Default>
            </Object>
            </Declarations>
            <Code Language="CSharp">
                <![CDATA[
                    "use strict";
                    var Snt = Snt || {};
                    Snt.$Namespace$ = Snt.$Namespace$ || {};
                    Snt.$Namespace$.ViewManager = (function () {
                        var options = null;
                       
                        function init(optionsParam) {
                            if (optionsParam) {
                                $$.extend(options, optionsParam);
                            }
                        }
                        return {
                            Init : init                       
                        };
                    })();
                ]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Sep 24, 2018

Azure Cosmos Db tips (SQL)

https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sql-query
Clause FROM refers to Collection of something.
If you deal with only one collection you can replace it with special keyword:

Root

; like this:

SELECT
Root.id,
Root.description,
Root.tags,
Root.foodGroup,
Root.manufacturerName,
Root.version
FROM Root
WHERE (Root.manufacturerName = "The Coca-Cola Company" AND Root.version > 0)


Here is good practical explanation in approaching the document design vs relational design.

https://docs.microsoft.com/en-us/azure/cosmos-db/modeling-data

When to embed and when not, or when to normalize and when keep stuff denormalized.