Friday 27 April 2012

File Upload not working with update panel



I was having problem while using File upload control which is inside the update panel and which was placed in user control. While doing post-back the value of PostedFile was blank, although page was properly valid.
Then I checked the Form property of Request object, the file upload control was missing in the AllKeys collection
We all know that if you want file uploads the form encode must be multipart/form-data. This is the reason why File Upload is not working properly inside Update Panel, lets understand this with following example.
Problem:
File upload is not working with update panel + asp.net
You are having two controls which needs to get display after one-another or post-back, first control does not have File upload and Second control does. Things to notice here is form tag will be reside either in ASPX page or Master page not in UserControl; and our File Upload is inside user control. Now when we load first control which does not have File Upload so the form will not encoded with multipart/form-data, now when you load second control which has the File Upload hence fort encode must be multipart/form-data, which is unfortunately not changing due to Update Panel.
Solution:
In problem definition we come to know that form must be encoded with multipart/form-data if we want to upload the file; solution is very simple, we just need to change encoded attribute of form with following single line!!!
Page.Form.Attributes.Add("enctype", "multipart/form-data");
</ASP:UPDATEPANEL>

THis is also working Fine.

Wednesday 4 April 2012

Numbers to Words


Lots of programming involves calculations with numbers. The problem comes when you want to display the result of your calculations and just printing the plain number isn't going to be good enough for what you want. You can of course format the number by adding commas and so forth but sometimes a number as a number isn't appropriate and you need the equivalent of the number in words. Converting a number into words isn't exactly the most straightforward of tasks but it can be done using javascript as the following number to word conversion form demonstrates.
I
f you want to be able to do these conversions on your site then the you will need a Javascript that can do the conversion for you. The simplest way to get one is to take a copy of mine. The first step to obtain it is to select the code from the text box below (there is a highlight all button beneath it to make this easier) and copy it into a file called toword.js.




=======================================================
// Convert numbers to words
// copyright 25th July 2006, by Stephen Chapman http://javascript.about.com
// permission to use this Javascript on your web page is granted
// provided that all of the code (including this copyright notice) is
// used exactly as shown (you can change the numbering system if you wish)

// American Numbering System
var th = ['','thousand','million', 'billion','trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];

var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine']; var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; function toWords(s){s = s.toString(); s = s.replace(/[\, ]/g,''); 
if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big';
 var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) {if ((x-i)%3==2) {if (n[i] == '1') {str += tn[Number(n[i+1])] + ' '; i++; sk=1;} else if (n[i]!=0) {str += tw[n[i]-2] + ' ';sk=1;}}
 else if (n[i]!=0) {str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred ';sk=1;} if ((x-i)%3==1) 
{if (sk) str += th[(x-i-1)/3] + ' ';sk=0;}} if (x != s.length) {var y = s.length; str += 'point ';
 for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';} return str.replace(/\s+/g,' ');}
===========================================================
Next you link the script into the head of your page using the following code:
<script type="text/javascript" src="toword.js">
</script>
The final step is to call the script to perform the conversion to words for you. To get a number converted to words you just need to call the function passing it the number you want to convert and the corresponding words will be returned.
var words = toWords(num);
Note that this function can convert numbers as big as 999,999,999,999,999 with as many decimal places as you like into words. If you try to convert a number bigger than that it will return "too big". Numbers, commas, spaces, and a single period for the decimal point are all acceptable content for the number but it will return "not a number" if it contains anything else. If you want to convert negativ numbers of currency values to words you should remove those symbols from the number first and convert those to words separately.

(or)

with C# Code:


 private string NumberToText(decimal iAmt)
    {
       decimal  v = iAmt;
        if (v == 0)
        {
            return "zero";
        }
        else
        {
            var units = "|One|Two|Three|Four|Five|Six|Seven|Eight|Nine".Split('|');
            var teens = "|eleven|twelve|thir#|four#|fif#|six#|seven#|eigh#|nine#".Replace("#", "teen").Split('|');
            var tens = "|Ten|Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety".Split('|');
            var thou = "|Thousand|m#|b#|tr#|quadr#|quint#|sex#|sept#|oct#".Replace("#", "illion").Split('|');
            //var g = (v < style="color: rgb(163, 21, 21);">"minus " : "");
            var g = (v < 0 ? "Minus" : "");
            var w = "";
            var p = 0;
            v = Math.Abs(v);
            while (v > 0)
            {
                int b = (int)(v % 1000);
                if (b > 0)
                {
                    var h = (b / 100);
                    var t = (b - h * 100) / 10;
                    var u = (b - h * 100 - t * 10);
                    var s = ((h > 0) ? units[h] + " Hundred" + ((t > 0 | u > 0) ? " and " : "") : "") + ((t > 0) ? (t == 1 && u > 0) ? teens[u] : tens[t] + ((u > 0) ? "-" : "") : "") + ((t != 1) ? units[u] : ""); s = (((v > 1000) && (h == 0) && (p == 0)) ? " and " : (v > 1000) ? ", " : "") + s; w = s + " " + thou[p] + w;
                }
                v = v / 1000; p++;
            }
            return g + w;
        }
    }


under Button Click Event:

        string strAmount = NumberToText(iAmt);
        Label1.Text = strAmount;



Installing Enterprise Library 5.0 - Enterprise Library 5.0 Tutorial Part 1


Microsoft has released Enterprise Library on April 2010. it’s free you can download and install from “Download Enterprise Library”. you can also find older version of enterprise library 4.1 still if your project needs it for maintenance purpose. but I suggest go for 5.0 as it has great enhancements and improved UI configuration tool.
Will it work only with Visual Studio 2008? Yes, it works with also .NET 3.5 and Visual Studio 2008. you can take advantage of new improved UI configuration tool which comes from enterprise library 5.0 with VS2008. I suggest you to install it including documentation. you can also find community links.
You’ll find 2 types of installers Whilst download. You might want to chose 2nd type with no source code option for production usage you .
1. “Enterprise Library 5.0 - Source Code.msi” which is of 5.3 MB size contains source code of enterprise library.
This installer is useful if you want to have a insight of the enterprise patterns source code. In this installation you would need to go through following steps.
imageimage
image
Once you finish above wizard you can see that all the source code has been copied to the folder given in first step. Folders are as follows…
image
You can find the source code at the folder Blocks. If you want to build the assemblies yourself or dig into the code for advanced usage. but once you complete the wizard automatically installer initiate the MSBuild script file “BuildLibrary.bat” which compiles the source code and copies all the required dlls in bin folder. You can find the batch script execution screen below. This step completes the required installation with default configuration.
image
2. “Enterprise Library 5.0.msi” which is of 11 MB size. You can get following things with this installer.
1. Source Code
2. All compiled binaries/assemblies
3. Configuration Editor for Visual Studio.
Once you start the installer, You would need to read and agree the license terms as shown below.
image
image
image

In this following screen you can find that installer is going to install Configuration tool for Visual Studio 2008. if you have Visual Studio 2010 installed in your machine, then this wizard also installs the configuration tool for Visual Studio 2010.
image
In this link you can find all overview and system requirements to use these patterns. In my next blog posts I’ll provide more insight to various blocks of Enterprise Library 5.0.

How to use Logging Application Block in Enterprise Library 5.0


Here I'm writing about Logging Application Block of Enterprise Library 5.0. For using application blocks first you have to install Microsoft Patterns and Practices Enterprise Library 5.0. After installing this you will get an edit mode while right clicking the web.config from your application .

Different application blocks available in Enterprise Library 5.0 are:

  • Caching Application Block
  • Data Access Application Block
  • Exception Handling Application Block
  • Logging Application Block
  • Policy Injection Application Block
  • Cryptography Application Block
  • Security Application Block
  • Validation Application Block
The edit mode of web.config looks like the below picture.


By clicking on the blocks menu you can add the desired blocks into your application. So here I'm adding Logging Application Block into my application. So the web.config  looks like below


Use of Logging Application Block

Logging Application Block is used to write information’s to variety of locations like:

  • event log
  • an email
  • a database
  • a message queue
  • a text file
  • a WMI event
  • custom locations using application block extension points.

You can log messages to any locations by editing web.config without changing the c# codes.

Here I'm showing how to log information’s to an event log, an email and a text file.

1.Logging messages to event log (Event Viewer)

First you have to configure the web.config. By default the messages are logged into the event log. 


You can edit the web.config  Give the source name as the name of your application.


Below example shows how to log event viewer in a button click.

First you have to add the reference Enterprise Library Logging Application Block to the bin folder of your application.

aspx page

<head runat="server">
    <title> Event Viewer</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btn1" runat="server" Text="Submit" onclick="btn1_Click" />
    </div>
    </form>
</body>

aspx.cs

using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
       
        LogEntry logEntry = new LogEntry();
        logEntry.EventId = 100;
        logEntry.Priority = 2;
        logEntry.Message = "Informational message";
        Logger.Write(logEntry);   
    
    }
}


When you click on the button the message will be logged into the event viewer. Instead of using LogEntry class, you can  use only  the Write() method of the Logger class as shown below.

using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        
        Logger.Write("Informational message","EventLog",2,100);
    }
}


2. Logging messages to an email

There is no need to change the c# code only configure the web.config. You have to change the logging target listener from event log listener to email trace listener. You can do this by clicking on the + sign on the right of logging target listeners.

You have to give the From Address, Smtp port, Smtp Server, To Address in the web.config.


While clicking the button the message will be logged to the email.

3. Logging messages to a text file

No need to change the c# code. Configure the web.config. Select Flat file trace listener as logging target listener. The web.config is shown below.


While clicking the button, a log file (here trace.log) will be created in your application and the message will be logged into that file.

Conclusion

Logging Application Block in the Enterprise Library is used to log messages to different locations by configuring the web.config, without any changes in the code.

Monday 2 April 2012

Import Spreadsheet to SharePoint


Creating a Custom Field Type for SharePoint 2010 (Email Validation Field)



In this article I am describing how to create a custom field type for SharePoint 2010. I have searched the internet but didn't find any relevant documentation for this. Here I am creating a simple field type for Email validation; it will accept only valid email addresses.

First we start with the project

Creating Visual Studio Project
  1. In Visual Studio, create an Empty SharePoint Project. Give a suitable name for your project

    customfield1.gif
     
  2. Right-click the project name in Solution Explorer and select Properties.

    customfield2.gif
     
  3. On the Application tab of the Properties dialog, enter Email.SharePoint.ISBN_Field_Type as the Assembly name and Email. SharePoint as the Default namespace. Leave the Target framework set to .NET Framework 3.5.

    customfield3.gif
     
  4. Click Save
  5. Right-click the project name in Solution Explorer and select Add | New Item
  6. In the Add New Item dialog box, select Visual C#
  7. Select Class from the template and give name as Email.Field.cs

    customfield4.gif
     
  8. Create two classes (in the same way as described) named Email.FieldControl.cs and EmailValidationRule.cs
  9. In Solution Explorer, right-click the project name and select Add, then SharePoint Mapped Folder

    customfield5.gif
     
  10. Use the tree control that opens to map the folder to TEMPLATE\ControlTemplates and click OK.

    customfield6.gif
     
  11. Right-click the new ControlTemplates folder (not the project name) in Solution Explorer and select Add | New Item
  12. In the Add New Item dialog box, select SharePoint | 2010 in the Installed Templates tree
  13. Select a SharePoint User Control in the Templates box, and give the ascx file the name EmailControl.ascx. Click Add. Visual Studio automatically adds the file to the SharePoint Solution manifest and sets it to be deployed to ProgramFiles\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\ControlTemplates. It also at this time adds the assembly to the manifest and sets it to be deployed to the Global Assembly Cache (GAC).

    customfield7.gif
     
  14. Delete the EmailFieldControl.ascx.cs and ISBNFieldControl.ascx.designer.cs files that are created automatically under the EmailFieldControl.ascx file. They are not needed for this project. The default content of EmailFieldControl.ascx refers to the EmailFieldControl.ascx.cs file you just deleted and, if you build the project at this point, the compiler will give you a warning about the missing file. Ignore it; no need to worry about it.

    customfield8.gif
     
  15. In Solution Explorer, right-click the project name and select Add, then SharePoint Mapped Folder.

    customfield9.gif
     
  16. Use the tree control that opens to map the folder to TEMPLATE\XML and click OK.

    customfield10.gif
     
  17. Right-click the new XML folder (not the project name) in Solution Explorer and select Add | New Item.
  18. In the Add New Item dialog box, select Visual C# and select an XML file; give the name as Fldtypes_EmailField.xml.

    customfield11.gif
     
  19. In Solution Explorer, right-click the project name and select Add, then SharePoint Mapped Folder.
  20. Use the tree control that opens to map the folder to TEMPLATE\LAYOUTS\XSL and click OK.

    customfield12.gif
     
  21. Right-click the new XSL folder (not the project name) in Solution Explorer and select Add | New Item.

    customfield13.gif
     
  22. In the Add New Item dialog box, select Visual C# then select XSLT File in the Templates window.

    customfield14.gif
     
  23. In the Name box, type fldtypes_EmailField.xsl and click Add. Note this is very similar to the name of the previous file you created. The two files have different purposes and are deployed to different folders.
  24. Right-click the References node in Solution Explorer, click Add Reference, and select PresentationFramework.dll on the .NET tab in the Add Reference dialog box. Click OK.

Creating the Validation Rule Class
  1. Open the EmailValidationRule.cs file and add the following statements.

    using
     System.Text.RegularExpressions;
    using
     System.Windows.Controls;
    using
     System.Globalization;
     
  2. Replace the class declaration with the following code.

    using
     System;
    using
     System.Collections.Generic;
    using
     System.Linq;
    using System.Text;
    using
     System.Drawing;
    using
     System.IO;
    using
     System.Web;
    using
     System.Web.UI;
    using
     Microsoft.SharePoint;
    using
     System.Text.RegularExpressions;
    using
     System.Windows.Controls;
    using
     System.Globalization;
    using
     System.Web.UI.WebControls;
    using
     System.Web.SessionState;
    namespace Email.System.Windows.Controls
    {
        public class Email10ValidationRule : ValidationRule    {
             public override ValidationResult Validate(object value, CultureInfo cultureInfo)
             {
                    String Email = (String)value;
                    bool result = isEmailID(Email);            
                    if (result != true)
                    {
                        return new ValidationResult(false"Enter valid Email.");
                    }
                    else                {
                        return new ValidationResult(true"Email Entered is correct.");
                    }         
            }
             public static bool isEmailID(string inputEmail)
            {
                string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                      @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                      @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(strRegex);
                if (re.IsMatch(inputEmail))
                    return (true);
                else                return (false);
            }
        }

    }

Creating the Custom Field Class
  1. Open the Email.Field.cs file.
  2. Add the following name spaces.

    using
     Microsoft.SharePoint;
    using
     Microsoft.SharePoint.WebControls;
    using
     Microsoft.SharePoint.Security;
    using
     System.Windows.Controls;
    using
     System.Globalization;
    using
     System.Runtime.InteropServices;
    using
     System.Security.Permissions;
     
  3. Add the following statements. These enables our class implementation to reference other classes you create in later steps. Until you create those classes you may see compiler warnings about these statements. Don't worry about that; we are moving to that in a following step.

    using
     Control.Validation.WebControls;
    using
     Control.System.Windows.Controls;
     
  4. Please find the following updated code.
    using System;
    using
     System.Collections.Generic;
    using
     System.Linq;
    using
     System.Text;
    using
     Microsoft.SharePoint;
    using
     Microsoft.SharePoint.WebControls;
    using
     Microsoft.SharePoint.Security;
    using
     System.Windows.Controls;
    using
     System.Globalization;
    using
     System.Runtime.InteropServices;
    using
     System.Security.Permissions;
    using
     Email.SharePoint.WebControls;
    using
     Email.System.Windows.Controls;
    using
     System.IO;
    using
     System.Web;
    using
     System.Web.UI;
    namespace
     Email.SharePoint
    {
        public class EmailField : SPFieldText    {
            public EmailField(SPFieldCollection fields, string fieldName)
                : base(fields, fieldName)
            {
            }
            public EmailField(SPFieldCollection fields, string typeName, string displayName)
                : base(fields, typeName, displayName)
            {
            }
            public override BaseFieldControl FieldRenderingControl
            {
                [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
                get            {
                    BaseFieldControl fieldControl = new EmailFieldControl();
                    fieldControl.FieldName = this.InternalName;
                    return fieldControl;
                }
            }
            public override string GetValidatedString(object value)
            {
                if ((this.Required == true) && ((value == null)|| ((String)value == "")))
                {
                    throw new SPFieldValidationException(this.Title + " must have a value.");
                }
                else            {
                    Email10ValidationRule rule = new Email10ValidationRule();
                    ValidationResult result = rule.Validate(value, CultureInfo.InvariantCulture);
                    if (!result.IsValid)
                    {
                        throw new SPFieldValidationException((String)result.ErrorContent);
                    }
                    else                {
                        return base.GetValidatedString(value);
                    }
                }
            }
        }

    }

Creating the Field Rendering Control
Please replace the code in EmailFieldControl.ascx.cs we created in step 20 with the following.
using System.Web;
using
 System.Web.UI;
using
 System.Web.UI.WebControls;
using
 System.Runtime.InteropServices;
using
 Microsoft.SharePoint;
using
 Microsoft.SharePoint.WebControls;
namespace
 Email.SharePoint.WebControls
{
    public class EmailFieldControl : TextField    {
        protected Label EmailPrefix;
        protected Label EmailValueForDisplay;
        protected override string DefaultTemplateName
        {
            get            {
                if (this.ControlMode == SPControlMode.Display)
                {
                    return this.DisplayTemplateName;
                }
                else                {
                    return "EmailFieldControl";
                }
            }
        }
        public override string DisplayTemplateName
        {
            get            {
                return "EmailFieldControlForDisplay";
            }
            set            {
                base.DisplayTemplateName = value;
            }
        }
        protected override void CreateChildControls()
        {
            if (this.Field != null)
            {
                base.CreateChildControls();
                //   this.EmailPrefix = (Label)TemplateContainer.FindControl("EmailPrefix");                this.textBox = (TextBox)TemplateContainer.FindControl("TextField");
                this.EmailValueForDisplay = (Label)TemplateContainer.FindControl("EmailValueForDisplay");
            }
            if (this.ControlMode != SPControlMode.Display)
            {
                if (!this.Page.IsPostBack)
                {
                    if (this.ControlMode == SPControlMode.New)
                    {
                        textBox.Text = "";
                    }
                }
            }
            else
            {
                EmailValueForDisplay.Text = (String)this.ItemFieldValue;
            }
        }
        public override object Value
        {
            get            {
                EnsureChildControls();
                return base.Value;
            }
            set            {
                EnsureChildControls();
                base.Value = (String)value;
            }
        }
    }

}


Creating the Field Rendering Template
  1. Open the EmailControl.ascx file.
  2. The following directives are already in the file.

    <%
    @ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%
    @ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%
    @ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%
    @ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%
    @ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%
    @ Import Namespace="Microsoft.SharePoint" %> 
    <%
    @ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%
    @ Control Language="C#" %>
    <
    SharePoint:RenderingTemplate ID="EmailFieldControl" runat="server">  <Template>    <table>    <tr>    <td >    <asp:Label ID="EmailPrefix"  runat="server" />    </td>
         <td>   <asp:TextBox id="TextField" runat="server" Width="50%" ></asp:TextBox>
       </td>     </tr>     <tr>   </tr>   </table>  </Template>

    </
    SharePoint:RenderingTemplate> 
    <
    SharePoint:RenderingTemplate ID="EmailFieldControlForDisplay" runat="server">  <Template>    <asp:Label ID="EmailValueForDisplay" runat="server" />  </Template>
    </
    SharePoint:RenderingTemplate>
  3. Below this markup is a <%@ Control directive that makes reference to files that you deleted in an earlier step and contains other attributes that are not used in this project. Replace it with the following simplified directive. I have already done this change in the above code.

    <%@ Control Language="C#" %>

Creating the Field Type Definition
  1. In Visual Studio, build the project. The project is not finished, but you need to do a build at this time to generate a GUID and a Public Key Token for the assembly.
  2. Open the fldtypes_EmailField.xml file and replace it's contents with the following markup.

    <?
    xml version="1.0" encoding="utf-8" ?>
    <
    FieldTypes>
     <
    FieldType>
    <
    Field Name="TypeName">Email</Field>
     <
    Field Name="ParentType">Text</Field>
     <
    Field Name="TypeDisplayName">Email</Field>
     <
    Field Name="TypeShortDescription">Email Validation Text</Field>
     <
    Field Name="UserCreatable">TRUE</Field>
     <
    Field Name="ShowOnListCreate">TRUE</Field>
    <
    Field Name="ShowOnSurveyCreate">TRUE</Field>
     <
    Field Name="ShowOnDocumentLibraryCreate">TRUE</Field>
    <
    Field Name="ShowOnColumnTemplateCreate">TRUE</Field>
    <
    Field Name="FieldTypeClass">Email.SharePoint.EmailField,$SharePoint.Project.AssemblyFullName$</Field>
    </
    FieldType>
    </
    FieldTypes>

Creating the XSLT Style sheet

Open the fldtypes_EmailField.xsl file and replace the code.


<
xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
                
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
                
version="1.0"
                
exclude-result-prefixes="xsl msxsl ddwrt"
                
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
                
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
                
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
                
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
                
xmlns:ddwrt2="urn:frontpage:internal">
  <
xsl:template match="FieldRef[@Name = 'Email']" mode="Text_body">
    <
xsl:param name="thisNode" select="." />
    <
span style="background-color:lightgreen;font-weight:bold">
      <
xsl:value-of select="$thisNode/@*[name()=current()/@Name]" />
    </
span>
  </
xsl:template >
</
xsl:stylesheet>

Build and Test the Custom Field Type
  1. Select Deploy on the Build menu. This automatically rebuilds the assembly, deploys the assembly to the GAC, deploys the ascx file to %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\ControlTemplates, deploys the fldtypes*.xml file to %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\XML, deploys the fldtypes*.xsl file to %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\XSL, and recycles the Web application.
  2. Go to site actions -->Site Settings
  3. Click on site libraries and list

    customfield15.gif
     
  4. Click on Create new Content
  5. Create a custom list named Test For Email

    customfield16.gif
     
  6. From the ribbon click on create column

    customfield17.gif
     
  7. You will see that our custom field is added there successfully. Give the details as shown below to add a custom column to your list.

    customfield18.gif
     
  8. From the screen shot shown below you can see our custom email field in action.

    customfield19.gif

    customfield20.gif

The data is added as shown below.
customfield21.gif

For more details, you can refer to the article of creating custom field for SharePoint 2010 in MSDN.