Docker commands

Pull down the SQL Server Docker Image from DockerHub
docker pull microsoft/mssql-server-linux:2017-latest

Create a Docker container using the microsoft/mssql-server-linux:2017-latest
Automatically accept the EULA, set the password to for the sa user, and map port container port 1433 to host port 1433
docker run --name sql \
-e 'ACCEPT_EULA=Y' \
-e 'SA_PASSWORD=' \
-p 1433:1433 \
-d microsoft/mssql-server-linux:2017-latest

Check if the container is up (running) – in STATUS column
sudo docker ps -a

To stop the container (assuming its name is “sql”) just type
docker stop sql
Now, typing sudo docker ps -a the container STATUS is Exited

To restart the container just type
docker start sql

Test the connection with Azure Data Studio or SQLPro for MSSQL

Here there is a Microsoft Reference Guide on Docker

Deletes pulled images with IMAGE ID 810001cb03af
docker images | grep 810001cb03af | awk '{print $1 ":" $2}' | xargs docker rmi

Existing SQL Server

Generating a model from an existing database .Net Core 2.0

In a folder that will contain your demo project type the following command:
dotnet new console for a console application or dotnet new mvc for a MVC or Web API application

Add the Entity Framework Core and Tools packages to the project:
This is the EF Core provider for SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

This package contains the Entity Framework Core commands. Both of these packages are required for any Entity Framework Core application that targets SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.Tools

The final package is required for supporting the scaffolding of the model.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design

Test if Entity Framework is available
dotnet ef -h

Now use the DbContext Scaffold command to generate the model passing two arguments:

  • a connection string
  • a provider

dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorks;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

dotnet ef dbcontext scaffold "Server=localhost,1433\\Catalog=AdventureWorks;Database=AdventureWorks;User=SA;Password=;" Microsoft.EntityFrameworkCore.SqlServer -o Models

Once you have executed the command, you will see that a folder named Models has been created in the project folder, containing a collection of class files representing the entities.
You can find also a class file containing the DbContext class.
The DbContext class will take the name of the database plus “Context”.
You can override this using the -c or –context option e.g.
dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -c "AdventureContext"

Singleton

<p><code style="display:block;white-space:pre-wrap">
using System;

namespace SingletonPatternEx
{
    public sealed class Singleton
    {
        private static readonly Singleton instance=new Singleton();
        private int numberOfInstances = 0;
        //Private constructor is used to prevent
        //creation of instances with 'new' keyword outside this class
        private Singleton()
        {
         Console.WriteLine("Instantiating inside the private constructor.");
         numberOfInstances++;
         Console.WriteLine("Number of instances ={0}", numberOfInstances);
        }
        public static Singleton Instance
        {
            get
            {
                Console.WriteLine("We already have an instance now.Use it.");
               return instance;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)                                                                                              
        {
            Console.WriteLine("***Singleton Pattern Demo***\n");
            //Console.WriteLine(Singleton.MyInt);
            // Private Constructor.So,we cannot use 'new' keyword.            
            Console.WriteLine("Trying to create instance s1.");
            Singleton s1 = Singleton.Instance;
            Console.WriteLine("Trying to create instance s2.");
            Singleton s2 = Singleton.Instance;
            if (s1 == s2)
            {
                Console.WriteLine("Only one instance exists.");
            }
            else
            {
                Console.WriteLine("Different instances exist.");
            }
            Console.Read();
        }
    }
}
</code></p>

Prototype

<p><code style="display:block;white-space:pre-wrap">
//BasicCar.cs
using System;

namespace PrototypePattern
{
   public abstract class BasicCar
    {
        public string ModelName{get;set;}
        public int Price {get; set;}
        public static int SetPrice()
        {
            int price = 0;
            Random r = new Random();
            int p = r.Next(200000, 500000);
            price = p;
            return price;
        }
        public abstract BasicCar Clone();
    }
}
//Nano.cs
using System;

namespace PrototypePattern
{
    public class Nano:BasicCar
    {
        public Nano(string m)
        {
            ModelName = m;
        }

        public override BasicCar Clone()
        {
            return (Nano) this.MemberwiseClone();//shallow Clone
        }
    }
}
//Ford.cs

using System;

namespace PrototypePattern
{
    public class Ford:BasicCar
    {
        public Ford(string m)
        {
            ModelName = m;
        }

        public override BasicCar Clone()
        {
            return (Ford)this.MemberwiseClone();
        }
    }
}

//Client

using System;

namespace PrototypePattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***Prototype Pattern Demo***\n");
            //Base or Original Copy
            BasicCar nano_base = new Nano("Green Nano") {Price = 100000};
            BasicCar ford_base = new Ford("Ford Yellow") {Price = 500000};
            BasicCar bc1;
            //Nano
            bc1 = nano_base.Clone();
            bc1.Price = nano_base.Price+BasicCar.SetPrice();
            Console.WriteLine("Car is: {0}, and it's price is Rs. {1} ",bc1.ModelName,bc1.Price);

            //Ford            
            bc1 = ford_base.Clone();
            bc1.Price = ford_base.Price+BasicCar.SetPrice();
            Console.WriteLine("Car is: {0}, and it's price is Rs. {1}", bc1.ModelName, bc1.Price);

            Console.ReadLine();
        }
    }
}
</code></p>

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