Hi Guys,
Today i am going tell you how to use MongoDB with ASP.NET
1. Create reference of MongoDB in c#
a. Download MongoDb from http://www.mongodb.org/downloads
b. Extract the zip file into c:\mongodb folder
c. Create another folder in c: drive with name "data"
d. Inside "data" folder create a new folder with name "db".
e. go to command prompt and execute the file c:\mongodb\mongod, this will run mongodb service.
f. run another command prompt window and execute c:\mongodb\mongo
g. Some commands
i. show dbs (To show all the databases)
ii. use [dbname] (to switch to the mentioned database) , This also creates a new database incase its not there when a collection(table) is created.
iii. db.users.insert({name:"test",age:"32",department:"Computer"});
The above command will create a table "users" in the database ([dbname]) name provided by the user.
iv. db.users.findAll()
The above command will show all the records in users table.
2. Include reference dlls in your project.
Run the command in visual studio's Package manager console.
PM> Install MongoDB-Driver
Now reference the following dll's in your project from the installed driver location.
a. MongoDB.Bson
b. MongoDB.Driver
3. Create a form
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Testmongo.aspx.cs" Inherits="MongoDBApp.Testmongo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>
<div>
Age<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtAge" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
</div>
<div>
Department<asp:TextBox ID="txtDepartment" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtDepartment" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%#Eval("_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%#Eval("age") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<%#Eval("department") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
</body>
</html>
4. Create the code
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MongoDBApp
{
public partial class Testmongo : System.Web.UI.Page
{
static MongoServer server = MongoServer.Create(ConfigurationManager.AppSettings["connectionString"]);
MongoDatabase myDB = server.GetDatabase("ritesh");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
GetData();
}
protected void SaveData()
{
MongoCollection<User> notesCollection = myDB.GetCollection<User>("users");
User newuser = new User();
newuser.name = txtName.Text;
newuser.department = txtDepartment.Text;
newuser.age = txtAge.Text;
notesCollection.Insert(newuser);
txtAge.Text = "";
txtDepartment.Text = "";
txtName.Text = "";
HiddenField1.Value = "";
}
protected void UpdateData(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
suser.name=txtName.Text;
suser.department=txtDepartment.Text;
suser.age=txtAge.Text;
Users.Save(suser);
txtAge.Text = "";
txtDepartment.Text = "";
txtName.Text = "";
HiddenField1.Value = "";
btnSave.Text = "Save";
}
protected void GetData()
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
List<User> names = new List<User>();
foreach (User u in Users.FindAll())
{
names.Add(u);
}
GridView1.DataSource = names;
GridView1.DataBind();
}
protected void GetDataByObjectId(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
txtName.Text = suser.name;
txtDepartment.Text = suser.department;
txtAge.Text = suser.age;
HiddenField1.Value = suser._id.ToString();
btnSave.Text = "Update";
}
protected void DeleteDataByObjectId(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
Users.Remove(finduserquery);
GetData();
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (btnSave.Text == "Save")
{
SaveData();
GetData();
}
else if (btnSave.Text == "Update")
{
UpdateData(HiddenField1.Value);
GetData();
}
}
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string objectid = ((Label)GridView1.Rows[e.NewSelectedIndex].FindControl("lblId")).Text;
GetDataByObjectId(objectid);
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string objectid = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text;
DeleteDataByObjectId(objectid);
}
}
}
Thanks
Ritesh Tandon
Today i am going tell you how to use MongoDB with ASP.NET
1. Create reference of MongoDB in c#
a. Download MongoDb from http://www.mongodb.org/downloads
b. Extract the zip file into c:\mongodb folder
c. Create another folder in c: drive with name "data"
d. Inside "data" folder create a new folder with name "db".
e. go to command prompt and execute the file c:\mongodb\mongod, this will run mongodb service.
f. run another command prompt window and execute c:\mongodb\mongo
g. Some commands
i. show dbs (To show all the databases)
ii. use [dbname] (to switch to the mentioned database) , This also creates a new database incase its not there when a collection(table) is created.
iii. db.users.insert({name:"test",age:"32",department:"Computer"});
The above command will create a table "users" in the database ([dbname]) name provided by the user.
iv. db.users.findAll()
The above command will show all the records in users table.
2. Include reference dlls in your project.
Run the command in visual studio's Package manager console.
PM> Install MongoDB-Driver
Now reference the following dll's in your project from the installed driver location.
a. MongoDB.Bson
b. MongoDB.Driver
3. Create a form
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Testmongo.aspx.cs" Inherits="MongoDBApp.Testmongo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>
<div>
Age<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtAge" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
</div>
<div>
Department<asp:TextBox ID="txtDepartment" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtDepartment" EnableClientScript="False" ErrorMessage="* Required"></asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%#Eval("_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%#Eval("age") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<%#Eval("department") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
</body>
</html>
4. Create the code
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MongoDBApp
{
public partial class Testmongo : System.Web.UI.Page
{
static MongoServer server = MongoServer.Create(ConfigurationManager.AppSettings["connectionString"]);
MongoDatabase myDB = server.GetDatabase("ritesh");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
GetData();
}
protected void SaveData()
{
MongoCollection<User> notesCollection = myDB.GetCollection<User>("users");
User newuser = new User();
newuser.name = txtName.Text;
newuser.department = txtDepartment.Text;
newuser.age = txtAge.Text;
notesCollection.Insert(newuser);
txtAge.Text = "";
txtDepartment.Text = "";
txtName.Text = "";
HiddenField1.Value = "";
}
protected void UpdateData(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
suser.name=txtName.Text;
suser.department=txtDepartment.Text;
suser.age=txtAge.Text;
Users.Save(suser);
txtAge.Text = "";
txtDepartment.Text = "";
txtName.Text = "";
HiddenField1.Value = "";
btnSave.Text = "Save";
}
protected void GetData()
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
List<User> names = new List<User>();
foreach (User u in Users.FindAll())
{
names.Add(u);
}
GridView1.DataSource = names;
GridView1.DataBind();
}
protected void GetDataByObjectId(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
txtName.Text = suser.name;
txtDepartment.Text = suser.department;
txtAge.Text = suser.age;
HiddenField1.Value = suser._id.ToString();
btnSave.Text = "Update";
}
protected void DeleteDataByObjectId(string _id)
{
MongoCollection<User> Users = myDB.GetCollection<User>("users");
IMongoQuery finduserquery = Query.EQ("_id", new ObjectId(_id));
User suser = Users.Find(finduserquery).FirstOrDefault();
Users.Remove(finduserquery);
GetData();
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (btnSave.Text == "Save")
{
SaveData();
GetData();
}
else if (btnSave.Text == "Update")
{
UpdateData(HiddenField1.Value);
GetData();
}
}
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string objectid = ((Label)GridView1.Rows[e.NewSelectedIndex].FindControl("lblId")).Text;
GetDataByObjectId(objectid);
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string objectid = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text;
DeleteDataByObjectId(objectid);
}
}
}
Thanks
Ritesh Tandon
No comments:
Post a Comment
Comments are welcome, Please join me on my Linked In account
http://in.linkedin.com/pub/ritesh-tandon/21/644/33b