Tuesday, 25 October 2016

Difference between ASP.NET MVC and ASP.NET Web API – Exposing Functionality of Web Application

ASP.NET MVC or Model View Controller is a three tier architectural deweb application development using ASP.NET technology. In MVC framework, models are the components responsible for information retrieval and storage in database, while view displays the information and controllers are used for managing and responding to user inputs.
sign or framework for
Talking about ASP.NET Web API, this is a framework used for developing HTTP services to provide response to the client requests. Web API is an open source technology that is used to develop web services for applications such that they can reach broader range of clients with HTTP protocols.
Now let us compare the two technologies with regards to exposing functionality of web applications.
While it is possible to expose functionality of web application through Web API, it can also be done through MVC by using the action methods. However, in order to decide between these two technologies to use for functionality exposing, there are a few main things to consider and they are as follows.
Exposing Functionality or Creating Full-Fledged REST Service:
When it comes to exposing functionality of a web application, there could be two considerations – one is exposing the functionality within the web application and the second is to expose it as a generic functionality that is independent of any specific application. Relying on MVC is a good option if exposing functionality within application is your requirement, because MVC controllers are tightly tied to a particular application. On the other hand with Web API, it would require to create a whole new API and hence, the process will get more complicated and time consuming.
Considering the second case, it’s better to create full-fledged REST service for the purpose using Web API because the REST service is not limited to just a single applications and can be used by several applications for their tasks. So, if your application functionality is data oriented then Web API offers an elegant solution, while MVC is good for developing the web application that replies as both data and views.
Formats to Deal With
MVC returns data in typical JSON format using JSONResult. Hence, one can use action methods to expose functionality of an application here. But, Web API returns various kinds of data including the JSON, XML or any other data format based on accept header. With MVC you are required to specify the data format explicitly while it is done automatically in Web API.
Hosting
Hosting is an important consideration during ASP.NET development. As MVC controller is part of an ASP.NET MVC application, it depends on IIS environment for application hosting while on other hand, Web API is a service based framework which can allow the developer to host his application in a custom host other than IIS. Hence, with Web API you can host your applications in light weight host server as per your needs and save overheads usually witnessed in IIS hosted ASP.NET applications. Web API is therefore a reliable technology for developing web, console and desktop applications.
Hence, by considering the above points during ASP.NET development, one can easily select between Web API and MVC technologies to expose the functionality of a web application.

Sunday, 18 September 2016

How to send email from MVC 5 application-Mozammal Farhad

Do the following step:

1.
Make a new MVC project name

 Send_Email_MVC

then make a model class in model folder in your mvc project.

public class EmailModel
    {
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public HttpPostedFileBase Attachment { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }


2.

Second make a controller name     Home   in controller folder in your mvc project




using Send_Email_MVC.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;


namespace Send_Email_MVC.Controllers
{

[HttpPost]
        public ActionResult Index(EmailModel model)
        {
            using (MailMessage mm = new MailMessage(model.Email, model.To))
            {
                mm.Subject = model.Subject;
                mm.Body = model.Body;
                if (model.Attachment.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(model.Attachment.FileName);
                    mm.Attachments.Add(new Attachment(model.Attachment.InputStream, fileName));
                }
                mm.IsBodyHtml = false;
                using (SmtpClient smtp = new SmtpClient())
                {
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;
                    smtp.Send(mm);
                    ViewBag.Message = "Email sent.";
                }
            }

            return View();
        }
}




3.



Finally make a view by right clicking on your controller Action Method




the view look like this



@model Send_Email_MVC.Models.EmailModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        table th, table td {
            padding: 5px;
        }
    </style>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td style="width: 80px">
                        To:
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.To)
                    </td>
                </tr>
                <tr>
                    <td>
                        Subject:
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.Subject)
                    </td>
                </tr>
                <tr>
                    <td valign="top">
                        Body:
                    </td>
                    <td>
                        @Html.TextAreaFor(model => model.Body, new { rows = "3", cols = "20" })
                    </td>
                </tr>
                <tr>
                    <td>
                        File Attachment:
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.Attachment, new { type = "file" })
                    </td>
                </tr>
                <tr>
                    <td>
                        Gmail Email:
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.Email)
                    </td>
                </tr>
                <tr>
                    <td>
                        Gmail Password:
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.Password, new { type = "password" })
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="submit" value="Send" />
                    </td>
                </tr>
            </table>
            <br />
            <span style="color:green">@ViewBag.Message</span>
        }
    </div>
</body>

</html>





Now run the project 

you can see the view in ur browser by filling up the data then click sent


Tuesday, 30 August 2016

MVC5 CRUD OPERATION STEP BY STEP

Step 1:
Create a Model class———-
public class Booking
{
public virtual int Id { get; set; }
public virtual string HallName { get; set; }
public virtual DateTime bookDate { get; set; }
public virtual string fromtime { get; set; }
public virtual string toTime { get; set; }
public virtual int people { get; set; }
public virtual string status { get; set; }
}
public class ResultObject
{
public int ResultID { get; set; }
public string ResultMessage { get; set; }
public Object Obj { get; set; }
public string Code { get; set; }
}
public class PagedBookingModel
{
public int TotalRows { get; set; }
public IEnumerable Booking { get; set; }
public int PageSize { get; set; }
}
Step 2: Create a Contex of EntityFrmework to access database–
public class BookHallContext : DbContext
{
public BookHallContext() : base(“name=BookHallContext”)
{
}
public System.Data.Entity.DbSet Bookings { get; set; }
}
Step 3: Create a dataAccess Layer—————–
public class BookDataAccess
{
public BookDataAccess() { }
public BookHallContext db = new BookHallContext();
//public DataTable GetDataTable(string commandText)
//{
// // get a configured DbCommand object
// DbCommand comm = GenericDataAcccess.CreateCommand();
// // set the stored procedure name
// comm.CommandText = commandText;
// // execute the stored procedure and return the results
// return GenericDataAcccess.ExecuteSelectCommand(comm);
//}
public IEnumerable GetBookingPage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber m.HallName)
.Skip((pageNumber – 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllHall()
{
return db.Bookings.Count();
}
public void Dispose()
{
db.Dispose();
}
public Booking GetBookingDetail(int mCustID)
{
return db.Bookings.Where(m => m.Id == mCustID).FirstOrDefault();
}
public bool AddBooking(Booking book)
{
try
{
db.Bookings.Add(book);
db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool UpdateEmployee(Booking bk)
{
try
{
Booking data = db.Bookings.Where(m => m.Id ==bk.Id).FirstOrDefault();
data.HallName = bk.HallName;
data.bookDate = bk.bookDate;
data.fromtime = bk.fromtime;
data.toTime = bk.toTime;
data.people = bk.people;
db.SaveChanges();
return true;
}
catch (Exception mex)
{
return false;
}
}
public bool DeleteBooking(int mCustID)
{
try
{
Booking data = db.Bookings.Where(m => m.Id == mCustID).FirstOrDefault();
db.Bookings.Remove(data);
db.SaveChanges();
return true;
}
catch (Exception mex)
{
return false;
}
}
public ResultObject InsertBookInfo(Booking binfo)
{
string error;
ResultObject resObj = new ResultObject();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand(“”, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = @”Insert into Bookings( bookDate,HallName,fromtime,toTime,people) Values(‘” + (binfo.bookDate).ToString(“yyyy/MM/dd”) + “‘,'” + binfo.HallName + “‘,'” + binfo.fromtime + “‘,'” + binfo.toTime + “‘,'” + binfo.people + “‘)”;
int result = -1;
try
{
result = cmd.ExecuteNonQuery();
}
catch
{
result = -1;
}
resObj.ResultID = result;
if (result > 0)
{
resObj.ResultMessage = “Data Saved Successfully”;
resObj.Obj = GetBookingInfoList();
}
else
{
resObj.ResultMessage = “Data Not Saved”;
}
con.Close();
return resObj;
}
public ResultObject UpdateBookInfo(Booking binfo)
{
string error;
ResultObject resObj = new ResultObject();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand(“”, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = @”Update Bookings set bookDate='” + binfo.bookDate.ToString(“yyyy/MM/dd”) + “‘,HallName='” + binfo.HallName + “‘,fromtime='” + binfo.fromtime + “‘,toTime='” + binfo.toTime + “‘,people='” + binfo.people + “‘ where Id='”+binfo.Id+”‘)”;
int result = -1;
try
{
result = cmd.ExecuteNonQuery();
}
catch
{
result = -1;
}
resObj.ResultID = result;
if (result > 0)
{
resObj.ResultMessage = “Data Updated Successfully”;
resObj.Obj = GetBookingInfoList();
}
else
{
resObj.ResultMessage = “Data Not Saved”;
}
con.Close();
return resObj;
}
public List GetBookingInfoList()
{
List objList = new List();
DataTable dt = GetAllBookingInfo();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objList.Add(new Booking
{
Id = int.Parse(dt.Rows[i]["Id"].ToString()),
bookDate = Convert.ToDateTime(dt.Rows[i]["bookDate"]),
fromtime = dt.Rows[i]["fromtime"].ToString(),
toTime = dt.Rows[i]["toTime"].ToString(),
HallName = dt.Rows[i]["HallName"].ToString(),
people = Int32.Parse(dt.Rows[i]["people"].ToString())
});
}
}
return objList;
}
public DataTable GetAllBookingInfo()
{
DataTable tbl = new DataTable();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand("", con);
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"Select Id,bookDate,HallName,fromtime,toTime,people from Bookings";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(tbl);
return tbl;
}
Step 4: Create a Controller
public class BookingController : Controller
{
public BookHallContext db = new BookHallContext();
// GET: /Booking/
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
// GET: /Booking/Details/5
public ActionResult LoadBookInfo()
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.GetBookingInfoList());
}
public ActionResult InsertBookInfo(Booking obj)
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.InsertBookInfo(obj));
}
public ActionResult UpdateBookInfo(Booking obj)
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.UpdateBookInfo(obj));
}
}
Step 5: Create a view—————–
@{
//WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
//grid.Bind(Model.Bookings,
// autoSortAndPage: false,
// rowCount: Model.TotalRows
//);
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
$(document).ready(function () {
// alert(“ok”);
$(“#dvLoading”).hide();
LoadInfo();
$(“#btnSave”).click(function () {
$(“#dvLoading”).dialog();
$(“#lblInfo”).html(”);
var bookInfo = {
“HallName”: $(“#txtHallName”).val(),
“bookDate”: $(“#txtbookDate”).val(),
“fromtime”: $(“#txtfromtime”).val(),
“toTime”: $(“#txttoTime”).val(),
“people”: $(“#txtPeople”).val(),
“Id”: $(“#txtId”).val()
};
var Method = ”;
if ($(“#btnSave”).val() == ‘Update’) {
Method = “UpdateBookInfo”;
}
else {
Method = “InsertBookInfo”;
}
$.ajax({
type: “post”,
url: “/Booking/” + Method,
dataType: “JSON”,
contentType: “application/json;charset=utf-8”,
data: JSON.stringify({ “obj”: bookInfo }),
//data: JSON.stringify({ “_pinfo”: patientInfo }),
success: function (response) {
$(“#dvLoading”).hide();
// var response = data.d;
//
if (response.ResultID != ‘-1’) {
$(“#lblInfo”).html(‘‘ + response.ResultMessage + ‘‘);
ClearField();
BindTable(response.Obj);
$(“#btnSave”).val(“Save”);
}
else {
$(“#lblInfo”).html(‘‘ + response.Code + ‘‘);
}
},
error: function (a, b, c) {
$(“#dvLoading”).hide();
alert(a + ‘..’ + c.statusCode);
}
});
});
function LoadInfo() {
// alert(“Load info mcalled”);
$(“#dvLoading”).show();
$.ajax({
type: “POST”,
url: “/Booking/LoadBookInfo”,
contentType: ‘application/json; charset=utf-8’,
dataType: ‘json’,
cache: false,
success: function (result) {
$(“#dvLoading”).hide();
//var response = result.d;
BindTable(result)
// console.log(response);
},
error: function (xhr, textStatus, errorThrown) {
$(“#dvLoading”).hide();
// alert(xhr.responseText);
alert((“Error thrown ” + errorThrown + “Status: ” + xhr.status));
console.log(xhr + textStatus + errorThrown);
}
});
}
function BindTable(data) {
$(“#tbldata tr:gt(0)”).remove();
var content = ”;
$.each(data, function (i, quality) {
content += ‘
‘ + quality.HallName + ‘ ‘ + quality.bookDate + ‘ ‘ + quality.fromtime + ‘ ‘ + quality.toTime + ‘ ‘ + quality.people + ‘ ‘ + quality.status + ‘ ‘ + quality.Id + ‘
‘;
});
console.log(content);
$(“#tbldata”).append(content);
}
$(“#tbldata”).on(‘click’, “tr:gt(0)”, function () {
var url = $(this).attr(‘href’);
$(“#popdialog”).dialog({
title: ‘Add New Booking’,
autoOpen: false,
resizable: false,
height: 500,
width: 400,
show: { effect: ‘drop’, direction: “up” },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
//alert(Id);
},
close: function (event, ui) {
$(this).dialog(‘close’);
}
});
var Id = $(this).find(“td:eq(6)”).text();
$(“#txtHallName”).val($(this).find(“td:eq(0)”).text());
$(“#txtbookDate”).val($(this).find(“td:eq(1)”).text());
$(“#txtfromtime”).val($(this).find(“td:eq(2)”).text());
$(“#txttoTime”).val($(this).find(“td:eq(3)”).text());
$(“#txtpeople”).val($(this).find(“td:eq(4)”).text());
$(“#txtId”).val($(this).find(“td:eq(6)”).text());
$(“#btnSave”).val(“Update”);
$(“#popdialog”).dialog(‘open’);
return false;
});
function ClearField() {
$(“#txtHallName”).val(”),
$(“#txtbookDate”).val(”),
$(“#txtfromtime”).val(”),
$(“txttoTime”).val(”),
$(“#txtpeople”).val(”),
$(“#txtId”).val(”)
}
});
.CSSTableGenerator {
margin: 0px;
padding: 0px;
width: 100%;
border: 1px solid #000000;
}
.CSSTableGenerator table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.CSSTableGenerator tr:nth-child(odd) {
background-color: #aad4ff;
}
.CSSTableGenerator tr:nth-child(even) {
background-color: #ffffff;
}
.CSSTableGenerator td {
vertical-align: middle;
border: 1px solid #000000;
border-width: 0px 1px 1px 0px;
text-align: left;
padding: 4px;
font-size: .8em;
font-family: Arial;
font-weight: normal;
}
.CSSTableGenerator tr:last-child td {
border-width: 0px 1px 0px 0px;
}
.CSSTableGenerator tr td:last-child {
border-width: 0px 0px 1px 0px;
}
.CSSTableGenerator tr:last-child td:last-child {
border-width: 0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td {
background-color: #005fbf;
border: 0px solid #000000;
text-align: center;
border-width: 0px 0px 1px 1px;
font-size: .8em;
font-family: Arial;
font-weight: bold;
color: #ffffff;
}
.CSSTableGenerator tr:first-child td:first-child {
border-width: 0px 0px 1px 0px;
}
.CSSTableGenerator tr:first-child td:last-child {
border-width: 0px 0px 1px 1px;
}
@*
Please wait.......
*@
HallName
BookDate
From Time
To Time
People
ID
HallNameBookDateFromTimeToTimePeopleID
$(document).ready(function () {
$(“.inputdate”).datepicker({ dateFormat: “yy-mm-dd” });
// $(“.inputtime”).timespinner();
});
====================================File Upload=========================================
public class NewsController : Controller
{
private WebAppDb db = new WebAppDb();
//
// GET: /News/
public ActionResult Index()
{
var post = db.Posts.OrderByDescending(d => d.PublishDate);
return View(post.ToList());
}
//
// GET: /News/List/
[Authorize]
public ActionResult List()
{
var post = db.Posts.OrderByDescending(d => d.PublishDate);
return View(post.ToList());
}
//
// GET: /News/Create/
[Authorize]
public ActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult Create(BlogPost newpost, HttpPostedFileBase file)
{
if(file != null && file.ContentLength > 0){
string GetFileName = Path.GetFileName(file.FileName);
var ServerPath = Path.Combine(Server.MapPath(“~/Content/Uploads/”), file.FileName);
file.SaveAs(ServerPath);
newpost.Image = “/Content/Uploads/” + file.FileName;
}
if(ModelState.IsValid){
db.Posts.Add(newpost);
db.SaveChanges();
return RedirectToAction(“List”);
}
return View(newpost);
}
//
// GET: /News/Edit/
[Authorize]
public ActionResult Edit(int id = 0)
{
var post = db.Posts.Find(id);
return View(post);
}
[Authorize]
[HttpPost]
public ActionResult Edit(BlogPost post, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
string GetFileName = Path.GetFileName(file.FileName);
var ServerPath = Path.Combine(Server.MapPath(“~/Content/Uploads/”), file.FileName);
file.SaveAs(ServerPath);
post.Image = “/Content/Uploads/” + file.FileName;
}
if (ModelState.IsValid)
{
db.Entry(post).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“List”);
}
return View(post);
}
//
// GET: /News/Delete/
[Authorize]
public ActionResult Delete(int id = 0)
{
BlogPost post = db.Posts.Find(id);
if(post == null){
return HttpNotFound();
}
return View(post);
}
[Authorize]
[HttpPost, ActionName(“Delete”)]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id = 0)
{
BlogPost post = db.Posts.Find(id);
db.Posts.Remove(post);
db.SaveChanges();
return RedirectToAction(“List”);
}
}
Create——————————————————————-
@model NGO_Project.Models.BlogPost
@{
ViewBag.Title = “Create News”;
Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
}
@*@section Sidebar{

  • @Html.ActionLink(“Back to List”, “list”)

  • }*@
    @using (Html.BeginForm(“Create”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin”, enctype = “multipart/form-data” }))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.LabelFor(model => model.Title)
    @Html.EditorFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title, null, new { @class = “parsley-error-list” })
    @Html.LabelFor(model => model.Image)



    @Html.LabelFor(model => model.Description)
    @Html.TextAreaFor(model => model.Description, new { @class = “textarea-no-resize”, style = “margin: 0px; height: 200px;” })
    @Html.ValidationMessageFor(model => model.Description, null, new { @class = “parsley-error-list” })
    @Html.HiddenFor(model => model.PublishDate, new { Value = @DateTime.Now })
    }
    @section Scripts {
    @Scripts.Render(“~/bundles/jqueryval”)
    }
    Edit————————————————————————————-
    @model NGO_Project.Models.BlogPost
    @{
    ViewBag.Title = “Edit News”;
    Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
    }
    @using (Html.BeginForm(“Edit”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin”, enctype = “multipart/form-data” }))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.LabelFor(model => model.Title)
    @Html.EditorFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title, null, new { @class = “parsley-error-list” })
    @Html.LabelFor(model => model.Image)



    @Html.LabelFor(model => model.Description)
    @Html.TextAreaFor(model => model.Description, new { @class = “textarea-no-resize”, style = “margin: 0px; height: 200px;” })
    @Html.ValidationMessageFor(model => model.Description, null, new { @class = “parsley-error-list” })
    @Html.HiddenFor(model => model.Image, new { Value = @Model.Image })
    @Html.HiddenFor(model => model.PublishDate)
    }
    @section Scripts {
    @Scripts.Render(“~/bundles/jqueryval”)
    }
    —————————————————————–Delete————————————-
    @model NGO_Project.Models.BlogPost
    @{
    ViewBag.Title = “Delete”;
    ViewBag.Subheading = “Are you sure you want to delete this?”;
    Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
    }
    @using (Html.BeginForm(“Delete”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin” }))
    {
    @Html.AntiForgeryToken()
    @Html.LabelFor(model => model.Title)
    @Html.DisplayFor(model => model.Title)
    @Html.LabelFor(model => model.PublishDate)
    @Html.DisplayFor(model => model.PublishDate)
    @Html.LabelFor(model => model.Image)
    @Html.LabelFor(model => model.Description)
    @Html.DisplayFor(model => model.Description)
    }
    Index———————————————————————-
    @model IEnumerable
    @{
    ViewBag.Title = “News | NGO Web App”;
    ViewBag.Page = “News”;
    }
    @foreach (var item in Model)
    {

    @Html.DisplayFor(modelItem => item.Title)

    @Html.DisplayFor(modelItem => item.PublishDate) @if (item.Image != null)
    { item.Image)” alt=”Image” width=”113″>}
    @Html.Raw(item.Description)

    Comments system

    Advertising

    Disqus Shortname