Thursday, November 20, 2014

Retrieving Records from MongoDb and Displaying in GridView

We earlier discussed about Inserting the records to mongoDB via C#.
now the Next Step in the CRUD cycle is Read the data from MongoDb and Flash it on the UI screen.
This is how I did :

Drag and Drop the Gridview control and apply the styles which suites your website screen design


Create Connection like Before :
MongoClient monClient = new MongoClient("mongodb://localhost");
MongoServer ms = monClient.GetServer();



ms.Connect();
 
MongoDatabase db = ms.GetDatabase("testdb");
MongoCollection collection = db.GetCollection<Tasks>("Tasks");
Tasks tsk = new Tasks();

Query the collection and Convert to List
 
var ShowTasks = collection.FindAllAs<Tasks>().ToList<Tasks>();

Set the List as Data source
gvShowTasks.DataSource = ShowTasks;

Binds the Grid

gvShowTasks.DataBind();

Run the Solution.(f5) Bammmm!!! you see that
 

Tuesday, November 11, 2014

Inserting to MongoDB from C#

I have always been a technology enthusiast and like to implement New things .
When I was introduced to mongo DB, an opensource database tool , I wondered how do I perform basic operations thru .Net .
Hence I created a simple application  .
Note : Mongo DB is NoSQL database and not Relational Database Like MSSQL or Oracle.

How I did it .

1.       Add MongoDb Dll Reference.
using MongoDB.Bson;
1.       using MongoDB.Driver;
2.       In the Button Click Event Create Mongo Connection
MongoClient monClient = new MongoClient("mongodb://localhost");
3.       Get Database name
       MongoServer ms = monClient.GetServer();
       ms.Connect();
MongoDatabase db = ms.GetDatabase("testdb");

Get Collections(tables)
MongoCollection collection = db.GetCollection<NewProjects>("Projects");

Add a new class similar to the structure u want the schema to be
public class NewProjects
{
       public NewProjects()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    public string ProjectName { get; set; }
    public string ServiceName { get; set; }
    public string DescriptionName { get; set; }

}

Assign Values to each field (Binding the values from Front End )
NewProjects proj=new NewProjects();
              proj.ProjectName=txtProjName.Text;
              proj.ServiceName=txtServiceName.Text;
       proj.DescriptionName=txtdesc.Text;

Finally Hit Insert Command
collection.Insert(proj);

View the Result in the backend database


Observe that Unique ID  is automatically Created .

Values Passed from Front End





PS: I know you may find it little strange to read Json like Documents(records) because Mongodb stores it in json format . so I have  converted these documents from Json like structure to Table format

Here we go




This application was build with Bootstrap JS