Prabir's Blog

where the tech matters...

Organizing Javascript codes from a C# perspective using object oriented concepts

July 18
by prabir 18. July 2010 16:49

This is a follow up article on Organizing Javascript codes from a C# perspective using namespaces. If you haven’t read the previous article I strongly recommend it do so.

In this article I will discuss on how to structure the Javascript codes using Object Oriented Programming (OOP) concepts which you are highly familiar with in C#.

Lets start first by writing a C# class. (These naming conventions are not of C# standards and never try to write one in this way. Its been written only as an example to map with Javascript codes for convenience.)

namespace A.B
{
    using System;

    public class Test
    {
        public Test()
        {
            Console.WriteLine("constructor");
        }

        private string private_property = "private_property (field)";
        private void private_method()
        {
            Console.WriteLine("private method");
        }

        public string public_property = "public_property (field)";
        public void public_method()
        {
            Console.WriteLine("public_method");
        }

        public static string static_property = "public static property";
        public static void static_method()
        {
            Console.WriteLine("public static_method");
        }
    }
}

First of all we need to wrap code in the namespace block A.B.

if (!A) var A = {};
if (!A.B) A.B = {}; // careful here, var is not present here, only in the first one

Please refer to the my tutorial on  Organizing Javascript codes from a C# perspective using namespaces which describes in more details.

Then we create the class same as in C#. 

A.B.Test = function () {
};

This looks similar to a function. Well it is a function. So in order to instantiate the object of this class you call the function.

var t = A.B.Test();

Now that we are able to create the class, lets create public and private properties and methods.

A.B.Test = function () {
    // ctor
    alert('constructor');

    var _private_var = 'private var';

    private_method = function () {
        alert('private method');
    }

    alert('or can even write ctor anywhere');

    return {
        public_property: "public_property",

        public_method: function () {
            alert("public_method");
        }
    };
};
A.B.Test.public_static_property = 'public static property';
A.B.Test.public_static_method = function () {
    alert('public static method');
};

And here’s are the tests. 

var t = A.B.Test();
alert(t.public_property);
t.public_method();
if (typeof (t._private_var) != 'undefined')
    alert('can access private var, test failed');
else
    alert('cannot access private var, test passed');
try {
    t.private_method();
    alert('can access private method, test failed');
} catch (e) {
    alert('cannot access private method, test passed');
}
alert(A.B.Test.public_static_property);
A.B.Test.public_static_method();

So next time you write Javascript, try implementing these OOP concepts. It will really help you out in organizing your codes.

jsoop.zip (727.00 bytes) [Downloads: 54]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

Javascript | snippets

Organizing Javascript codes from a C# perspective using namespaces

July 15
by prabir 15. July 2010 18:23

Recently I had been writing a lot of Javascript codes and was very unhappy about the code organization and the architect of my source code. Having lots of functions all jumbled up with UI logic and business logic was getting me no where. I decided to stop all my coding and search for a better way to organize my javascript codes.

I saw some solutions by using 3rd party javascript libraries such as YUI and Microsoft Ajax Client library to name a few. It did provide a great way to solve my problems, but what if I wanted to distribute my Javascript codes as an SDK for other devs to build upon (like the Facebook Javascript SDK). They would have to reference it, and even learn how to use YUI or MSAjax libraries. I wanted simpler solution less bulky solution.

Then after searching around, I found out a lot of ways to do it. I have broken up this tutorial into various parts which I will be posting soon. The first one is using the concepts of namespaces as you would do in C#.

Lets say I want to create a SDK called MySDK. I would want to have it under the company’s name like CompanyName.MySDK.

In C# you would do it as …

namespace Prabir.Shrestha
{
   public MyClass
   {
   }
}

 Equivalent code for Javascript would be as follows:

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MyClass = function(){
};

Lets examine the first line in details. var Prabir tells us to create a Javascript variable called Prabir. The right hand side tells to assign Prabir (rhs) to Prabir (lhs) and if Prabir(rhs) is not defined create a new object and assign it to Prabir (lhs) – counfusing isn’t it. Well just remember it as a sort of C# null coalescing operator (??). The next line does the similar thing. It is very important to check if the object already exists as you might have another SDK under the same namespace, and if you create a new one it would override the old variable, so only the last referenced SDK would be available.

Note: Put var only in the root namespace lines and not in others.

So now you could create public functions using the following code.

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MySDK = function(){
     return {
          public_method : function() {
               alert('I am a public method');
          }
     };
};

To call the public method you would need to create an instance of the object as you would do in C# and call the function.

var mySdk = new Prabir.Shrestha.MySDK();
mySdk.public_method();

Congrats. That’s the first way to organize your Javascript using namespaces as in C#.

To make it more easy, I actually landed up creating a new Javascript library to make managing namespace easier. You can find this library at http://github.com/prabirshrestha/js-namespace

/*!
 * js-namespace Javascript Library v1.0
 *
 * http://www.prabir.me
 * http://github.com/prabirshrestha/js-namespace
 *
 */
NS = {
	register: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i)
			root = root[nsParts[i]] = root[nsParts[i]] || {};
		return root;
	},
	exists: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i){
			if(!root[nsParts[i]])
				return false;
			root = root[nsParts[i]];
		}
		return true;
	}
};
// alias
NS.r = NS.register;
NS.e = NS.exists;

To create a namespace you would call the register method.

NS.register('Prabir.Shrestha');

and to check if the namespace exists call the exists function. Instead of using NS.register and NS.exists you could also use the shorthand NS.r and NS.e respectively.

The uncompressed file is 900 bytes and the minimized gziped file is around 368 bytes.

Next tutorial is about Object Oriented Programming in Javascript. So stay tuned.

js-namespace-samples.zip (1.92 kb) [Downloads: 54]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

Javascript | snippets

Using jqGrid with ASP.NET Web Forms - Part II

December 06
by prabir 6. December 2009 19:43

This article is continuation of my previous article.

To start of with, we first need to create an asmx web service in JSON format. If you are not sure of how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery.

Lets create a web service method called GetListOfPersons. Remember to decorate it with ScriptMethod Attribute as our means of data communication will be in JSON format. In the following example JsonHelper.GetPersons() is responsible for retrieving the list of persons. You can have a appropriate data access logic out there.

[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
    List<Person> persons = JsonHelper.GetPersons();
    return Newtonsoft.Json.JsonConvert.SerializeObject(
        new PagedList(persons, persons.Count, 1, persons.Count));
}

Then we create a new instance of PagedList object that we defined in the previous post. Here’s one of the constructor that we will be using in case you have forgotten.

public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize);

For simplicity we will not be including features such as paging and sorting for now. (I will include it in later posts.) So, here the rows will be the list of persons retrieved, totalRecords will be the number of persons in the list hence persons.Count, pageIndex will just be simple as 1 as all data will be displayed on the same page number 1. pageSize will be the totalRecords as we don’t want to having paging enabled for now.

Now that the instance of PageList has been created. We need to serialize the object into JSON format which can be recognized easily by jqGrid. To achieve this we make use of Newtonsoft.JSON library by calling the SerializeObject method as shown above.

Now that we are done with the web service, we need to start coding the user interface in HTML and JavaScript.

Create a HTML table along with an ID. This table will be rendered as jqGrid when previewed in the browser.

 

<table id="table" cellpadding="0" cellspacing="0">
</table>

 

Include appropriate css style sheets and javascript files required for jqGrid to function. You will need the JQuery UI,  and multiselect also. Multiselect JQuery plugin can be obtained from http://quasipartikel.at/multiselect.

 

<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-1.3.2.min.js") %>"></script>
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/redmond/jquery-ui-1.7.2.custom.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.jqgrid.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.multiselect.css") %>" />
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/ui.multiselect.js") %>"></script>

 

Let me write the code first and then explain later on. So it would be easier for you guys to copy paste and learn.

 

<script type="text/javascript">
    $(function () {
        $("#table").jqGrid({
            datatype: function (pdata) { getData(pdata); },
            height: 250,
            colNames: ['ID', 'First Name', 'Last Name'],
            colModel: [
           		{ name: 'ID', width: 60, sortable: false },
           		{ name: 'FirstName', width: 200, sortable: false },
           		{ name: 'LastName', width: 200, sortable: false }
           	],
            imgpath: '<%= ResolveClientUrl("~/styles/redmon/images") %>',
            caption: "Sample JSON data retrieved from ASMX web services"
        });
    });
    function getData(pData) {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
            data: '{}',
            dataType: "json",
            success: function (data, textStatus) {
                if (textStatus == "success")
                    ReceivedClientData(JSON.parse(getMain(data)).rows);
            },
            error: function (data, textStatus) {
                alert('An error has occured retrieving data!');
            }
        });
    }
    function ReceivedClientData(data) {
        var thegrid = $("#table");
        thegrid.clearGridData();
        for (var i = 0; i < data.length; i++)
            thegrid.addRowData(i + 1, data[i]);
    }
    function getMain(dObj) {
        if (dObj.hasOwnProperty('d'))
            return dObj.d;
        else
            return dObj;
    }
</script>

 

jQuery ready function initializes the jqGrid. The data type we have chosen is a custom function with a parameter called pdata. pdata is a short of ParameterData. You can name it what ever you feel comfortable with. It then calls the function called getData. ColName is an array of string containing the column header. ColModal contains more information on how to render data.

Note: The name in ColModal is not the same as ColName but rather its same as that of the list of objects, which was passed as enumerable rows when creating PageList.

Function getData is responsible for doing an AJAX request to the webservice. If success it calls another function called ReceivedClientData. RetrieveClientData function is responsible for appending the data to the grid.

As the data is Ajax request and our response is in string, we need to parse the JSON string to JSON object using json2.js. (We will not be using eval due to security reasons though it is possible.)

GetMain function is used to trip of the “d” property, which is generated by web services if using new versions of ASP.NET for security reasons.

jqGridAspNetWebForms.zip (617.09 kb) [Downloads: 766]

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 744]
jquery-ui-1.7.2.custom.zip (745.92 kb) [Downloads: 352]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , , ,

ASP.NET | JQuery

Javascript debugging in IE8 with console

August 21
by prabir 21. August 2009 20:42

Internet Explorer 8 has taken the javascript development to the next level by providing a rich developer integration with the browser. In this post I will explain one of the core feature that I use often when debugging my web applications containing javascript.

Traditionally one of the best way to debug was using the alert function. But this is quite annoying as we have to press ok all the time. IE8 creators understood this and have created a set of functions to easily allow us to debug.

Instead of using alert, you can use console.clear(), console.log(), console.info(),console.error(),console.warn() to provide better information when debugging.

console.clear();
console.log("hello world from js to ie8 console");
console.info("sample info");
console.error("sample error");
console.warn("sample warning");
var x = "hello";
var y = 10;
var z=1.1;
console.log("string:%s:int:%i,real:%f",x,y,z);
image

The parameters for the console functions have the same format as printf function in c. Anyways I have put some examples above to make it easier.

  • %s  string
  • %i   integer (whole numbers only)
  • %f   floating point numbers (decimal values)

I would recommend you to use proper info, error and warn rather than just log as it even allows us to filter as shown below.

image

If you get image  at the bottom of you IE on status bar, it is basically the error telling the the console is undefined. In order to solve it, open the IE developer tools (press F12) and refresh the page. This automatically registers the console and you will not get any javascript errors.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Load JQuery from Google

August 16
by prabir 16. August 2009 11:34

Due to JQuery’s huge popularity, many of the websites have been using JQuery. To decrease the bandwidth to and get faster download performance, it would be better to load from a general website such as Google. If other websites have downloaded it from Google, then the browser can serve from the local cache.

In this tutorial we will be using Google to load JQuery.

This can be achieved by adding a reference to JQuery url from Google.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Or it could be achieved by using Google AJAX Libraries API.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
	google.load('jquery','1.3.2');
</script>

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

JQuery

Get Intellisense support for JQuery in VS

July 25
by prabir 25. July 2009 17:27

JQuery intellisense has been around for quite a long time. And the great news is that it is officially supported by Microsoft. Its a lightweight JavaScript framework having huger users.

Installing Intellisense support:

  1. Make sure you are running the Service Pack 1 of Visual Studio installed. You can download it from here.
  2. Then download the JScript editor support for “-vsdoc.js” patch (KB958502) at the end of this post or from MSDN.
  3. Then go to the official JQuery download page at http://docs.jquery.com/Downloading_jQuery#Download_jQuery.

imageSelect the Visual Studio documentation when downloading.

Then reference the JavaScript file you just downloaded

<script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>

 

Now you must be getting the intellisense support in your visual studio. Pages that inherits from master page will get the intellisense support, But the user controls will not be getting the intellisense support. To do that you can use the following hack.

<% if (false){ %>
        <script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>
<% } %>

The expression will always evaluate to false. That means *-vsdoc2.js file will never be added to the webpage. But the visual studio will evaluate it and provide the intellisense support.

image

The way I use JQuery:

Since the *-vsdoc2.js file is quite huge I prefer to use .min.js version of JQuery. I reference it by using the following way.

<script type="text/javascript" src='<%= ResolveClientUrl("~/js/jquery-1.3.2.min.js") %>'></script>
<% if (false){ %>
     <script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>
<% } %>

Notice the ResolveClientUrl. Its helpful when your page inherits from the master page and the page lies in different folder.

Another way is rather just reference .min.js file and add the following line at the top of the file.

/// <reference path="jquery-1.3.2-vsdoc.js" />

This allows the Visual Studio to automatically recognize the file and provide appropriate intellisense support.

VS90SP1-KB958502-x86.exe (JSEditor Patch) (2.13 mb) [Downloads: 741]
jquery-1.3.2-all.zip (95.67 kb) [Downloads: 662]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

JQuery