Thursday, October 12, 2017

C# Boxing and Unboxing

Boxing in C# means wrapping a value inside an object. Correspondingly, Unboxing is a reverse operation allowing you to extract a value from an object. Value in this case implies a variable of Value Type, not instance of any type as it is in C++ for example. Here is what boxing looks like:

int number = 9;
object obj = number;

As you can see, conversion is implicit. Well, of course, if you want you can do it explicitly:

 int number = 9;
object obj = (object)number;

Unboxing is not as as safe as boxing, that's why you have to do it explicitly:

int number = 9;
object obj = number;
int numberOuttaBox = (int)obj;

Oh, and remember to extract exactly what you previously boxed, because for some reason C# is like real strict about it. Basically what I mean is that you cannot get away with this:

int number = 9;
object obj = number;
float numberOuttaBox = (float)obj;

Such misbehaving is gonna result in getting the following exception:
System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Single'.'

In general, its very easy to bypass it, just unbox what you previously put and then cast to whatever you want either implicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (int)obj;

Or explicitly:

int number = 9;
object obj = number;
float numberOuttaBox = (float)(int)obj; // Excessive, but it's just an example.

Please keep in mind that boxing/unboxing is not casting and excessive use of this operation may severely affect overall performance.

.NET Garbage Collector



.NET got quite sophisticated garbage collector operating over so-called managed heap, which is basically just a heap combining two more specific heaps intended for small and large objects. All objects on a heap belong to certain generation. The first generation (Generation 0) is small recently created objects with shortest life expectancy, second generation (Generation 1) is what objects of generation 0 become if they manage to survive garbage collection being younger generation and finally third generation (Generation 2) is a generation for either true survivors, meaning objects of younger generations that got promoted or just large objects (over 85kB).

If you need more flexibility you can actually control your Grabage Collector behavior through static class GC.

For example, you might want to collect some certain generation:

GC.Collect(0);
GC.Collect(1);
GC.Collect(2);
GC.Collect(); // This one is gonna collect all generations.


Or you can make GC enter so-called "no GC region latency mode" which allows you to execute certain parts of your code without GC intervention:

// Specify how much may be allocated without disturbing GC
GC.TryStartNoGCRegion(48);
// Your time-critical code
GC.EndNoGCRegion();


Keep in mind that TryStartNoGCRegion accepts size per heap.There are two heaps
(for small and large objects), so total size is whatever you pass in there
multiplied by 2. In the example above, total size would be 48 * 2 = 96.

C# multithreading

C# multithreading is a pretty straightforward thingy. Here is how we spawn a thread:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.start();
        }
    }
}

using System;
using System.Threading;

namespace ConsoleApp
{
    class Dummy
    {
        public void Whatever(){}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dummy dummy = new Dummy();
            Thread thread = new Thread(dummy.Whatever());

            thread.start();
        }
    }
}

Thread class constructor accepts two types of delegate - ThreadStart and ParametrizedThreadStart. The difference between the two is that ParametrizedThreadStart allows us to pass some arbitrary object to a thread function like this:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.Start("Whatever");
        }
    }
}

If your project requires massive parallelism, it probably makes sense to try using so-called thread pool which is basically nothing more than a collection of dormant threads you can reuse.

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj)
        {
            (obj as ManualResetEvent).Set();
        }

        static void Main(string[] args)
        {
            ManualResetEvent[] events = new ManualResetEvent[2];

            for (int i = 0; i < events.Length; ++i)
            {
                events[i] = new ManualResetEvent(false);

                ThreadPool.QueueUserWorkItem(Whatever, events[i]);
            }

            WaitHandle.WaitAll(events);
        }
    }
}



Monday, October 9, 2017

Fun with C# MongoDB driver

using MongoDB.Driver;

namespace MongoDBFun
{
    class Individual
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Program
    {
        static IMongoClient _client;
        static IMongoDatabase _database;

        static void Main(string[] args)
        {
            _client = new MongoClient();
            _database = _client.GetDatabase("mydb");

            var individuals = _database.GetCollection<Individual>("individuals");

            individuals.InsertOne(new Individual {
                FirstName = "John",
                LastName = "Smith"
            });
        }
    }
}

C# delegates

A delegate is socalled reference type possessing certain qualities of C pointer, but meant for methods. Yeah, exactly, you can use a delegate to pass around a method with a compatible signature of absolutely any class. Here is what a delegate looks like:

using System;

namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate();
            BDelegate();
            CDelegate();
        }
    }
}

As you can see it doesn't care whose method it refers to or if its static or not. Also one delegate may contain other delegates. Such a delegate is called multicast delegate and it looks like this:

using System;

 namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate += BDelegate + CDelegate;
            ADelegate(); // Now ADelegate is multicast delegate
        }
    }
}

If you want, you can exclude certain delegate or delegates from multicast delegate list:

using System;

 namespace MyConsoleApp
{
    delegate void MyDelegate();

    class A
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is A");
        }
    }

    class B
    {
        public void SayYourName()
        {
            Console.WriteLine("My name is B");
        }
    }

    class C
    {
        public static void SayYourName()
        {
            Console.WriteLine("My name is C");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            MyDelegate ADelegate = a.SayYourName;
            MyDelegate BDelegate = b.SayYourName;
            MyDelegate CDelegate = C.SayYourName;

            ADelegate += BDelegate + CDelegate;
            ADelegate -= BDelegate; // BDelegate has been excluded from ADelegate list
            ADelegate();
        }
    }
}

Brief ASP.NET MVC overview

Here is what MVC controller looks like:

namespace MyApplication.Controllers
{
    public class MyController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Basically it's job is to do some stuff and then render socalled View which normally represents corresponding web page content. If you don't explicitly specify View name, View helper picks .cshtml file with the same name like the method rendering it. Normally, before rendering, that specific .cshtml file get injected into shared _layout.cshtml file representing a common frame of your site or just a piece of it related to this view in particular. For example, _layout.cshtml could contain header and footer, maybe some sorta menu, I mean, you get the idea. Now you may be wondering why your View files got .cshtml extension, its because they are combination of c# and html so to speak. In order to make it possible, ASP.NET developers invented Razor which serves as a middleman between the two.

This is implicit Razor expression:
@

This is explicit Razor expression:
@()

This is Razor code block:
@{
    // C# code only. Not meant to be rendered.
}

Unlike code block, expressions are meant to be evaluated and rendered as html.

All of the above share the same scope, meaning, for example, you can access a variable defined in code block from an expression or another block. By the way, order matters!


MongoDB fast-forward

Right into it

First of, here is how you create a new database in MongoDB:

use YOUR_DATABASE_NAME_HERE

You may be wondering why they called it "use". Well, because it's primarily intended for selecting database you wanna work with, but if such a database doesn't exist the command "use" creates it.

Now, if you wanna delete your database, you can do it this way:

db.dropDatabase()

But please, before you do, make sure you selected the right one using "use" command. If your uncertain which database you're working with, just enter "db" command  and it will show you the name of the currently selected database.

db

In case you're after different database, use "show dbs" command to see the list of all databases you possess:

show dbs

Keep in mind that newly created database won't get on that list until after you insert at least one document into it.

Documents

A document is basically MongoDB equivalent of SQL table. If you wanna create one, you can easily do it with "insert" command:

db.individuals.insert({
firstName: "John",
lastName: "Smith"
})


If you have been paying attention, you probably noticed that we used JSON to describe our document. Well, actually its a little bit more extended variety of JSON which MongoDB uses to store its documents as BSON (Binary JSON).

Now that you know how to create a document, naturally you might wanna know how to delete it. Let's start with deleting all available documents(we got just one, but imagine there are like tons of them):

db.individuals.remove()

Wait, what if we wanna remove only those whose last name is Smith? Well, thats why remove method accepts two optional arguments: deletion criteria and justOne flag. The signature looks somewhat like this:

db.individuals.remove(deletion_criteria, justOne)

Deletion criteria is simple JSON object describing what exactly you wanna remove, for example:

db.individuals.remove({lastName: "Smith"})

justOne flag, if passed, merely means that you wanna remove only the first document matching the criteria:

db.individuals.remove({lastName: "Smith"}, 1)

Collections

A collection is where you insert your documents into. Collections may be created either explicitly or implicitly. Until now we created them implicitly simply putting name of a collection in between db and insert:

db.YOUR_COLLECTION_NAME_HERE.insert()

If you wanna create a collection explicitly you need to call db.createCollection method, its signature looks like this:

db.createCollection(name, options)

Naturally, "name" is your collection name and "options" is where you put JSON object telling MongoDB what kind of a collection you want. Here you can get familiar with all the available collection options.

Ok, let's just explicitly create a collection without options:

db.createCollection("individuals")

Now, if you wanna make sure your collection exists, enter "show collections" command:

show collections