Developing with jQuery in Microsoft Visual Studio 2008

Started by dhilipkumar, Mar 10, 2009, 11:21 AM

Previous topic - Next topic

dhilipkumar

Developing with jQuery in Microsoft Visual Studio 2008

Microsoft is fully supporting jQuery, the open-source JavaScript library, in Visual Studio 2008. Though jQuery has been popular with Web application developers for two years, Microsoft until now has not given it full support. Now, with the help of IntelliSense, writing jQuery code in Visual Studio just got a lot easier.
jQuery is an open-source JavaScript library that simplifies the coding and manipulation of HTML elements on a Web page. Without jQuery, developers can still access all the elements in the Document Object Model, but jQuery makes it much quicker and easier.


jQuery initially was created in early 2006, and has become popular with Web developers. On the other hand, for many years, Visual Studio has been extremely popular with ASP.NET developers, but was limited in its handling of JavaScript in general, with little or no support for third-party JavaScript libraries. This is probably because early versions of ASP.NET primarily focused on server-side development.

In fact, although Microsoft never explicitly discouraged client-side development with JavaScript in conjunction with ASP.NET, the company tried to control JavaScript coding by forcing developers to go through a cumbersome set of APIs to generate JavaScript code. (Interestingly, this set of APIs was a precursor to ASP.NET's support for AJAX.)

That has changed with Visual Studio 2008, released Nov. 19, 2007, as Microsoft has added significant support for JavaScript to its Visual Studio platform. Still, until recently, Visual Studio had no knowledge or understanding of third-party libraries, even though most client-side Web development is now done with the help of such third-party libraries.

However, that has changed as well. In September, Scott Guthrie, corporate vice president for Microsoft's .NET Developer Division, announced on his official blog that from now on Visual Studio will have full support for jQuery.

In this article, I'm going to take the jQuery aspects of Visual Studio for a spin and see what I find. I ran my tests on a Satellite U305 system powered by an Intel Core 2 Duo 1.8GHz, with 2GB RAM, running Windows Vista with Visual Studio 2008 and Internet Explorer 7

JavaScript support before jQuery

First, let's see how Visual Studio handles JavaScript in general, without jQuery. There are two general areas we should explore: coding (with the help of IntelliSense) and debugging.

To start, I created a new Web site in Visual Studio 2008. To keep it simple, I used the ASP.NET development server, rather than creating a new site in IIS (Internet Information Services). Next, I created a simple HTML page.

Remember, the purpose of IntelliSense is to help speed up coding by helping programmers type less and by minimizing how often they have to search the online docs for method names and parameters. When doing C# development, IntelliSense excels at such help. However, what about JavaScript?

To test this out, I created three elements on my HTML page: a div, a button and a text box. Here's the HTML code:


<div id="mydiv1">Here's the first div.</div>

<input id="mytext1" type="text" />

<input id="mybutton1" type="button" value="click me" onclick="javascript:foo()" />

Next, in the head section of my page, I created a function and started trying out the JavaScript IntelliSense. Here's the function I started typing in:

function foo() {

    document.getElementById('mydiv1').innerHTML =

        document.getElementById('mytext1').value;

}


(This code just takes what was typed into the text box and copies it into the div.) When I typed in the code, IntelliSense kicked in and made suggestions for me. As I typed "do", I saw "document" appear in a dropdown as in the following figure. I typed one more character, "c", and then typed a period and the word "document" was filled in for me.

The period I typed was taken to mean I wanted a member name, and so IntelliSense offered me the members of the document object. I typed "get" and then an open parentheses, and IntelliSense filled in "getElementById" for me. After I typed the string, then the closing parentheses followed by a period, IntelliSense appeared again and offered up the available members, including the innerHTML member that I needed.

But if you play with this, look more closely, because something isn't quite right. The element I obtained was a div element, and the list I saw was the same fixed list that appeared every time I typed getElementById. Included in the list is value, which isn't a member of a div element.

Clearly, IntelliSense handles JavaScript differently from C#. In fact, the difference is that with C#, IntelliSense actually performs a background compile, and then (presumably) digs through the necessary assemblies to determine the exact members the object a developer's creating contains.

With JavaScript, there's apparently no background compilation going on here. (Yes, I know JavaScript isn't normally compiled per se, but there are just-in-time compilers available that could be used here.) Instead, IntelliSense is parsing the JavaScript code itself and, in this particular case, has a prefilled list that pops up for the members of HTML elements.

Still, it works, and it works well. And I'm probably not being totally fair, because IntelliSense does do a good job of parsing the JavaScript code. For example, if you type this in:

var x = {a:1, b:2};

IntelliSense will spread the code out evenly and from then on will know that a and b are parameters of x, and show them in x's parameter list. It also will notify you of syntax errors in JavaScript code. Finally, JavaScript is radically different from C# in that there are no classes for the objects; you can dynamically add new members to objects, and the only way to know the members is to not just compile the code but to actually run it. That could make for a messy coding experience. In general, Microsoft had no choice but to handle JavaScript differently with IntelliSense.

Now let's briefly try out the debugging.

dhilipkumar

Debugging with Visual Studio

hink about how debugging Web pages works: When you're doing Web development, you're likely coding for both server-side (using, for example, ASP.NET and C#) and client-side (using JavaScript). The C# code runs on the server, and the JavaScript code runs inside the user's browser. When you're debugging, you're probably running both the server and client browser on a single machine.

For debugging server-side code, Visual Studio hooks into the IIS server, letting programmers set breakpoints and step through the server-side code. Such breakpoints typically occur as a result of the user interacting with the Web page; during this time, the browser will be waiting for the server, unaware that the server is being debugged. (In that case, Visual Studio must either be on the same machine as IIS, or set up to remotely debug.)

But to debug client-side, developers need to set breakpoints that cause the browser itself to pause and wait for the debugger. Given that, the browser must be aware of the debugger and be on the same computer as the debugger.

That means if a developer has a single instance of Visual Studio running, then it needs to be aware that it's potentially debugging two separate processes: the server-side (through IIS) and the client-side (through the browser).

There are different ways to debug JavaScript—for one, simply putting the debugger; statement right in the code. But for that to work, the browser needs to know to let Visual Studio kick in. Internet Explorer does, but other browsers don't automatically know about Visual Studio. Even then, IE will ask which instance of a debugger to fire up.

Instead, a good way is to set a breakpoint in the code (by right-clicking and clicking Insert Breakpoint in the context menu). Then set the HTML page you want to test out as the startup page (by right-clicking the page name in Solution Explorer and clicking Set As Start Page). Make sure the project is set up to use IE as the default browser (by right-clicking on the HTML file in Solution Explorer, and clicking Browse With. In the window that opens, click Internet Explorer, and then Set As Default. Close the window by clicking the upper-right button; don't click Browse, as you don't want to open the page from here, because it won't be set for debugging.) Finally, press F5 to start up the debugger in Visual Studio.

At this point, things worked really well. I set a breakpoint on the first line inside my function. When I typed something into the Web page and clicked the button, the page waited as Visual Studio activated with the code waiting at my breakpoint's line.

From there I could do all the usual debugging goodies, like float the mouse over one of the identifiers (such as document), which resulted in a popup showing me all the members. This time, the debugger is hooked into the JavaScript engine and can read the values; I can even change them as I should be able to do with any good debugger.

All is cool so far. Now let's try out the jQuery support.

dhilipkumar

Developing with jQuery in Microsoft Visual Studio 2008 - jQuery Support in Visual Studio

First, I needed to get jQuery. Since my version of Visual Studio doesn't yet understand jQuery, I also needed to get the jQuery support files. Fortunately, they're both available from one place, here.

There are two .js files; one (jQuery-1.2.6.js) is the actual jQuery library and the other (jQuery-1.2.6-vsdoc.js) is a support file for IntelliSense to use. To keep my day simple, I put both files in the same directory as my HTML file.

According to a blog that I found here, I needed to add these lines to my source code:

<script src="jQuery-1.2.6.js" type="text/javascript"></script>

<% if (false) { %>     <script src="jQuery-1.2.6-vsdoc.js"

type="text/javascript"></script>

<% } %>

The odd-looking second through fourth lines are surrounded by some C# code that will prevent the second JavaScript file from being sent down to the browser, as it's only needed within Visual Studio during coding.

But now I had a problem. I had created just an HTML page, not an ASP.NET ASPX page. This page didn't do C#. That's fine; I just simplified these lines like so:

<script src="jQuery-1.2.6-vsdoc.js" type="text/javascript"></script>

And then if I were to release something, I'd replace this line with the following:

<script src="jQuery-1.2.6.js" type="text/javascript"></script>

(I'll explain in a moment why this works.)

Next I tried out IntelliSense in the coding. The previous code example can be rewritten to use jQuery like so:

function foo() {

    $('#mydiv1').html($('#mytext1').val());

}


Although I'm talking about IntelliSense here, there probably is curiosity about this code. Like many JavaScript libraries, jQuery recognizes that the document.getElementById() function is probably the single most used function in JavaScript programming, and as such offers a simpler function, one whose name is just the dollar sign, as in $( ).

The parameter to the $ function isn't just the name of an element. Instead, it's a Cascading Style Sheets selector, and as such can be a style class name, an element type or an element name. In CSS, element names are prepended with a pound sign. Since I'm looking for the element named mydiv1, I pass #mydiv1 to the function.

The function doesn't return an HTML object but rather a jQuery object that serves as a proxy to my HTML element. This object includes a method called html() that either returns the inner HTML of the element (when you pass no parameters) or sets the contents (when you pass a string as a parameter). I wanted to set the contents, so I passed a string consisting of the value of the text element. Obtaining the text element's value works similarly, except I called val() instead of html(), and since I wanted to read the value, I passed no parameters.

Easy enough. But when I typed this into Visual Studio, IntelliSense went to work and then understood jQuery. When I type $, a popup appears listing commands, and that one is first. But the whole command is a single character, so I just continued. I typed an open parentheses, and an expanded IntelliSense message displayed.

This message told me the name of the function and the parameters, and additionally described each parameter for me; the message changed as I typed each next parameter. That's just like coding in C#.

dhilipkumar

IntelliSense and jQuery: Making It Work



As it turns out, making this work in Visual Studio really didn't require modifying Visual Studio at all. In my case, I started with a Visual Studio installation that knew nothing about jQuery. To get Visual Studio to understand jQuery, all I did was add a single line of code to my source file:

<script src="jQuery-1.2.6-vsdoc.js" type="text/javascript"></script>

This source file is actually identical to the standard jQuery JavaScript file (the first of the two I was talking about earlier), except all the functions and objects in it have been annotated with special comments. These comments tell IntelliSense about the objects as it parses the file. This feature has been with Visual Studio 2008 since it was released in November 2007. What's new here is that somebody took the time to annotate the jQuery file. That's it; no enhancements to Visual Studio were necessary.

Programmers can run their code with this annotated version of jQuery if they like; they don't have to use the unannotated version. However, most people prefer to release tighter code. To do so, they can replace the line with one that loads the regular jQuery JavaScript file. If they're creating an ASPX page, they can use the fancy version I showed earlier with the C# code present.

Conclusion

The support for jQuery isn't technically an enhancement to Visual Studio so much as a special version of jQuery that Visual Studio's IntelliSense recognizes. However, it does the job, and it does it well. Somebody spent a lot of time putting it together, and this should really help people who write jQuery code in Visual Studio.

But this might also get you thinking, as it did me. Certainly you can annotate all your JavaScript files so that IntelliSense is fully aware of them. Here's one page I found online that shows you how to do just that, from Scott Guthrie's ubiquitous blog. (Guthrie also explains how IntelliSense handles JavaScript differently from other languages, going into more detail than I did earlier.)

And if you're ambitious, you can take any other JavaScript library, open source or otherwise, and go though and annotate it. In fact, some people already have. If you have a favorite library, search Google and you might find the annotated files out there.