Silverlight Grid for Easy Data Visualization

By at October 28, 2010 15:09
Filed Under: Entity Framework, FlexGrid

My recorded webinar, "Silverlight Grid for Easy Data Visualization" is up on Vimeo. You can see it here, http://www.vimeo.com/16241316. And as promised I've uploaded the Slides and Code. You can get them in the attachments.

Thanks for listening.... Happy Programming,

James

 

jQuery and MVC–Part 1

By at October 27, 2010 07:27
Filed Under: JavaScript, MVC, jQuery

This is the first in a four-part series on using the JavaScript library jQuery with the ASP.NET MVC framework.

Introduction

In the beginning there was static HTML and it was good. The World Wide Web was in its infancy and anyone with a computer, a text editor, an FTP program and a connection to the internet – more than likely dial-up – could create and publish web pages. But quickly these pages became boring, as they were after all, static, and web publishers began clamoring for something to make their pages zing.

Then along came a scripting language called JavaScript, and changed the way web pages and sites looked and acted, creating new ways to provide interactivity between the user and the web server. It was first released by Netscape as LiveScript in September 1995, and was renamed to JavaScript in December 1995 when it was included in the release of the Netscape browser.

As a programming language it is dynamic, weakly typed, prototype-based and supports closures and higher order functions. Not to be confused with the Java language it does have some similarities in its syntax with curly braces “{}” and semi-colons “;” and copies many names and naming conventions. However like Java, it does have a fairly steep learning curve. Because of this, JavaScript “scripts” started to become more and more popular on web development sites, allowing for easy copy and pasting. While this made JavaScript to quickly become one of the most popular languages for web development, in some circles it gained the reputation of being a “kiddie” language.

In 1999, Microsoft released the IXMLHTTPRequest interface as part of their Outlook Web Access for Microsoft Exchange Server. The Mozilla Foundation developed a wrapper to use this interface through a JavaScript object which was called XMLHttpRequest. In April, 2006 the World Wide Web Consortium published a working draft to “document a minimum set of interoperable features based on existing implementations, allowing Web developers to use these features without platform specific code”. The last revision to the specification was in November, 2009. (http://en.wikipedia.org/wiki/Xmlhttp)

With the advent of Ajax (Asynchronous JavaScript and XML) in 2005, JavaScript had begun to be looked on more favorably by the programming community, and as a more full-featured language.

The Pros and Cons

As with all languages there are many pros and cons, likes and dislikes, friends and foes. JavaScript is no different and some of the most common are:

Pros Cons
Dynamic
Easy to develop with and debug with the appropriate tools
Similar, comfortable syntax to Java, C#, C
Browsers seem to have their own JavaScript engine
Can be difficult to have the same behaviors act the same across browsers

The Development Experience

You get into the learning curve, and spend all your waking hours writing the most unique and elegant piece of JavaScript code, and test it in your favorite browser. It works just how you planned, until you open your site in a different browser. Ugh, events are different, you can’t seem to get to the correct DOM element, nothing just seems to work between browsers, let alone platforms. You pour over your trusty JavaScript manuals, scour forums, Google on Bing for obscure error messages, and generally get frustrated. You just feel like giving up, so what do you do?

JavaScript Libraries to the rescue

JavaScript libraries are pre-written snippets of code and controls which usually form a much larger JavaScript Framework. These libraries allow for the easier development of JavaScript intensive applications, as the majority of them handle the problems of cross-browser, cross-platform issues. Numerous libraries are available including, but not limited to, Dojo, Echo, Ext, Google Web Toolkit, jQuery, MochiKit, MooTools, Prototype, qooxdoo, Rico, script.aculo.us, Spry, and Yahoo! UI Library.

While each library has it’s good and bad points, it’s pros and cons, the rest of this series will focus the jQuery library, found at www.jquery.com

jQuery

In January 2006 John Resig, released the first version of jQuery at BarCamp NYC, as a free, open source, dual-licensed (MIT and GNU) library. According to http://trends.builtwith.com, jQuery is the most popular JavaScript library; with 38.62% of web sites tested using some form of the code. Some of the main features of jQuery are:

  1. Its syntax makes it easier to navigate the DOM (Document Object Model)
  2. Easily handles and binds events to any DOM element
  3. Creates both simple and complex animations
  4. Has a complete suite of Ajax grooviness baked in
  5. Easy extensibility with plug-ins
  6. Unobtrusive
  7. Microsoft bundles jQuery with ASP.NET Web Applications and ASP.NET MVC

That’s right. Microsoft has jumped on the jQuery bandwagon, and gives it full support, even committing code back into source control. In fact, you can call Microsoft Support and get help with jQuery.

Syntax

The learning curve for getting up to speed with jQuery is not terribly steep. In only a short time you can easily grok the basics, and in a few hours, do some really nifty things with jQuery.

The jQuery syntax is easy to learn with all statements starting off with a “$”. One of the cool things about jQuery is since other libraries may use the $ as well, to prevent collisions, you can use the literal “jQuery” instead. For example:

$(“some element”); or jQuery(“some element”);

DOM elements are selected by either their ID, or a className that has been assigned to them.

$(“#myElement”); returns the only ID in the DOM, “myElement”
$(“div.myElement”); returns all div elements having a class assigned of “myElement”

jQuery makes it very easy to traverse through the children of each element as well.

$(“div.main ul li”); returns all li tags within the div tag with a class of “main”

Whereas

$(“div.main”).find(“li”); returns the same collection as above.

You can select specific elements in the collection with special selectors such as :odd, :even, :first, :last, :not(), etc.

$(“div.main”).find(“li:odd”);
     returns all odd (zero-based) li tags inside the div with a class of “main”

$(“div.main”).find(“li:even”);
     returns all even (zero-based) li tags inside the div with a class of “main”

$(“div.main”).find(“li:first”);
     returns the first li tag

$(“div.main”).find(“li:last”);
     returns the last li tag

$(“div.main”).find(“li:not(li.someDifferentClass)”);
     returns all li tags that don’t have the “someDifferentClass” assigned to them

Unobtrusive JavaScript

How many times have we added our own “BLOCKED SCRIPTonclick(doSomething();)” code directly in our elements. It makes it difficult to maintain and debug, and rails against the philosophy of separation of concerns. jQuery helps us to get away from this by using selectors and assigning events to the elements we have found.

Additionally, unless you have written some really terrible jQuery/JavaScript, if there is an error in your jQuery syntax, jQuery will fail gracefully. This means there won’t be any pesky little JavaScript error icons in your browser or JavaScript console.

Events

It is very easy to assign an event (click, focus, blur, etc.) to any DOM element with jQuery, and there are two main methods to do this.

The first is to wait until the DOM is fully loaded, which is checked by the jQuery event, .ready(). This event is fired when the DOM is complete and has been loaded into the memory of the browser.

$(document).ready(function() {
    $(“myElement”).click(function() { doSomething(); });
});

The second method is to attach a “live” event to the element with

$(“myElement”).live(“click”, function(){ doSomething(); });

The differences between these two methods are slight, but important. In the first example, we are assuming there will be an element called “myElement” in the DOM. This could be an element that is hard coded in the HTML, a button, text field, image, div or p tag. However, with jQuery’s dynamic DOM manipulation, it is possible that you would reference an element that has not been created yet.

The .live() event attaches the function you want to call to all matched elements in the selector, regardless of if they have or have not been created yet.

In the examples above, the “doSomething()” is referencing a separate JavaScript function. Another method is to replace the “doSomething()” with more jQuery functions.

$("ul.demo li:odd").each(function (index) {
     var targ = this;
     setTimeout(function () {
       $(targ).addClass("liSelected");
     }, index * 500);
   });
}

jQuery functions can have standard JavaScript functions in them as well. Can you look at the code above and figure out what this event will do?

First, all of the odd li elements in the ul element with a className of “demo” are selected. Second, the jQuery .each() function loops through the collection, setting a brief timer. Third when the timer is hit, the li element has the class of “liSelected” assigned to it.

jQuery’s silent error handling will not show any indication of something going wrong, just since the element hasn’t been created it won’t be able to have the click event attached to it.

Chaining

Once an element has been found, a reference to the element is kept in memory. So, instead of the following:

$(“div.myElement”).hide();
$(“div.myElement”).html(“howdy”);
$(“div.myElement”).addClass(“red”);
$(“div.myElement”).fadeIn(“slow”);

You can chain the actions like so:

$(“div.myElement”).hide().html(“howdy”).addClass(“red”).fadeIn(“slow”);

This makes for much cleaner or succinct code writing and will help with memory as well.

Stuff you can do

As this series progresses, we will dive deeper into all the jQuery goodness. Here is a sampling:

  • Selectors – find elements in the DOM
  • Attributes – get/set attributes of found elements
  • Traversing – moving up/down elements in the DOM
  • Manipulation – get/set contents of found elements
  • CSS – get/set style attributes of found elements
  • Events – fire on click, hover, load, etc. of found elements
  • Effects – fadeIn/Out, slideIn/Out, hide/show
  • Ajax – full and complete Ajax capabilities
  • Utilities – inArray, isArray, makeArray, etc.

Benefits

In closing the benefits of using jQuery are incredibly apparent. It is a solid, standardized JavaScript library, which allows for fast development, and gracefully fails with no glaring errors or frozen pages. Because of its popularity, there are lots and lots of examples, and it is very easy to get ramped up and understand its simplicity.

Check back next week when we will dive deeper into jQuery, and how you can easily spiff up your sites. Take a look at the attached demos, and send me some comments and questions.

James

So Cal Code Camp–USC

By James at October 25, 2010 21:12
Filed Under:

I love code camps, especially the So Cal Code Camps. Yup, that’s plural as Southern California is lucky enough to have three per year. Last weekend, October 23-24 was So Cal Code Camp – USC and I was lucky enough to get the chance to present again. I gave the same presentation as what I did at Silicon Valley Code Camp three weeks ago – ASP.NET MVC and Entity Framework 4 – but this time it went a whole lot smoother. The room was ready, the projector was working correctly, and the audience was right on. Just about 50 attendees with standing room only and five people sitting on the floor. I brought along six of our C1 beanies which I tossed out during my talk to people who made good comments, pointed out different ways to do things, and laughed at my jokes.

I also manned the ComponentOne booth during the day and had a great time talking to the wide variety of Code Campers about our products, passing out literature, key chain carabineers, and our magic “wear these and you’ll never write bad code again” sunglasses.

Thanks to Art Villa and everyone who helped to put on a successful event. It’s a lot of work and they all deserve a big round of applause. And a special thanks to my wife, Carmina, (my own personal booth babe) who took over for me when I went to present.

7215.sccc1_418F1F563678.sccc2_3DC154B9

5165.sccc4_2521919C8372.sccc3_730A671E

My slides are at http://www.slideshare.net/latringo/mvc-and-entity-framework-4, and if you happened to be in attendance, please take a few minutes to tell me what you thought of my presentation at http://speakerrate.com/latringo

James

About the author

James James is a five time and current Microsoft MVP in Client App Development, a Telerik Insider, a past Director on the INETA North America Board, a husband and dad, and has been developing software since the early days of Laser Discs and HyperCard stacks. As the Founder and President of the Inland Empire .NET User's Group, he has fondly watched it grow from a twice-a-month, early Saturday morning group of five in 2003, to a robust and rambunctious gathering of all types and sizes of .NET developers.

James loves to dig deep into the latest cutting edge technologies - sometimes with spectacular disasters - and spread the word about the latest and greatest bits, getting people excited about developing web sites and applications on the .NET platform, and using the best tools for the job. He tries to blog as often as he can, but usually gets distracted by EF, LINQ, MVC, ASP, SQL, XML, and most other types of acronyms. To keep calm James plays a mean Djembe and tries to practice his violin. You can follow him on twitter at @latringo.

And as usual, the comments, suggestions, writings and rants are my own, and really shouldn't reflect the opinions of my employer. That is, unless it really does.

James Twitter Feed

Recent Comments

Comment RSS

Month List