Monday, 30 September 2013

populating drop down in mvc 3.0

first create table structure like this:


create  table.[country](

[pkCountryId] [int] primary key NOT NULL, [CountryName] [varchar](100) NULL)

CREATE TABLE [dbo].[State](
[pkStateId] [int] NOT NULL,
[StateName] [varchar](100) NULL,
[fkCountryId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
[pkStateId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
---------------------------------------------------------------------------------------------
create controller Country

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mukesh_Dropdown_example.EF;
using Mukesh_Dropdown_example.Models;

namespace Mukesh_Dropdown_example.Controllers
{
    public class CountryController : Controller
    {
        //
        // GET: /Country/
        masterEntities2 db;// = new masterEntities1();

        public CountryController()
        {
            db = new masterEntities2();
        }
        
        public ActionResult Index()
        {
            CountryModel cm = new CountryModel();
           
            cm.CountryList = new SelectList(db.Countries,
              "pkCountryId", "CountryName");
            cm.StateList = new SelectList(db.States, "pkStateId", "StateName");
            return View(cm);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult FillState(string CountryId)
        {
            int i = 0;
            Int32.TryParse(CountryId, out i);
            var r = db.States.Where(c => c.fkCountryId == i).ToList();
            var j = r.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = Convert.ToString(m.pkStateId)
            });
            return Json(j, JsonRequestBehavior.AllowGet);
        }

    }
}
--------------------------------------------------------------------------------------
create model CountryModel

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

namespace Mukesh_Dropdown_example.Models
{
    public class CountryModel
    {

        public int CountryId { get; set; }
        public SelectList CountryList { get; set; }

        public int StateId { get; set; }
        public SelectList StateList { get; set; }
    }
}
----------------------------------------------------------------------------------------------

now create view

@model Mukesh_Dropdown_example.Models.CountryModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
        <script  type="text/javascript">
            $(document).ready(function () {

                $("#CountryId").change(function () {


                    var idCountry = $(this).val();
                    $.getJSON("/Country/FillState", { CountryId: idCountry },
                    function (stateData) {
                        var select = $("#StateId");
                        select.empty();
                        select.append($('<option/>', {
                            value: "0",
                            text: "Select"
                        }));

                        var ddlCity = $("#City");
                        ddlCity.empty();
                        ddlCity.append($('<option/>', {
                            value: "0",
                            text: "Select"
                        }));
                        $.each(stateData, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
                });
                /*End Bind State by Country*/
             });
     
    </script>

</head>
<body>
    <div>
        @Html.DropDownListFor(em => Model.CountryId, Model.CountryList, "Select")
        @Html.DropDownListFor(em => Model.StateId, Model.StateList, "Select")
        
    </div>
</body>
</html>
----------------------------------------------------------------------------------------------
out put look like this


binding dropdown in mvc 3.0

1.first take controller  name depController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using dropdownbind.EF;

namespace dropdownbind.Controllers
{
    public class depController : Controller
    {
        //
        // GET: /dep/
        CustomerDBEntities db=new CustomerDBEntities ();      

        public ActionResult Index()
        {
            var items = db.Countries.ToList();
            SelectList list = new SelectList(items, "CountryId", "Name");
            ViewData["CountryList"] = list;
            return View();
        }

    }
}


2. step take class in model

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

namespace dropdownbind.Models
{
    public class CountryModel
    {
        public Guid CountryId { get; set; }
        public string CountryName { get; set; }
    }
}

3.now go to view  and do this


@model dropdownbind.Models.CountryModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{
<div>
@Html.DropDownList("CountryId", (SelectList)ViewData["CountryList"]);
</div>
}

output would be like this-


insert delete in grid in MVC 3.0 using jquery

first add controller Emp and do the code  and take one folder for EF and add .edmx
file in it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using viewbagwithjquery.EF;

namespace viewbagwithjquery.Controllers
{
    public class EmpController : Controller
    {
        //
        // GET: /Emp/
        //test_dbModel obj = new test_dbModel();
        test_dbEntities obj = new test_dbEntities();
        public ActionResult Index()
        {
            return View();
        }
       [OutputCache(Duration = 0)]
        public JsonResult ShowEmployee()
        {

            return Json(obj.emps, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult SaveEmployee(int empId, string empName, int empSalary)
        {
            obj.AddToemps(new emp { id = empId, name =empName,age= empSalary });
            obj.SaveChanges();

            return Json("Record has Inserted", JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteEmployee(int empId)
        {
            string Msg = string.Empty;

            try
            {
                emp Emp =obj.emps.Single(em => em.id == empId);
                obj.DeleteObject(Emp);
                obj.SaveChanges();
                Msg = "Record has Deleted";
            }
            catch (Exception ex)
            {
                Msg = ex.Message;

            }


            return Json(Msg, JsonRequestBehavior.AllowGet);
        }

    }
}

---------------------------------------------------------------------------------------
view

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
 
    <script  type="text/javascript">
        $(document).ready(function () {
            show();
        });      

        function show() {

            $.get('/Emp/ShowEmployee', null, function (data) { chk(data); });
        }
        function chk(abc) {
     
            BuildTable(abc)
         }
          function BuildTable(msg) {
       
             var table = '<table><thead><tr><th style=background-color:#FAEBD7;width:100px; >Emp Id</th><th style=background-color:#FAEBD7;width:100px; >Emp Name</th><th style=background-color:#FAEBD7;width:100px; >Emp age</th><th style=background-color:#FAEBD7;width:100px; >Operation</th></thead><tbody>';
             for (var cd in msg) {
                 var row = '<tr>';
                 row += '<td style=background-color:Silver;width:100px; >' + msg[cd].id + '</td>';
                 row += '<td style=background-color:Silver;width:100px; >' + msg[cd].name + '</td>';
                 row += '<td style=background-color:Silver;width:100px; >' + msg[cd].age + '</td>';
                 row += '<td style=background-color:Silver;width:100px; >'
                 + '<input id="btnDelete" onclick="Delete(' + msg[cd].id + ')"  type="button" value="Delete" /></td>';
                 row += '</tr>';
                 table += row;
             }
             row = '<tr><td style=background-color:#FAEBD7;width:100px; ><input id="txtEmpId" type="text" /></td>';
             row += '<td style=background-color:#FAEBD7;width:100px; ><input id="txtEmpName" type="text" /></td>';
             row += '<td style=background-color:#FAEBD7;width:100px; ><input id="txtEmpSalary" type="text" /></td>';
             row += '<td style=background-color:#FAEBD7;width:100px; ><input id="btnSave" onClick="save();" type="button" value="Save" /></td>';
             row += '</tr>';
             table += row;
             table += '</tbody></table>';
             $('#d1').html(table);
         }
         function save() {

             var EmpId = $('#txtEmpId').val();
             var EmpName = $('#txtEmpName').val();
             var EmpSalary = $('#txtEmpSalary').val();

             $.post('/Emp/SaveEmployee', { empId: EmpId, empName: EmpName, empSalary: EmpSalary },
              function (data) { chkSave(data); });
         }
         function chkSave(abc) {
             alert(abc);
             show();
         }
         function Delete(EmpId) {

             $.post('/Emp/DeleteEmployee', { empId: EmpId }, function (data) { chkDelete(data); });
         }
         function chkDelete(abc) {
             alert(abc);
             show();
         }
        </script>
        </head>
<body>

    <div id="d1" >
     
    </div>
</body>
</html>
----------------------------------------------------------------------

Emp Id Emp Name Emp age Operation
23 deepak 45
24 hari 35

Friday, 20 September 2013

interview questions in asp.net

Q1.

public partial class ser1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Server.Transfer("ser2.aspx");
        }
        catch
        {
            Server.Transfer("ser3.aspx");
        }
        finally
        {
            Server.Transfer("ser4.aspx");
        }
    }
}

and page  ser2 on page _load
Response.Write("2");
and page  ser3on page _load
Response.Write("3");
and page  ser4 on page _load
Response.Write("3");

so what would be output if we run ser1  page







Thursday, 12 September 2013

insert delete update in wcf using entity framework

first create table

create table book
( ID int identity(1,1),
BooKName varchar(50)
)
-------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestBookexample
{
    // 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 IService1
    {

        [OperationContract]
        List<Booki> GetBooksList();

        [OperationContract]
        List<Booki> GetBookById(string id);

        [OperationContract]
        void AddBook(string name);

        [OperationContract]
        void UpdateBook(string id, string name);

        [OperationContract]
        void DeleteBook(string id);

     
        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Booki
    {

        int Id = 0;
        string bookName ="";

        [DataMember]
        public string BookName
        {
            get { return bookName; }
            set { bookName = value; }
        }
        [DataMember]
        public int ID
        {
            get { return Id; }
            set { Id = value; }
        }
     
    }
}
----------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestBookexample
{

    public class Service1 : IService1
    {

        public List<Booki> GetBooksList()
        {
            test_dbEntities entities = new test_dbEntities();
            Booki boo = null;
            List<Booki> booklist = new List<Booki>();
            for (int i = 0; i < entities.books.ToList().Count; i++)
            {
                 boo = new Booki();
                 boo.BookName = entities.books.ToList()[i].BooKName;
                 boo.ID = entities.books.ToList()[i].ID;
                 booklist.Add(boo);            

            }
            return booklist;      
            
        }

        public List<Booki> GetBookById(string id)
        {
            int bookId = Convert.ToInt32(id);
            List<Booki> booklist = new List<Booki>();
            try
            {                              
            
            test_dbEntities entities = new test_dbEntities();
            Booki boo = null;
            
            for (int i = 0; i < entities.books.ToList().Count; i++)
            {
                 boo = new Booki();
                 boo.BookName = entities.books.ToList()[i].BooKName;
                 boo.ID = entities.books.ToList()[i].ID;
                 booklist.Add(boo); 
            }         
               
            }
            catch
            {
                throw new FaultException("Something went wrong");
            }
            return booklist.Where(em => em.ID == bookId).ToList().Take(1).ToList();
        }

        public void AddBook(string name)
        {
            test_dbEntities entities = new test_dbEntities();
            book boo = new book();
            boo.BooKName = name;
            entities.AddTobooks(boo);
            entities.SaveChanges();
        }

        public void UpdateBook(string id, string name)
        {
            try
            {
                int bookId = Convert.ToInt32(id);

                using (test_dbEntities entities = new test_dbEntities())
                {
                    book book1 = entities.books.SingleOrDefault(b => b.ID == bookId);
                    book1.BooKName = name;
                    entities.SaveChanges();
                }
            }
            catch
            {
                throw new FaultException("Something went wrong");
            }
        }

        public void DeleteBook(string id)
        {
            try
            {
                int bookId = Convert.ToInt32(id);

                using (test_dbEntities entities = new test_dbEntities())
                {
                    book book1 = entities.books.SingleOrDefault(b => b.ID == bookId);
                    entities.DeleteObject(book1);
                    entities.SaveChanges();
                }
            }
            catch
            {
                throw new FaultException("Something went wrong");
            }
        }
    }
}

creatting wcf service with two end points

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


namespace WcfService2
{
    // 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 IService1
    {
        [OperationContract]
        List<empdata> getemp();            
    }
    [ServiceContract]
    public interface IService2
    {
        [OperationContract]
        List<empdata> getemp1();
        [OperationContract(IsOneWay=true)]
        void display();    

    }
    [DataContract]
    public class empdata
    {
        private int id;
        private string name;
        private int age;

        [DataMember]
        public int ID
        {
            get { return id; }
            set { id = value; }
        }
        [DataMember]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        [DataMember]
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}
-------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
   [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class Service1 : IService1, IService2
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        DataTable dt = new DataTable();
        SqlDataReader dr;
        public List<empdata> getemp()
        {
            List<empdata> emplist = new List<empdata>();
            try
            {            
                empdata data = null;
                if (con.State == ConnectionState.Open)
                    con.Close();
                SqlCommand cmd = new SqlCommand("sp_fetchdata", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    data = new empdata();
                    data.ID = Convert.ToInt32(dt.Rows[i]["id"].ToString());
                    data.Name = Convert.ToString(dt.Rows[i]["name"].ToString());
                    data.Age = Convert.ToInt32(dt.Rows[i]["age"].ToString());
                    emplist.Add(data);
                }
            }
            catch (Exception ex)
            {

            }
            return emplist;        
        }
        public List<empdata> getemp1()
        {
            List<empdata> emplist = new List<empdata>();
            empdata data = null;
            if (con.State == ConnectionState.Open)
                con.Close();
            SqlCommand cmd = new SqlCommand("sp_fetchdata", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            dr = cmd.ExecuteReader();
            dt.Load(dr);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = new empdata();
                data.ID = Convert.ToInt32(dt.Rows[i]["id"].ToString());
                data.Name = Convert.ToString(dt.Rows[i]["name"].ToString());
                data.Age = Convert.ToInt32(dt.Rows[i]["age"].ToString());
                emplist.Add(data);
            }
            return emplist;
        }
 public void display()
      {
          string str = "method";

      }

  }
}
--------------------------------------------------------------------------------------------
web.config

  <services>
      <service name="WcfService2.Service1" behaviorConfiguration="WcfService2.Service1Behavior">
        <!-- Service Endpoints -->
        <endpoint address=" " binding="wsHttpBinding" contract="WcfService2.IService1">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="" binding="wsHttpBinding" contract="WcfService2.IService2">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfService2.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

Friday, 6 September 2013

some lambda expression with list

some lambda expression with list

1. finding max
 var max = db.emps.ToList().Max(em=>em.id);

2. order by
var order = db.emps.ToList().OrderByDescending(em=>em.name) ;

3. sum
var sum= db.emps.ToList().Sum(p => p.id);

generate grid using jquery

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

<!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">
   <script src="Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
 function showData() {

            $.ajax({
                url: 'Default4.aspx/Show',
                type: 'post',
                data: '{}',
                contentType: 'application/json;charset=utf-8',
                dataType:'json',
                success: function (amit) {
                 chkShowData(amit);
                 },
             Error: function (amit) {
                alert(amit)
                }
            });
     }
     function chkShowData(abc) {
         //debugger;
         FillEmployee(abc.d);
     }

     function FillEmployee(EmpData) {
         var table = "<table>"
         + "<tr>"
         + "<td style=width:100px;background-color:silver;color:navy;>Emp Id</td>"
         + "<td style=width:100px;background-color:silver;color:navy;>Emp Name</td>"
         + "<td style=width:100px;background-color:silver;color:navy;>Emp age</td>"
         + "</tr>";
         var Row = "";
         for (var indx in EmpData) {
             Row += "<tr>"
         + "<td style=width:100px;background-color:silver;color:navy;>" +
         EmpData[indx].id+ "</td>"
         + "<td style=width:100px;background-color:silver;color:navy;>" +
         EmpData[indx].name + "</td>"
         + "<td style=width:100px;background-color:silver;color:navy;>" +
         EmpData[indx].age + "</td>"
         + "</tr>"
         }
         table += Row;
         table += "</table>";
         $('#d1').html(table);
     }
     
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="d1"></div>
    <input id="Button1" onclick="showData();" type="button" value="Show" />
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------------------
default4.aspx page code


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

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static List<emp> Show()
    {
        test_dbEntities db = new test_dbEntities();      

        return db.emps.ToList();
    }
}