Sunday, February 28, 2016

Mongo DB With C# API V2

Let's start and check the latest  MongoDb Driver for C# (Mongo V2).

If you are not still configured your Mongo Server yet. see this Post

If you need some guide on old MongoDb Driver V1. See this Post

New Features In V2

  •  Async Support 
  • Method Naming convention with helpful names ( SelectOne, InsertOne etc) 
  • Legacy API Support 

Here is the Db Structure and Sample Data I'm going to Use 

 DB Structure : Create Collection in Mongo Server With name of  Students

















Here is some sample Json Data for Students Collection 

/* 1 */
{
    "_id" : ObjectId("56c3206ddaa3d39f5a130bcc"),
    "StudentId" : 1,
    "Name" : "Saman kumara",
    "Address" : "Sample"
}

/* 2 */
{
    "_id" : ObjectId("56c69ed3926ffb2c80ed00bb"),
    "StudentId" : 2,
    "Name" : "Piyal kumara",
    "Address" : "adadasd"
}


1. Create New MVC Website from Visual Studio

2. Add New Class to the models called Student

public class Student
    {
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { getset; }
        public int StudentId { getset; }
        public string Name { getset; }
        public string Address { getset; }
    }
 
 
 
3. Install MongoCsharpDriver Nuget package from the Nuget
















4. Create ConnetcionString  and Database Variables for mongodb by  R-click on Project -> Properties -> Settings Add relevant values of variables.













5.  Create DbContext Class MongoDbContext 

public class MongoDbContext
    {
        public IMongoDatabase Database;
 
        public MongoDbContext()
        {
            var client = new MongoClient(Settings.Default.ConnectionString);
            Database = client.GetDatabase(Settings.Default.Database);
        }
 
        public IMongoCollection<Student> Students
        {
            get { return Database.GetCollection<Student>("Students"); }
        }
    }


Get data From Mongo

1. Add following code to the HomeController
 Create Private property of Context and initialize it

private MongoDbContext _context { getset; }
 
       public HomeController()
       {
           _context = new MongoDbContext();
       }
       // GET: Home
       public  ActionResult Index()
       {
           //Get Data from Db
           ViewBag.Data = _context.Students.AsQueryable().Select(a=>new Student { Name=a.Name,Address=a.Address ,StudentId=a.StudentId}).ToList();
           return View();
       }

2. Edit The View as following

@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
@Html.ActionLink("Create""Create")
 
 
<table class="table">
    <tr>
        <th>
            Student Id
        </th>
        <th>
            Name
        </th>
        <th>
            Address
        </th>
        <th>
 
        </th>
    </tr>
 
    @foreach (var stu in ViewBag.Data)
    {
        <tr>
            <td>
               @stu.StudentId
            </td>
            <td>
                @stu.Name
                
            </td>
            <td>
               @stu.Address
            </td>
            <td>
                @Html.ActionLink("Edit""Edit"new { id = @stu.StudentId }) | 
                @Html.ActionLink("Delete""Delete"new { id = @stu.StudentId }) 
            </td>
        </tr>
    }
 
</table>


3. Run and see the result ..

Add Documents


Here is sample async code for insert element to the Mongo Context

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Create([Bind(Include = "StudentId,Name,Address")] Student student)
       {
           try
           {
               //Insert one item 
               await _context.Students.InsertOneAsync(student);
               return View();
 
           }
           catch (Exception)
           {
               return View(student);
           }
 
       }
 

Filter Elements

private Student GetStudent(int id)
        {
            //Filter element
            var std = _context.Students
                .Find(r => r.StudentId == id)
                .FirstOrDefault();
            return std;
        }


Update Or Replace Element 

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Edit([Bind(Include = "id,StudentId,Name,Address")] Student student)
       {
           //Full update /replace
           // await _context.Students.ReplaceOneAsync(r => r.StudentId == student.StudentId, student);
          
           //Partial Update
           var update = Builders<Student>.Update.Set(s => s.Name, student.Name);
           await _context.Students.UpdateOneAsync(r => r.StudentId == student.StudentId, update);
           return RedirectToAction("index");
       }


Delete element


public async Task<ActionResult> Delete(int id)
       { 
           //Delete element           
           await _context.Students.DeleteOneAsync(s=> s.StudentId==id);
           return RedirectToAction("index");
       }



Full code In Git ..

https://github.com/prabathsl/DI_Sample


 Enjoy Coding









Tuesday, February 23, 2016

Dependancy Injection With Unity

In Last post I gave you introduction for dependency  Injection.

Here we gonna Use it in real code

First I create MVC project and Add following classes to it.

public interface IUserService
   {
       string GetUserName(string name);
   }
 
public class UserService : IUserService
    {
        public string GetUserName(string name)
        {
            return string.Format("Hello {0}", name);
        }
    } 
 


Here is my folder structure



















Then  I create My MVC UserController and Its View. Code is same as I did in prev post

public class UserController : Controller
   {
       private IUserService _userService;
 
       public UserController(IUserService userService)
       {
           _userService = userService;
       }
       // GET: User
       public ActionResult Index()
       {
           ViewBag.UserMessage = _userService.GetUserName("Dependency Unity");
           return View();
       }
   }

Here is View

@{
    ViewBag.Title = "Index";
}
 
<h2>@ViewBag.UserMessage</h2> 
 
 
 That's all. 

Now I'm gonna install Unity Nuget package for DI framework






 Then real Dependency Injection begins.

Main Focus  
  1. Register
  2. Resolver
 We use dependency Injection Register for register dependency  and resolver for resolve dependency.  It will be done by Unity framework for you if you implement it


1. Create Class DI_Register 

public static class Di_Register
    {
        /// <summary>
        /// Register And resolver of Dependency 
        /// </summary>
        public static void RegisterDependancy()
        {
            IUnityContainer container = new UnityContainer();
            RegisterDependancy(container);
 
            DependencyResolver.SetResolver(new UserResolver(container));
        }
 
        /// <summary>
        /// Type registration
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterDependancy(IUnityContainer container)
        {
            container.RegisterType<IUserServiceUserService>();
        }
    }
 

2. Create UserResolver Class for dependency resolving. It will  using the Unity's IDependancyResolver Interface for resolving implementation . It eill take care of your dependency resolving 


/// <summary>
   /// Resolver 
   /// </summary>
   internal class UserResolver : IDependencyResolver
   {
       private IUnityContainer _unityContainer;
 
       public UserResolver(IUnityContainer unityContainer)
       {
           _unityContainer = unityContainer;
       }
 
       /// <summary>
       /// For one object 
       /// </summary>
       /// <param name="serviceType"></param>
       /// <returns></returns>
       public object GetService(Type serviceType)
       {
           try
           {
               return _unityContainer.Resolve(serviceType);
           }
           catch (Exception)
           {
 
               return null;
           }
       }
 
       /// <summary>
       /// For multiple objects 
       /// </summary>
       /// <param name="serviceType"></param>
       /// <returns></returns>
       public IEnumerable<object> GetServices(Type serviceType)
       {
           try
           {
               return _unityContainer.ResolveAll(serviceType);
 
           }
           catch (Exception)
           {
 
               return null;
           }
       }
   }

 3. Then go to the AppStart (startup.auth.cs) and call dependency register in application bigining

Di_Register.RegisterDependancy(); 
 
 


 Then Run and see the magic :)


Full code In Git ..

https://github.com/prabathsl/DI_Sample


 Enjoy Coding