Tuesday, 15 January 2013

Basic Links for MVC Developers


jQuery
==================
Async Call
-----------

http://forums.asp.net/t/1741929.aspx/1
http://api.jquery.com/jQuery.getJSON/


Entity Framework
==================
EF 4 Tutorial
---------------

http://www.entityframeworktutorial.net/entityframework4.aspx


DB First
-----------
http://programmaticponderings.wordpress.com/2012/11/22/first-impressions-of-database-first-development-with-entity-framework-5-in-visual-studio-2012/

http://msdn.microsoft.com/en-us/data/jj206878.aspx

Calling Stored Procedures
----------------------------

http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values


Simple Unit Of Work
--------------------

http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Generic Unit Of Work
---------------------

http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/

Multiple Submit Button on MVC page



Thanks to
http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx


public class HttpParamActionAttribute : ActionNameSelectorAttribute {
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
            return false;
        
        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}
How to use it? Just have a form similar to this:
<% using (Html.BeginForm("Action", "Post")) { %>
  <!— …form fields… -->
  <input type="submit" name="saveDraft" value="Save Draft" />
  <input type="submit" name="publish" value="Publish" />
<% } %>
and controller with two methods
public class PostController : Controller {
    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SaveDraft() {
        //…
    }

    [HttpParamAction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Publish() {
        //…
    }
}
As you see, the attribute does not require you to specify anything at all. Also, name of the buttons are translated directly to the method names. Additionally (I haven’t tried that) these should work as normal actions as well, so you can post to any of them directly.

Monday, 14 January 2013

Async Call using Ajax


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PCO.Web3.Models;

namespace PCO.Web3.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

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


        [HttpGet]
        public ActionResult Employees()
        {
            return View();
        }

        [HttpGet]
        public ActionResult ListEmployee(string id, Int64 age=0)
        {
            EmployeeViewModel model = new EmployeeViewModel();
            model.Name=id ;
            model.Age= age ;

            return PartialView(model);
        }

        public JsonResult GetEmployeeList(string id, Int64 age = 0)
        {
            List<EmployeeViewModel> model = new List<EmployeeViewModel>();
            model.Add(new EmployeeViewModel() { Name = "Puru", Age=36, Salary=5000});
            model.Add(new EmployeeViewModel() { Name = "Puru1", Age = 36, Salary = 5000 });
            model.Add(new EmployeeViewModel() { Name = "Puru2", Age = 39, Salary = 8000 });
            model.Add(new EmployeeViewModel() { Name = "Puru3", Age = 34, Salary = 6000 });

            return  Json(model, JsonRequestBehavior.AllowGet);
        }
    }
}



HTML


@model  PCO.Web3.Models.EmployeeViewModel

@{
    ViewBag.Title = "Employees";
}

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#btnSearch").click(function () {
            //GetList();
            //GetListUsingAjax();
            GetJsonListUsingAjax();
        });
    });


    function GetListUsingAjax() {
        var strName = $("#Name").val();

        var targetUrl = "/home/ListEmployee/" + strName;

        $.ajax({
            url: targetUrl,
            dataType: 'text',
            data: { id: strName, age: $("#Age").val() },
            success: function (bsHTML) {
                alert(123456);
                $("#listContainer").html(bsHTML);
            },
            error: function (req, status, ex) {
                alert(2);
            }
        });
    }

    function GetJsonListUsingAjax() {
        var strName = $("#Name").val();

        var targetUrl = "/home/GetEmployeeList/" + strName;

        $.ajax({
            url: targetUrl,
            dataType: 'json',
            data: { id: strName, age: $("#Age").val() },
            success: function (bsHTML) {
                alert(bsHTML[1].Name);
                $("#listContainer").html(bsHTML.name[1]);
                
            },
            error: function (req, status, ex) {
                alert(ex);
            }
        });
    }


    function GetList() {
        var strName = $("#Name").val();

        var url = "/home/ListEmployee/" + strName;
        $("#listContainer").load(url);
        $("#partialHeader").load(url);

        return false;
    }
</script>

<h2>Employees</h2>

@using (Html.BeginForm())
    @Html.LabelFor(x => x.Name)
    @Html.TextBoxFor(x => x.Name)

    @Html.LabelFor(x => x.Age)
    @Html.TextBoxFor(x => x.Age)

    //@Html.ActionLink("Search", "ListEmployee", new { id = 1})
    <input id="btnSearch" type="button" value="Search"/>
    
    <div id="listContainer">
    
    </div>
    
}


Dpendency Resolver Using Ninject


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

namespace BasicMVCDemo.Infrastructure
{
    public class NinjactDependencyResolver: IDependencyResolver
    {

        private readonly IResolutionRoot _resolutionRoot;

        public NinjactDependencyResolver(IResolutionRoot kernel)
        {
            _resolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            return _resolutionRoot.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _resolutionRoot.GetAll(serviceType);
        }
    }
}

Setting in Global.asax


public void SetupDependencyInjection()
        {
            // Create Ninject DI kernel
            IKernel kernel = new StandardKernel();

            // Register services with Ninject DI Container
            kernel.Bind<DbContext>().To<DBFirstDemoEntities>();
            kernel.Bind<ICustomerRepository>().To<CustomerRepository>();

            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjactDependencyResolver(kernel));
        }

DB Connection

<add name="DBFirstDemoEntities" connectionString="Server=(local);Database=DBFirstDemo;Trusted_Connection=True;" providerName="System.Data.SqlClient" />

OnModelCreating


protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //throw new UnintentionalCodeFirstException();
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new ArticleConfiguration());

        }

DbConfiguration


public class ArticleConfiguration : EntityTypeConfiguration<Article>
{
   public ArticleConfiguration()
   {
      this.HasMany(x=>x.RelatedArticles)
         .WithMany(x=>x.OtherRelatedArticles)
         .Map(x=>x.ToTable("RelatedArticles"));
   }
}

Tuesday, 17 January 2012

MVC3 Razor - Basics

Creating Dropdownbox


Step 1: Create Data provider so that we can bind with drop down list



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

namespace WebRepository
{
    public class UserProvider: IUserProvider
    {

        public List<SelectListItem> GetRoles()
        {
            List<SelectListItem> roles = new List<SelectListItem>();

            roles.Add(new SelectListItem() { Selected = false, Text = "Admin", Value = "0" });
            roles.Add(new SelectListItem() { Selected = true, Text = "Standard User", Value = "1" });
            roles.Add(new SelectListItem() { Selected = false, Text = "Super User", Value = "2" });

            return roles;
        }
    }
}



Step 2: Create action and fetch the data from data provider, bind with model and pass model to view.

        public ActionResult Index()
        {
            WebUser webUser = new WebUser();

            webUser.Name = "My Name";
            webUser.Role = new UserProvider().GetRoles();

            return View(webUser);
        }


Step 3:Pass model data to select list and bind with dropdown.



       @Html.DropDownList("UserRolesId", Model.Role)



Displaying Selected Value using JQuery


<script language="javascript">
    $('#UserRolesId').change(function () {
        $("option:selected").each(function () {
            alert($(this).text());
        });
    });
</script>



Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.



<!DOCTYPE html>
<html>
<head>
  <style>

  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <select name="sweets" multiple="multiple">
    <option>Chocolate</option>
    <option selected="selected">Candy</option>

    <option>Taffy</option>
    <option selected="selected">Caramel</option>
    <option>Fudge</option>
    <option>Cookie</option>

  </select>
  <div></div>
<script>
    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();
</script>

</body>
</html>



jQuery
==================
Async Call
-----------

http://forums.asp.net/t/1741929.aspx/1
http://api.jquery.com/jQuery.getJSON/


Entity Framework
==================

DB First
-----------

http://msdn.microsoft.com/en-us/data/jj206878.aspx


Simple Unit Of Work
--------------------

http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Generic Unit Of Work
---------------------

http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/



Friday, 8 July 2011

Working with MSBuild - <ItemGroup>

While working on MSBuild and doing some RND, I found that if we utilize <ItemGroup> properly we can achieve lot's things very easily and keep the build file very clean. I am not going in details but still trying to highlight how we can use it in various scenarios. You can utilize it then according to your requirement.


I assume you have created build file. If not then create build.xml (you can use naming convention as per your requirement). In my case I have created it "build.xml" at "C:\Projects\MSBuildDemo\", which contains some basic code as under. 


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 
       <ItemGroup>
              <Department Include="Admin">
                     <Id>0001</Id>
                     <Name>Paul</Name>
       <Package>£45000</Package>
              </Department>
              <Department Include="HR">
                     <Id>0002</Id>
                     <Name>Ewen</Name>
      <Package>£51000</Package>
              </Department>
              <Department Include="Finance">
                     <Id>0003</Id>
                     <Name>Jacob</Name>
      <Package>£48000</Package>
              </Department>
              <Department Include="HR">
                     <Id>0004</Id>
                     <Name>Jacob</Name>
      <Package>£41000</Package>
              </Department>
       </ItemGroup>
 
</Project>
   

Note: Our example will be based on the </ItemGroup> which is added in it. 

Scenario 1: I want list of all departments in ItemGroup.


Add target as under in build file which will display list of all departments.


<Target Name="DepartmentsInItemGroup">
    <Message Text="***** Display department in ItemGroup  *****"/>

    <Message Text="@(Department)" />
</Target>

If you will open Visual Studio Command Prompt and execute the target "DepartmentsInItemGroup", you will see the result as under.


Notice here you will get "HR" department twice.

Scenario 2: I want list of unique departments in ItemGroup.

Same as above create target as below and execute it.




<Target Name="DepartmentList">
    <Message Text="***** List of Departments *****"/>

    <Message Text="%(Department.Identity)" />
</Target>


You will get the result as under having unique department.


Scenario 3: If you will see the <ItemGroup> above there are two person with the same name "Jacob". One is in Finance and other is in HR department. I want unique names from the <ItemGroup>.

Same as above create target as below and execute it.


<Target Name="UniqueEmployeeName">
    <Message Text="***** List of Unqiue Employee Names *****"/>

    <Message Text="%(Department.Name)"/>
</Target>

You will see the result as under.



If you will notice you will see names "Paul", "Ewen", "Jacob". There are two Jacob's but only one is displayed.


Scenario 4: I want Department based employee names list from the <ItemGroup>.

Create target as below and execute it.

<Target Name="DepartmentBasedEmployeeName">
    <Message Text="***** List of Department Based Employee Name *****"/>

    <Message Text="%(Department.Identity): @(Department->'%(Name)')" />
</Target>


You will see the result as under.


Scenario 5: I want to display same departments list for multiple authorized branches (Cross Join ItemGroups).


Create a property containing Authorized branches as under.



<PropertyGroup>
       <AuthorizedBranches>Branch1;Branch2;Branch3</AuthorizedBranches>
</PropertyGroup>

Create Target as under

<Target Name="DepartmentsInItemGroup">
    <Message Text="***** Display department in ItemGroup  *****"/>

       <ItemGroup>
              <AuthorizedBranch Include="$(AuthorizedBranches)"/>
       </ItemGroup>
      
    <Message Text="%(AuthorizedBranch.Identity)" />
       <Message Text=" "/>
      
       <CreateItem Include="@(Department)" AdditionalMetadata="BranchName=%(AuthorizedBranch.Identity)">
              <Output TaskParameter="Include" ItemName="BranchDetails"/>
       </CreateItem>

       <Message Text="Department : %(BranchDetails.Identity); AuthorsizedBranchName : %(BranchDetails.BranchName)" />
      
       <Message Text=" "/>
       <Message Text="Department : %(BranchDetails.Identity)"/>
      
  </Target>

You will see the Output as under.





Hope this will help to get started with <ItemGroup>. If you notice we have used different @, % with department itemgorup. So what that stands for?

@ is for an item in collection, which is a group of files with attached metadata under a name.

% denote an access to a metadata of an item.
There are wellknown metadatas (like RecursiveDir, see the definition in msdn) automatically attached to an item, or you can attach your own metadata when you define your items.
$ denotes access to a property.