Category Archives: .NET2010 MVC

Building Multilingual Application

Multilingual applications are those which which supports the different Language for customers of different counties.

The most important thing to develope the ML Application is Resource file, which contains all the ML Data such as the text which is to be displayed on the form (in different languages).

These resource files can be the file with “resx” extension or may be with “txt” extensions.
Suppose we want to generate one resource file for Hindi Language one for Franch Language and soon.

These files will be named as follows :
Hindi Language : Resource.HI.txt
French Language : Resource.FR.txt
…..
…..

We know that the Satellite Assembely id needed to make Multilingual Application.
So we will use “Resgen.exe” comand to generate Satellite Assembely, that can be done as follows :

resgen C:\Resource.HI.txt
resgen C:\Resource.FR.txt

These two commands will generate the Satellite Assembely for these resource files with following names :

Resource.HI.resources
Resource.FR.resources

These generated resource files we will put in a folder named “Resources”.
With this we have completed our first round of work.. 🙂
We will build this application and this will generate two new folders in “Bin” directory with the name “FR” and “HI”.

Along with this we need to place these two files in Resource Folder inside Bin.

Now we have done with the Satellite Assembely generation part, now all we need to do is use these Satellite Assembely in our code by reading content from it.

For this we will create one class and place following code in that to read the Resource content.

This HI resource file contains :

 

In this file we need to place different Namespaces :

This is the main code which will read the Resource file.

Now we will write the code to call this function on some button…

This above function we can call on any control say on Button Click…
And we are done with the Localisation… 🙂

 

 

SqlServer 2008 new features

Below are some of the SqlServer 2008 new features :

1) Inline variable assignment :
Instead of:
DECLARE @myVar int
SET @myVar = 5

you can do it in one line:
DECLARE @myVar int = 5

2) C# like syntax:
SET @i += 5

3) Auditing :
Sql Server2008 Auditing feature is a superb feature to audit ur changes later, for this SqlServer2008 introduced the automatic auditing feature.

4) Processing of delimited strings:
This is awesome and I have used this feature.
Currently, we pass in delimited strings in the following manner:

exec sp_demoProc ‘Rohit,35;Mayank,31;Rider,27;Lakhan,42’

In 2008, Microsoft introduced Table Value Parameters (TVP).

CREATE TYPE PeepsType AS TABLE (Name varchar(20), Age int)
DECLARE @myPeeps PeepsType
INSERT @myString SELECT ‘Rohit’, 35
INSERT @myString SELECT ‘Mayank’, 31
INSERT @myString SELECT ‘Rider’, 27
INSERT @myString SELECT ‘Lakhan’, 42

exec sp_MySproc2 @myString

5) Intellisense :
This is another great feature of SqlServer2008, now user gets the Intellisense while writing the SPs and Queries just like we get in .Net.

Returning a ViewModel in MVC

Some time it happes when we want to display certain Information in form according to some ID.
This form may contain some Dropdown fields some textboxes or may be other web controls, these controls should display
proper information according to to that ID.
So Instead of writing this code on the Controller class (making controller massy 😦 ) or a smart way could be
creating a ViewModelClass and retutn it.

What a ViewModelClass contains is all the methods and functions which are required to fill all controls according to ID.

Suppose I have a view contains different Dropdowns and textboxes.
I will create a ViewModelClass for this as below :

 public class AddEditScheduleViewModel
    {
        #region Public Properties
        public SelectList ddlClient { get;  set; }
        public SelectList ddlStaff { get;  set; }
        public string txtScheduleDate { get;  set; }
        #endregion 

        #region Contructor
        public AddEditScheduleViewModel()
        {
            ddlClient = new SelectList(ClientsDAL.GetClientList(SessionHandler.LoggedinUserInfo.AgencyID, "02"), "clientID", "entDisplayName");
            ddlStaff = new SelectList(StaffDAL.GetStaffList(SessionHandler.LoggedinUserInfo.AgencyID), "staffID", "staffName");
            txtScheduleDate = DateTime.Now.ToShortDateString();
        }
	#endregion 
     }

Here we have made one Constructor “AddEditScheduleViewModel()” where we have written code to get data for dropdown.

<%=Html.DropDownList("ddlClient",(SelectList)ViewData["ddlClient"], "", new { onChange="return onClientChange(this)" , @Style = "width:65%" })%>
<%=Html.DropDownList("ddlStaff",(SelectList)ViewData["ddlStaff"], "", new { onChange="return onStaffChange(this)", @Style = "width:65%" })%>

This ViewModel may also contains some method Overloads like below :

public AddEditScheduleViewModel(string ScheduleID)
{
    getSchedulDataByID(ScheduleID, "none");
}
public AddEditScheduleViewModel(string ScheduleID,string mode)
{
    getSchedulDataByID(ScheduleID,mode);
}

Now how to use this ViewModelClass and how to call these Overload methods :

public ActionResult AddEditSchedule(string Submit) { 
switch (Submit)
    {
	case "Save":
		AddSchedule(ScheduleID); //Add Edit Schedule Event
		return View(new AddEditScheduleViewModel());
	case "Delete":
		DeleteSchedule(ScheduleID);
		return View(new AddEditScheduleViewModel());
	case "Show Conflict":
		return View(new AddEditScheduleViewModel(Request.Form["hdnConflictSchedID"].ToString()));
	default:
	    //your custom code will go here
    }
}

How to capture Multiple Button events in MVC

1. Suppose I have one View say Operations.
2. Where I have got multiple buttons which performs different operations (add, edit, delete or may be update)
3. So how will I be able to capture these events while I am having only one View and only one Action method ?
4. Lets consider following Example.

Operations.aspx
<input type="submit" id="btnShowOriginal" value="Show Original" name="Submit" title="Click to Show Original"  />
<input type="submit" id="btnShowConflict" value="Show Conflict" name="Submit" title="Click to Show Conflict" />
<input type="hidden" id="hdnConflictSchedID" name="hdnConflictSchedID" value="" />
<input type="hidden" id="hdnSchedID" value="0" name="hdnSchedID" />

When we add a Controller for this View, so we will get an ActionResult method just as below.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddEditSchedule(string Submit) { }

In above Signature of method we have passed one string Parameter “Submit” which will refer to the submit button we have placed in View “Operations” above.
So now we can customized this method as follows :

public ActionResult AddEditSchedule(string Submit) { 
switch (Submit)
    {
	case "Save":
	    //your custom code will go here
	case "Cancel":
	    //your custom code will go here
	case "Delete":
	    //your custom code will go here
	case "Show Conflict":
	    //your custom code will go here
	case "Show Original":
	    //your custom code will go here
	case "ThemeGreen":
	    //your custom code will go here
	case "ThemeBlue":
	    //your custom code will go here
	default:
	    //your custom code will go here
    }
}

LINQ Operations

.NET Language-Integrated Query (LINQ) defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable-based information source.

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="JSON.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        LINQ Demo :-
    </h2>
       <table style="width:100%;">
        <tr>
            <td>
                <asp:Button ID="btngetdata" runat="server" onclick="btngetdata_Click" 
                    Text="Fill with LINQ" />
            </td>
            <td>
                <asp:DropDownList ID="ddlgetdata" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                    Text="Declaritive Short Hand " />
            </td>
            <td>
                <asp:DropDownList ID="ddlshorthand" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" 
                    Text="Lambda Expressions and Expression Trees" />
            </td>
            <td>
                <asp:DropDownList ID="ddlextressiontree" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button4" runat="server" onclick="Button4_Click" 
                    Text="LINQ anonymous methods" />
            </td>
            <td>
                <asp:DropDownList ID="ddlanonymous" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnwhere" runat="server" onclick="btnwhere_Click" 
                    Text="where" />
            </td>
            <td>
                <asp:DropDownList ID="ddlwhere" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btndatatable" runat="server" onclick="btndatatable_Click" 
                    Text="LINQ with DataTable" />
            </td>
            <td>
                <asp:DropDownList ID="ddlDatatable" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

Here we are having an Array on which we are going to Implement LINQ :

string[] names = { "Abhishek", "Rohit", "Mayank", 
                       "Rider", "Lucky", "Utkarsh", 
                       "Lakhan", "Manish" };

Below is the Source code how to fill a Dropdown list using Simple LINQ :-

protected void btngetdata_Click(object sender, EventArgs e)
{
    IEnumerable<string> data = from d in names
			       where d.Length < 6
			       select d.ToUpper();
    foreach (string da in data)
    {
	ddlgetdata.Items.Add(da.ToString());
    }
}

This above query can also be written as below, this approach is called Method based :-

protected void methodbased_Click(object sender, EventArgs e)
{
    IEnumerable<string> str = names
       .Where(s => s.Length < 6)
       .OrderBy(s => s)
       .Select(s => s.ToUpper());

    foreach (string da1 in str)
    {
	ddlshorthand.Items.Add(da1.ToString());
    }
}

Lambda Expressions and Expression Trees (Func delegate type) :-

protected void Button3_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = s => s.Length < 6;
    Func<string, string> Order = s => s;
    Func<string, string> sel = s => s.ToUpper();

    IEnumerable<string> d = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string i in d)
    {
	ddlextressiontree.Items.Add(i);
    }
}

We can also write the above method using anonymous methods (Delegates) like below :-

protected void Button4_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = delegate(string s)
    {
	return s.Length < 6;
    };

    Func<string, string> Order = delegate(string s)
    {
	return s;
    };

    Func<string, string> sel = delegate(string s)
    {
	return s.ToUpper();
    };

    IEnumerable<string> query = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string s in query)
    {
	ddlanonymous.Items.Add(s);
    }
}
protected void btnwhere_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    IEnumerable<string> query = names.Where(s => s[0] == 'A');
    foreach (string z in query)
    {
	ddlwhere.Items.Add(z);
    }
}

Now we are going to see how to implement LINQ on DataTable, However DataTable is not an IEnumerable type and LINQ is only work with IEnumerable Types.
So here we need to convert this DataTable to IEnumerable Types and then we can apply LINQ over it.

We can have a DataTable as follows :-

static DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Id", typeof(int));
    table.Columns.Add("Address", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    table.Rows.Add(1, "Indore", "Abhishek", DateTime.Now);
    table.Rows.Add(2, "Pune", "Rohit", DateTime.Now);
    table.Rows.Add(3, "Hydrabad", "Mayank", DateTime.Now);
    table.Rows.Add(4, "Mumbai", "Rider", DateTime.Now);
    table.Rows.Add(5, "Bangalore", "Lucky", DateTime.Now);
    return table;
}

In below code we have used “AsEnumerable()” method to make DataTable of IEnumerable Type.

protected void btndatatable_Click(object sender, EventArgs e)
{
    //AsEnumerable() Used here to convert Datatable (DataTable is NOT IEnumerable Type) in to IEnumerable type so that we can apply LINQ in it.
    var query = from data in GetTable().AsEnumerable()
		where data.Field<int>("Id") > 2 && data.Field<string>("Name").StartsWith("M")
		select new
		{
		    Name = data.Field<string>("Name"),
		    Id = data.Field<int>("Id")
		};

    foreach (var v in query)
    {
	ddlDatatable.DataTextField = v.Name.ToString();
	ddlDatatable.DataValueField = v.Id.ToString();
	ddlDatatable.Items.Add(v.Name.ToString());
    }
}

LINQ Demo

Note :-
As per my thinking this LINQ can be very usefull for small data to Operate on.. If we retrieve data from DB in bulk and keep it in memory so that we can apply LINQ on that data that is not a good option..

Html Extension method to generate Html Table.

We are creating a custom Html method Extension in which we write code to generate a class which will return you a html table.

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

namespace LINQtoSQL.HtmlTable
{
     public static class HtmlTable
     {
        public static string DPHtmlTable(this HtmlHelper html, IEnumerable dataSource, string cssClassName, string noDataMessage, string columnLink)
        {
StringBuilder tableBuilder = new StringBuilder();
        tableBuilder.Append("<table cellspacing='0' cellpading='0' border='0' width='100%'>");
        IEnumerator tableEnumerator = dataSource.GetEnumerator();
        Type itemType;

        if (tableEnumerator.MoveNext() == false)
        {
               tableBuilder.AppendLine("<tr>");
               tableBuilder.AppendLine("<th>" + noDataMessage + "</th>");
               tableBuilder.AppendLine("</tr>");
               tableBuilder.AppendLine("</table>");
               return tableBuilder.ToString();
        }
        else
        {
               itemType = tableEnumerator.Current.GetType();
        }
               PropertyInfo[] properties = itemType.GetProperties();

 //Table Header column
               tableBuilder.AppendLine("<tr>");
               foreach (PropertyInfo property in properties)
               {
                 tableBuilder.AppendLine("<th>");
                 tableBuilder.Append(property.Name.ToString());
                 tableBuilder.AppendLine("</th>");
               }
                 tableBuilder.AppendLine("</tr>");

 //Table Data column
         foreach (object item in dataSource)
         {
            tableBuilder.AppendLine("<tr>");
            foreach (PropertyInfo property in properties)
            {
                 tableBuilder.Append("<td>");
                 if (property.Name.ToString().ToLower() == columnLink.ToString().ToLower()) {
                 tableBuilder.Append("<a onclick=alert("+ property.GetValue(item,null) +")>" + property.GetValue(item, null) + "</a>");
                }
                else
                {
                   tableBuilder.Append(property.GetValue(item, null));
                }
                  tableBuilder.Append("</td>");
            }
           tableBuilder.AppendLine("</tr>");
        }

        tableBuilder.Append("</table>");
         return tableBuilder.ToString();
    }
  }
}


You need to include the class we have created :-

<%@ Import Namespace="LINQtoSQL.HtmlTable" %>

This MVC table control can be used in your code as follows :-

<%=Html.DPHtmlTable((IEnumerable)this.ViewData.Model, "tableClass","No Data Available to Display!", "prodKey")%>

 

LINQ to SQL DataModel

Here In this very new topic we are going to learn how to display the Data from DataBase using LINQ to SQL..
This we will do using the DataContext class :
1.    For this we will need one DataBase and having any table as of your own Interest.. In my case I am using a very simple Table called “tblSoftware” which consists of three very simple fields namely id, Name and ProdKey.
2.    Now we will Include this DataBase in our application for that you need to follow these simple steps:
3.    Right click on “App_Data”  folder in your application and Click on “Add new Item”, there you select “SQL Server Database”
4.    Name that Database as “SoftwareDB”.
5.    When you will doubleClick this DataBase , then in Server Explorer you will get it along with all the tables Included in this DataBase.

7.    Just drag the table in blank space.
8.    Now we are going to display the name of Softwares on to the Page (HomeController >> Index)
9.    We have to put this below code In HomeController Class.

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

namespace LINQtoSQL.Controllers
{
 [HandleError]
 public class HomeController : Controller
 {
 public ActionResult Index()
 {
 var dataContext = new SoftwareDataContext();
 var softwareData = from m in dataContext.Softwares
 select m;
 return View(softwareData);
 }

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

Now this above code will return a “softwareData” view and we can display this data in View Index.aspx.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace ="LINQtoSQL.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <p>
  <ul>
     <%  foreach (Software s in (IEnumerable)ViewData.Model) %>
    <% { %>
     <li>
        <%= s.Name %>
     </li>
    <% } %>
 </ul>
 </p>
</asp:Content>

 

Extending ASP.NET MVC HtmlHelper Class

Extending HtmlHelper Class in ASP.Net 2010

HtmlHelper Class can be used in ASP.Net MVC Framework to render HTML like textbox, Label, checkbox etc.

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

Now suppose if I want to render an Label using HtmlHelper Class, so that I can do as follows:

<%=Html.Label(“lblHome”) %>

Since these Html Helpers are build as an extension methods. This Extension methods can be made in two ways (according to me 🙂 )
1.    Easy Method of Extending HtmlHelper.
2.    Less Easy Method..
First we will go for the Easy Method  :
For  this we will make one folder in our MVC Application. We will add one Class and named it as “LabelHelper.cs” as shown in below screen shot.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PresentationDEMO.LabelHelper
{
 public class LabelHelper
 {
 public static string DPLabel(string target, string text)
 {
 return string.Format("<Label for='{0}'>{1}</label>", target, text);
 }
 public static string DPTextbox(string target, string text)
 {
 return string.Format("<input id='{0}' type='text' value='{1}'></input>", target, text);
 }
 }
}

And that’s it all Done.
Now Code below shows how to use this extension in View.
For this you need to Include Namespace/Class:

<%@ Import Namespace="PresentationDEMO.LabelHelper" %>
<%@ Import Namespace="PresentationDEMO.LabelHelperExtension" %>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="PresentationDEMO.LabelHelper" %>
<%@ Import Namespace="PresentationDEMO.LabelHelperExtension" %>
<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
 About Us
</asp:Content>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
 <h2>About</h2>
 <p>
 <%= LabelHelper.DPLabel("lblFirstName","This is custom Label") %>
 <%= LabelHelper.DPTextbox("txtFirstName","Abhishek") %>
 </p>
</asp:Content>

Secondly we will go for the Less Easy Method  :
For  this we will make one folder in our MVC Application. We will add one Class and named it as “LabelHelperExtension.cs” as shown in below screen shot.
For this we need to Include one extra Namespace called

using System.Runtime.CompilerServices;”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
namespace PresentationDEMO.LabelHelperExtension
{
 public static class LabelHelperExtension
 {
 public static string DPLabelExtension(this HtmlHelper DPHelper, string target, string text)
 {
 return string.Format("<Label for='{0}'>{1}</Label>", target, text);
 }
 }
}

Now here we are Extending HtmlHelper Class so we need to pass it as a “very first” parameter in our Method.
In current it is passed with the name “DPHelper”.
This is the main difference while creating these Extension in a simple manner and in Less Easy way .
Now below code shows how to use this newely Extended method in View.

<%= Html.DPLabelExtension("lblDPExtension","abhishek A. Sharma") %>

Lets see another example for truncation a string :

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

namespace PresentationDEMO.StringTruncateExtender
{
    public static class StringTruncateExtender
    {
        public static string DPTruncate(this HtmlHelper helper, string stringToTruncate, int length)
        {
            if (stringToTruncate.Length <= length)
            {
                return stringToTruncate;
            }
            else {
                return stringToTruncate.Substring(0, length) + "...";    
            }
        }
    }
}

Now how this can be used :

<%= Html.DPTruncate("Abhishek A. Sharma", 8)%>

This will return you “Abhishek” and rest of all string will get truncated.

MVC and IIS

The Deployment of MVC Application is much straight fwd.. as far as Virtual directory and Mapping of our Application is concern.

The only twist while deploying the MVC Application because we never have the Extension of Pages while serving to user . This is some what like this “Scheduling/Index/24” etc.

Follow the following steps :

  1. Open the Property window of Virtual Directory (in our case “mvc”).
  1. Click on the Configuration Button.
  2. Now we need to add one new Extension to run MVC Application on IIS.
  3. Now search for “aspnet_isapi.dll” (you can get it easily by selecting .aspx extension and click on “Edit” button)
  4. Now restart the IIS and its done…

In this way we can Deploy MVC Application.

Creating First MVC Application (VS2010)

Creating First MVC Application :

Now just let the Application Open into VS and Hit run. Here we can see the very clean URL in browser and application by default displaying the Home Page of Application.

Now we will Add a new Page in the Application. There is nothing much complicated in doing so. For that we will first add a “Controller” who is actually responsible for the navigating and displaying a particular “View”.

After adding this Scheduling Controller, we are going to add another “View” called Scheduling which will be controlled by Scheduling Controller we have just added in our Application. For that just open the Scheduling Controller and right click and click on “Add View”.

Now to run this Scheduling View and see output, we need to place an Action Method for this View in Scheduling Controller which will return this Scheduling View. Here we need to take care of one thing is that , the name of Action Result Method should be same as that of View we have Added . In our case it is “Scheduling” and “Index” so we have added the method with the name “Scheduling”.

If we have mentioned a different name in to the ActionResult then it will go and Search this View Name in to the Shared Folder and if it is not even there then an Error Page is displayed from Shared Folder.

This Clean and Clear URL all is given by the “Route” which is defined in Global.asax file. User can define his/her choice of URL Route and the page will get displayed accordingly as shown in below screen shot…