Sunday, March 8, 2015

MongoDb With C Sharp

This post is related with the post that I put few months ago, If you don't have already configured Mongodb on the machine Here is the post that I put

Big question ?? How we use Mongo With C#? Is it hard?

Its really easy to use Mongo in .NET ,

Here im going to create Asp.NET Web API project for demonstration. (You can use any type of project )

Then Install official MongoDb Driver for .NET it name as MongoCsharpDriver Nuget package














Here is screenshot of my Mongo Database and document that I'm going to use


Here is the class I created for mongo operations


using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MongoDb.Models.MongoModels
{
    public class MongoConnection
    {
        private MongoServer _ServerConnection { getset; }
        public MongoDatabase _Database { getset; }
        public string _ConnectionString { get { return "Server=localhost:27017"; } }
        public MongoConnection()
        {
            MongoClient client = new MongoClient(_ConnectionString);
            this._ServerConnection = client.GetServer();
            ////////////////////Old way of create server////////////////////
            //this._ServerConnection=MongoServer.Create(_ConnectionString);
 
            //Set the database 
            this._Database = _ServerConnection.GetDatabase("DocumentOrDb");
        }
 
        /// <summary>
        /// Get all data in the document
        /// </summary>
        /// <returns></returns>
        public MongoCursor<BsonDocument> GetAllUserdata()
        {
            return _Database.GetCollection<BsonDocument>("UserDetails").FindAll();
        }
 
        /// <summary>
        /// Insert Item
        /// </summary>
        /// <param name="name"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public BsonDocument Insert(string name, string address)
        {
            MongoCollection<BsonDocument> UserDetails = _Database.GetCollection<BsonDocument>("UserDetails");
 
            BsonDocument NewRecord = new BsonDocument()
            {
               { "Name",name},
               {"Address",address}
            };
 
            UserDetails.Insert(NewRecord);
            //return last inserted element 
            return UserDetails.FindAll().Last();
        }
    }
 
}

**This code is use latest standards of official mongo driver up to today 
Then use this class with the code. That's It

Enjoy :)









Full Code 
http://bit.ly/MongoCSharp

Thursday, March 5, 2015

First SignalR Codes

Lets start SignalR with hands on ,

Not like usual chat demos in SignalR , We are going to make counter application which displays number of connected nodes to the web

1. Create New empty ASP.Net web project with visual studio
2. The install following Nuget on the Application
   Microsoft.AspNet.SignalR
 After Installing SignalR Your solution automatically get the Scripts for signal R














3. Add Hub Class to the solution by Add -> New Item -> SignalR Hub Class(v2)
Name it as CountHub 








4. Then Modify the CountHub with following code
[HubName("hithub")]
   public class CountHub : Hub
   {
       public static int count = 0;
 
       /// <summary>
       /// Once user open window with this URL hitter called 
       /// </summary>
       public void Hitter()
       {
           count++;
           Clients.All.OnHit(count);
       }
 
       /// <summary>
       /// User disconnected OnDisconnected automatically fired 
       /// </summary>
       /// <param name="stopCalled"></param>
       /// <returns></returns>
       public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
       {
           count--;
           Clients.All.OnHit(count);
            return base.OnDisconnected(stopCalled);
       }
   }

in here HubName attribute should be start with simple letter. Otherwise it will not working

In here Client.All broadcast with all connected clients .

5. Then add Owin Start up class to build the start up with the web application Named it as StartUp



6. add Configuration for SingnalR in Startup
public void Configuration(IAppBuilder app)
       {
           app.MapSignalR();
       }

8. Now we are done with SignaR server side coding. Lets build HTML client for SignalR
Create html page in solution (default.html) and refer signalR and Jquery to the web page

<script src="Scripts/jquery-1.6.4.js"></script>
   <script src="Scripts/jquery.signalR-2.2.0.js"></script>
  
9. Then add following script after it . Comments discribes the code

<script type="text/javascript">
    $(function () {
        //Create hub connection 
        var conection = $.hubConnection();
 
        //create hub proxy 
        var hub = conection.createHubProxy("hithub");
 
        //get message with the hub proxy to latest update in count 
        hub.on("OnHit"function (count) {
            $('#count').text(count);
        });
 
        //Call hitter 
        conection.start(function()
        {
            hub.invoke('hitter')
        });
    })
</script> 
 
 
10. Modify the body of html as follows

<body>
    <h2 id="count">0</h2>
</body>
 
 

Run and enjoy,


Happy coding







Full Code 
http://bit.ly/1G1YOze