Ajax with jQuery

December 7, 2008 at 1:17 pm | Posted in Javascript, jQuery | 1 Comment
Tags: , , ,

jQuery has gained a lot of popularity as a Javascript framework that simplifies working with Document Object Model (DOM) and Ajax for web applications. jQuery provides a number of functions that makes dealing with Ajax easier and more powerful .

You can download jQuery framework from here, rename the downloaded file to jquery.js .

In the following example, We will take username from the user as an input, then submit this data to the server which retrieves the user details as a response.

The client page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demonstrating Ajax with jQuery</title>
    <script src="scripts/jquery.js" type="text/javascript" ></script>
</head>
<body>
     <form id="MyForm" >
<div id="inputDiv">
        <b> Username : </b>
        <input type="text" id="tbUsername" />
<a href="#" id="uLink">Get my info !</a></div>
<div id="outputDiv" style="display:none;"></div>
</form>
</body>
<script type="text/javascript">
    $(document).ready(function() {
        $("#uLink").click(function() {
            $.post("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $("#outputDiv").html(output);
                $("#outputDiv").css("display", "block");
            });
        });
    });
</script>
</html>

Our simple client page has a single HTML text input where the user enters his username then on clicking on Get My info , the username data is sent to the server and the retrieved result will be added to the outputDiv div element which is initially hidden.

let’s take a look at our code, first we have to add a reference to our jquery file which I added in a folder named scripts:

<script src="scripts/jquery.js" type="text/javascript" ></script>

Let’s now see how jQuery simplifies working with DOM and Ajax:

$(document).ready(function() {
        $("#uLink").click(function() {
            $.post("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $("#outputDiv").html(output);
                $("#outputDiv").css("display", "block");
            });
        });
    });

$(document).ready() is the event handler that binds a function to be executed when the document is ready to be manipulated.

$(“#uLink”).click() finds the element with id “uLink” and binds a function whenever this anchor is clicked.

$.post() is one of the jQuery functions that sends POST request to the server.

Let’s take a look on its arguments:

$.post(url,data,callback)

-url : is the url of the server page where the function sends the POST request. In our example it’s UserData.aspx?Func=RetrieveUserInfo

-data : is the data to be sent in the request in the form of key/value pairs .here we provide a single key/value pair where the key is username and its value is the value of the tbUsername input element.

-callback : is the function to executed only if the response from the server is successful .
Our callback function loads the response text to outputDiv div element and changes its display style to block to be visible.

Our UserData.aspx is quite simple,it checks the Func querystring and if it matches the RetrieveUserInfo operation, it executes the appropriate method.

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Func"] != null && Request.QueryString["Func"] != "")
        {
            if (Request.QueryString["Func"] == "RetrieveUserInfo")
            {
                RetrieveUserInfo();
            }
            Response.End();
        }
    }

    private void RetrieveUserInfo()
    {
        string UserName=Request.Params["username"];
        string userDetails = "";
        if (UserName != null && UserName != "")
        {
            if (UserName == "Mohamed.Abdelghani")
            {
                userDetails = "<B>First Name</B> : Mohamed
";
                userDetails += "<B>Last Name</B> : Abdelghani
";
                userDetails += "<B>Location</B> : Cairo
";
            }
            else
            {
                userDetails = "<B>First Name</B> : FN
";
                userDetails += "<B>Last Name</B> : LN
";
                userDetails += "<B>Location</B> :  LOC
";
            }
        }
        else
        {
            userDetails = "Please provide correct username !";
        }
        Response.Write(userDetails);
    }

The RetrieveUserInfo method is so simple and just for demonstrating the idea , in a real world scenario, it would be a query from database.

The username data sent by the $.post function is added as a parameter to the request,and is retrieved as shown :

string UserName=Request.Params["username"];

Let’s go back to our client page, Actually jQuery provides a lot of functions to simplify working with Ajax.

Another jQuery function for handling Ajax is $(“#elementID”).load(url,[data],[callback]) which loads the response data directly to the element.

Our javascript code will change to :

$(document).ready(function() {
        $("#uLink").click(function() {
            $("#outputDiv").load("UserData.aspx?Func=RetrieveUserInfo",
            { username: $("#tbUsername").val() }, function(output) {
                $(this).css("display", "block");

            });
        });
    });

The most powerful jQuery function for ajax is $.ajax() which provides more functionality like error callback that executes when the response is not successful.

Let’s take a look at our example with $.ajax() function:

$(document).ready(function() {
        $("#uLink").click(function() {
            $.ajax({
                type: "POST",
                url: "UserData.aspx?Func=RetrieveUserInfo",
                data: "username=" + $("#tbUsername").val(),
                success: function(output) {
                    $("#outputDiv").html(output);
                    $("#outputDiv").css("display", "block");
                },
                error: function()
                {
                    alert("Error");
                }
            });
        });
    });

For a full list of jQuery functions for Ajax click here.

Adding custom assemblies in SQL Server Reporting Services 2005

October 27, 2008 at 4:09 pm | Posted in Reporting Services | Leave a comment
Tags:

SQL Server Reporting Services (SSRS) is a very powerful tool for generating reports and one of the important features in SSRS is adding custom code and custom assemblies to it to add more functionality to your reports.

I will work with SSRS 2005 , First I will add custom code to a sample report .Please note that you can only add VB.Net code as custom code for your reports.

I will work with Visual Studio.Net 2005 ,so let’s start and open it and create a new Report Server Project from Business Intelligence Projects and give it a name ReportSample and specify a location for the project.

Open your Solution explorer, choose Add New Item , select Report template and give it a name SampleRpt.rdl .
Three tabs will be shown for the newly created report: data, Layout and Preview, Open the Layout tab and then go to your menu choose Report->Report Properties, then choose Code tab from the Report Properties window, write the following in Custom Code Field:

Public Function TestFun(ByVal name As String) as String
 Return "Welcome "& name
End Function
Adding custom code to the report

Adding custom code to the report

After adding the custom code, go back to the report layout and drag textbox from the Toolbox to the report and write the following in the textbox
=Code.TestFun(“M. Abdelghani”)
Choose Preview tab , you shall see Welcome M. Abdelghani

Now we are done with adding custom code to the reports , you can add whatever functions you want by adding it to the custom code field in the report properties but what if I don’t write my code in VB.Net and what if I already have multiple classes and I want to use their methods in an object oriented way so it’s time to know how to add custom assemblies to the report .

Open a new instance of VS.Net 2005 and create a new class library template, I will use C# but you can use any other language, Give it a name TestLib and specify its location.

Rename Class1.cs in the solution explorer to WelcomeClass.cs then open it , add the following methods to the class.

public  string  TestFun(string name)
{
return "Welcome "+name;
}
public static string StTestFun(string name)
{
return "Welcome "+name;
}

I’ve added both static and instance methods to the class to demonstrate how to call them from the report , now build the project , go to the project folder and open Bin\Debug folder and copy the TestLib.dll file to the following folder:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies

Please modify the path to match the path where VS.Net 2005 is installed on your machine.

Now we will return back to our ReportSample project , go to the menu, choose Report->Report Properties and then open the References tab . In the References section , add our assembly by clicking the browse button and browse for the TestLib.dll file , After adding the assembly and in the same window go the Classes section and specify the class name as TestLib.WelcomeClass , and choose an instance name to be MyWelcomeClass.

Adding a reference in the report to the custom assembly

Adding a reference to the custom assembly in the report

We need to add the class name and instance name if we are going to use instance methods , we don’t need to specify a class name for calling static methods.

Now go to the layout tab of our report and drag another textbox . I will call the TestFun instance method , to call the instance method in the report you have to specify an instance of WelcomeClass class which is already done and we have an instance called MyWelcomeClass.

We will write in the new textbox the following :
=Code.MyWelcomeClass.TestFun(“M. Abdelghani”)

Now click on the preview tab of the report we have another “Welcome M. Abdelghani” displayed on the report.

So to call an instance method in the report , it will have the following format:
=Code.ClassInstanceName.InstanceMethodName(ListOfParameters)

Go back to the layout tab and drag another textbox where we will call our static method, we will write in the textbox the following:
=TestLib.WelcomeClass.StTestFun(“M. Abdelghani”)

Then switch back once more to the preview tab , the new textbox will display “Welcome M. Abdelghani”

So to call a static method in the report , it will have the following format

=AssemblyName.ClassName.StaticMethodName(ListOfParameters)

It’s time now to deploy our report project ,Go to Solution Explorer ,choose the properties of the ReportSample project .

In the ReportSample Property Pages window :
-set the configuration to be Production.
-set the StartItem to be SampleRpt.rdl.
-set TargetServerURL to your URL of the report server , for me :

http://localhost/ReportServer

Then click Ctrl+F5 to deploy the project, Deployment will fail and the following error is displayed:

Error while loading code module: ‘TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’. Details: Could not load file or assembly ‘TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified.

We will go back to the project folder of TestLib class library and copy the TestLib.dll to the following folder
C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\ReportServer\bin

Please modify the path to match the installation folder of SQL Server on your machine.

Now try again to deploy the ReportSample project and the deployment will succeed.

Missing ASP.Net tab in IIS

October 13, 2008 at 11:06 am | Posted in IIS | 2 Comments
Tags:

I realized that the ASP.Net tab no longer exists in IIS after installing VMWare Server. My machine has Windows Server 2003 SP2 and I work mainly with Visual Studio.Net 2003 and 2005.
After googling on the web I found this solution:

1- Stop IIS Admin service.
2- Search for Enable32BitAppOnWin64=”TRUE” in MetaBase.xml and delete that line.
You can find the MetaBase.xml in the following path:
<Your windows folder path>\system32\inetsrv\MetaBase.xml.
3- Restart IIS .

But the issue didn’t get fixed until I run  aspnet_regiis -i for both ASP.Net 1.1 and 2  .

And now the ASP.Net tab is back again in IIS.

Javascript Closures

September 16, 2008 at 2:10 pm | Posted in Javascript | Leave a comment
Tags:

One of the features of Javascript is closures , Javascript closures keep the local variables of a function even after it returns. That happens when a function is declared inside another function ,the local variables of the outer function will still exist even after the outer function returns.

function outer()
{
var name="mabdelghani";
var inner=function()
{
alert(name);
};
return inner;
}

var testFunction=outer();
alert(testFunction);
testFunction();

In the above code snippet , a function inner is defined inside another function outer , the local variable name is available even after function outer returns.

The result of the following line

alert(testFunction);

is
function()
{
alert(name);
}
and the result of the following line

testFunction();

is mabdelghani
Which means that the inner function which is referenced by testFunction doesn’t keep a copy of the name variable and it references the value of the local variable inside outer function though that function is returned.

It’s not necessary that the local variables in closures are to be declared before the inner function, They can be declared anywhere in the outer function before returning from it.

the following links are useful to know more about Javascript closures

http://www.jibbering.com/faq/faq_notes/closures.html

http://blog.morrisjohns.com/javascript_closures_for_dummies

Blog at WordPress.com. | The Pool Theme.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.