Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

December 2011 - Posts

How to move the ViewState from a hidden field on the client to a session on the server

This is a post relevant to all the developers out there that use Web Forms as their main ASP.Net platform.

In this post I would like to talk about ViewState and how we can move it and store it in a session on the server's memory. We know that the default hidden client field for ViewState can become very large on pages.That can problematic in terms of SEO and performance.

Let's talk a little bit about ViewState since not everybody knows what it is and why we need it. We need those state preserving mechanisms due to the fact that the web and HTTP in particular, are stateless.

ViewState represents the state of the page when it was last processed on the server. We use it to retain values across two successive requests for the same page. It is a hidden field added to the page and is restored on the server before the page request is processed. The Viewstate information travels back and forth with the page itself, but contains no visual elements that need to be rendered.

Have a look here and here to see two posts of mine talking about ViewState.If you want to see some other posts of mine that I talk about State mechanisms have a look  here and here

I am going to create a simple website that retrieves data from a database using the well established Entity Framework ORM.

I will be using Entity Framework version 4.0 that ships with Visual Studio 2010 and .Net 4.0. 

We will create a simple website and use Entity Framework as our data access layer.

I assume that you have access to a version of SQL Server and AdventureWorkLT database.

If you do not, you can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample AdventureWorkLT database, click here

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Add a new item to your site, a ADO.Net Entity Data model. Choose a suitable name for it, e.g AdventureWorkLT.edmx.

4) Then the Wizard pops up. Choose "Generate from Database". Have a look at the picture below

 

 

 5) Click Next and Create a New Connection (as you see in the picture below) and hit the Continue button.

 

 

6) Then follow the instructions as shown in the picture below.Select the local installation of your SQL Server and the database name and then click OK.

 

 

7) After you complete the steps above you will see something like the picture below. You can see the Entity connection string and where these setting will be saved.Hit the Next button.Then click Finish

 

8)  Now the wizard will identify the database objects and let us choose which database objects we want to include in our model.I included all the database objects.Hit the Finish button.

 

9) Have a look at your entity model as it is visualized in the Entity Model Designer. Have a look at the Entity classes and their relationships/associations.Have a look at the properties of each Entity class. Have also a look at the Navigation Properties of each entity class.Basically the entity framework generates classes for all the entities in the designer. You can have a look at the generated code if you want by opening the class file, which in my case is AdvWorks.Designer.cs.

10)  Now we are ready to start querying our database. We will issue a Linq to Entities query against the conceptual schema.

Let's create a new query and bind the resultset to a GridView control. Add a GridView control to the default.aspx page.

In this query we want to get only the customers that have more than one order and the Title equals "Ms"

If you are not so familiar with Linq queries, have a look at my other posts in this blog regarding LINQ.

In the Page_Load event handling routine  type:

AdventureWorksLTEntities ctx = new AdventureWorksLTEntities();
 
var query = from mycust in ctx.Customers
       join sho in ctx.SalesOrderHeaders on mycust.CustomerID 
equals sho.CustomerID
       into myorders
       where (mycust.Title=="Ms." && mycust.SalesOrderHeaders.Count >= 1)
       select new { mycust.FirstName, mycust.LastName,OrdersCount = 
myorders.Count() };

        GridView1.DataSource = query;
        GridView1.DataBind();

 

Do not forget to add this as well in .cs file

using AdventureWorksLTModel;

 

11)  Run your application and you will see the results.

12) Have a look at the View Source of your page and see the ViewState hidden field.You will see a large hidden field with lots of encoded data in it. We need to move it from the client (the browser will not have to download it) and store it on the server's memory where RAM is not an issue.Have a look at the picture below

 

 

13) Now let's see how we can accomplish that.I am going to use an Adapter which is basically a class file. Add another class file in the App_Code special folder.Name it ServerSideViewStateAdapter.cs.

 The code for the .cs file follows

 

public class ServerSideViewStateAdapter:PageAdapter
{
	public override PageStatePersister  GetStatePersister()
{
 	 return new SessionPageStatePersister(this.Page);
}
	
}

Let me explain what the code above does.I have my newly created class that needs to implement the PageAdapter class.

There is a method in that class called GetStatePersister that returns the SessionPageStatePersister that stores ASP.Net page view state on the web server.

You can read more here.

 

Do not to forget to use in your code the two namespaces

using System.Web.UI.Adapters;
using System.Web.UI;
 

14) Now we need to configure the Adapter. We need to add a new special folder to our site, a App_Browsers folder. Add a new item to this special folder,a .browser file and name it ViewStateAdapter.browser.

The code inside this file follows

<browsers>
    <browser refID="Default">
        <controlAdapters>
            <adapter controlType="System.Web.UI.Page"
                     adapterType ="ServerSideViewStateAdapter">
                
                
 
            </adapter>
            
        </controlAdapters>
    </browser>
</browsers>

I define that this Adapter (that I have already created) will target all browsers ( <browser refID="Default">)

15) Now that you have everything configured, view the page on the browser again. You will have the same results. Look now in the Page --> View Source and you will see that the ViewState has been removed and there is only a simple key now present.If I had huge ViewState info in my page by using this technique my clients would download much less client code. My website's responsiveness and performance would significantly increase.

 Have a look at the picture below to see what I actually mean.

 

 

Having said all that I would like to mention once more that you can disable ViewState at application,page and control level.

If you go to your web.config file you can disable it for the whole application

<pages enableViewState-"false" />

You can disable it on page level inside the Page directive

<%@ Page EnableViewState = "false" %>

and you can also disable it on each individual control

<asp:Button id="mybutton" runat="server" EnableViewState="false" />


Drop me an email if you need the source code.

Hope it helps!!


Adding search functionality in a GridView in an ASP.Net application

In my seminars I always show how to fetch data from an SQL Server database to some UI controls (usually a GridView control). I use the connected data access model,I use the disconnected data access model (datasets) and obviously I provide samples that leverage LINQ to SQL and Entity Framework. Sometimes I get asked how to search through the results that are bound to a GridView control.

In this post I would like to show you how to get data from an SQL Server database and bind the data to a Gridview web server control (which is the easy part) and then demonstrate how to search through the results according the serach terms the user enters. Let's move on with our hands-on example.I will use datasets to bind data to the GridView control.

I assume that you have access to a version of SQL Server and Northwind database.

If you do not, you can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample Northwind database, click here.

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Add ASP.Net folder in your site, App_Code. Add another folder inside the App_Code special folder and name it DataAccess.

4) Go to View - > Server Explorer (Database Explorer) and add a connection to the Northwind database.You have just to set the instance of the SQL Server and the name of the database.Test the connection.

5) In your web.config (which is pretty much empty) add a <connectionStrings>. Ιn my case it like the one below. In your case you must set the Data Source property to your SQL server instance.
<connectionStrings>
<add name="NorthwindConnectionString" 
connectionString="Data Source=.;Initial Catalog=Northwind;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

6) Add a class file inside the DataAccess folder. Name the file Connection.cs.So we have a Connection class. The code for the whole class is 

public class Connection
{

public static SqlConnection GetDBConnection()
{
      
string connectionString = ConfigurationManager.
ConnectionStrings["NorthwindConnectionString"].ConnectionString;

SqlConnection connection = new SqlConnection(connectionString);

      
connection.Open();
return connection;
    }

}

This is very simple static method. It returns an SQL connection.Inside this method I do the following.

 

  • I get the connection string from the configuration file

  • I create a new connection object

  • I open the connection and return the connection object. 

Do not forget to add these lines of code in the top of the file. 

using System.Data.SqlClient;
using System.Configuration;
 
7) Add a GridView web server control to the Default.aspx page. Add a button,label and a textbox to the Default.aspx. Leave the default names. The user will enter the Category ID and then they will get the Product Names that belong to this category.
8) Now let's retrieve some data from our database. We will add another file to the DataAccess folder.So add a class file inside that folder and call it DataAccess.cs.
9) Now let's implement the method that will return rows from the Product table that belong to a particular category, the user enters in the textbox.Inside the DataAccess.cs file add this method
 
public static DataSet GetProductsPerCategory(int categoryID)
    {
        DataSet dataSet = new DataSet();

        using (SqlConnection connection = Connection.GetDBConnection())
        {
   string sql = "SELECT * FROM Products WHERE CategoryID=@CategoryID";
   SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@CategoryID"SqlDbType.Int).Value = categoryID;
   command.CommandType = CommandType.Text;

   SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
   dataAdapter.Fill(dataSet, "Products");
        }
        return dataSet;
    }

10) The code above is very simple.I have a static method that I pass a value as input parameter(CategoryID). It also returns a dataset.Inside the method

  • I create a Dataset object
  • I get the connection object back from the GetDBConnection function that "lives" inside the Connection class.I define the SQL statement
  • I create a SqlCommand object by passing as parameters the name of the stored procedure and the connection object
  • I set the input parameter value of the method as the input parameter to the stored procedure
  • I use the ExecuteNonQuery() method of the command object to return the rows affected by the update statement.
  • I create a DataAdapter object and fill the dataset.Finally I return the dataset.

 

11) Now we need to write some code in the code behind in the Default.aspx page to call these methods we created in our data access layer.In the Button1_Click event handling routine I just call the GetProducts() method I create just below it. The code follows 

 

    protected void Button1_Click(object sender, EventArgs e)
    {
        GetProducts();
 
    }
 
    private void GetProducts()
    {
        try
        {
            int categoryID = int.Parse(TextBox1.Text);
 
 
      DataSet ds = DataAccess.GetProductsPerCategory(categoryID);
 
 
      GridView1.DataSource = ds;
      GridView1.DataBind();
 
        }
        catch (SqlException ex)
        {
 
            Label1.Text = "Cannot get product data." + ex.Message;
        }
    }

 

12) Now run your application and enter something in the textbox (e.g 1). You will see the Product names appearing in the Gridview.
13) Now we need to add some more web server controls to allow the user to enter search terms when he will be looking to highlight rows in the GridView that contain those search terms. Add a button, and a textbox to the Default.aspx.
 
   Search terms: <asp:TextBox ID="Textbox2" runat="server" />
 <asp:Button ID="Button2" runat="server" BackColor="#FF3300" 
BorderColor="#0000CC" BorderStyle="Dashed" BorderWidth="2px" 
Font-Bold="True" ForeColor="Yellow" 
onclick="Button2_Click" Text="Search" /> 
14) Now we need to add in the code behind - Default.aspx page - the code that will implement the searching in the GridView results.I will create the FoundText method that will highlight the search terms in the GridView control. We need to use regular expressions. Do not forget to include the namespace
using System.Text.RegularExpressions;
 

   protected string search = String.Empty;
 
    protected string FoundText(string searchitem, string input)
    {
 
 Regex myexpr = new Regex(searchitem.Replace(" ""|"),
 RegexOptions.IgnoreCase);
 
  return myexpr.Replace(input, new MatchEvaluator(Replacewords));
 
    }
 
 
 
    public string Replacewords(Match word)
    {
 
        return "<span class='found'>" + word.Value + "</span>";
 
    } 


The Replacewords method adds a style to the found/matched text and returns it to the FoundText method.  In the head section of the Default.aspx  we need to add the style for the css class found.

<style type="text/css">
   .found {text-decorationnone;color:#FF0000;background:#E07516;}
</style>

 

15) Now we need to add the code in the Button2_Click event handling routine
    protected void Button2_Click(object sender, EventArgs e)
    {
        search = Textbox2.Text;
 
        GetProducts();
    }
} 

The code above is very easy to follow.I just get the search term entered by the user and then call again the GetProducts method.

16) Finally we need to make changes to the GridView web server control. We will change it to use the FoundText method on the ProductName column.The markup follows.

 

 <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" 
 BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" 
   GridLines="None" AutoGenerateColumns="false">
  <AlternatingRowStyle BackColor="PaleGoldenrod" />
  <FooterStyle BackColor="Tan" />
  <HeaderStyle BackColor="Tan" Font-Bold="True" />
   <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" 
     HorizontalAlign="Center" />
   <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
   <SortedAscendingCellStyle BackColor="#FAFAE7" />
   <SortedAscendingHeaderStyle BackColor="#DAC09E" />
   <SortedDescendingCellStyle BackColor="#E1DB9C" />
   <SortedDescendingHeaderStyle BackColor="#C2A47B" />
 
 
   <Columns>
        
  <asp:TemplateField HeaderText="Product Results">
   <ItemTemplate>
  <%# FoundText(search, (string)Eval("ProductName"))%>
   </ItemTemplate>
        
   </asp:TemplateField>
        
        </Columns>
        </asp:GridView>

17) Now run your application again. Type something in the first textbox (CategoryID) and click the first button that displays the results in the GridView. In the textbox for the search terms, enter your own terms.

Have a look at the picture below to see what are the results in my case where I enter 1 as CategoryID and "ac" as the search terms.

 

 

 

That is all folks!!!

Email me if you need the source code.

Hope it helps!!!


Create an Ajax enabled WCF service and invoking it using client-side code

In this post I would like to show you again with a hands-on example how to create an Ajax enabled WCF Service and invoke it using the Ajax Script Manager web server control.

This is going to be a very simple example and it is for people who are not familiar with WCF and in general with SOA architecture. My main concern here is to show how you can invoke that service (service method) using client side code.

In a later post I will show you something similar using JQuery.

Let's move on with our hands on example.I will create a simple service that adds two numbers when called.In the web form we will have two textboxes and a button. The 2 textboxes will contain the parameters we will pass the to the WCF service.

1) Launch Visual Studio. I will use the ultimate edition. You can use the Web Developer Express edition. Create an empty website and choose C# as the development language

2) Add a new item to your site, a web form. Leave the default name. Inside the <body> tags add the following markup

    First Number:<input type="text" id="txtnuma"/><br />
    Second Number:<input type="text" id="txtnumb" /><br />
        <input type="button"  value="ADD" onclick="AddNums()"/>
 
        <br />
 
        <span id="additionres"></span>

3) Add a new item to your site, an Ajax-enabled WCF Service. Name it MyCalculatorService.svc. In the MyCalculatorService.cs add the following code.

 [OperationContract]
	public string Add(int num1, int num2)
        {
 
            int res;
 
            res = num1 + num2;
 
 
        return res.ToString();
        }

 

4) In the default.aspx page drag and drop a ScriptManager web server control. I use the Services tag to specify the path to the service.

  <asp:ScriptManager ID="ScriptManager1" runat="server">
 
<Services>
 
<asp:ServiceReference Path="~/MyCalculatorService.svc" />
        
</Services>
</asp:ScriptManager>

 

The whole markup for the default.aspx is

 

    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
 
        <Services>
 
        <asp:ServiceReference Path="~/MyCalculatorService.svc" />
        
        </Services>
        </asp:ScriptManager>
 
 
     First Number:<input type="text" id="txtnuma"/><br />
    Second Number:<input type="text" id="txtnumb" /><br />
        <input type="button"  value="ADD" onclick="AddNums()"/>
 
        <br />
 
        <span id="additionres"></span>
 
    </div>
    </form>

 

5) Now we need to add the code for the Javascript function (AddNums()) that will be invoked when the button is clicked and will pass the arguments to the remote service.This is the JavaScript code.You should place it in the head section of the page.

 

    <script type="text/javascript">
 
 
 
  function AddNums() {
 
 
 MyCalculatorService.Add($get("txtnuma").value, $get("txtnumb").value,onSuccess);
 
        }
 
 
   function onSuccess(result) {
 
 
        var myres = $get("additionres");
        myres.innerHTML = result;
 
      }
 
 
    </script>

 

We get the values from the textboxes using $get which is short for document.getElementByID . We do have another parameter(onSuccess method) which is required by our client. This method will be called asynchronously. This is called a callback method.

Then we add a new function onSuccess. This is going to receive a result which is the result of the Ajax-enabled WCF service method (Add). The result will be the string that our service returns. 

Then I just get the value that the Ajax-enabled WCF service returns and assign it to my <span> element that has an ID of "additionres".

6) Run your website and add 2 numbers in the textboxes. Click the button. If you have followed everything correctly so far, you will get a response back from the WCF Service.

Email me if you need the source code.

Hope it helps!!!

Using JQuery to call a WCF Service in an ASP.Net application

In this post I would like to show you with a hands-on example how to invoke a WCF service from JQuery. I have already posted a few posts regarding JQuery and server communication.Have a look in this post and in this post. This is a similar post .

In order to follow what I am about to say in this post, I assume that you know what JQuery is and have a basic understanding of how to traverse the DOM or handle events with JQuery.

You can find more posts regarding JQuery by clicking here. So we can invoke an AJax enabled WCF service from JQuery as long the binding is webHttpBinding.

 

1) Launch Visual Studio 2010 (express edition will also work) and create a new empty website.Choose a suitable name for your website.Choose C# as the development language.

Add a new item in your project , a web form. Name it jQueryWCF.aspx.We are going to have some <a> links in the page. We are going to instantiate some calls to the WCF service through JQuery.

These links represent the names of Liverpool footballers. This is the code for the markup

<body>
  
        <p>Liverpool Players</p>
 
            <a href="#">Steven</a> 
            <a href="#">Kenny</a> 
            <a href="#">Robbie</a>    
  
    <br />
 
    <br />
 
    <br />
    <div id="loginfo">
    
    </div>
    <br />    
    <div id="res">
    
    </div>
</body>

 

Nothing difficult in this code.

2) Add another item to your website, an Ajax-enabled WCF service.Name it FootballersInfo.svc. The markup is generated automatically

<%@ ServiceHost Language="C#" Debug="true" Service="FootballersInfo" 
CodeBehind="~/App_Code/FootballersInfo.cs" %>

3) In the App_Code folder we need to add a new item, a class file. I name it Footballers.cs

This is the code for the class

[DataContract]
public class Footballers
{
    [DataMember]
    public string FirstName { getset; }
 
    [DataMember]
    public string LastName { getset; }
 
    [DataMember]
    public DateTime BirthDate { getset; }
 
}

This is a simple class with 3 properties.

Also in the App_Code special folder we have the FootballersInfo.cs

The code for this class follows. Have a look at the comments. I would use those lines if I would use a HTTP GET.In this example I will use HTTP POST.

In this class we have a method (GetFootballerInfo) that gets a string as an input parameter and we return back to the calling code a footballer object depending on the input string parameter (name)

public class FootballersInfo
{
// To use HTTP GET, add [WebGet] attribute. 
//(Default ResponseFormat is WebMessageFormat.Json)
	// To create an operation that returns XML,
//     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
//     and include the following line in the operation body:
//   WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
 // Add more operations here and mark them with [OperationContract]
 
    [OperationContract]
    public Footballers GetFootballerInfo(string name)
    {
        Footballers footballer = null;
 
        if (name == "Steven")
        {
            footballer = new Footballers
            {
                FirstName = "Steven",
                LastName = "Gerrard",
                BirthDate = new DateTime(1980, 11, 11),
 
            };
        }
 
        if (name == "Kenny")
        {
            footballer = new Footballers
            {
                FirstName = "Kenny",
                LastName = "Dalglish",
                BirthDate = new DateTime(1950, 11, 11),
 
            };
        }
 
        if (name == "Robbie")
        {
            footballer = new Footballers
            {
                FirstName = "Robbie",
                LastName = "Fowler",
                BirthDate = new DateTime(1975, 11, 11),
 
            };
        }
 
   
 
        return footballer;
    }
} 

 

4) Now we need to write some JavaScript code that will invoke the WCF service and get back the results from the service and display them on the screen.Add a folder to your website, called scripts.

Add a new item to the scripts folder, a javascript file. Name it jQueryWCF.aspx.js . Go to the main JQuery website -http://jquery.com/- and download the latest Jquery library. Include those library files in the scripts folder.

In the head section of the jQueryWCF.aspx page add the following

<head runat="server">
    <title></title>
   
 
  <script src="scripts/jquery-1.7.js" type="text/javascript"></script>

    <script src="scripts/jQueryWCF.aspx.js" type="text/javascript"></script>
</head>

 

I will post below the contents of the jQueryWCF.aspx.js  and I will explain what I do

 
$(function() {
    $("a").click(GetFootballerInfo)
 
 
 $("#loginfo").ajaxComplete(function(event, xhr, options) { 
$(this).append("complete <br/>"); })
   .ajaxError(function(event, xhr, options) { $(this).append("error <br/>"); })
   .ajaxSend(function(event, xhr, options) { $(this).append("send <br/>"); })
   .ajaxStart(function(event, xhr, options) { $(this).append("start <br/>"); })
   .ajaxStop(function(event, xhr, options) { $(this).append("stop <br/>"); })
   .ajaxSuccess(function(event, xhr, options) { $(this).append("success <br/>"); });
});
 
 
 
function GetFootballerInfo(event) {
    var footballerName = $(this).text();
    $.ajax(
        {
            type: "POST",                                           
            url: "FootballersInfo.svc/GetFootballerInfo",     
            data: '{ "name": "' + footballerName + '" }',           
            timeout: 7000,                                          
            contentType: "application/json",                       
            dataFilter: parseJson,
            success: onSuccess                
        });
}
 
function parseJson(data, type) {
    var dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)
(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"''g');
    var exp = data.replace(dateRegEx, "$1new Date($2)");
    var result = eval('(' + exp + ')');
    return result.d;
}
 
function onSuccess(footballer) {
 
    var html = "<ul>";
 
    html += "</ul>";
   html += "<br/>First Name: " + footballer.FirstName;
  html += "<br/>Last Name: " + footballer.LastName;
  html += "<br/>Birthdate: " + footballer.BirthDate;
  
  $("#res").html(html);
}

 

When the link is clicked then I call the GetFootballerInfo function. The function does the following:

1) I get the text of the link that was pressed, (footballer name). Then I make a low level call to the ajax JQuery method to perform the asynchronous HTTP (Ajax) request and fill in all the parameters the method requires.Then I use HTTP post to pass the data to the WCF service (type: "POST",  )

2) The URL or endpoint is set to the  (url: "FootballersInfo.svc/GetFootballerInfo",). We invoke the GetFootballerInfo method.

3) Then I define that the input parameter is in JSon format (data: '{ "name": "' + footballerName + '" }',).What I mean is that we serialise the input data as JSon format. WCF will make a note of that and deserialise it.

4)  We have a timeout of 7 seconds  (timeout: 7000, )

5)  We tell WCF that JSon format is what we are going to pass it and we expect JSon format as a response. ( contentType: "application/json",  )

6) The WCF will return JSon to the asynchronous call and JQuery will attempt to parse that JSon. But that does not work well with datetime fields.We can get round that by writing our own parsing JSon datetime method. (  dataFilter: parseJson, ). Have a look at the parseJson method.

7) When everything is successfull we call the onSuccess method. (success: onSuccess). Have a look at the onSuccess method. We get back the answer from the server and then using simple JQuery we stick that output to the page  ($("#res").html(html); })

Finally I would like to say a few things about the global Ajax events. This is the only bit of code I have not explained.

 

 $("#loginfo").ajaxComplete(function(event, xhr, options)
 { $(this).append("complete <br/>"); })
    .ajaxError(function(event, xhr, options) { $(this).append("error <br/>"); })
    .ajaxSend(function(event, xhr, options) { $(this).append("send <br/>"); })
    .ajaxStart(function(event, xhr, options) { $(this).append("start <br/>"); })
    .ajaxStop(function(event, xhr, options) { $(this).append("stop <br/>"); })
    .ajaxSuccess(function(event, xhr, options) { $(this).append("success <br/>"); });

What I do here is basically using these events to get information such as when the ajax call  started, was sent, was successful,completed and finally stopped.I also find out if something was wrong (error). I print this information to the screen.By all means have a look in the documentation for global Ajax events.

By all means use Firebug to debug / place breakpoints for the .js files.

5) Finally view the page in the browser and click the link. The asynchronous call to the service will be made. The WCF service will get the parameter and will return back JSon results that JQuery will know how to parse.

Have a look at the picture below to see what happened when I loaded the page and clicked one of the links.

 

Now I would like to show you how to use Firebug which is an excellent add-on to do some basic debugging.You must download firebug and invoke it.I will add a watch (footballerName) and place a breakpoint.Then I  run the page again. Have a look at the picture below

 

Finally we can see the JSon response the WCF Service sent back to the calling application. Have a look at the picture below.

 

So we saw how easy it is to invoke a WCF Service with JQuery. Hope the screenshots helped to clear things out.

Email me if you need the source code.

Hope it helps !!!

Using Audio and Video in HTML 5

This is the second post in the new HTML 5 post series. You can find the first post about HTML 5 input form elements and validation here.

In this post I would like to show you how to use audio and video.We all know that audio and video are everywhere on the web nowadays and are part of the web experience in many sites.

This is a new way of adding audio and video (new html elements) with HTML 5 which does not require any plugins.We can have audio and video playing natively in the browser.

Since the media does not require a plug-in, the user's web browser must support the video/audio codec. Not all web browsers support the same video/audio codecs.You should include multiple formats of the media and let the browser decide which format to use.That can be a time-consuming process since we must encode videos in multiple formats.

These new HTML 5 tags for audio and video are supported by the latest versions of Internet Explorer,Firefox,Opera and Safari.

Finally, before I go on showing you a hands on demo on video and audio tags on HTML 5, I would like to mention a few limitations that video support has.At this time there is no provision for streaming video files so the file must be downloaded completely before a user can seek to a place in a video.There is no mechanism for managing digital rights so it is difficult to prevent piracy.

1) Launch Visual Studio 2010, (Web Developer Edition will do) or any other editor of your choice.In Visual Studio 2010 we have Intellisense and support for HTML 5.Create an empty web site. Add an HTML item to your website

Name it audio.htm. I will be demonstrating the audio support in HTML 5 first.Add a new folder to your project, called media. In the media folder add these audio and video items that you can download from here.

The markup for the page is

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Sound Samples</title>
  </head>
  
  <body>
    <h1>Audio Samples</h1>

    <article class="audio">
      <header><h2>1st audio</h2></header>
        <audio controls>
            <source src="media/piano.mp3" type="audio/mp3" />
           <!-- <source src="media/piano.ogg" type="audio/ogg" />-->
          
            <p>Your browser does not support HTML 5 audio element</p>
    
        </audio>
    
    </article>
  
    <article class="audio">
      <header><h2>2nd audio</h2></header>

       <audio controls>
            <source src="media/guitar.mp3" type="audio/mp3" />
           <!-- <source src="media/guitar.ogg" type="audio/ogg" />-->

            <p>Your browser does not support HTML 5 audio element</p>
    
    </audio>
    </article>
    
  </body>
</html>
 

The code is very easy to follow. I am using some new HTML 5 elements like header,article. I also use the audio element (<audio controls) to specify that I need the audio controls to be displayed on the page. I just specify the source of the audio files.In the comment you will see that I have another format of the audio , .ogg,  (which is not present in the media folder). You should provide alternative audio formats in your websites.

Run your page on the browser and listen to the audio samples. If you have IE9 you will see that it works just fine. But if you hit the compatibility button in the address bar, you will see this message

 Your browser does not support HTML 5 audio element

2) Add another HTML item to your site and name it video.htm. The markup follows

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Video Samples</title>
  </head>
  
  <body>
    <h1>Video Samples</h1>

    <article class="video">
      <header><h2>1st video</h2></header>
        <video controls="controls" autoplay="autoplay">
            <source src="media/gizmo.mp4" type="video/mp4" />

<!--            <source src="media/gizmo.ogv" type="video/ogv" />
            <source src="media/gizmo.web" type="video/web"  />-->
     
          
            <p>Your browser does not support HTML 5 video element</p>
    
        </video>
    
    </article>
  

    
  </body>
</html>

 

 

The code is very easy to follow. I am using some new HTML 5 elements like header,article. I also use the audio element (<video controls) to specify that I need the video controls to be displayed on the page. I just specify the source of the video files.In the comment you will see that I have other formats of the video ,.ogv, .web,  (which is not present in the media folder). You should provide alternative video formats in your websites.

Run your page on the browser and listen to the video sample. If you have IE9 you will see that it works just fine. But if you hit the compatibility button in the address bar, you will see this message

 Your browser does not support HTML 5 video element

Run your page on the browser and see the video in your browser.Note that you have all the controls needed to play the videos.

Hope it helps!!!


 

Posted: Dec 26 2011, 02:03 AM by nikolaosk | with 7 comment(s) |
Filed under: , , ,
Using HTML 5 form input elements in ASP.Net applications

I am going to start a new series of posts that focus on HTML 5. HTML 5 is something I wanted to learn and finally I have covered enough ground to feel confident.HTML 5 gives us things like Semantic tags, the possibility to add video and audio in our pages without any plugins.With Canvas we can have very rich animations to our web pages.

I see that now with all these emerging technologies there are many things you can do on the client. JQuery is amazing and you can do so many things. Please have a look at my posts on JQuery. CSS3 is another big player that all developers should look into.

Some people might argue that front-end developers cannot use HTML 5 and CSS3 right now, because there are many browser versions from various vendors that do not support them or support them partially. IE6- IE8 do not support CSS3 (or there is a little support) but IE 9 supports many of them.In general (with some exceptions) IE9, Opera 10+, Firefox 3.5+, pretty much any reasonably recent version of Chrome, and Safari 3+ support CSS3.

CSS3 comes with Color enhancements,Transforms,Shadowing,Rounded corners and much more.

Two very nice sites that show you what features and specifications are implemented by various browsers and their versions are http://caniuse.com/ and http://html5test.com/. At this times Chrome seems to support most of HTML 5 specifications.Another excellent way to find out if the browser supports HTML 5 and CSS 3 features is to use the Javascript lightweight library Modernizr.

Maybe now it is not the best time to implement a solution with HTML5 and CSS3 but we should definitely learn and master those new technologies.In this post I will talk about HTML 5 and more particular HTML 5 new form input element tags and attributes. You will be amazed at what you can do with HTML 5 form input tags and how easy it is to add watermarks, validation and also how to receive focus on an element.

Let's begin with our example. This is going to be a very simple form and I will show you how to upgrade it to HTML 5.Note that for all these examples I will be using Chrome version 15, since it supports most of the HTML 5 new features.


1) Launch Visual Studio and create an empty website.

2) Add a simple html item to your site. This is the mark up for the html form

<body>
 
        <header>
    	    
            <h1>Fill in the form to win special prizes!!!</h1>
            
        </header>
   
        <section id="contactform">
            <hgroup>
                
                <h2>Make sure everything is correct.</h2>
            
            </hgroup>
 
        <form id="mainform"> 
        <label for="name">Name</label>    
        <input tabindex="1" class="data" id="name" name="name" 
        type="text"  title="enter your name"  />  
 
        <label for="age">Age</label> 
   <input tabindex="2" class="data" id="age" name="age" title="enter your age"
            type="text" />
                
         <label for="email">Email</label>  
         <input tabindex="3" class="data" id="email" name="email"   
                 type="text"  title="enter an email"  /> 
 
         <label for="date">Date</label>  
         <input tabindex="4" class="data" id="date" name="date"   
          type="text"  title="enter a date" /> 
 
              
         <label for="site">Site</label>    
         <input tabindex="5" class="data" id="site"  name="site" 
         type="text"  title="enter the url of your site"  />
                
          <label for="phone">Phone</label>  
         <input tabindex="6" class="data" id="phone" name="phone"
         type="text"  title="enter a phone number"  /> 
 
                
     <input tabindex="7" class="linkButton" id="submit" name="submit" 
         type="submit" value="Send Data" /> 
            </form>
    	</section>
    	
        <footer>
    		<h3>Thanks for your time!!!!! </h3>
    	</footer>
   
</body>

 

3) Let's style the form. In the head section of the form we add

   <link rel="stylesheet" href="styles/site.css" media="screen" />

 The site.css inside the Styles folder code follows

html
{
    margin0;
    padding0;
  
    
}
 footerheaderhgroup,  section
{
    displayblock;
}
body
{
    line-height1;
    background-color:#eaeaea;
    font-family:Tahoma;
}
 
h1
{
    font-family:@Batang;
    font-size:2.3em;
    color:DeepSkyBlue;
}
 
 
hgroup
{
    padding-bottom:         20px;
    padding-left:           145px;
}
 
hgroup h2
{
    font-size:              24px;
    color:                 #9B6145;
  
}
 
 
label
{
    float:                  left;
    color:                  #ff5400;
    display:                inline-block;
    width:                  100px;
    height:                 auto;
    margin-bottom:          25px;
    margin-top:             15px;
}
 
input
{
    float:                  left;
    width:                  300px;
    padding:                25px;
    color:                  #4b4b4b;
    font-size:              16px;
    margin-bottom:          15px;
    margin-top:             -10px;
    margin-right:           15px;
}
input[type="submit"]
{
    border:                 none;
    float:                  left;
    clear:                  left;
    cursor:                 pointer;
    color:                  #fff;
    font-size:              19px;
    padding:                8px 32px 8px 32px;
    margin-left:            100px;
    width:                  auto;
}
input[type="submit"]:active
{
    position:               relative;
    top:                    1px;
}
footer
{
    float:left;
    clear:left;
 
}
 
footer h3
{
 
    font-size:1.3em;
}
 
 
#contactform label
{
    clear:left;
}
 
 
.linkButton
{
    color:#000;
    background-color#CC0000;
}
.linkButton:hover
{
    background-color#808080;
}

4) View your form in the browser. This is a typical form. We will have a name field,an email field, an age field,a date field, a site field, a phone field and a submit button.

Later on I will add a "range" field called Priority.

5) Now let's upgrade the form to HTML 5.Let's say that we want to require for every input field to have some data. We could do that with custom javascript code, or using the built in web server validation controls

I have provided some examples on how to use validation with all the ways mentioned above.You can find them here, here and here.

In HTML 5 the only thing I must do is to add the required attribute.

Have a look at the code below for the name field

 <input tabindex="1" class="data" id="name" name="name" 
                 type="text" required />  

Make sure you do that for all the input fields you require to have a value.

So without any Javascript I have validation out of the box.How cool is that. View your page with Firefox or Chrome and see the result for yourself.

Now we can add some watermark effect very easily to our page. I have provided in this blog another example on how to do that with JQuery. Have a look here if you want.

We can do that in HTML 5 without any Javascript code simply by adding the placeholder attribute to the input field.

 <input tabindex="1" class="data" id="name" name="name" 
                 type="text" required placeholder="fill in your name" />  

Make sure you do that for the rest of the input fields you think it is appropriate.

In the Age field we need to make sure that only positive numbers from 18-88 are allowed.

We can do that by changing the input type to number and setting the min and max values appropriately. (This will not work in Firefox)

  <input tabindex="2" class="data" id="age" name="age" 
title="enter your age"  type="number" required  min="18" max="88" value="18"/>

 

Another validation we want to perform is to have a valid email.We can do that by changing the input type to email.

 The code looks like that

  <input tabindex="3" class="data" id="email" name="email"   
                 type="email" required placeholder="info@domain.com" />   

View it in the browser and see for yourself. Have a look at the Page Source. We have pure HTML that our users and search engines will love.

Another validation we want to perform is to have a valid date.We can do that by changing the input type to date.This will provide us with a datetime picker control.

This will not work in Firefox and Chrome. But works great on Opera.

The code looks like that


    <input tabindex="4" class="data" id="date" name="date"   
         type="date" required  title="enter a date" /> 
 

View it in the browser and see for yourself. Have a look at the Page Source. We have pure HTML that our users and search engines will love.

Now we need to add some sort of validation for the Site field.I just change the type from text to url.

   input tabindex="5" class="data" id="site"  name="site" 
    type="url" required placeholder="http://www.site.com" 
title="enter the url of your site" />

Then we need to have some sort of validation for the telephone field , so the define a new type=tel attribute and a new pattern attribute

  <input tabindex="6" class="data" id="phone" name="phone"
 type="tel" pattern="\(\d\d\d\) \d\d\d\-\d\d\d\d" required 
placeholder="(###) ###-####" /> 

 

I have added another field with a new field Priority that is of type "range" , that give us a slider effect.

 <label for="priority">Priority</label> 
  <input tabindex="7" class="data" id="priority" name="priority" 
title="from 0 to 5" type="range" min="0" max="5" value="2" />

 

If we need to set the focus on the first field, we just add the autofocus attribute.

<input tabindex="1" class="data" id="name" name="name" 
 type="text" required placeholder="fill in your name" autofocus 
title="enter your name"  />  

 If we do not the browser to suggest values to enter in the field, then we can turn it off by using the autocomplete attribute to off.

I am showing that only for the first field.

<input tabindex="1" class="data" id="name" name="name" 
type="text" required placeholder="fill in your name" autofocus 
title="enter your name" autocomplete="off" />  

You could do that for all the fields you do not want the auto-complete feature on.

Well, I am going to post now the complete markup.

<body>
 
        <header>
    	    
            <h1>Fill in the form to win special prizes!!!</h1>
            
        </header>
   
        <section id="contactform">
            <hgroup>
                
                <h2>Make sure everything is correct.</h2>
            
            </hgroup>
 
            <form id="mainform"> 
       <label for="name">Name</label>    
        <input tabindex="1" class="data" id="name" name="name" 
        type="text" required placeholder="fill in your name" autofocus 
title="enter your name" autocomplete="off" />  
 
       <label for="age">Age</label> 
       <input tabindex="2" class="data" id="age" name="age" title="enter your age"
       type="number" required  min="18" max="88" value="18"/>
                
    	<label for="email">Email</label>  
        <input tabindex="3" class="data" id="email" name="email"   
        type="email" required placeholder="info@domain.com" title="enter an email" 
        autocomplete="off" /> 
 
        <label for="date">Date</label>  
        <input tabindex="4" class="data" id="date" name="date"   
        type="date" required  title="enter a date" /> 
 
              
    <label for="site">Site</label>    
    <input tabindex="5" class="data" id="site"  name="site" 
     type="url" required placeholder="http://www.site.com" 
title="enter the url of your site" autocomplete="off" />
                
   <label for="phone">Phone</label>  
   <input tabindex="6" class="data" id="phone" name="phone"
 type="tel" pattern="\(\d\d\d\) \d\d\d\-\d\d\d\d" required 
placeholder="(###) ###-####" title="enter a phone number" autocomplete="off" /> 
 
 
  <label for="service">Priority</label> 
<input tabindex="7" class="data" id="priority" name="priority" title="from 0 to 5"
  type="range" min="0" max="5" value="2" />
 
            
                
  <input tabindex="8" class="linkButton" id="submit" name="submit" 
  type="submit" value="Send Data" /> 
            </form>
    	</section>
    	
        <footer>
    		<h3>Thanks for your time!!!!! </h3>
    	</footer>
   
</body>

 

Run the form in the browser.See all the amazing validation and watermark effects and functionality.No JavaScript is required to do all that.

All the features will work in Opera latest version and partially in Chrome and Firefox.I will add more posts on HTML 5 and later on CSS3 transitions.

Hope it helps!!!

Looking into Web performance in ASP.Net applications
 

In these series of posts I am going to have a look into the various factors that make our web applications slower and how we can rectify that. Ι have already blogged about caching in this blog and you can find these blog posts below

Caching an ASP.Net page

Data caching in ASP.Net applications

How to cache an asp.net page depending on the user's browser language

Caching is very important and vast topic and I might talk more in depth about this issue in future blog posts.Certainly with caching you can reduce the round trips between the client and the server.We can move content closer to the clients and reduce the amount it needs to be retrieved.

Ajax is another topic I blogged extensively about in this blog and definitely increases the responsiveness and performance of our web applications. You can find all the blog posts on Ajax here.

By optimising client side and server side code, we can also save money by reduced bandwidths and make money by having satisfied customers. Imagine two eshops created by 2 different web agencies. Visitors in the first one are very pleased with the overall performance of the site and the responsiveness. Visitors on the second eshop are not so pleased with the performance.It is profound that the first eshop will get more traffic and sales. Bear in mind that the better your site performs the higher Google and other search engines will rank your site.So there is a connection between site's performance and the site's ranking.

In this blog post I would like to concentrate on client/frontend performance issues.Before I go on looking into client side techniques that will improve the site's responsiveness I must say a few things regarding some general rules that will help our site performing better. We should make as many HTTP requests as necessary and we should try to reduce them.We should send as little as possible information to the client.A good example is to use the minified versions of the popular JQuery library instead of the full version.You can reduce the size of the file by 200Kbytes.

A lot of developers and web users in general seem to focus all their efforts how to enhance the performance of the server side components while neglecting to look into the client side performance issues.

As I often say in order to build a fast web application you need the browser to be fast, the server to be fast and the network to be fast. Do not focus solely on how to make the server-side code run faster.

Sometimes by improving issues on the client side makes you site's performance increase significantly.

One aspect that is very important to bear in mind is that when we use a tableless layout using DIVs and CSS. I am a big fan of using CSS. I think it is great idea to have the content HTML and styling CSS seperated.

It is much easier to make changes in the layout/colors of a web site by using an external CSS. From all the available options that we have with CSS (internal,external,inline) I prefer to use external CSS files.

When we adopt this approach our web sites are much faster. Another important issue for all the sites is Search Engine Optimisation. We want our web site to be indexed by search engines and to appear high on search engine results. When the content of our page is closer to the beginning of the file improves the ranking of the page. We should avoid including the large chunks of html code into a single table.

So, we must use external CSS and Javascript files. We should also try to use the minified versions of Javascript libraries when possible.In the case of JQuery library we must use the minified version (.min) since it decreases the amount of bytes that have to travel to the client through the wire.

You can find some good tools for minifying your CSS and Javascript files in the following links

http://www.minifycss.com/

http://yuilibrary.com/download/yuicompressor/

You can also find a nice minifying tool in the Codeplex repository

http://ajaxmin.codeplex.com/

Let me show you a little example using the CSS Compressor that can be found on the http://www.minifycss.com/css-compressor/

I have visited a rather large greek website/portal. Then I clicked on the View--->Page Source and found the external .css file.I copied all the contents in the CSS Input window and then I hit the button Process CSS.

In this example we have a new minified .css file that is 30% smaller in size than the original one. 

Have a look at the picture below

 

It is all very easy to use, so I urge you to try your own CSS files.

If you have used external CSS and Javascript files and minified them the next step is to optimise the images in your site.Images take a lot of bandwidth and sometimes takes a lot of time to load and cause our whole site to delay.Sometimes you will sacrifice image quality for size but sometimes you can reduce the size of an image without compromising its quality.

So we can compress our images, reducing significantly the size of the image but at the same time not decreasing the quality of the image too much...I am going to use Paint.Net to compress a .jpeg image. You can download Paint.Net from here.

Have a look at the picture below to see the image (a windows 7 .jpeg) before the compression

 

Then I save the same with another name and performing compression (10%). The quality of the image is almost the same and totally acceptable.The size has gone down from 67KBytes to 20.5Kbytes.This is a significant decrease in size. Imagine if you have a site with many images. Compression of the images could help significantly the performance of our site.

Have a look at the picture below

 

 

Obviously another thing to consider is if you really need all the images on the site.In my humble opinion I think that sites that do not have many images are "better looking" and "eye-candy". When you want to place a black background on the page, instead of using a .jpeg , use CSS and black color (#000). The same principle should also apply when using section dividers. Do not use images for that.You can use border thickness with the appropriate colors.I have seen sites where little, tiny thumbnails "cost" a lot in terms of size. I am sure you can afford to have your thumbnails in lower quality.

In case you want to have rollover effect on some images in your site, you can use transparency instead of rollover images. I am going to provide you with a simple example.

1) Launch  Visual studio 2010 or Express edition and create a new empty asp.net website.Add a web form to your site. Leave the default name(default.aspx). Add an images folder to your site. Add a styles folder to your site.You can download the image that you will place inside the images folder from arrow.zip.

2) In the default.aspx page add the following markup

 

<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
 
</head>
<body>
    <form id="form1" runat="server">
   
 
<a class="hoverimage" href="#">
<img src="images/arrow.jpeg" border="0" alt="arrow" />
</a>
 
    </form>
</body>
 

 

3) Add a stylesheet file to the styles folder. The code inside the .css external file is this

.hoverimage:hover img{-ms-filter:"progid:DXImageTransform.Microsoft.
Alpha(Opacity=70)";filter:alpha(opacity=70);opacity:0.7}
 

4) Run your site and you will see a nice rollover effect using one image and tranparency.

Another thing we can do in our site that has "text images" is to replace them with CSS and appropriate font types.Let's see that with an example.

Αdd another web form to your site. Leave the default name (Default2.aspx). In the images folder add this img11.zip

The markup follows

<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
 
</head>
<body>
    <form id="form1" runat="server">
   
 
<a class="hoverimage" href="#">
<img src="images/arrow.jpeg" border="0" alt="arrow" />
</a>
 
    </form>
</body>

 

This is the css rules we should add in the external stylesheet.

.wrapper{border:1px solid #000;height:60px;background:url(../images/img11.gif)}
.maintext{font-family:Monotype Corsiva;font-size:48px;color:#A01F1F;padding:5px}
.maintext span{color:#A01F1F}

So instead of having a a fancy "text image" you can have the same visual effect with CSS and nice fonts that all modern browsers support.

Run your site and see the results.

Statistics have shown that 85% of the time that a web site is loaded is spent on HTTP requests that request and load images,.css,.js files.

We can use "CSS Sprites" to decrease the size of the files being downloaded and the amount of HTTP requests. Remember that every image that is being downloaded is a seperate HTTP request.

CSS Sprites is a technique that combines small images into a single image.Then we use CSS to index into the larger image.

In most sites we have images like the mail icon,twitter icon,facebook icon,newsletter icon. For all those images there are different HTTP requests.

I am using Fiddler, which is a great web debugger/listener tool, to monitor what is happening as my site loads.

I have visited a site that does not use CSS sprites. Have a look at the Fiddler image below.You can see that there are 4 separate HTTP requests to the server.

 

Now let me show you how you can use CSS sprites to change that.

Add another web form to your site (Default3.aspx).This is the markup and this is the csssprites.zip file that you can get the images and place them in the images folder.

 

 <form id="form1" runat="server">
    <div>
        <img src="images/home.png" /> | 
        <img src="images/mail.png" /> |
        <img src="images/sitemap.png" /> |
        <img src="images/facebook.png" />
    </div>
    </form>

Run your application and have Fiddler up and running at the same time.

You will see something like the picture below

 

Let's see now how we can use CSS sprites. First of all zip the folder that has all the images.

Then navigate to the http://spritegen.website-performance.org/ and upload the .zip file to this excellent CSS and Image sprite generator.

There are many options there, but I would not change anything for the time.

In my case when I do that I get the following results as shown in the picture below

 

When I add the sprite image in my page and the relevant CSS rules and run my page in the browser, I get the following results through the Fiddler

 

As you can see I have one request for the sprite image.

Another important issue that not many people know when it comes to images, is how the browser downloads images. The browser cache is case sensitive. If you do not use lowercase or uppercase when referencing the images then the browser would download the same image twice.

<img src="theimage.jpg" width="100" height="100" />

 <img src="TheImage.jpg" width="100" height="100" />

If you have those two lines of code in a page the browser will download the image twice even if it was cached.So apply the same naming pattern everywhere.

We all have in our websites the favicon.ico file that is used in the address bar and in the Favorites bar.Most browsers look for this icon in the root folder.

This request is being made every time people visit our site.

We can use a different way to reference the favicon.ico image and take advantage of caching.For example I could write it like that by using a link.

<link rel="shortcut icon" href="images/favicon.ico" />

Another important issue is the CDNs (Content Delivery Networks) and why we should use them.As it was said countless times in this post, static content accounts for the majority of the initial download time for a web page.

Due to network latency the closer the static content it is to your user the faster it will download. CDNs allow you to publish the static content files to their servers.These static files become replicated across a network of servers around the world.Each of those files is assigned a unique URL and we can place that URL to our web pages.When the browser requests one of your pages, it will make its request for the page's static content to the CDN.The CDN will determine which is the best server to deliver the content and the transfer will begin.Have a look how CDN links look like when referencing the popular Javascript Library JQuery in Google,Microsoft and JQuery servers.

http://code.jquery.com/jquery-1.7.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js

 

In a nutshell CDNs give us performance since it locates the closest server to download static content from and caching.If you are wondering what will happen if the CDN servers are down have a look here.

Finally I would like to talk about a few tips that you could use to optimise your client side experience.

You should remove redundant HTML tags and you should also remove <meta refresh> tags. You should minimise the length of the alt tag. Remove unused CSS and use self-closing tags whenever possible.

Use <img/> instead of <img></img>.

That is all for now.

Hope it helps!!!

More Posts