WebsiteSpark

Monday 2 July 2012

Interfacing with MongoDB using C#

Requirements:
1)      MongoDB installable
2)      MongoDB C# driver
3)      VS.Net 2008 / 2010.
Before we begin:
1)      Install MongoDB as per the instruction given on the MongoDB website.
a.       For development version, just download the .zip file, extract to specific folder
b.      Crete a folder with name “Data” and a subfolder with name “DB” like in “d:\ Data\DB”
c.       Open a command prompt, navigate to the MongoDB folder with extracted MongoDB binaries and start MongoDB using the command “D:\MongoDB\bin\mongod.exe --dbpath "D:\MongoDB\Data\DB"” if in case DBPath happens to be “C:\ Data\DB” then the command “D:\MongoDB\bin\mongod.exe” is enough to start the database.
2)      Installation of MongoDB driver
a.       Download the C# drivers from website.
b.      Extract the binaries (optionally including source).

Start visual studio 2010, add a new windows application project, with few text boxes, a grid and a command button to specify the values and operate upon the items. Name the controls appropriately.

Figure 1 : VS2010 win form application
Add a new class, let’s call this Entity, the definition of the class is as follows.


namespace MongoDB
{
    class Entity
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
        public string Prop4 { get; set; }
        public string Prop5 { get; set; }
        public Bson.BsonObjectId  _id { get; set; }
    }
}



Following code helps in setting the stage for getting connected to MongoDB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace MongoDB
{
    public partial class frmMain : Form
    {

        private const string mongoConnStr = "mongodb://localhost/?safe=true";
        private MongoCollection<Entity> collection;
        private Entity _entity; // selected entity

        private void frmMain_Load(object sender, EventArgs e)
        {
            var server = MongoServer.Create(mongoConnStr);
            var database = server.GetDatabase("test");
            if (!database.CollectionExists("entities"))
            {
                database.CreateCollection("entities");
            }
            collection = database.GetCollection<Entity>("entities");

            PopulcateGrid();

        }

        void PopulcateGrid()
        {
            List<Entity> list = collection.FindAllAs<Entity>().ToList();
            dg.DataSource = list;
            Clear();
        }

        void Clear()
        {
            _entity = null;
            txt1.Text = string.Empty;
            txt2.Text = string.Empty;
            txt3.Text = string.Empty;
            txt4.Text = string.Empty;
            txt5.Text = string.Empty;

        }
        }
}


Here what we have done is declared a mongo connection string as “mongodb://localhost/?safe=true”, created a mongo Server using the mentioned connection string and finally pointed to the “test” database on the server and “entities” collection within the database. All these happens within the form_Load event of the main form.
The form_Load first checks for the existence of the “entities” collection within the database, if not then it creates a new collection by the name “entities”. The PopulcateGrid() function and  Clear() functions are straight forward, used to populated the grid and initialize the controls.
The grid_Click event uses the search function to identify the selected entity and populate the respective values into the text boxes.

        private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // ground work for updation
           
            if (e.RowIndex < 0) return;

            List<Entity> list = dg.DataSource as List<Entity>;
            _entity = list[e.RowIndex];

            txt1.Text = _entity.Prop1;
            txt2.Text = _entity.Prop2;
            txt3.Text = _entity.Prop3;
            txt4.Text = _entity.Prop4;
            txt5.Text = _entity.Prop5;

        }



Double click event on the grid deletes the selected entity from the collection and database and refreshes the grid. Selection of entity item is based on _id of the entity through IMongoQuery object, created using static method Query.EQ.

        private void dg_CellContentDblClick(object sender, DataGridViewCellEventArgs e)
        {

            //delete
            if (e.RowIndex < 0) return;

            List<Entity> list = dg.DataSource as List<Entity>;
            Entity item = list[e.RowIndex];

            IMongoQuery query = Query.EQ("_id", item._id);
            collection.Remove(query);

            PopulcateGrid();
        }



Insert and update is handled by the Insert / update command button, depending upon the state of the _entity private object (set by single clicking a row on the grid).

            // insert / update

            if (_entity == null)
            {
                _entity = new Entity()
                              {
                                  Prop1 = txt1.Text,
                                  Prop2 = txt2.Text,
                                  Prop3 = txt3.Text,
                                  Prop4 = txt4.Text,
                                  Prop5 = txt5.Text
                              };
                collection.Insert(_entity);
            }

            else // update
            {
                _entity.Prop1 = txt1.Text;
                _entity.Prop2 = txt2.Text;
                _entity.Prop3 = txt3.Text;
                _entity.Prop4 = txt4.Text;
                _entity.Prop5 = txt5.Text;

                IMongoQuery query = Query.EQ("_id", _entity._id);
                IMongoUpdate update = MongoDB.Driver.Builders.Update
                    .Set("Prop1", _entity.Prop1)
                    .Set("Prop2", _entity.Prop2)
                    .Set("Prop3", _entity.Prop3)
                    .Set("Prop4", _entity.Prop4)
                    .Set("Prop5", _entity.Prop5);

                collection.Update(query,update);

            }




The entire code for the windows form is printed below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Driver.Builders;


namespace MongoDB
{
    public partial class frmMain : Form
    {
        private const string mongoConnStr = "mongodb://localhost/?safe=true";
        private MongoCollection<Entity> collection;
        private Entity _entity; // selected entity
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            // insert / update

            if (_entity == null)
            {
                _entity = new Entity()
                              {
                                  Prop1 = txt1.Text,
                                  Prop2 = txt2.Text,
                                  Prop3 = txt3.Text,
                                  Prop4 = txt4.Text,
                                  Prop5 = txt5.Text
                              };
                collection.Insert(_entity);
            }
            else
            {
                _entity.Prop1 = txt1.Text;
                _entity.Prop2 = txt2.Text;
                _entity.Prop3 = txt3.Text;
                _entity.Prop4 = txt4.Text;
                _entity.Prop5 = txt5.Text;

                IMongoQuery query = Query.EQ("_id", _entity._id);
                IMongoUpdate update = MongoDB.Driver.Builders.Update
                    .Set("Prop1", _entity.Prop1)
                    .Set("Prop2", _entity.Prop2)
                    .Set("Prop3", _entity.Prop3)
                    .Set("Prop4", _entity.Prop4)
                    .Set("Prop5", _entity.Prop5);

                collection.Update(query,update);

            }

            PopulcateGrid();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            var server = MongoServer.Create(mongoConnStr);
            var database = server.GetDatabase("test");
            if (!database.CollectionExists("entities"))
            {
                database.CreateCollection("entities");
            }
            collection = database.GetCollection<Entity>("entities");

            PopulcateGrid();

        }

        private void dg_CellContentDblClick(object sender, DataGridViewCellEventArgs e)
        {

            //delete
            if (e.RowIndex < 0) return;

            List<Entity> list = dg.DataSource as List<Entity>;
            Entity item = list[e.RowIndex];

            IMongoQuery query = Query.EQ("_id", item._id);

            collection.Remove(query);

            PopulcateGrid();

        }


        void Clear()
        {
            _entity = null;
            txt1.Text = string.Empty;
            txt2.Text = string.Empty;
            txt3.Text = string.Empty;
            txt4.Text = string.Empty;
            txt5.Text = string.Empty;

        }

        void PopulcateGrid()
        {
            List<Entity> list = collection.FindAllAs<Entity>().ToList();
            dg.DataSource = list;
            Clear();
        }

        private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // ground work for updation
           
            if (e.RowIndex < 0) return;

            List<Entity> list = dg.DataSource as List<Entity>;
            _entity = list[e.RowIndex];

            txt1.Text = _entity.Prop1;
            txt2.Text = _entity.Prop2;
            txt3.Text = _entity.Prop3;
            txt4.Text = _entity.Prop4;
            txt5.Text = _entity.Prop5;

        }
    }
}


 Enjoy!!!