ASP.NET MVC

I’ve been interested in ASP.NET MVC since its announcement. I downloaded the beta and worked on retrofitting this site around MVC, but other projects took precedence over my side projects. Beginning JavaScript, 4th Edition is in full swing, but I wanted to get this particular project done. So I took an evening and finished it.

Behold! WDOnline.com powered by ASP.NET MVC!

I know it’s not much to look at; there’s nothing sexy in the front end (except for the complete lack of ViewState!). But URLs did change (again). This time, though, I don’t foresee any changes for a very long time. I think I have all the legacy URL routes covered; so using the old URLs should 301 redirect you to the correct blog post, download description/file, ect. Feel free to contact me if I missed something.

6/18/2009 9:47:00 AM | Tags: .NET, Blog

JavaScript Without Libraries

I’ve noticed an increasing amount of JavaScript tutorials (without the use of libraries) over the past few months ranging from simple, fundamental concepts to DOM Scripting and Ajax requests. This a good thing; I think too many people place far too much importance in JavaScript libraries. I don’t deny that such libraries are helpful, and there are many instances where it’s much easier and efficient to use an already written component than to write your own (jQuery UI’s DatePicker and *cough*XWebMenu*cough* comes to mind).

But at the end of the day, these libraries are still JavaScript, and anyone using them needs to have an understanding of the language. Case in point is a comment I ran across at one of the recent “plain-jane” JavaScript tutorials at NetTuts:

“I have just started working for another web development company, and the owner wants all of the code to be 100% ours - no third party, no matter what the license. So a weekend or two ago I am pulling my hair out trying to figure out AJAX request with my own JavaScript code. Yes, I could do it in JQuery, and easy, but company policy prohibited it. So now I am going to have to do all the the sweet JavaScript things JQuery and other JavaScript libraries do, but from scratch on my own - meaning building my own JavaScript framework/library. Thanks again!! This is perfect timing.”

Sadly, the replies to this comment encourage the user to jump ship for another company; one that allows the use of a third party library like jQuery. Libraries are nice to have, and they’re useful in many occasions. But don’t sell yourself short by being dependent on them.

5/11/2009 9:59:07 AM | Tags: JavaScript

Service Test

I’ve had some issues with the WCF service that I use to update my blog since the server switch. It looks like it’s up and running again, but I want to make sure with this test post.

I want to take the time to thank DailyRazor.com, my host provider, for the time they put into moving my account to the new box, and for putting up with my question after question. My hat’s off to you guys.

5/6/2009 8:48:41 AM | Tags: Blog, Web, WCF

Server Migration Complete!

My site is now running off a Server 2008 box with SQL Server 2008! Whether you can see this depends on DNS propagation. I’m slowly building a MVC-based version of the site (no more viewstate!! yay!!!!), and I’ve been waiting for the switch to begin. Now if only I can find the spare time to do it...

5/4/2009 12:45:54 PM | Tags: Web, Blog

Windows and SQL Server 2008 Here I Come!

It’s finally happening; this website is getting transferred to a Server 2008 box! Finally my production environment mirrors my development environment. I don’t foresee any outages, but the transfer is the cause if any do occur. See you on the other side!

5/1/2009 12:48:33 PM | Tags: Blog, Web

Performance Follow-up: Retrieving Data with Nullable Fields

I received an email from a Mr. Grimes asking if there are any performance issues with using generics to retrieve nullable data from a database. To answer his question: yes, and the hit on performance depends on two factors:

  • How many nullable fields are processed
  • How many records are processed

After perusing the source code for SqlDataReader, the "Get" methods (like GetInt32(), GetGuid(), ect) return the specified field’s value without a conversion operation; this is confirmed by MSDN (check the remarks section; OleDbDataReader and OdbcDataReader say the same thing). The code I posted last week uses the Item property to retrieve the field’s value (in C# the Item property is transparent, and you use it as an indexer. Example: dataReader[i]). This value is boxed and must be unboxed if you want to do anything other than display the string representation of the value. Boxing and unboxing are expensive operations, and performance begins to degrade the more they’re performed.

I tested my generic methods on a table with 119,000 records and three nullable fields. The test selects all records and reads the value of each field. My generic methods averaged 111ms slower than the appropriate "Get" methods to process all 119,000 records. It’s up to you to decide if that’s acceptable for your project; so use at your own discretion.

4/6/2009 2:12:07 PM | Tags: .NET, C#

Generic Power: Retrieving Data with Nullable Fields

I’m working on a quick project here at work where I build a report from a third party’s SQL database. Every field in this database, except for the primary keys, can be null. This makes my job slightly annoying because I must check every field in a result set to determine if it contains null or an actual value. I could use an ORM tool, but this is a small project with a HUGE database. I only need a few tables, and I can write my DAL quickly (there’s also no relations defined in the database). My code to read the result set used to look like the following:

DateTime? date = null;

if (!_Reader.IsDBNull(dateOrdinal))
{
    date = _Reader.GetDateTime(dateOrdinal);
}

There's technically nothing wrong with this code. It works, but it consists of at least five lines of code. I could shorten this by using a ternary operator:

DateTime? date = (!_Reader.IsDBNull(dateOrdinal)) ? _Reader.GetDateTime(dateOrdinal) : null;

This approach is ugly. I have no qualms using ternary operators in JavaScript. In JavaScript, anything that cuts down file size without limiting performance is a-ok in my book, but I’m dealing with the compiled language of C#. Readability is more important than file size. As I’ve recounted many times, I’m lazy; I want to write less code, and in this case without sacrificing readability and performance. Then I thought of the solution: generics.

MSDN defines generics as “the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.” I use generics all the time, but I rarely use them outside the realm of collections. I saw generics as the perfect solution to this particular problem. So I wrote two methods to check if the field has a value and return either the value as a specified data type or the type’s default value.

private T GetValue<T>(int ordinal)
{
    if (!_Reader.IsDBNull(ordinal))
    {
        return (T)_Reader[ordinal];
    }
    else
    {
        return default(T);
    }
}

private T GetValue<T>(string columnName)
{
    try
    {
        int ordinal = _Reader.GetOrdinal(columnName);
        return GetValue<T>(ordinal);
    }
    catch (IndexOutOfRangeException ex)
    {
        throw new Exception("Column name does not exist");
    }
}

These methods make retrieving data easy and readable:

DateTime? date = GetValue<DateTime?>(dateOrdinal);
string grantor = GetValue<string>("grantor");
decimal? amount = GetValue<decimal?>(4);

Of course, this solution’s benefits extend only to retrieving database fields that can be null; use the “Get” methods (GetDateTime(), GetString(), GetInt32(), ect) on fields that cannot be null.

Update (April 6, 2009): There are some performance issues with this approach. Check this blog post for more info.

4/1/2009 10:14:11 AM | Tags: .NET, C#

XWebMenu Version 3 Alpha

It’s definitely not the week I originally planned, but here is XWebMenu v3 Alpha. This DHTML menu comes as-is and without documentation. Most of the gory details will be in this post because I haven’t yet written an article component for my website.

Unlike previous versions, version 3 encapsulates all public reference types and objects within a namespace called xwebMenu.

Like version 2, you can create and populate menu systems using XML to define the system's structure. Here’s a sample of the schema:

<xwebMenuStrip>
    <items>
        <item text="Item Text" href="http://www.google.com">
            <menu>
                <items>
                    <item text="Item with Script" enabled="false">
                        <clickEvents>
                            <event>
                                functionToCall();
                            </event>
                        </clickEvents>
                    </item>
                </items>
            </menu>
        </item>
    </items>
</xwebMenuStrip>

The <xwebMenuStrip /> and <menu /> elements contain one <items /> element which can contain multiple <item /> elements. Items are broken into two groups: menu strip items and menu items, and they follow these rules:

  • Menu strip items must have a value specified for the text attribute, but all other attributes and elements are optional (but it won’t be very functional).
  • Menu items have no such restriction; empty menu items result in a separator.
  • All items can have one optional <clickEvents /> element that contains one or more <event /> elements. The <event /> element contains the JavaScript code that executes when the user clicks that item.
  • All items ignore the href attribute when a menu is specified within that item.

Use the create() method to create and populate a menu system. This method accepts an object called an options object. One such option is xmlFile; its value is the URL of the XML file that defines the system's structure. Version 3 uses XmlHttp to retrieve the XML file asynchronously. The following code sample illustrates the use of the xmlFile option:

var menuOptions = { xmlFile : "someXmlFile.xml" };

var menu = xwebMenu.create(menuOptions);

Menu systems get appended to the document body by default; change this behavior by using the parentElement option. Make sure the element exists to avoid errors.

var menuOptions = {
    xmlFile : "someXmlFile.xml",
    parentElement : document.getElementById("divMyMenu")
};

var menu = xwebMenu.create(menuOptions);

View the XML demo.

Similarly, a system's structure can be defined with JSON. The JSON schema is similar to the XML schema:

items : [
    {
        text : "Item Text",
        href : "http://www.google.com",
        menu : {
            items : [
                {
                    enabled : false,
                    text : "Item with Script",
                    clickEvents : [ functionToCall ]
                }
            ]
        }
    }
]

The following code demonstrates a system's creation with JSON:

View the JSON Demo.

Like version 2, this new version has two behaviors: normal and hover. Normal behavior, the default, causes XWebMenu to behave in a normal manner; the system responds to the user's mouse clicks to show and hide menus. The hover behavior causes the system to respond to the user's mouse movement. Menus are shown and hidden according to where the user's mouse pointer is located.

You can set the menu system's behavior with another option when creating the system. If using XML , use the behavior attribute in the <xwebMenuStrip /> element. Valid values for this attribute are "normal" and "hover".

You can also assign a value to the behavior option in the option object:

I apologize for the lack of documentation. There are other features available in this widget that I did not cover (icons, disabling/enabling items, and other parts of the API). I’ll write a full blown article and reference when the widget is final. Chances are good that there won’t be a beta until the end of the year, as other projects take precedence. However, let me know if you find any bugs, and I’ll do my best to keep the .zip updated. Any feedback is appreciated.

Download XWebMenu Version 3 Alpha

3/17/2009 4:10:20 PM | Tags: JavaScript, DHTML

Beginning JavaScript, 4th Edition

Almost two years passed since the third edition’s release, and I can now say that the fourth edition is underway. This new edition improves the third edition by:

  • Removing areas covering outdated technologies and browsers and concentrating on current web standards such as the W3C DOM.
  • Trimming the fat. The fourth edition aims to focus more on the JavaScript language and its use in programming the browser (as opposed to other platforms like Classic ASP).
  • Reordering chapters to be more suitable for teaching JavaScript.
  • Adding (and updating) the reference sections from the second edition.

I’m really excited about this new and improved edition. I can’t provide an official release date; my rough estimate is very late 2009 or first quarter 2010.

3/12/2009 3:42:00 PM | Tags: Beginning JavaScript, JavaScript, Books

JavaScript Physics Engine

I follow Scott Hanselman through his blog and Twitter, and he tweeted about a JavaScript physics engine called Box2DJS. This is cool on a couple of levels.

First, it’s a physics engine... in JavaScript. Yeah, that’s frakking sweet (short aside: I hate Battlestar Galactica is just a few episodes away from the series finale!!).

Second, it an excellent test bed for the performance of JavaScript engines in the various browser. The demo on the page has multiple examples. I chose to use the first example for my “testing”. I use that word loosely, as my scientific approach was to create an object every second and count the number of objects before the performance started to wane. My test subjects were IE7, IE8 RC1, Firefox 3.0.6, Firefox 3.1b2, Opera 9.63, Safari 3.2, and Chrome 1.0.154.48. I found Chrome to be the best, which really isn’t surprising because V8 is the best performing JavaScript engine in a shipping browser. I stopped counting at 25, and in fact I could nearly fill the open spaces in the example area before I noticed a slow down. Firefox 3.1b2 came in second with sixteen. Firefox 3.0.6, Safari, and Opera tied at eight. IE8 slowed at #2, and IE7 brought up the rear at #1 (no surprise there).

I can’t think of a good reason to use such an engine in a production environment unless your target platform is Chrome, as it’s useless in IE and next to useless in Firefox, Safari, and Opera. JavaScript execution performance needs an across-the-board boost before a physics engine is practical for the browser. We’re on the way of seeing such boosts thanks to engines with JIT compilers like V8 and TraceMonkey (I’m disappointed in the latter’s performance in this little test).

Still, it is cool to see a physics engine written in JavaScript; even if it is impractical.

2/18/2009 3:42:27 PM | Tags: Internet Explorer, Browsers, JavaScript, Chrome, Firefox, Opera, Safari
© 2008 Jeremy McPeak