Showing posts with label C#. Show all posts

Up and running Mongodb with C#

Following is the step for up and running Mongodb with C#

Download the Mongodb package from here

Mongodb package come with binary executable and msi (Microsoft Installer) in 32bit and 64bit version. I would prefer to use 64bit msi version if your OS is capable of.Here is the url to download from.

Running mongod instance server

After installing your package to run mongodb instance server open a command prompt window and execute command mongod -dbpath="<your database storage path>". To test every thing is OK run a mongo client executable from command prompt to connect with running server. Use this command below like that mongo. mongo client automatically connect to the localhost server with default port 27017.  To know more about the mongod and mongo command use -help argument.
Here is the output generated by mongod command on my machine


And output generated by mongo client


After executing mongod command it create some files and allocate few space on disk for data storage. Open a visual studio editor and create a new console project. To install mongodb official drivers using nuget package manager console and type the following command into the console PM> Install-Package mongocsharpdriver It will install the most recent driver for you. If you are interested in particular version of driver use -version command argument to specify in nuget command.

Lets write the first code to connect to our mongodb server

namespace MongoFirst
{
    using MongoDB.Bson;
    using MongoDB.Driver;
    using System;

    public class Program
    {
        static void Main(string[] args)
        {
            // create a client object
            MongoClient client = new MongoClient("mongodb://localhost:27017/"); // mongodb connection string
            // create a server object
            MongoServer server = client.GetServer();
            // create a database object with database name "test"
            MongoDatabase db = server.GetDatabase("test");
            // get collection object cars from test database
            MongoCollection cars = db.GetCollection("cars");
            // insert documents
            cars.Save(new Cars { Name = "Mongodb" });
            cars.Save(new Cars { Name = "Oracle" });

            // loop throug each item in cars collection
            foreach (var car in cars.FindAllAs())
            {
                Console.WriteLine("Database : {0}", car.Name);
            }

            Console.ReadKey();
        }
    }

    public class Cars
    {
        // a collection always have a field '_id' in mongodb, 
        // you can also use different type rather that ObjectId here
        public ObjectId Id { get; set; } 
        public string Name { get; set; }
    }
}
You can also specify mongodb database name in connection string. For more details about the mongodb connection string visit here

What is 'await' looking for !

The way of running asynchronous operation from C# 5.0 is now has dramatic changes. Specifically there are two new operators async and await introduce by C# 5.0 language to support linear asynchronous programming model.

async

operator use as a modifier to specify that a method, lambda expression, or anonymous method is asynchronous.If you use this modifier on a method or expression, it's referred to as an asynchronous method.

await

operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

We are going to look into the internals of how await operator works,
C# code uses await operator,
public async void DoSomething()
{
    string result = await obj.GetResultAsync(); // return immediately to calling code
    Console.WriteLine(result); // execution continue from here once above work completed 
}
A pseudo code generated by compiler is give below, When an await operator encounter by compiler.
public async void DoSomething()
{
    // obj - any object that have GetAwaiter method with appropriate return type
    var temp = obj.GetAwaiter(); 
    if (!temp.IsCompleted)
    {
        SAVE_STATE()
        temp.OnCompleted(&cont);
        return;
        cont:
        RESTORE_STATE()
        result = temp.GetResult();
        Console.WriteLine(result); // code below await expression
    }
}
snippet taken from (http://stackoverflow.com/questions/12661348/custom-awaitables-for-dummies)

Here program try to get the awaiter instance from the asynchronous method. This instance temp has an IsCompleted boolean property member which is use to determine if asynchronous task execution completes. If it return false the program store the current machine state and inject an Action (&cont) delegate by using OnCompleted() method of the awaiter instance. Note that this method is part of INotifyCompletion interface. Once the blocking operation execution completes program restore the machine state and get output result by calling GetResult() on awaiter instance. Further program continue below the await statement where its left control.

Condition that compiler check when we use await operator

  1. It check if the return type of await expression does have GetAwaiter() method. This method can also be a extension method for the instance type.
  2. GetAwaiter() must return type that have boolean type property IsCompleted.
  3. Return type of GetAwaiter() must implement INotifyCompletion interface.
  4. Return type of GetAwaiter() must have GetResult() method that return instance of expected type by await expression