A day with .Net

My day to day experince in .net

Archive for May, 2013

Seed database on application start EF code first

Posted by vivekcek on May 30, 2013

Create Your Context Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
 
namespace ContosoUniversity.Models
{
    public class SchoolContext : DbContext
    {
       
    }
}

Create a context initializer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {

        }
    }
}

Add this code under Application_Start(). Please remove this code in production.

Database.SetInitializer<SchoolContext>(new SchoolInitializer());

Posted in Entity Framework | Leave a Comment »

Remove Pluralizing TableName Entity Framework Code First

Posted by vivekcek on May 30, 2013

Try this code. Look at the namespaces used.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace ContosoUniversity.Models
{
    public class SchoolContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

Posted in Entity Framework | Leave a Comment »

Create database in App_Data folder Entity Frame Work Code First.

Posted by vivekcek on May 30, 2013

If you want EF to create your database under App_Data folder.

First set your connection string as below. Please note that the name should be same as your DbContext class name.

<add name="AppDB"
           connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|mydatabase.mdf;User Instance=true;Initial Catalog=myDataBase"
           providerName="System.Data.SqlClient" />

Example of context file.

public class AppDB : DbContext
    {
        public AppDB()
            : base("name=AppDB")
        {
            
        }
    }

Posted in Entity Framework, MVC | Leave a Comment »

ASP.NET MVC Request Pipeline and participating classes – Familiarization – Part1 – Routing

Posted by vivekcek on May 28, 2013

In this post, i would like to give you a small overview how MVC is working. I advise you to have a better look at System.Web.Routing and System.Web.Mvc. You can download MVC source code from codeplex too.

1. Request like http://mysite.com/Home/Index is issued by the browser.

The routing mechanism in MVC is implemented by System.Web.Routing available with .NET 4.0.
When the Application_Start() in Global.asax is fired, we register all Routes in our application and which will be stored in RouteTable.

Have a look at the high level diagram of classes in System.Web.Routing.

1

Now have a look at a detailed diagram of classes in System.Web.Routing.

2

UrlRoutingModule(System.Web.Routing)
—————————————————–

UrlRoutingModule is an HttpModule. Which inspect our URL pattern {controller}/{action} and try to match that pattern against Routes in RouteCollection.

Once a match is found, UrlRoutingModule call the GetHttpHandler() method of Route.
(GetHttpHandler() method is defined in IRouteHandler interface. Route class implement this interface)

At the same time UrlRoutingModule create RouteData and wrap it in a RequestContext object.

RouteData contain your request parameters.

ex: var controller=RouteData.Values[“Controller”];

So back to GetHttpHandler() method , which will return an instance of UrlRoutingHandler.
UrlRoutingModule pass the RequestContext to UrlRoutingHandler’s ProcessRequest() method.

3


UrlRoutingHandler(System.Web.Routing)

———————————————

UrlRoutingHandler create an instance of MvcHandler(System.Web.Mvc) and pass the RequestContext. From here we enter to the MVC Request Pipeline. That will be explained in next post

4

Posted in MVC | Leave a Comment »

MVC automatically adds required tags to non-nullable value types.

Posted by vivekcek on May 28, 2013

Your model contain an integer field and you haven’t specified any Required attribute. But on your create view the validation failed and show a message ‘This field is required’.

To turn this off add the below code to to Application_Start or make your int nullable

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Posted in MVC | Leave a Comment »

Auto-complete with MVC 4 and Jquery

Posted by vivekcek on May 28, 2013

1. Refer required CSS and Jquery libraries(jquery,jquerui)

2. Implement a controller action like this

public JsonResult Search(string term)
        {
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            };

            var movies = Movies.Where(x => x.Title.StartsWith(term)).Select(r => new {label=r.Title });
            return Json(movies, JsonRequestBehavior.AllowGet);
        }

Please note that parameter name should be ‘term‘. And returned json result should contain a ‘label‘ attribute.

3. Now write the below script in your page.

$(function () {
    $('#SearchBox').autocomplete({
        source: '/Home/Search'
    });
});

Posted in Jquery, MVC | Leave a Comment »

Error handling Ajax and MVC 4

Posted by vivekcek on May 27, 2013

Write a script

function handleError(ajaxContext) {
    alert(ajaxContext.status+" "+ajaxContext.statusText);
}

Now use the OnFailure property to point to error handling function

@using (
    Ajax.BeginForm("Index", "Home", new AjaxOptions
    {
        
        UpdateTargetId = "MovieTable",
        OnFailure = "handleError"
    }))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}

Posted in AJAX, MVC | Leave a Comment »

Partial Page Rendering MVC 4

Posted by vivekcek on May 27, 2013

1. Create a model

public class Movie
    {
        private string _title;

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
    }

2. Implement the home controllers Index action as given below.

public class HomeController : Controller
    {
             
        
        public ActionResult Index(string query)
        {
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            };
           
            var movies=Movies.Where(x=>x.ReleaseYear==(Convert.ToInt32(query))||query==null).ToList();
            if (Request.IsAjaxRequest())
            {
                return PartialView("_Movie", movies);
            }
            return View(movies);
        }
              
    }

3. Update the Razor of Index.cshtml as

@model IEnumerable<Learan.Models.Movie>
<h3>
    Move Search By year</h3>
@using (
    Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "MovieTable" }))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}
<div id="MovieTable">
    @Html.Partial("_Movie", Model)
</div>

4. Create the partial view _Movie.cshtml

@model IEnumerable<Learan.Models.Movie>

<p>
   Movie List
</p>
<table>
    <tr>
        <th>Title</th>
        <th>Year</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.Encode(item.Title)
        </td>
         <td>
            @Html.Encode(item.ReleaseYear)
        </td>
    </tr>
}

</table>

Posted in AJAX, MVC | Leave a Comment »

Implement a search box using MVC 4

Posted by vivekcek on May 27, 2013

1. Create a model

public class Movie
    {
        private string _title;

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
    }

2. Implement the home controllers Index action as given below.

public class HomeController : Controller
    {
             
        
        public ActionResult Index(string query)
        {
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            };
           
            var movies=Movies.Where(x=>x.ReleaseYear==(Convert.ToInt32(query))||query==null).ToList();
            return View(movies);
        }
              
    }

3. Update the Razor of Index.cshtml as

@model IEnumerable<Learan.Models.Movie>

<h3>
    Move Search By year</h3>
@using (
    Html.BeginForm("Index", "Home"))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}

<div id="MovieTable">
@Html.Partial("_Movie",Model)
</div>

4. Create the partial view _Movie.cshtml

@model IEnumerable<Learan.Models.Movie>

<p>
   Movie List
</p>
<table>
    <tr>
        <th>Title</th>
        <th>Year</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.Encode(item.Title)
        </td>
         <td>
            @Html.Encode(item.ReleaseYear)
        </td>
    </tr>
}

</table>

Posted in MVC | Leave a Comment »

Update Progress in MVC 4

Posted by vivekcek on May 27, 2013

The below code is used for showing a progress bar when an ajax link is clicked. The ‘LoadingElementId’ attribute of AjaxOptions can be used to specify a progress div.

<div id="timeDiv">
@Ajax.ActionLink("Click to get Server time", "GetServerTime", new AjaxOptions
{
    LoadingElementId = "Progress",
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "timeDiv"
})
</div>

<div id="Progress" style="display:none">
    <img src="../../Content/spinner.gif" alt="IMG" />
</div>

Posted in AJAX, MVC | Leave a Comment »