Saturday, March 16, 2013

Add, Update with Entity Framework 5

CRUD sample with Entity Framework 5.

in EF 5 there is something called DBContext, which is little different than earlier ObjectContext, DBContext generate less code to achieve the same functionality, and is based on code first principle

this is how the dbcontext file look like and connection string to be set

public partial class GoldEntities : DbContext
    {
        static string secureConnectionString = Util.EntityFrameworkConnectionString;

        public GoldEntities()
            : base(secureConnectionString)
        {
        }
}


ADD :

public bool AddDesignType(tbProductType designType)
        {
            bool result = false;
            using (var context = new GoldEntities())
            {
                context.tbProductTypes.Add(designType);
                context.SaveChanges();
                result = true;
            }
            return result;
        }

UPDATE using Entityframework 5:
to update an entity you wont find applychanges method, so here is how you can update an entity.

public bool UpdateColorStoneName(tbColorStoneName colorStoneName)
        {
            bool isSaved = false;
            using (var context = new GoldEntities())
            {
                tbColorStoneName csn = context.tbColorStoneNames
                    .Where(d => d.ColorStoneNameId == colorStoneName.ColorStoneNameId)
                    .FirstOrDefault();

                if (csn != null)
                {
                    context.Entry(csn).State = EntityState.Modified;
                    context.SaveChanges();
                    isSaved = true;
                }
            }
            return isSaved;
        }




Tuesday, February 26, 2013

Loading dropdownlist in MVC2 and MVC4

Loading doropdownlist in MVC2 and MVC4.


This is the code you will write in Models, here you create a cs file called ProfileModel inside Models folder an write the following code.

public interface IAdminService
    {
        List< tblCountry > GetCountries();
    }


    public class AdminService : IAdminService
    {
        /* this you can cosider as data provider, like any Services, any other assembly etc. */
AdminDTO _adminProvider;
        MasterDTO _masterProvider;

        public AdminService()
        {
            _adminProvider = new AdminDTO();
            _masterProvider = new MasterDTO();
        }


        public List< tblCountry > GetCountries()
        {
            return MasterDTO.GetContries();
        }
    }

now here we see how to call the dataService in controller

public class ProfileController : Controller
    {

        public IDataService dataService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if dataService == null) { dataService = new DataService(); }

            base.Initialize(requestContext);
        }


/* this is an example of view implementation in example  */
[HttpGet]
        public ActionResult ManageProfile()
        {
            ViewBag.Countries = dataService.GetCountries();
            ViewBag.Message = string.Format("There are {0} contries", dataService.GetCountries().Count);


            List countryList = (from p in
                                                   dataService.GetCountries().ToList()
                                               select new SelectListItem()
                                               {
                                                   Value = p.CountryId.ToString(),
                                                   Text = p.CountryName
                                               }).ToList();

            ViewBag.CountryDropdown = countryList;

            return View();
        }
}

Now your view is ready with data, you just need to display on screen , so here is how you can achieve that.
In "Views" folder you need to create a folder called "Profile", inside the "Profile" folder create a razor page with name ManageProfile, and write the code below.


this is an example of country dorpdown, "CountryDropdown" is nothing but the variable of your view bag
@Html.DropDownList("CountryDropdown")


  this is an example of how the collection object can be displayed like datalist/gridview/collectionbinding
    @{
        var countries = ViewBag.Countries;
    }
    < table >
        @foreach (tblCountry c in countries)
        {
            < tr >
                < td >@c.CountryId
                < /td >
                < td >
                    @Html.ActionLink(c.CountryName, "AddEditState", new { cid = c.CountryId, name = c.CountryName });
                < /td >
                < td >@c.CurrencyCode
                < /td >
                < td >@c.Currency
                < /td >
                < td >@c.Capital
                < /td >
                < td >@c.Population
                < /td >
            < /tr >
        }
    < /table >


 please note : example how to pass parameters with Html.ActionLink()  @Html.ActionLink(c.CountryName, "AddEditState", new { cid = c.CountryId, name = c.CountryName });




Tuesday, February 19, 2013

WCF Rest example

Create a WCF Service, Delete the default added service and follow the steps below.

Step 1: Create a object called Student, this object we use in our example


 [DataContract]
    public class Student
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public int ClassId { get; set; }

        [DataMember]
        public string Firstname { get; set; }

        [DataMember]
        public string Lastname { get; set; }
    }

Now create a WCF service with any business name as per your requirement, here i have created a service called RestfulServiceExample.svc , open the interface created with name IRestfulServiceExample, here i have added four example of Json and XML with single object and collection object

Here is how the definition would look like.

using System.ServiceModel;
using System.ServiceModel.Web;
using WcfRestExample.BusinessObjects;
using System.Collections.Generic;

namespace WcfRestExample
{

    [ServiceContract(Namespace = "http://arindamachakraborty.blogspot.in")]
    public interface IRestfulServiceExample
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xml/{id}")]
        Student XMLStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "json/{id}")]
        Student JSONStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xmls/{id}")]
        List XMLStudents(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "jsons/{id}")]
        List JSONStudents(string id);
    }
}

Note : in WebInvoke attribute Method value is case sensitive, that should always be  Method = "GET", not Method = "Get" or Method = "get"

Now lets look at the implementation of interface.


public class RestfulServiceExample : IRestfulServiceExample
    {

        public Student JSONStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }

        public Student XMLStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }


        public List< Student > XMLStudents(string id)
        {
            List< Student > students = new List< Student >();
            students.Add(new Student(){ ClassId=1, Firstname="Arindam", Lastname="Chakraborty", StudentId=1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });


            return students;
        }

        public List< Student > JSONStudents(string id)
        {
            List< Student  > students = new List< Student >();
            students.Add(new Student() { ClassId = 1, Firstname = "Arindam", Lastname = "Chakraborty", StudentId = 1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });
         
            return students;
        }
    }

We are done with service development, now we look at service configuration and how to publish

< system.serviceModel >
    < services >
      < service name="WcfRestExample.RestfulServiceExample" behaviorConfiguration="ServiceBehavior" >
        < endpoint  binding="webHttpBinding"
                  contract="WcfRestExample.IRestfulServiceExample"
                  behaviorConfiguration="web" >
        < /endpoint >
      < /service >
    < /services >

Notice we have set binding="webHttpBinding"

    < behaviors >
      < serviceBehaviors >
        < behavior name="ServiceBehavior" >
          < !-- 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 >
      < endpointBehaviors >
        < behavior name="web" >
          < webHttp / >
        < /behavior >
      < /endpointBehaviors >
    < /behaviors >
    < serviceHostingEnvironment multipleSiteBindingsEnabled="true" / >
  < /system.serviceModel >

Now we have successfully built and published the service, so its time to test the service, so you can see how the end result will look like.

Here is the url you need to run
http://machinename/servicename/xml - xml output for single objetc
http://machinename/servicename/xmls - xml output for collection object
http://machinename/servicename/json - json single object
http://machinename/servicename/jsons -  json output collection objects

Tuesday, January 22, 2013

Masterpage in mvc4 or layout design in mvc4

Wondering how to set masterpage in MVC4 ! _Layout.cshtml is same as master page in aspx, the moment you create mvc4 application you may notice the file in shared folder inside the root. First time it may look like how to customize the masterpage ( template ) with user control as per your business need,  MVC 4 is much easier than i expected it to be.

I am happy to share my first template design with MVC4

< html >
< head >
    < meta charset="utf-8" / >
    < meta name="viewport" content="width=device-width" / >
    < title >@ViewBag.Title< /title >
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
< /head >
< body >
    < div >
        @{Html.RenderPartial("TopNavigation");}
    < /div >
    < div style="float: left; width: 15%;" >
        @{Html.RenderPartial("LeftNavigation");}
    < /div >
    < div style="float: left; width: 85%;" >
        @RenderBody()
        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    < /div >
    < div style="clear: both;" >
    < /div >
    < div >
        @{Html.RenderPartial("BottomNav");}
    < /div >
< /body >
< /html >


if you notice @{Html.RenderPartial("PartialViewName");} is the syntax for adding any partial view (similar to user control )

Now lets use the master page in some mvc4 razor page, so i have created a razor page called aboutus.cshtml , and have written the code below

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

< h2 >AboutUs< /h2 >

< div >
This is something about the current organisation
< /div >

done, my master page / layout has been set successfully.

Wednesday, December 26, 2012

search using Ajax form in MVC2 implementation example

Here i will give you an example of how to perform search, display result using Ajax form in Asp.net MVC2. You may find this very useful in your realtime application devepoment in MVC 2

In this example i have used one view page and two usercontrol, the way i have implemented you should be able to use it direcly in any place of you application, wherever search action needs to be performed.

User control 1 ( named "SearchClient.ascx" ).
this will have a ajax form with a search text box and a submit button, so lets look at the code.

<   %@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl" % >
 <   script language="javascript" type="text/javascript">
     function searchValidate() {
         $get("dvResult").innerHTML = "Searching...";
         $get("btnSearch").disabled = true;
     }
     function searchSuccess(ajaxContext) {
         $get("dvResult").innerHTML = " successfully";
         $get("btnSearch").disabled = false;
     }
     function searchFaliure(ajaxContext) {
          $get("dvResult").innerHTML = "Search fail.";
         $get("btnSearch").disabled = false;
     }
    < /script>
    < div style="padding: 4px;">
        <  % using (Ajax.BeginForm("SearchClients",
               new AjaxOptions
               {
                   //Url = "SearchClients",
                   UpdateTargetId = "dvClients",
                   InsertionMode = InsertionMode.Replace,
                   OnBegin = "searchValidate",
                   OnSuccess = "searchSuccess",
                   OnFailure = "searchFaliure",
                   Confirm = "You sure you want to perform this search?",
                   HttpMethod = "Post"
               }))
           {%>
        < %= Html.TextBox("Search")% >
        < input type="submit" value="Search" id="btnSearch" />
       
        < div id="dvResult" >
        < /div>
        < %} %>
    < /div>

Now we see the controller implementation
        [ HttpPost ]
        [ AcceptVerbs(HttpVerbs.Post) ]
        public ActionResult SearchClients(FormCollection cols)
        {
           
            string searchText = cols["Search"] as string;
           
            List list = ClientService.SearchContacts(searchText);
            ViewData["SearchResult"] = list;

            ViewData["Message"] = string.Format("We performed search for \"{0}\", and found {1} results. ", searchText, list.Count);
            return PartialView("SearchClients", list);
        }

here i am not explaining how the database call is made, i am assuming you are familier with that part.

Now we see the second usercontrol (name "SearchClients.ascx" ) where we implement the search result, so lets look at how the result to be displayed.

<    %@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %  >
<  %@ Import Namespace="ETG.CRM2.MVC.Models" %  >
<  %@ Import Namespace=" ETG.CRM.Data" %  >
<  div id="dvResult"  >
    <  div style="padding: 2px; background-color: #feffd5;"  >
        <  %=ViewData["Message"]%  ><  /div  >
    <  table  >
        <  %foreach (tbContact c in (List<  tbContact  >)ViewData["SearchResult"])
          {%  >
        <  tr  >
           
            <  td  >
                <  %: c.OrgName%  >
            <  /td  >
            <  td  >
                <  %: c.OrgType%  >
            <  /td  >
            <  td  >
                <  %: c.Email%  >
            <  /td  >
            <  td  >
                <  %: c.ConcernPerson%  >
            <  /td  >
            <  td  >
                <  %: c.Phone%  >
            <  /td  >
           
        <  /tr  >
        <  %}%  >
    <  /table  >
<  /div  >
Now we need to have one page where we can render the first usercontrol. So you can create a simple mvc page and inside the content place the following line of code.
 
 < div style="padding:8px;" >
        < % Html.RenderPartial("SearchClient"); % >
    < /div >

We are done! make sure you have implemented the database call properly, ( in this example i have not mentioned that. ) then you should be able to use this search functionality from any place of the application.