Wednesday, October 17, 2012

Make Your Pages Load Faster

Here is some tips which will make your page load faster

Avoid table layouts and use Div.

Don't use images to display text.

Call up your images through css if possible.

Use contextual selectors

Use shorthand css properties.

Remove white space, line breaks, and commented tags.

Use relative path instead of absolute

Remove unnecessary Meta tags and Meta contents.

Put you css and JavaScript in separate files.

Use '/' and the end directory links.

Use compressed version of css and JS files

Enable compression on your IIS while deploying the site on IIS.

Thursday, October 11, 2012

How to check Complete Page Load by JavaScript

In a client-side application. your application is initializing any control or populating a large amount of data in your control. 

You need to execute a script after DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.

Use window.onload event. This event will not fire until both DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.

Once your page is loaded completely this event automatically fired.

There is other way around put onload event in your body tag.

If you need to execute some script after your page load in your js file. 

window.onload = function(){

  // Write your script
  alert("Page is loaded completely");

}

Sunday, October 7, 2012

How to create a jquery plugin control

This post will explain you to create a jQuery plugin, here we will create a simple plugin which will show your input as an alert. It's just few line of code and very easy to use.

We will start with JS file.


Step 1. Create a JS file. And name it "alertService.js"

To start with JS. First you need to add function as given below to start with your plugin. Rest of your plugin code will come under this.
(function ($) {

})(jQuery);
-----------------------------------------------------------------------------------------------------------------------------
(function ($) {
    //Here we put the name of the plugin..
    // and input parameters will comes in options object.
    $.fn.alertService = function (options) {
        // here we put the default values to the parameters
        var defaults = {
            messege: ""
        };
        // if user pass the parameters then it will pick those. Other wise pick default parameter and put it in options
        var options = $.extend(defaults, options);
        // function which will be called form this plugin.
        function alertMessege() {
            alert("This messege is coming from alertService. And your input text is " + options.messege);
        }
        // Here we call the alertMessege function
        $.fn.alertService = alertMessege();
    };

})(jQuery);
----------------------------------------------------------------------------------------------------------------------------------
Step 2. Now we need to call this plugin form our page.

Here you need to add a Jquery file in your page
I am using jquery-1.4.1.js. You can use any of the version which is available with you.
Add your Plugin js "alertService.js" in your page.

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/js/alertService.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("body").alertService({
                messege: "Test Pass"
            });
        });
    </script>






Tuesday, October 2, 2012

Restful WCF service with Jquery

This is my first post about how to call a WCF service with jquery.

This post will describe how do you pass your parameters through your jquery ajax method to a WCF service.

First we will start with WCF Service....(Restful Service)

Step 1. Create a WCF Service Application


Step 2.  Open your IService1.cs File and put the below code there...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RestFullService
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/Test", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string Test(Parameters param);
    }
    [DataContract]
    public class Parameters
    {
        [DataMember]
        public string Value { get; set; }
    }

}

Step 3. Now open your Service1.svc.cs File and paste the below code there...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;
using System.Data;

namespace RestFullService
{
    public class Service1 : IService1
    {
        public string Test(Parameters param)
        {
            JavaScriptSerializer jSerializer = new JavaScriptSerializer();
            dynamic oParam = jSerializer.Deserialize<dynamic>(param.Value);
            Employee emp = new Employee();
            DataTable dtEmployee = emp.GetEmployee(oParam["id"], oParam["name"]);
            //Here is the code to Serialize the Datatable
            //This will serialize you databale as a List Array.
            List<Dictionary<string, object>> lstSerializeList = new List<Dictionary<string, object>>();
            Array.ForEach(dtEmployee.Select(), row =>
            {
               Dictionary<stringobject> Dictionary = new Dictionary<stringobject>();
                foreach (DataColumn col in dtEmployee.Columns)
                    Dictionary.Add(col.ColumnName, row[col]);
                lstSerializeList.Add(Dictionary);
            });

            return jSerializer.Serialize(lstSerializeList);

        }
    }
    public class Employee
    {
        //Call your Database as your way to get the Data
        // I am using DataTable as a return type... 
        public DataTable GetEmployee(string id,string Name)
        {
            //Do your Code here
            return new DataTable();
        }
    }
}

Step 4. We are done with WCF. Now we will call Javascript to call this service and pass parameters. For this we will add a empty web application which will consume this service and pass parameters to it. WCF Service will return a JSON string to jquery ajax method.

You will need some jquery js files.

jquery.js
jquery.ui.core.js
jquery-1.7.2.js

<script language=javascript>
    function passParameterToService() {
        //By this way you can declare your parameters...
        var data= {};
        data.id = "1";
        data.Name = "EmployeeName";

        var dataAsString = data;
        if ($.type(data) === "object")
       {
            dataAsString = JSON.stringify(data);
       }
       else
       {
          dataAsString = data;
       }

       var dataString = { Value: dataAsString };
       dataString = { param: dataString };
        // This Method will call your ajax service with the parameters
        CallService(dataString );

    }
function CallService(data)
{
    $.ajax({
        type: "PUT",
        url: "http://localhost:<PortNumber>/EndPointName/Test", 
        data: data,
        contentType: "json", 
        dataType: "application/json; charset=utf-8",
        success: function (msg) {
            //On Successful service call
            sucessFunction(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result)
{
  alert('Service call failed: \n Status : ' + result.status + ' Status Text : ' + result.statusText);
}
function sucessFunction(msg) {
     // Here you will receive your JSON string.......
}
</script>