Ehsan Tavakoli

Writing About .NET Programming and other stuff

LabelFor HtmlHelper with HtmlAttributes and custom Prefix and Postfix

leave a comment »

For some reason I needed to use Html.LabelFor MVC helper and I realised that by default this Html Helper just have two overloads which none of them support custom Html Attributes and if you want to add a simple prefix or postfix text to the label you are going to have few problems. It’s common for labels to be displayed in block mode therefore it’s going to be a bit tricky if you want to add your custom text just before or after the generated label without dropping to the next line in display. For example you want to add a colon or comma at the end of your label ([labelname]:). So I’ve written a extension for LabelFor helper like this:

public static class LabelForExtension
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string prefix, string postfix, object htmlAttributes)
        {
            return LabelFor(html, expression, prefix, postfix, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string prefix, string postfix, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.InnerHtml = prefix + labelText + postfix;
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }

and you can use it in your view like this (Razor view):

@Html.LabelFor(model => model.Attribute, "Custom Prefix Text", "Custom Postfix Text", new { @class = "customClass" })

it supports Html format for prefix and postfix so can customize it as you like

Advertisements

Written by Ehsan Tavakoli

March 10, 2011 at 1:40 pm

Ninject – Dependency Injection Container for ASP.NET MVC

leave a comment »

I came across a very interesting DI container for ASP.NET MVC when I was reading Pro ASP.NET MVC 2 Framework by Steven Sanderson. It called Ninject (cool name for start! and cool site too). It can manage DI in your application very simple but highly extensible. It used the term kernel for mapping abstract types (interfaces) to specific concrete types.

It seems there are few other open source DI container for .NET, thanks to Scott Hanselman they have been covered comprehensively: http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx

Written by Ehsan Tavakoli

September 12, 2010 at 5:20 pm

How to use Implicitly Typed Local Variables and Auto-Implemented Properties

leave a comment »

Today I want to write a very simple sample about how we can use implicitly typed local variable and also Auto-Implemented properties. As you may know, these two new features (and few others) have been introduced by Microsoft in C# 3.0. And to be honest they are quite handy in many solutions. First see what they mean. With Implicitly Typed Local Variables, you can define a local variable without specified what its type is. You should use var keyword to instruct the completer to get the type from expression on the right side. These types can be built-in types or anonymous type or even user-defined type.
Speaking of Anonymous type is not bad to glance over what it means. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. Here is an example:

var v = new { Amount = 108, Message = "Hello" };

Here we defined a variable name v with our anonymous type which has two properties (Amount and Hello). As you noticed, we don’t need to specified the types of properties and we used var keyword to instruct the compiler to grasp our new anonymous type and assign it to our variable.

Back to another new feature “Auto-Implemented Properties”, In C# 3.0 auto-implemented properties make property declaration more simple when no additional logic is required in the property accessors. for example:

class ProcessData
{
    public Int32 Id { get; set; }
    public Int64 Memory { get; set; }
    public String Name { get; set; }
}

as you can see here we just implemented our class ProcessData with three properties and their setters and getters.

I found a very good example in book “Linq in Action”. here is the example with a little modification:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ConsoleApplication1
{
    class SampleClass
    {
        class ProcessData
        {
            public Int32 Id { get; set; }
            public Int64 Memory { get; set; }
            public String Name { get; set; }
        }
        static void DisplayProcesses()
        {
            var processes = new List<ProcessData>();
            foreach (var process in Process.GetProcesses())
                processes.Add(new ProcessData{Id = process.Id, Name = process.ProcessName, Memory = process.WorkingSet64});
            ObjectDumper.Write(processes);
        }
        static void Main()
        {
            DisplayProcesses();
            Console.ReadKey();
        }
    }

}

As you can see here in this code, I used Implicitly Typed Local Variables (processes) and also Auto Implemented Properties (for class ProcessData) and also initialized ProcessData in new format (object initialiser) that doesn’t need to call its constructor (which it doesn’t have). And also please take note that I used ObjectDumper class which it’s provided by Microsoft as part of the LINQ code samples.

ObjectDumper can be used to dump an object graph in memory to the console. It’s particularly useful for debugging purposes. You can find its source code here: http://code.msdn.microsoft.com/wpfobjectdumper

Written by Ehsan Tavakoli

September 7, 2010 at 10:50 pm

Three common ways to Connect to database in ASP.NET

with one comment

There are numbers of ways for building database driven websites using ASP.NET. In this post I’m going to show you three common ways of doing that. Please note these three are not the best ways for retrieving data from database and present it on the web. However, you may find one or coup of this ways easy, fast or even flexible for your specific project. In next articles I’m going to develop a small project using 3-layer architecture. But before that, I’m going to show other ways.

The Spaghetti Model

Oh yeah, the old fashion way for dealing with any kind of algorithm or database or even interface design.  To be honest, it still works well. Depends on what do you want to get. Or how much time do you have. Or simply about how much you care! No just joking! Here is sample page: retrieving information from [tblProduct] in [dbShop]. Present those two field on page and you can update them! Easy and straight forward.

using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ecom
{
    public partial class spaghetti : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string sql = @"SELECT Title, Price FROM tblProduct WHERE ID=1";

                using (
                    SqlConnection myConnection =
                        new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
                {
                    using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
                    {
                        myConnection.Open();
                        using (SqlDataReader myReader = myCommand.ExecuteReader())
                        {
                            if (myReader.Read())
                            {
                                txtTitle.Text = myReader.GetString(0).ToString();
                                txtPrice.Text = myReader.GetValue((1)).ToString();

                            }
                            myReader.Close();
                        }
                        myConnection.Close();
                    }
                }

        }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            string sqlBase = @"UPDATE tblProduct SET Title='{0}', Price='{1}' WHERE ID=1";
            using (SqlConnection myConnection =
                new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
            {
                string sql = string.Format(sqlBase, txtTitle.Text, txtPrice.Text);
                SqlCommand myCommand = new SqlCommand(sql, myConnection);
                myConnection.Open();
                myCommand.ExecuteNonQuery();
                myConnection.Close();
            }
        }
    }
}

But there is number of issues:

  1. SQL injection is a piece of cake for this code. However, you can put another method there to handle SQL Injection. Otherwise, you can loss your data in a snap!
  2. This code is hard to write and remember. And it’s hard to modify any fields in DB or add new field.
  3. You cannot use this code for other scenarios.



Using SqlDataSource Control

It’s another common ways to connect to database is using SqlDataSource. There are easy to configure and create CRUD (Create, Read, Update and Delete) procedures in a glance. Then you can easily assign them to control like the GrideView or ForView.

The problem is they make huge amount of codes on your page. And really you don’t know how they manage the transaction. Of course they put all things in XML files but it’s kind of hard to manage and edit these files. And it will become more complicated if you want to add your own function for conversation or validation of data.

Here is an example of using SqlDataSource Control for previous scenario.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="sqldatasource.aspx.cs" Inherits="ecom.sqldatasource" %>

<!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">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:SqlDataSource ID="SqlDataSource1"
            ConnectionString="<%$ ConnectionStrings:dbEcomConnectionString %>"
            SelectCommand="SELECT * FROM [tblProduct]" runat="server"></asp:SqlDataSource>

    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
                ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Using TableAdapters
Another alternative way for working with database is using TableAdapters. They can be made by Visual Studio and all you need it’s just put your query statements and using the tools. You can access to business object by using classes that inherit form System.Data.DataTable and System.Data.DataRow by using method like AcceptChanges.
There is valuable article about using TableAdapters by Scott Mitchell’s here

In next few posts I’m going to build a simple website using 3-layer architecture..

*This article is highly adopted from here

Written by Ehsan Tavakoli

May 24, 2010 at 2:33 am

Simple code to use LINQ on a Generic list

with 2 comments

What is LINQ?

Most programmers today are required to integrate some sort of data into their applications. Often, you have to take data from multiple sources such as memory collections, relational databases, XML files, etc. With the current implementation of .NET Framework, getting to this data is often tedious and requires familiarity with multiple data access technologies and XML APIs. To make matters worse, all data sources have different means of querying the data in them: SQL for databases, XQuery for XML, LDAP queries for Active Directory etc. In short, today’s data access story lacks a unified approach to accessing data from disparate data sources, which is exactly what the LINQ (Language INtegrated Query) family of technologies are intended to solve.

Introduction to LINQ

The official goal of LINQ family of technologies is to add “general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data”. One of the nice things about LINQ is that it integrates seamlessly with the existing .NET languages such as C#, VB.NET because the underlying LINQ API is just nothing but a set of .NET classes that operate like any other .NET class. In addition, the query functionality is not just restricted to SQL or XML data; you can apply LINQ to query any class as long as that class implements IEnumerable class.

read it more here: http://www.15seconds.com/Issue/060713.htm

Here is a sample code to use LINQ on a generic list in ASP.NET 3.5. First, I’m going to create a sample class (Customer) with three variables: name, family and phone. Here is the code:

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

public class Customer
{
    private String _name;
    private String _family;
    private String _phone;

	public List<Customer> fillCustomer()
	{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
	}

    public Customer() { }

    public Customer(String name, String family, String phone)
    {
        _name = name;
        _family = family;
        _phone = phone;
    }

    public String name
    {
        get {return _name;}

        set {_name = value;}
    }

    public String family
    {
        get {return _family;}

        set {_family = value;}
    }

    public String phone
    {
        get {return _phone;}

        set {_phone = value;}
    }
}

As you can see, there are two Constructors for this class: Customer() and Customer(String name, String Family, String Phone) and there is method which generate our generic list of Customer

public List<Customer> fillCustomer()
{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
}

In this method, first we create a list of Customer(s) and then add 3 sample Customer into this list.

Now, let look at our page:

Here is the code:

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

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
        Customer customer = new Customer();
        List<Customer> customerList = customer.fillCustomer();


        IEnumerable<Customer> customerQuery =
        from cust in customerList
        where cust.name == "Ehsan"
        select cust;
        
        foreach (Customer customerrow in customerQuery)
        {
            Response.Write(customerrow.family + ", " + customerrow.name);
        }

    }
}

you can see, we filled the “customerList” with our method. And then we use a Linq query over customerList. In this case, we just select customers with the first name “Ehsan”. And finally we just print them out using foreach loop.

Learn LINQ from MSDN:
http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

Written by Ehsan Tavakoli

March 8, 2010 at 12:16 pm

Posted in asp.net, Generic, Linq

Browser-Specific Master Pages

with 5 comments

When you are trying to create a master page for your website, you may just wonder how can you make them that every user with any browser can call your pages up. No matter they are using IE or Firefox or even Opera on their tiny PocketPC.

You can easily design different pages for different container. How? By adding an attribute into master page property.

<%@ Page language="C#" MasterPageFile="~/Test.master"
      Mozilla:MasterPageFile="~/TestMozilla.master"
      Opera:MasterPageFile="~/TestOpera.master" %>
....

You can find a list of available browsers on the production server where the application will be hosted at C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers\

  • avantgo
  • cassio
  • Default
  • docomo
  • ericsson
  • EZWap
  • gateway
  • generic
  • goAmerica
  • ie
  • Jataayu
  • jphone
  • legend
  • MME
  • mozilla
  • netscape
  • nokia
  • openwave
  • opera
  • palm
  • panasonic
  • pie
  • webtv
  • winwap
  • xiino

Written by Ehsan Tavakoli

February 20, 2010 at 12:36 pm

How to set FireFox as a default browser in Visual Studio 2008

leave a comment »

I just found such an easy way to set Firefox as a default browser in VS 2008. I felt silly when I had to open Firefox by myself each time I was trying to debug a web site.
The solution? It’s piece of cake!

Right Click on your project name in Solution Explorer:

Click on “Browse with…” and then select Firefox as a default.

Here we go! 🙂

Written by Ehsan Tavakoli

February 18, 2010 at 1:05 pm