Thursday 29 August 2013


MongoDB And Asp.Net

MongoDB is a document database that provides high performance, high availability, and easy scalability.

MongoDB is a server process that runs on Linux, Windows and OS X. It can be run both as a 32 or 64-bit application. We recommend running in 64-bit mode, since MongoDB is limited to a total data size of about 2GB for all databases in 32-bit mode.

The MongoDB process listens on port 27017 by default

MongoDB stores its data in files (default location is /data/db/), and uses memory mapped files for data management for efficiency.

Some steps to install MongoDB in your system(Description with following images)
1.       Dwonload the latest production release of MongoDB from the http://www.mongodb.org/downloads
2.       Extract the archive to C:\ by right clicking on the archive and selecting Extract All and browsing to C:\.
   

3.       Open command prompt as Administrator and  issue the following commands:
·         cd \
·         move c:\mongodb-win32-* c:\mongodb


4.       The default location for the MongoDB data directory is C:\data\db. Create this folder using the Command Prompt. Issue the following command sequence:
·         md data
·         md data\db


5.       After this steps please check your c drive



6.       To start MongoDB, execute from the Command Prompt:  c:\mongodb\bin\mongod.exe



Note: This will start the main MongoDB database server.  Depending on the security level of your system, Windows will issue a Security Alert dialog box about blocking “some features” of C:\\mongodb\bin\mongod.exe from communicating on networks. All users should select Domain networks or Private Networks, such as my home or work network and click Allow access.
See you can start it into service directly. For guidance please see the following image



7.       Connect to MongoDB using the mongo.exe shell. Open another Command Prompt and issue with the command : c:\mongodb\bin\mongo.exe        



Install and Run the MongoDB Service

Run all of the following commands in Command Prompt with “Administrative Privileges:”
1.      To install the MongoDB service:                                                      C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg –install
Modify the path to the mongod.cfg file as needed. For the --install option to succeed, you must specify a logpath setting or the --logpath run-time option.
2.      To run the MongoDB service: net start MongoDB

End of install process









Make Insert, Update, Delete and Select withe MongoDB Service using ASP.NET C#


Start visual studio 2010, add a new WebSite, with few text boxes, a gridview and a command button to specify the values and operate upon the items. Name the controls appropriately.
See for this we need to Installation of MongoDB driver
·         Download the C# drivers from website.
·         Extract the binaries (optionally including source).
Steps:
è Select “Tools” from visual studio top menu
è Library Package Manager
è Package Manager Console
è Write PM> Install-Package mongocsharpdriver
è Then press enter button to install into visual studio



You will see success information with mongo dll in you your Bin Folder

  
Now make a simple web design with asp.net, my code following below
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="border: 1px solid #CCCCCC; padding: 10px; text-align: left;">
        <asp:Label ID="Label2" runat="server" Text="Employee" CssClass="HeaderSmall"></asp:Label>
        <table cellpadding="2" cellspacing="4" style="width: 50%; margin-left: 200px;">
            <tr>
                <td style="width: 120px">
                    Employee Name
                </td>
                <td>
                    <asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtEmployeeName"
                        Display="Dynamic" ErrorMessage="*" ValidationGroup="e"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv5" runat="server" ControlToValidate="txtAge" Display="Dynamic"
                        ErrorMessage="*" ValidationGroup="e"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Address
                </td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="txtAddress"
                        Display="Dynamic" ErrorMessage="*" ValidationGroup="e"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    City
                </td>
                <td>
                    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv3" runat="server" ControlToValidate="txtCity"
                        Display="Dynamic" ErrorMessage="*" ValidationGroup="e"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Department
                </td>
                <td>
                    <asp:TextBox ID="txtDepartment" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv4" runat="server" ControlToValidate="txtDepartment"
                        Display="Dynamic" ErrorMessage="*" ValidationGroup="e"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td align="right" colspan="2">
                    <asp:Button ID="btnSubmitE" runat="server" Text="Submit" CssClass="w8-button d-blue"
                        ValidationGroup="e" OnClick="btnSubmitE_Click" />
                    <asp:Button ID="btnCancelE" runat="server" Text="Cancel" CssClass="w8-button violet"
                        CausesValidation="False" OnClick="btnCancelE_Click" />
                </td>
            </tr>
        </table>
        <asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false" Width="99%">
            <Columns>
                <asp:TemplateField ItemStyle-Width="70px">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" OnClick="btnEdit_Click" CommandArgument='<%# Eval("_id") %>'>Edit</asp:LinkButton>&nbsp;
                        <asp:LinkButton ID="btnDelete" runat="server" OnClick="btnDelete_Click" CommandArgument='<%# Eval("_id") %>'>Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" HeaderStyle-HorizontalAlign="Left" />
                <asp:BoundField DataField="Age" HeaderText="Age" HeaderStyle-HorizontalAlign="Left" />
                <asp:BoundField DataField="Address" HeaderText="Address" HeaderStyle-HorizontalAlign="Left" />
                <asp:BoundField DataField="City" HeaderText="City" HeaderStyle-HorizontalAlign="Left" />
                <asp:BoundField DataField="DepartmentName" HeaderText="Department Name" HeaderStyle-HorizontalAlign="Left" />
            </Columns>
        </asp:GridView>
        <asp:HiddenField ID="hdnEmployeeOperation" runat="server" />
    </div>
    </form>
</body>
</html>

MongoDB with c# backend code

For to use MongoDB commands in c# we have to use following namespaces
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

The common way to access a database from inside an ASP page is to:

MongoServer creates a new instance. Normally you will use one of the Create methods instead of the constructor to create instances of this class.
The MongoServer class is used to provide more control over the driver. It contains advanced ways of getting a database and pushing a sequence of operations through a single socket in order to guarantee consistency.

GetDatabase Method
You can navigate from an instance of MongoServer to an instance of MongoDatabase  using   GetDatabase methods  
è MongoDatabase GetDatabase(string databaseName)

Sample code:
string ConnectionString = "";
    MongoServer server;
    MongoDatabase myDatabase;
    protected void Page_Load(object sender, EventArgs e)
    {
        ConnectionString = "Server=localhost:27017";// ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        server = MongoServer.Create(ConnectionString);
        myDatabase = server.GetDatabase("MyDatabase");
        if (!IsPostBack)
        {
            LoadEmployee();
        }
    }


Add a new class, let’s call this Entity, the definition of the class is as follows.
public class Employees
{
    public ObjectId _id { get; set; }
    public string EmployeeName { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string DepartmentName { get; set; }
}

Following codes will help you  in setting the stage for getting connected to MongoDB
We can declare a mongo connection string as “Server=localhost:27017”, created a mongo Server using the mentioned connection string.  All these happens within the Page_Load event of the Default page.
The Page_Load first checks for the existence of the “Employees” collection within the database, if not then it creates a new collection by the name “Employees”. The PopulcateGrid() function and Clear() functions are straight forward, used to populated the grid and initialize the controls.
 Now I am not going to tell you how write codes for insert update, update delete. It’s so simple to understand if you will check the following codes below. Just Keep your constraints in MongoDB objects from methods.
using System;
using System.Linq;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

public partial class _Default : System.Web.UI.Page
{
    string ConnectionString = "";
    MongoServer server;
    MongoDatabase myDatabase;
    protected void Page_Load(object sender, EventArgs e)
    {
        ConnectionString = "Server=localhost:27017";// ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        server = MongoServer.Create(ConnectionString);
        myDatabase = server.GetDatabase("MyDatabase");
        if (!IsPostBack)
        {
            LoadEmployee();
        }
    }
    protected void btnSubmitE_Click(object sender, EventArgs e)
    {
        Employees emp = new Employees();
        if (ViewState["_id"] != "" && ViewState["_id"] != null)
            emp._id = ObjectId.Parse(ViewState["_id"].ToString());
        emp.EmployeeName = txtEmployeeName.Text;
        emp.Age = Convert.ToInt32(txtAge.Text);
        emp.Address = txtAddress.Text;
        emp.City = txtCity.Text;
        emp.DepartmentName = txtDepartment.Text;

        if (hdnEmployeeOperation.Value == "") InsertEmployee(emp);
        else UpdateEmployee(emp);
        CancelEmployee();
        LoadEmployee();
    }
    protected void btnCancelE_Click(object sender, EventArgs e)
    {
        CancelEmployee();
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        //Get the button that raised the event
        LinkButton btn = (LinkButton)sender;
        //Get the row that contains this button
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;

        //Get rowindex
        ViewState["_id"] = btn.CommandArgument;
        int rowindex = gvr.RowIndex;
        txtEmployeeName.Text = gvr.Cells[1].Text;
        txtAge.Text = gvr.Cells[2].Text;
        txtAddress.Text = gvr.Cells[3].Text;
        txtCity.Text = gvr.Cells[4].Text;
        txtDepartment.Text = gvr.Cells[5].Text;
        hdnEmployeeOperation.Value = "Update";
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //Get the button that raised the event
        LinkButton btn = (LinkButton)sender;
        //Get the row that contains this button
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;

        //Get rowindex
        ViewState["_id"] = btn.CommandArgument;
        int rowindex = gvr.RowIndex;

        DeleteEmployee(ObjectId.Parse(btn.CommandArgument));
        LoadEmployee();
        CancelEmployee();
    }




    void LoadEmployee()
    {
        try
        {
            grdEmployee.DataSource = GetEmployeeList();
            grdEmployee.DataBind();
        }
        catch (Exception) { }
    }
    void CancelEmployee()
    {
        txtAddress.Text = txtAge.Text = txtCity.Text = txtEmployeeName.Text = txtDepartment.Text = hdnEmployeeOperation.Value = "";
    }
    public void InsertEmployee(Employees emp)
    {
        MongoCollection<Employees> document = myDatabase.GetCollection<Employees>("Employees");
        BsonDocument Employee = new BsonDocument {
                {"EmployeeName",emp.EmployeeName},
                {"Age",emp.Age},
                {"Address",emp.Address},
                {"City",emp.City},
                { "DepartmentName", emp.DepartmentName } 
                };
        document.Insert(Employee);
    }
    void UpdateEmployee(Employees emp)
    {
        MongoCollection<Employees> employee = myDatabase.GetCollection<Employees>("Employees");
        IMongoQuery query = Query.EQ("_id", emp._id);
        IMongoUpdate update = MongoDB.Driver.Builders.Update
.Set("EmployeeName", emp.EmployeeName)
.Set("Age", emp.Age)
.Set("Address", emp.Address)
.Set("City", emp.City)
.Set("DepartmentName", emp.DepartmentName);
        employee.Update(query, update);
    }
    void DeleteEmployee(ObjectId _id)
    {
        MongoCollection<Employees> employee = myDatabase.GetCollection<Employees>("Employees");
        IMongoQuery query = Query.EQ("_id", _id);
        employee.Remove(query);
    }
    List<Employees> GetEmployeeList()
    {
        List<Employees> lst = new List<Employees>();
        var collection = myDatabase.GetCollection<Employees>("Employees");
        foreach (Employees memberMap in collection.FindAll())
        {
            lst.Add(memberMap);
        }
        //We can use FindAllAs() method to get Employee list
        //return collection.FindAllAs<Employee>().ToList();
        return lst;
    }


}