Navigation

Tuesday 27 September 2016

Create Window C# Application Using Mongo Database

Step 1: Install Mongo DB and Robomongo

             https://docs.mongodb.com/manual/installation/
             https://robomongo.org/

Step 2: To run Mongo DB use following steps.

    •  Open command prompt(Administrator)
      • Go to MongoDb/Bin folder.
      •  and Run this code 'mongod --dbpath C:\mongodb\data --port 27017

    • When 27017 is allotted to  mongodb it shows like this.


    • Now open your robomongo and create new connections with mongodb by filling follwing information.
      • Click on Create link you will get a popup of "Connection setting"
      • And fill Address  and port as an example given on the image. 
      • To test connection click on test button given on popup.





 Step 3: After starting MongoDB database, create a window application 'WinAppWithMongo' to connect your application with MongoDB.
             Add following Package from NuGet Package.

  • MongoDB.Bson
  • MongoDB.Driver
  • MongoDb.Driver.Core
  • MongoDB.Driver.GridFS
  • Mongocsharpdriver         
And do not forget to add reference of these dll. If they are not working.                

    • Form1 layout is like this.


    • And code on behing to connect application are :

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

namespace WinAppWithMongo
{
    public partial class Form1 : Form
    {
        const string connectionString = "mongodb://localhost:27017";

        public Form1()
        {

            InitializeComponent();
            fnbindGrid();


        }
       
       // Binding records in grid
        private void fnbindGrid()
        {
            // Create a MongoClient object by using the connection string
            var client = new MongoClient(connectionString);
            //Use the MongoClient to access the server
            MongoServer server = client.GetServer();
            server.Connect();

            // Use the server to access the 'test' database
            MongoDatabase database = server.GetDatabase("WISH");

            //Builds new Collection if 'entities' is not found
            MongoCollection<Employee> collection = database.GetCollection<Employee>("Employee");

            MongoCursor<Employee> members = collection.FindAll();
            List<Employee> emp = new List<Employee>();
            foreach (Employee item in members)
            {
                emp.Add(new Employee() { EmpId = item.EmpId, FName = item.FName, LName = item.LName });
            }
            dataGridView1.DataSource = emp.ToList();
            dataGridView1.Columns["id"].Visible = false;
            server.Disconnect();

        }

       // Add employees record 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // Create a MongoClient object by using the connection string
            var client = new MongoClient(connectionString);

           //Use the MongoClient to access the server
            MongoServer server = client.GetServer();
            server.Connect();
            // Use the server to access the 'test' database

            MongoDatabase database = server.GetDatabase("WISH");

            //Builds new Collection if 'entities' is not found
            MongoCollection<Employee> collection = database.GetCollection<Employee>("Employee");
            if (!string.IsNullOrEmpty(txtEmpId.Text))
            {
                var user = new Employee
                {
                    EmpId = Convert.ToInt32(txtEmpId.Text),
                    FName = txtFirstName.Text,
                    LName = txtLastName.Text,
                };
                collection.Insert(user);
            }
            server.Disconnect();
            fnbindGrid();
        }

     // Update employees record by EmpId
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            var client = new MongoClient(connectionString);

            MongoServer server = client.GetServer();
            server.Connect();
           
            MongoDatabase database = server.GetDatabase("WISH");
           
            MongoCollection<Employee> collection = database.GetCollection<Employee>("Employee");
            if (!string.IsNullOrEmpty(txtEmpId.Text))
            {               
                var query = Query.EQ("EmpId", Convert.ToInt32(txtEmpId.Text));
                var update = Update<Employee>.
                  Set(p => p.FName, txtFirstName.Text).
                  Set(p => p.LName, txtLastName.Text);
                  collection.Update(query,update);                
            }
            server.Disconnect();
            fnbindGrid();
        }
        
        class Employee
        {
            public ObjectId id { get; set; }
            public int EmpId { get; set; }
            public string FName { get; set; }
            public string LName { get; set; }
        }
     
       //Select employees record by EmpId
        private void txtEmpId_TextChanged(object sender, EventArgs e)
        {
            var client = new MongoClient(connectionString);
            MongoServer server = client.GetServer();
            server.Connect();
          
            MongoDatabase database = server.GetDatabase("WISH");
           
            MongoCollection<Employee> collection = database.GetCollection<Employee>("Employee");
            var query_id = Query.EQ("EmpId", Int32.Parse(txtEmpId.Text));
            MongoCursor<Employee> members = collection.Find(query_id);
            List<Employee> emp = new List<Employee>();
            foreach (Employee item in members)
            {
                emp.Add(new Employee() { EmpId = item.EmpId, FName = item.FName, LName = item.LName });
            }
            if (emp.Count > 0)
            {
                txtEmpId.Text = emp[0].EmpId.ToString();
                txtFirstName.Text = emp[0].FName;
                txtLastName.Text = emp[0].LName;
            }
            else
            {
                txtFirstName.Text = "";
                txtLastName.Text = "";
            }
            server.Disconnect();
            fnbindGrid();
        }

        //Delete employees record by EmpId
        private void btnDelete_Click(object sender, EventArgs e)
        {
            var client = new MongoClient(connectionString);
            MongoServer server = client.GetServer();
            server.Connect();
          
            MongoDatabase database = server.GetDatabase("WISH");
         
            MongoCollection<Employee> collection = database.GetCollection<Employee>("Employee");
            if (!string.IsNullOrEmpty(txtEmpId.Text))
            {               
                var query = Query.EQ("EmpId", Convert.ToInt32(txtEmpId.Text));                
                collection.Remove(query);
            }
            server.Disconnect();
            fnbindGrid();
        }
    }
}







2 comments:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time mongodb online training

    ReplyDelete