DotNetSlackers: ASP.NET News for lazy Developers

Showing posts with label asp.net mvc. Show all posts
Showing posts with label asp.net mvc. Show all posts

Monday, February 15, 2016

Understanding Structured, Unstructured and Modular programming approach

In this article I will try to explain about Structured, Unstructured and Modular programming approaches.

Introduction

Usually people start learning programming by writing simple and small programs. They usually write all logics at one place. This practice starts creating problems when program size gets bigger like duplicacy, redundancy, maintenance etc. To overcome this several approach came into light to make this efficient. In this article I will discuss few of those approaches.

Unstructured Programming approach

What we saw above was nothing but an example of unstructured programming style. In this approach programmer put all their code in one place or say in one program. There is no harm as such but when line of code increases, situation starts getting unmanageable. A programmer can face so many problems like:
  • Duplicacy and redundancy of code
  • Code maintenance problem
  • Readability and many more
This approach is totally useless if working on a large project. It can be only helpful while testing one or two features etc.

Structured Programming approach

To overcome above situation it was needed to come up with a structured approach to make some code separation keeping reusability in mind. So the next approach was Structured Programming or Procedure Oriented Programming (POP) approach. In this approach a new idea came up and a set of execution code was keep in a place and it was called function.
Program was divided into separate functions which was easier to manage and re-use as compared to unstructured approach. This was very helpful from reusability point of view but still all code was in same place so still there was a problem to manage them.

Modular Programming approach

A new idea came into light and common functionalities was grouped into modules. This approach helped in dividing programs into small parts called modules. This approach was really helpful. All was good except one. All modules can have their own data and also they were capable to maintain their internal state. But this came as a problem because there can be only one state per module so each module exists at most once in a program.
All the above approach was good enough in their own scope but still there was a need for something else which may be really helpful in making programmer's life easier. And a new approach came which we popularly knows as Object Oriented Programming System (OOPS). This is really great and is using world wide these days by programmers. Hope this article helped you a lot.

Friday, October 16, 2015

Learn MongoDb with Asp.Net MVC


In this tutorial, I’ll show you how to use MongoDB with Asp.Net MVC.

Before start, Let’s know about MongoDB.

What is MongoDB ?

MongoDB is document oriented database, Where Records are stored as documents.
Is it also called as NOSQL database.
MongoDb stores the data in the form of document which is similar to JSON , Known as BSON.

BSON : BSON is a binary representation of JSON with additional type information.
Terms related to MongoDB.
  • Collection : A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.
  • Documents : Document is set of Key-value pair. here is Document Sample
    ?
    1
    2
    3
    4
    {
    Name  : "Amit",
    Email : "amitverma0511@gmail.com"
    }
Advantage of using MongoDB.
  • A document-based data model. The basic unit of storage is analogous to JSON.
    This is a rich data structure capable of holding arrays and other documents.
  • No schema migrations. Since MongoDB is schema-free, your code defines your schema.
  • Replication is very easy.
  • You can perform rich queries.
  • More on MongoDB
Let’s get started
First of all Download the MongoDB.
How to Install MongoDB.
After installing MongoDb in your system .

Create Database in MongoDb.

Here I’m creating Database name as “School“.
Execute the following command in Mongo Shell.

1
use School
Learn MongoDb with Asp.Net MVC

Insert records in School Database .

Create an array which contains list of name of student.
using for loop we will insert records.

1
2
3
4
var Name=["Amit","Rohit","Ajay","Sumit","Rahul"];
 for(i=0 ;i<5;i++){
    db.Students.insert({Name : Name[i]});
}
Learn MongoDb with Asp.Net MVC
Now you see the inserted records by using following query.

1
db.Students.find()
Learn MongoDb with Asp.Net MVC
So far we have created Database and Inserted records in it.
Now let’s learn how to connect MongoDb with C#.

Download C# Driver for MongoDB

Extract the Zip file (if you have downloaded the .Zip file)

In Extracted folder, you will get two .dll file
  • MongoDB.Bson.dll
  • MongoDB.Driver.dll
Now create an Asp.Net MVC project.
Add the the reference of those two dll file.
Right click on Reference => Add Reference => Browse
Learn MongoDb with Asp.Net MVC
Add a Model Class Students.
?
01
02
03
04
05
06
07
08
09
10
11
using MongoDB.Bson;
 
namespace MvcWithMongoDb.Models
{
    public class Students
    {
 
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}
Add Home Controller .
Create constructor of HomeController.

01
02
03
04
05
06
07
08
09
10
11
12
13
private MongoDatabase mongoDatabase;
public HomeController()
{
    // create connectionstring
    var connect = "mongodb://localhost";
    var Client = new MongoClient(connect);
 
    // get Reference of server
    var Server = Client.GetServer();
 
    // get Reference of Database
    mongoDatabase = Server.GetDatabase("School");
}
In Constructor, I have created Mongo Client which need the connection string.
Mongo Client will interact with the server, so using MongoClient instance , call the GetServer method.
Now to Access the database of MongoDb, I have used this instance of Server.
Now Create Method which will return Json Type result.
?
01
02
03
04
05
06
07
08
09
10
11
public JsonResult GetAll()
{
    var collections = mongoDatabase.GetCollection<Students>("Students");
    IList<Students> students = new List<Students>();
    var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
    foreach (Students student in getStudents)
    {
          students.Add(student);
    }
    return Json(students, JsonRequestBehavior.AllowGet);
}
Complete code for controller.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System.Collections.Generic;
using System.Web.Mvc;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MvcWithMongoDb.Models;
namespace MvcWithMongoDb.Controllers
{
    public class HomeController : Controller
    {
        private MongoDatabase mongoDatabase;
        public HomeController()
        {
            // create connectionstring
            var connect = "mongodb://localhost";
            var Client = new MongoClient(connect);
 
            // get Reference of server
            var Server = Client.GetServer();
 
            // get Reference of Database
            mongoDatabase = Server.GetDatabase("School");
        }
 
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetAll()
        {
            var collections = mongoDatabase.GetCollection<Students>("Students");
            IList<Students> students = new List<Students>();
            var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
            foreach (Students student in getStudents)
            {
                  students.Add(student);
            }
            return Json(students, JsonRequestBehavior.AllowGet);
        }
    }
}
Add the Index view .
write the following code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Script/jquery-2.1.1.min.js"></script>
<script src="~/Script/School.js"></script>
<div id="divList">
    <p>
        <img src="~/Content/images/images.jpg" />
    </p>
    <table class="table table-bordered" id="tblList">
        <tr>
            <th colspan="2" style="text-align:center;">Student List</th>
        </tr>
        <tr>
            <th> SNo.</th>
            <th>Name</th>
        </tr>
    </table>
</div>
You can see, I have added Js file named “School.js”.
write the following code in School.js.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready(function () {
    GetAll();
});
 
function GetAll()
{
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        url: 'Home/GetAll',
        success: function (data) {
            var genHtml = "";
            $.each(data, function (index, value) {
                genHtml += "<tr><td>"+(index+1)+"</td><td>" + value.Name +"</td></tr>";
            });
            $('#tblList').append(genHtml);
        },
        error: function (data) {
            alert('Error in getting result');
        }
    });
}
See the Result.
Demo
Learn MongoDb with Asp.Net MVC
DOWNLOAD

Tuesday, October 13, 2015

CRUD Operation in ASP.NET MVC 4 and AngularJS

Hi, Today we will create an ASP.NET MVC 4 Application using AngularJS and perform CRUD (Create, Read, Update and Delete) operations using SPA (Single Page Application).

Let’s create a new MVC Application by Opening Visual Studio 2013.

1. File –> New –> Project –> Select ASP.NET Web Application & give the name as “CRUD_AngularJS_ASPNET_MVC”.

CRUD Operation in ASP.NET MVC 4 and AngularJS

2. Click on OK will open a new window, select MVC template & click on Change Authentication will open a popup on this select “No Authentication” and click on OK, OK will close the windows and create a new MVC 4.0 template project.

CRUD Operation in ASP.NET MVC 4 and AngularJS

3. Create a new Model class with name as Book.cs and add below listed properties.

public class Book
    {
        [Key]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string Publisher { get; set; }
        public string Isbn { get; set; }
    }
 
4. Add new BookDBContext.cs class in the model folder and add below code.
public class BookDBContext : DbContext
    {
        public DbSet<Book> book { get; set; }
    }
 
5. As we need to add System.Data.Entity namespace for which we have to install EntityFramework, to install this Goto Tools -> NuGet Package Manager -> Package Manager Console. In the Package Manager Console type below command "Install-Package EntityFramework as shown below image.
CRUD Operation in ASP.NET MVC 4 and AngularJS

6. Now let's add code in HomeController to get, add, edit and delete book records. (delete existing code)
public class HomeController : Controller
    {
        // GET: Book
        public ActionResult Index()
        {
            return View();
        }

        // GET: All books
        public JsonResult GetAllBooks()
        {
            using (BookDBContext contextObj = new BookDBContext())
            {
                var bookList = contextObj.book.ToList();
                return Json(bookList, JsonRequestBehavior.AllowGet);
            }
        }
        //GET: Book by Id
        public JsonResult GetBookById(string id)
        {
            using (BookDBContext contextObj = new BookDBContext())
            {
                var bookId = Convert.ToInt32(id);
                var getBookById = contextObj.book.Find(bookId);
                return Json(getBookById, JsonRequestBehavior.AllowGet);
            }
        }
        //Update Book
        public string UpdateBook(Book book)
        {
            if (book != null)
            {
                using (BookDBContext contextObj = new BookDBContext())
                {
                    int bookId = Convert.ToInt32(book.Id);
                    Book _book = contextObj.book.Where(b => b.Id == bookId).FirstOrDefault();
                    _book.Title = book.Title;
                    _book.Author = book.Author;
                    _book.Publisher = book.Publisher;
                    _book.Isbn = book.Isbn;
                    contextObj.SaveChanges();
                    return "Book record updated successfully";
                }
            }
            else
            {
                return "Invalid book record";
            }
        }
        // Add book
        public string AddBook(Book book)
        {
            if (book != null)
            {
                using (BookDBContext contextObj = new BookDBContext())
                {
                    contextObj.book.Add(book);
                    contextObj.SaveChanges();
                    return "Book record added successfully";
                }
            }
            else
            {
                return "Invalid book record";
            }
        }
        // Delete book
        public string DeleteBook(string bookId)
        {

            if (!String.IsNullOrEmpty(bookId))
            {
                try
                {
                    int _bookId = Int32.Parse(bookId);
                    using (BookDBContext contextObj = new BookDBContext())
                    {
                        var _book = contextObj.book.Find(_bookId);
                        contextObj.book.Remove(_book);
                        contextObj.SaveChanges();
                        return "Selected book record deleted sucessfully";
                    }
                }
                catch (Exception)
                {
                    return "Book details not found";
                }
            }
            else
            {
                return "Invalid operation";
            }
        }
    }
 
7. Add database connection in web.config (Database will be created using EF once we will add book data first time)
Insert code here...  <connectionStrings>
    <add name="BookDBContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CrudInAj-201412222;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CrudInAj-201412222.mdf" />
  </connectionStrings>
 
8. Now we have to add view markup using AngularJS directives (ng-model & ng-click) but before this we have to add AngularJS in our project using Package Manager Console (open PMC and write command "Install-Package AngularJS" will install AngularJS).
9. Go to Scripts and create a new folder as BookScripts, under BookScripts folder create 3 new js files as Controller.js, Module.js & Service.js.
10. Open BundleConfig.cs under App_Start and add below code.
bundles.Add(new ScriptBundle("~/bundles/angularJS").Include(
                     "~/Scripts/angular.js"));

bundles.Add(new ScriptBundle("~/bundles/customJS").Include(
                     "~/Scripts/BookScripts/Module.js",
                     "~/Scripts/BookScripts/Service.js",
                     "~/Scripts/BookScripts/Controller.js"));
 
11. Open Views -> Shared -> _Layout.cshtml and add @Script.Render block in the head tag of the page.
@Scripts.Render("~/bundles/angularJS")
@Scripts.Render("~/bundles/customJS")
 
12. Add ng-app AnularJS directive in the HTML section of the page and give name as mvcCRUDApp (removed About & Contact links). full page code is as below
<!DOCTYPE html>
<html ng-app="mvcCRUDApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Scripts.Render("~/bundles/angularJS")
    @Scripts.Render("~/bundles/customJS")
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Book Management", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>
                <p class="nav navbar-text navbar-right">Hello, @User.Identity.Name!</p>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>
 
13. Open Module.js and define angular module as below
var app = angular.module("mvcCRUDApp", []);
 
14. Open Service.js and define functions for Add, Update, Get and Delete book functions.
app.service("crudAJService", function ($http) {

    //get All Books
    this.getBooks = function () {
        return $http.get("Home/GetAllBooks");
    };

    // get Book by bookId
    this.getBook = function (bookId) {
        var response = $http({
            method: "post",
            url: "Home/GetBookById",
            params: {
                id: JSON.stringify(bookId)
            }
        });
        return response;
    }

    // Update Book 
    this.updateBook = function (book) {
        var response = $http({
            method: "post",
            url: "Home/UpdateBook",
            data: JSON.stringify(book),
            dataType: "json"
        });
        return response;
    }

    // Add Book
    this.AddBook = function (book) {
        var response = $http({
            method: "post",
            url: "Home/AddBook",
            data: JSON.stringify(book),
            dataType: "json"
        });
        return response;
    }

    //Delete Book
    this.DeleteBook = function (bookId) {
        var response = $http({
            method: "post",
            url: "Home/DeleteBook",
            params: {
                bookId: JSON.stringify(bookId)
            }
        });
        return response;
    }
});
 
15. Open Controller.js and add functions for GetAllBooks(), EditBook(), AddUpdateBook(), DeleteBook() & ClearFields()
app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
    $scope.divBook = false;
    GetAllBooks();
    //To Get all book records  
    function GetAllBooks() {
        debugger;
        var getBookData = crudAJService.getBooks();
        getBookData.then(function (book) {
            $scope.books = book.data;
        }, function () {
            alert('Error in getting book records');
        });
    }

    $scope.editBook = function (book) {
        var getBookData = crudAJService.getBook(book.Id);
        getBookData.then(function (_book) {
            $scope.book = _book.data;
            $scope.bookId = book.Id;
            $scope.bookTitle = book.Title;
            $scope.bookAuthor = book.Author;
            $scope.bookPublisher = book.Publisher;
            $scope.bookIsbn = book.Isbn;
            $scope.Action = "Update";
            $scope.divBook = true;
        }, function () {
            alert('Error in getting book records');
        });
    }

    $scope.AddUpdateBook = function () {
        var Book = {
            Title: $scope.bookTitle,
            Author: $scope.bookAuthor,
            Publisher: $scope.bookPublisher,
            Isbn: $scope.bookIsbn
        };
        var getBookAction = $scope.Action;

        if (getBookAction == "Update") {
            Book.Id = $scope.bookId;
            var getBookData = crudAJService.updateBook(Book);
            getBookData.then(function (msg) {
                GetAllBooks();
                alert(msg.data);
                $scope.divBook = false;
            }, function () {
                alert('Error in updating book record');
            });
        } else {
            var getBookData = crudAJService.AddBook(Book);
            getBookData.then(function (msg) {
                GetAllBooks();
                alert(msg.data);
                $scope.divBook = false;
            }, function () {
                alert('Error in adding book record');
            });
        }
    }

    $scope.AddBookDiv = function () {
        ClearFields();
        $scope.Action = "Add";
        $scope.divBook = true;
    }

    $scope.deleteBook = function (book) {
        var getBookData = crudAJService.DeleteBook(book.Id);
        getBookData.then(function (msg) {
            alert(msg.data);
            GetAllBooks();
        }, function () {
            alert('Error in deleting book record');
        });
    }

    function ClearFields() {
        $scope.bookId = "";
        $scope.bookTitle = "";
        $scope.bookAuthor = "";
        $scope.bookPublisher = "";
        $scope.bookIsbn = "";
    }
    $scope.Cancel = function () {
        $scope.divBook = false;
    };
});
 
16. At last open Views -> Home -> Index.cshtml and remove existing code and add code as below
@{
    ViewBag.Title = "Home Page";
}
<div ng-controller="mvcCRUDCtrl">
    <div class="divList">
        <p><b><i>Book List</i></b></p>
        <table class="table table-hover">
            <tr>
                <td><b>ID</b></td>
                <td><b>Title</b></td>
                <td><b>Author</b></td>
                <td><b>Publisher</b></td>
                <td><b>Isbn</b></td>
                <td><b>Action</b></td>
            </tr>
            <tr ng-repeat="book in books">
                <td>
                    {{book.Id}}
                </td>
                <td>
                    {{book.Title}}
                </td>
                <td>
                    {{book.Author}}
                </td>
                <td>
                    {{book.Publisher}}
                </td>
                <td>
                    {{book.Isbn}}
                </td>
                <td>
                    <span ng-click="editBook(book)" class="btn btn-primary">Edit</span>
                    <span ng-click="deleteBook(book)" class="btn btn-danger">Delete</span>
                </td>
            </tr>
        </table>
    </div>
    <span ng-click="AddBookDiv()" class="btn btn-default" >
        Add Book
    </span>
    <div ng-show="divBook">
        <p class="divHead"></p>
        <table class="table">
            <tr>
                <td><b><i>{{Action}} Book</i></b></td>
                <td></td>
                <td></td>
                <td></td>
            </tr> 
            <tr>
                <td><b>Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="bookId" />
                </td>
                <td><b>Title</b></td>
                <td>
                    <input type="text" ng-model="bookTitle" />
                </td>
            </tr>           
            <tr>
                <td><b>Author</b></td>
                <td>
                    <input type="text" ng-model="bookAuthor" />
                </td>
                <td><b>Publisher</b></td>
                <td>
                    <input type="text" ng-model="bookPublisher" />
                </td>
            </tr>
            <tr>
                <td><b>Isbn</b></td>
                <td>
                    <input type="text" ng-model="bookIsbn" />
                </td>
                <td></td>
                <td >
                    <input type="button" class="btn btn-default" value="Save" ng-click="AddUpdateBook()" />
                    <input type="button" class="btn btn-danger" value="Cancel" ng-click="Cancel()" />
                </td>
            </tr>
        </table>        
    </div>
</div>
 
17. Run the application and you can Create, Read, Update & Delete book details.
CRUD Operation in ASP.NET MVC 4 and AngularJS

Select, Zip and Download Files Programmatically in ASP.NET MVC

You might have already seen websites that display a list of files to the end user. The user can then select one or more files from the list and request a zipped bundle of those files as a single download. In this article you will learn how to do just that. You will use classes from System.IO.Compression namespace to zip the files programmatically.
http://www.binaryintellect.net/articles/fc62ebfd-fa2e-48e5-8854-d197e0fe30e8.aspx