Thursday, 9 June 2016

MVC inser update delete

DAL

using MyMVCAccount.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace MyMVCAccount
{
    public class DAL
    {
        public string InsertData(User user)
        {
            SqlConnection con = null;
            string result = "";
            try
            {
                con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
                SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Id", 0);
                // i will pass zero to MobileID beacause its Primary .
                cmd.Parameters.AddWithValue("@Name", user.Name);
                cmd.Parameters.AddWithValue("@LoginId", user.LoginId);
                cmd.Parameters.AddWithValue("@Password", user.Password);
                cmd.Parameters.AddWithValue("@Query", 1);
                con.Open();
                result = cmd.ExecuteScalar().ToString();
                return result;
            }
            catch
            {
                return result = "";
            }
            finally
            {
                con.Close();
            }
        }

        public IList<User> SelectAllData()
        {
            IList<User> users = new List<User>();
            SqlConnection con = null;
            //string result = "";
            DataSet ds = null;
            try
            {
                con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
                SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ID", 0);
                cmd.Parameters.AddWithValue("@Name", null);
                cmd.Parameters.AddWithValue("@LoginId", null);
                cmd.Parameters.AddWithValue("@Password", null);
                cmd.Parameters.AddWithValue("@Query", 4);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                ds = new DataSet(); da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        User user = new User()
                        {
                            Id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"].ToString()),
                            Name = ds.Tables[0].Rows[i]["Name"].ToString(),
                            LoginId = ds.Tables[0].Rows[i]["LoginId"].ToString(),
                            Password = ds.Tables[0].Rows[i]["Password"].ToString()
                        };
                        users.Add(user);
                    }

                }
                return users;
            }
            catch
            {
                return users;
            }
            finally
            {
                con.Close();
            }
        }

        public User SelectAllDatabyID(int Id)
        {
            User user=null;
            SqlConnection con = null;
            string result = "";
            DataSet ds = null;
            try
            {
                con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
                SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Id", Id); // i will pass zero to MobileID beacause its Primary .
                cmd.Parameters.AddWithValue("@Name", null);
                cmd.Parameters.AddWithValue("@LoginId", null);
                cmd.Parameters.AddWithValue("@Password", 0);
                cmd.Parameters.AddWithValue("@Query", 5);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    user = new User()
                    {
                        Id = Convert.ToInt32(ds.Tables[0].Rows[0]["ID"].ToString()),
                        Name = ds.Tables[0].Rows[0]["Name"].ToString(),
                        LoginId = ds.Tables[0].Rows[0]["LoginId"].ToString(),
                        Password = ds.Tables[0].Rows[0]["Password"].ToString()
                    };
                }

                return user;
            }
            catch
            {
                return user;
            }
            finally
            {
                con.Close();
            }
        }

        public string UpdateData(User user)
        {
            SqlConnection con = null;
            string result = "";
            try
            {
                con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString());
                SqlCommand cmd = new SqlCommand("Usp_InsertUpdateDelete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Id", user.Id);
                cmd.Parameters.AddWithValue("@Name", user.Name);
                cmd.Parameters.AddWithValue("@LoginId", user.LoginId);
                cmd.Parameters.AddWithValue("@Password", user.Password);
                cmd.Parameters.AddWithValue("@Query", 2);
                con.Open();
                result = cmd.ExecuteScalar().ToString();
                return result;
            }
            catch
            {
                return result = "";
            }
            finally
            {
                con.Close();
            }
        }

    }
}

Controller

using MyMVCAccount.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMVCAccount;

namespace MyMVCAccount.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            DAL objDAL = new DAL(); //calling class DBdata
            User user = new User();
            user.users = objDAL.SelectAllData();
            return View(user);           
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(User user)
        {           
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid) //checking model is valid or not
                {
                    DAL objDAL = new DAL(); //calling class DBdata
                    string result = objDAL.InsertData(user); // passing Value to DBClass from model
                    ViewData["result"] = result;
                    ModelState.Clear(); //clearing model
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "Error in saving data");
                    return View();
                }               
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id)
        {
            DAL obDAL = new DAL(); //calling class DBdata
            User user = obDAL.SelectAllDatabyID(id);
            User userDtl = new User()
            {
                Id = user.Id,
                Name=user.Name,
                LoginId=user.LoginId,
                Password=user.Password
            };           
            return View(userDtl);           
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            try
            {
                // TODO: Add update logic here
                DAL objDAL = new DAL(); //calling class DBdata
                string result = objDAL.UpdateData(user); // passing Value to DBClass from model
                ViewData["resultUpdate"] = result; // for dislaying message after updating data.              
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /User/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Web;

namespace MyMVCAccount.Models
{
    public class User
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "*")]
        public string Name { get; set; }

        [Required(ErrorMessage = "*")]
        public string LoginId { get; set; }

        [DataType(DataType.Password)]
        [Required(ErrorMessage = "*")]
        public string Password { get; set; }

        public IList<User> users { get; set; }
    }
}
View
Create
@model MyMVCAccount.Models.User

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<table>
    <tr>
        <td>
            @Html.ActionLink("Show Users", "Index")
        </td>
    </tr>
</table>
@using (Html.BeginForm())
{
    <table style="margin-left:100px" width="100%">
        <tr>
            <td>
                @Html.LabelFor(a => @Model.Name)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => @Model.Name)
                @Html.ValidationMessageFor(a => @Model.Name)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => @Model.LoginId)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => @Model.LoginId)
                @Html.ValidationMessageFor(a => @Model.LoginId)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => @Model.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.EditorFor(a => @Model.Password, new { @autocomplete = "off" })
                @Html.ValidationMessageFor(a => @Model.Password)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Submit1" type="submit" value="submit" />
            </td>
        </tr>
    </table>
}
@{
    @*if (ViewData["result"] != "" && ViewData["result"] != null)
        {
            ViewData["result"] = null;
            <script type="text/javascript" language="javascript">
                alert("Data saved Successfully");
            </script>
        }*@
}

Edit
@model MyMVCAccount.Models.User

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    <table width="100%">
        <tr>
            <td colspan="2">
                @Html.HiddenFor(a => Model.Id)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => Model.Name)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => Model.Name)
                @Html.ValidationMessageFor(a => Model.Name)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => Model.LoginId)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => Model.LoginId)
                @Html.ValidationMessageFor(a => Model.LoginId)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => Model.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => Model.Password)
                @Html.ValidationMessageFor(a => Model.Password)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Submit1" type="submit" value="Update" />
            </td>
        </tr>
    </table>
}

Index
@model MyMVCAccount.Models.User

@{
    Layout = null;
}

<h2>ShowAllMobileDetails</h2>
<style>
    table {
        border-collapse: collapse;
    }

    table, th, td {
        border: 1px solid black;
    }
</style>

<tr>
    <td>
        @Html.ActionLink("Add New User", "Create")
    </td>
</tr>
<br />
<br />
<table width="100%">
    <tr>
        <td>
            Name
        </td>
        <td>
            LoginId
        </td>
        <td>
            Password
        </td>
        <td>
            EDIT
        </td>
        <td>
            DELETE
        </td>
    </tr>
    @foreach (var item in Model.users)
    {
        <tr>
            <td>
                @Html.EditorFor(i=>item.Name)
            </td> 
            <td>
                @Html.EditorFor(i => item.LoginId)
            </td>
            <td>
                @Html.EditorFor(i => item.Password)
            </td>   
            <td>
                @Html.ActionLink("EDIT", "Edit", new { id = item.Id })
            </td>
            <td>
                @Html.ActionLink("Delete", "DELETEMOBILEDATA", new { id = item.Id })
            </td>     
        </tr>
    }
    @*@for (int i = 0; i < Model.users.Count; i++)
    {
        <tr>
            <td>
                @Model.users[i].Name
            </td>
            <td>
                @Model.users[i].LoginId
            </td>
            <td>
                @Model.users[i].Password
            </td>
            <td>
                @Html.ActionLink("EDIT", "Edit", new { id = Model.users[i].Id })
            </td>
            <td>
                @Html.ActionLink("Delete", "DELETEMOBILEDATA", new { id = Model.users[0].Id })
            </td>
        </tr>
    }*@

</table>


Sunday, 29 May 2016

Cascading Dropdown

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>

@Html.DropDownList("Country", (IEnumerable<SelectListItem>)ViewBag.dropdownbind, "--Choose Your Country--")
@Html.DropDownList("State", (IEnumerable<SelectListItem>)ViewBag.DropdowndataState, "--Choose Your State--")


<script type="text/javascript">

    $(document).ready(function () {
        $('#State').css('display', 'none');
        //Dropdownlist Selectedchange event
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")', // we are calling json method
                dataType: 'json',
                data: { id: $("#Country").val() },
                // here we are get value of selected country and passing same value as inputto json method GetStates.
                success: function (states) {
                    if (states.length == 0) {
                        $('#State').css('display', 'none');
                        alert("Country doesnt have any state");
                    }
                    else {
                        $('#State').css('display', 'block');
                        // states contains the JSON formatted list
                        // of states passed from the controller
                        $.each(states, function (i, state) {

                            $("#State").append('<option value="' + state.Value + '">' +
                                 state.Text + '</option>');
                            // here we are adding option for States
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });

</script>

Thursday, 19 May 2016

Machine Test MVC

MODEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data;

namespace MyMvcApplication.Models
{
    public class Mobiledata
    {
        public int MobileID { get; set; }

        [Required(ErrorMessage = "Please Enter Mobile Name")]
        [Display(Name = "Enter Mobile Name")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Mobile Name must be between 3 and 50 characters!")]
        public string MobileName { get; set; }

        [Required(ErrorMessage = "Please Enter MobileIMEno")]
        [Display(Name = "Enter MobileIMEno")]
        [MaxLength(100, ErrorMessage = "Exceeding Limit")]
        public string MobileIMEno { get; set; }

        [Required(ErrorMessage = "Please Enter Mobile Price")]
        [Display(Name = "Enter Mobile Price")]
        [DataType(DataType.Currency)]
        public string mobileprice { get; set; }

        [Required(ErrorMessage = "Please Enter Mobile Manufacured")]
        [Display(Name = "Enter Mobile Manufacured")]
        [DataType(DataType.Text)]
        public string mobileManufacured { get; set; }

        public DataSet StoreAllData { get; set; }

    }

}

CONTROLLER
using MyMvcApplication.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMvcApplication.Controllers
{
    public class MobileStoreController : Controller
    {
        //
        // GET: /MobileStore/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult InsertMobile() // Calling when we first hit controller.
        {
            return View();
        }

        [HttpPost]
        public ActionResult InsertMobile(Mobiledata MB) // Calling on http post (on Submit)
        {
            if (ModelState.IsValid) //checking model is valid or not
            {
                DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
                string result = objDB.InsertData(MB); // passing Value to DBClass from model
                ViewData["result"] = result;
                ModelState.Clear(); //clearing model
                return View();
            }
            else
            {
                ModelState.AddModelError("", "Error in saving data");
                return View();
            }
        }

        //(StoreAlldata)
        public ActionResult ShowAllMobileDetails(Mobiledata MB)
        {
            DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
            MB.StoreAllData = objDB.SelectAllData();
            return View(MB);
        }

        public ActionResult EDITMOBILEDATA(string id)
        {
            DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
            DataSet ds = objDB.SelectAllDatabyID(id);
            Mobiledata MB = new Mobiledata();
            MB.MobileID = Convert.ToInt32(ds.Tables[0].Rows[0]["MobileID"].ToString());
            MB.MobileName = ds.Tables[0].Rows[0]["MobileName"].ToString();
            MB.MobileIMEno = ds.Tables[0].Rows[0]["MobileIMEno"].ToString();
            MB.mobileprice = ds.Tables[0].Rows[0]["mobileprice"].ToString();
            MB.mobileManufacured = ds.Tables[0].Rows[0]["mobileManufacured"].ToString();
            return View(MB);
        }

        [HttpPost]
        public ActionResult EDITMOBILEDATA(Mobiledata MD)
        {
            DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
            string result = objDB.UpdateData(MD); // passing Value to DBClass from model
            ViewData["resultUpdate"] = result; // for dislaying message after updating data.
            return RedirectToAction("ShowAllMobileDetails", "Mobilestore");
        }

        public ActionResult DELETEMOBILEDATA(string id)
        {
            DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
            DataSet ds = objDB.SelectAllDatabyID(id);
            Mobiledata MB = new Mobiledata();
            MB.MobileID = Convert.ToInt32(ds.Tables[0].Rows[0]["MobileID"].ToString());
            MB.MobileName = ds.Tables[0].Rows[0]["MobileName"].ToString();
            MB.MobileIMEno = ds.Tables[0].Rows[0]["MobileIMEno"].ToString();
            MB.mobileprice = ds.Tables[0].Rows[0]["mobileprice"].ToString();
            MB.mobileManufacured = ds.Tables[0].Rows[0]["mobileManufacured"].ToString();
            return View(MB);
        }

        [HttpPost]
        public ActionResult DELETEMOBILEDATA(Mobiledata MD)
        {
            DataAccessLayer.DBData objDB = new DataAccessLayer.DBData(); //calling class DBdata
            string result = objDB.DeleteData(MD);
            return RedirectToAction("ShowAllMobileDetails", "Mobilestore");
        }
    }

}

VIEW
INSERT
@model MyMvcApplication.Models.Mobiledata

@{
    ViewBag.Title = "InsertMobile";
}

<h2>InsertMobile</h2>

<table>
    <tr>
        <td>
            @Html.ActionLink("Show All Mobile List", "ShowAllMobileDetails")
        </td>
    </tr>
</table>
@using (Html.BeginForm())
{
    <table width="100%">
        <tr>
            <td>
                @Html.LabelFor(a => a.MobileName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.MobileName)
                @Html.ValidationMessageFor(a => a.MobileName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.MobileIMEno)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.MobileIMEno)
                @Html.ValidationMessageFor(a => a.MobileIMEno)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.mobileManufacured)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.mobileManufacured)
                @Html.ValidationMessageFor(a => a.mobileManufacured)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.mobileprice)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.mobileprice)
                @Html.ValidationMessageFor(a => a.mobileprice)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Submit1" type="submit" value="submit" />
            </td>
        </tr>
    </table>
}
@{
    if (ViewData["result"] != "" && ViewData["result"] != null)
    {
        ViewData["result"] = null;
        <script type="text/javascript" language="javascript">
            alert("Data saved Successfully");
        </script>
    }
}

EDIT
@model MyMvcApplication.Models.Mobiledata

@{
    ViewBag.Title = "EDITMOBILEDATA";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>EDITMOBILEDATA</h2>

<table>
    <tr>
        <td>
            @Html.ActionLink("Show All Mobile List", "ShowAllMobileDetails")
        </td>
    </tr>
</table>
<br />
@using (Html.BeginForm())
{
    <table width="100%">
        <tr>
            <td colspan="2">
                @Html.HiddenFor(a => a.MobileID)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.MobileName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.MobileName)
                @Html.ValidationMessageFor(a => a.MobileName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.MobileIMEno)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.MobileIMEno)
                @Html.ValidationMessageFor(a => a.MobileIMEno)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.mobileManufacured)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.mobileManufacured)
                @Html.ValidationMessageFor(a => a.mobileManufacured)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.mobileprice)
            </td>
        </tr>
        <tr>
            <td>
                @Html.TextBoxFor(a => a.mobileprice)
                @Html.ValidationMessageFor(a => a.mobileprice)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Submit1" type="submit" value="Update" />
            </td>
        </tr>
    </table>
}
@{
    if (ViewData["resultUpdate"] != "" && ViewData["resultUpdate"] != null)
    {
        ViewData["resultUpdate"] = null;
        <script type="text/javascript" language="javascript">
            alert("Data Updated Successfully");
        </script>
    }
}
DELETE
@model MyMvcApplication.Models.Mobiledata

@{
    ViewBag.Title = "DELETEMOBILEDATA";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>DELETEMOBILEDATA</h2>

<table>
    <tr>
        <td>
            @Html.ActionLink("Add New Mobiles", "InsertMobile")
        </td>
        <td>
            @Html.ActionLink("Show All Mobile List", "ShowAllMobileDetails")
        </td>
    </tr>
</table>
<br />
@using (Html.BeginForm())
{
    <table width="100%">
        <tr>
            <td colspan="2">
                @Html.HiddenFor(a => a.MobileID)
            </td>
        </tr>
        <tr>
            <td>
                MobileName :-
                @Html.DisplayFor(a => a.MobileName)
            </td>
        </tr>
        <tr>
            <td>
                MobileIMEI Number:-
                @Html.DisplayFor(a => a.MobileIMEno)
            </td>
        </tr>
        <tr>
            <td>
                Mobile Manufacured :-
                @Html.DisplayFor(a => a.mobileManufacured)
            </td>
        </tr>
        <tr>
            <td>
                Mobileprice :-
                @Html.DisplayFor(a => a.mobileprice)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Submit1" onclick="return confirm('Are you sure you want delete');" type="submit"
                       value="Delete" />
            </td>
        </tr>
    </table>
}
SHOW
@model MyMvcApplication.Models.Mobiledata

@{
    ViewBag.Title = "ShowAllMobileDetails";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ShowAllMobileDetails</h2>

<table>
    <tr>
        <td>
            @Html.ActionLink("Add New Mobiles", "InsertMobile")
        </td>
    </tr>
</table>
@{
    for (int i = 0; i < Model.StoreAllData.Tables[0].Rows.Count; i++)
    {
        var MobileID = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString();
        var MobileName = Model.StoreAllData.Tables[0].Rows[i]["MobileName"].ToString();
        var MobileIMEno = Model.StoreAllData.Tables[0].Rows[i]["MobileIMEno"].ToString();
        var Mobileprice = Model.StoreAllData.Tables[0].Rows[i]["mobileprice"].ToString();
        var MobileManufacured = Model.StoreAllData.Tables[0].Rows[i]["mobileManufacured"].ToString();
        <table width="100%">
            <tr>
                <td>
                    MobileID
                </td>
                <td>
                    MobileName
                </td>
                <td>
                    Mobile IMEI No
                </td>
                <td>
                    Mobileprice
                </td>
                <td>
                    Mobile Manufactured
                </td>
                <td>
                    EDIT
                </td>
                <td>
                    DELETE
                </td>
            </tr>
            <tr>
                <td>
                    @MobileID
                </td>
                <td>
                    @MobileName
                </td>
                <td>
                    @MobileIMEno
                </td>
                <td>
                    @Mobileprice
                </td>
                <td>
                    @MobileManufacured
                </td>
                <td>
                    @Html.ActionLink("EDIT", "EDITMOBILEDATA", new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })
                </td>
                <td>
                    @Html.ActionLink("Delete", "DELETEMOBILEDATA", new { id = Model.StoreAllData.Tables[0].Rows[i]["MobileID"].ToString() })
                </td>
            </tr>
            <tr>
                <td>
                    @Html.ActionLink("Add New Mobiles", "InsertMobile")
                </td>
            </tr>
        </table>
    }
}

Sunday, 17 April 2016

WCF

create a wcf service->write below code in interface

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceDemo
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        CustomerData Get();

        [OperationContract]
        void Insert(string userName, string location);

        [OperationContract]
        void Update(int userId, string userName, string location);

        [OperationContract]
        void Delete(int userId);
    }
    [DataContract]
    public class CustomerData
    {
        public CustomerData()
        {
            this.CustomersTable = new DataTable("UserInformation");
        }

        [DataMember]
        public DataTable CustomersTable { get; set; }
    }
 }

write below code in service.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


namespace WcfServiceDemo
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class Service : IService
    {
        public CustomerData Get()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT UserId, UserName, Location FROM MySampleDB"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            CustomerData customers = new CustomerData();
                            sda.Fill(customers.CustomersTable);
                            return customers;
                        }
                    }
                }
            }
        }

        public void Insert(string userName, string location)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO MySampleDB (UserName, Location) VALUES (@UserName, @Location)"))
                {
                    cmd.Parameters.AddWithValue("@UserName", userName);
                    cmd.Parameters.AddWithValue("@Location", location);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        public void Update(int userId, string userName, string location)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE MySampleDB SET UserName = @UserName, Location = @Location WHERE UserId = @UserId"))
                {
                    cmd.Parameters.AddWithValue("@UserId", userId);
                    cmd.Parameters.AddWithValue("@UserName", userName);
                    cmd.Parameters.AddWithValue("@Location", location);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        public void Delete(int userId)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE UserId = @UserId"))
                {
                    cmd.Parameters.AddWithValue("@UserId", userId);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }
}

IN CLIENT WRITE BELOW CODE
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WcfClient.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="UserId"
                OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowUpdating="OnRowUpdating"
                 OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added.">
                <Columns>
                    <asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("UserName") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
                        <ItemTemplate>
                            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Location") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Location") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
                </Columns>
            </asp:GridView>
            <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
                <tr>
                    <td style="width: 150px">Name:<br />
                        <asp:TextBox ID="txtName" runat="server" Width="140" />
                    </td>
                    <td style="width: 150px">Country:<br />
                        <asp:TextBox ID="txtCountry" runat="server" Width="140" />
                    </td>
                    <td style="width: 100px">
                        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
in cs file write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WcfClient
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        private void BindGrid()
        {
            ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            GridView1.DataSource = client.Get().CustomersTable;
            GridView1.DataBind();
        }
        protected void Insert(object sender, EventArgs e)
        {
            ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            client.Insert(txtName.Text.Trim(), txtCountry.Text.Trim());
            this.BindGrid();
        }

        protected void OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.BindGrid();
        }

        protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = GridView1.Rows[e.RowIndex];
            int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
            string name = (row.FindControl("txtName") as TextBox).Text;
            string country = (row.FindControl("txtCountry") as TextBox).Text;
            //CRUD_Service.ServiceCS service = new CRUD_Service.ServiceCS();
            ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            client.Update(customerId, name, country);
            GridView1.EditIndex = -1;
            this.BindGrid();
        }

        protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
            //CRUD_Service.ServiceCS service = new CRUD_Service.ServiceCS();
            ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            client.Delete(customerId);
            this.BindGrid();
        }

        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
            {
                (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
            }
        }

    }
}

Saturday, 11 July 2015

Binary image

You can not simply bind binary image to a control. You have to create an HttpHandler(.ashx) that process the image.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace DisplayImages
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : System.Web.IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
            {
                const string SQL = "SELECT Image,ImageName FROM ImageToDB WHERE [ID] = @ID";
                SqlCommand myCommand = new SqlCommand(SQL, myConnection);
                myCommand.Parameters.AddWithValue("@ID", 4);

                myConnection.Open();
                SqlDataReader myReader = myCommand.ExecuteReader();

                if (myReader.Read())
                {
                    //byte[] buffer = GetPictureFromSomewhere();
                    context.Response.ContentType = "image/jpg";
                    context.Response.OutputStream.Write(((byte[])myReader["Image"]), 0, ((byte[])myReader["Image"]).Length);
                    //(byte[])myReader["Image"]
                    //string base64String = Convert.ToBase64String((byte[])myReader["Image"], 0, ((byte[])myReader["Image"]).Length);
                    //image.ImageUrl = "data:image/jpg;base64," + base64String;
                    //Image1.Visible = true;
                }

                myReader.Close();
                myConnection.Close();
            }           
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}

add the follwong code in default.aspx, design code is below the c# code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DisplayImages
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);
            string contenttype = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {
                case ".doc":
                    contenttype = "application/vnd.ms-word";
                    break;
                case ".docx":
                    contenttype = "application/vnd.ms-word";
                    break;
                case ".xls":
                    contenttype = "application/vnd.ms-excel";
                    break;
                case ".xlsx":
                    contenttype = "application/vnd.ms-excel";
                    break;
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
                case ".png":
                    contenttype = "image/png";
                    break;
                case ".gif":
                    contenttype = "image/gif";
                    break;
                case ".pdf":
                    contenttype = "application/pdf";
                    break;
            }
            if (contenttype != String.Empty)
            {

                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);

                //insert the file into database
                string strQuery = "insert into ImageToDB(Image,ImageName)" +
                   " values (@Image, @ImageName)";
                SqlCommand cmd = new SqlCommand(strQuery);
                cmd.Parameters.Add("@Image", SqlDbType.Binary).Value = bytes;
                cmd.Parameters.Add("@ImageName", SqlDbType.VarChar).Value = filename;
                //cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                InsertUpdateData(cmd);
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "File Uploaded Successfully";
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File format not recognised." +
                  " Upload Image/Word/PDF/Excel formats";
            }
        }

        private Boolean InsertUpdateData(SqlCommand cmd)
        {
            String strConnString = System.Configuration.ConfigurationManager
            .ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return false;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }
        private void BinaryToImage()
        {
            try
            {
                int PictureID = Convert.ToInt32(Request.QueryString["ID"]);

                using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
                {
                    const string SQL = "SELECT Image,ImageName FROM ImageToDB WHERE [ID] = @ID";
                    SqlCommand myCommand = new SqlCommand(SQL, myConnection);
                    myCommand.Parameters.AddWithValue("@ID", 4);

                    myConnection.Open();
                    SqlDataReader myReader = myCommand.ExecuteReader();

                    if (myReader.Read())
                    {
                        //Response.ContentType = myReader["MIME"].ToString();
                        Response.BinaryWrite((byte[])myReader["Image"]);
                    }

                    myReader.Close();
                    myConnection.Close();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void Show_Click(object sender, EventArgs e)
        {
            image.ImageUrl = "~/Handler1.ashx";          
            //image.ImageUrl = BinaryToImage();
            //BinaryToImage();
        }
    }
}

Design page of default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayImages.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload"
            OnClick="btnUpload_Click" />
        <br />
        <asp:Button ID="Show" runat="server" OnClick="Show_Click" Text="Show" />
        <br />
        <asp:Label ID="lblMessage" runat="server" Text=""
            Font-Names="Arial"></asp:Label>
        <asp:Image ID="image" runat="server" />
    </form>
</body>
</html>

Web.config file

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />

    <httpModules>
      <add name="Picture" type="Picture"/>
    </httpModules>
  </system.web>
  <connectionStrings>
    <add name="conString" connectionString="Server=SUNDARI-PC\SQLSERVER2012; Database=test; Integrated Security=True"/>
  </connectionStrings >
  <!--<configuration>
  <system.web>
    <httpModules>
      <add name="Picture" type="Picture"/>
     </httpModules>
  </system.web>
</configuration>-->
</configuration>



In your web.config you should add:
<httpHandlers>
    ...
    <add path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
      verb="*" validate="false" />
    ...
</httpHandlers>
To allow Asp.Net to manage every requests containig "ImageHandler.ashx" with the correct IHttpHandler class. And remember to add:
<system.webServer>
    <handlers>
    ...
    <add name="ImageHandler" path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
          verb="*" validate="false" />
    ...
    </handlers>
</system.webServer>

Sunday, 7 June 2015

jquery settimeout

setTimeout(function () {

window.location.href="form location";},2000);

or
in default.aspx design

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    Enter Name:
    <asp:TextBox ID="txtName" runat="server" />
    <br />
    <asp:Button Text="Submit" runat="server" OnClick="Submit" /><br />
    <br />
    <asp:Label ID="lblMessage" ForeColor="Green" Font-Bold="true" Text="Form has been submitted successfully."
        runat="server" Visible="false" />
    <script type="text/javascript">
       
        window.onload = function () {
            debugger;
            var seconds = 5;
            setTimeout(function () {
                document.getElementById("<%=lblMessage.ClientID %>").style.display = "none";
            }, seconds * 1000);
        };
    </script>
    </form>
</body>
</html>

in code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Submit(object sender, EventArgs e)
    {
        lblMessage.Visible = true;
    }
}

Jquery popup

1. put <script src="AppResource/JS/jquery-1.9.1.min.js" type="text/javascript"></script>  and
<script src="AppResource/JS/jquery-ui.js" type="text/javascript"></script>  into master page or corresponding page.

2. Inside aspx page write below codes

<script type="text/javascript">

function Confirmpopup(){
$('#hider').fadeIn("slow");
$("#divConfirm").dialog({modal:true})
}

function CloseModalWnd(){
$('#hider').fadeOut("slow");
$(".ui-dialog-content").dialog().dialog("close");

function HideModalWind() {
$("#hider").hide();
$("#divConfirm").hide();
}

<style type="text/css">

.ui-dialog-content ui-widget-content{
width: 800px !import;
height:500px !import;
}

#divConfirm{
background-color:white;
width:1000px !import;
margin-top: -40px;
height:500px !impotant;
margin-left:-200px;
}
</style>

3. In code behind

declare globaly

 bool isHideModel=true;

write
protected override void onInit(EventArgs e)
{
if(isHideModel)
ScriptManager.RegisterStartupScript(Page, typeof(Page),"Hidepopout","HideModalWind();",true);
}

in button click to display popup code

protected void popout_click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript('Page,typeof(Page),"popout","Confirmpopup();",true);
}

4. ok close button inside popup

<input type="button" id="btnOk" value="Ok" onClick=""/>
<input type="button" id="btnClose" value="Close" style="Width: 50px; font-weight:bold;" onClick="CloseModalWnd();" />