Saturday, December 12, 2009 #

Roll your own AJAX Extender for JQuery Calendar

Just for something different, I’ve created my first impromptu screencast demonstrating how easy it is to create your own AJAX Extender for JQuery controls, as opposed to using the AjaxToolkit.

I did realise that the sound quality wasn’t the greatest at first, and I wasn’t using any special equipment apart from my MacBook’s built-in mic and Expression Encoder, hopefully I’ll get the hang of it in the future.

Roll Your Own JQuery AJAX Extender from Brendan Kowitz on Vimeo.

Links

posted @ Saturday, December 12, 2009 8:21 PM | Feedback (0)

Thursday, September 03, 2009 #

Your code via NDepend

Recently I’d had the opportunity to begin exploring code through the eyes of NDepend. I’ve pointed NDepend at my code, open source projects, code at work, just about anything I’ve had the time to load into Visual Studio. Has it been a useful experience? I’d have to say at this point, yes. I’d like to now present a roundup of the features that I’ve enjoyed the most.

What is NDepend

NDepend is a tool that simplifies managing a complex .NET code base. Architects and developers can analyze code structure, specify design rules, plan massive refactoring, do effective code reviews and master evolution by comparing different versions of the code. (ndepend.com)

Top Features

NDepend, in my opinion is fairly complex, and there seems to be a fair depth to the number of features that you’ll discover as you continue using it, however, here are the features I found initially to be the most useful.

  • The predefined CQL Queries
  • Query results
  • Metrics window

Predefined CQL

I think the predefined CQL queries window really is the quick way to get up and running in learning about your code. There a dozens of queries ranging from design issues, naming issues, boxing, complex code to just name a few. Not only that, it’s really easy to actually get in there and customise the query to suit what you’re looking for.

The first feature I was able to use here was to generate and export a report of potentially unused methods. Most codebases seem to somehow accumulate orphan code that can be removed, however its probably hard to find easily without such tools.

The query I have running in the window below was helping diagnose the portion of the codebase still depending on Hashtables and ArrayLists. The very cool thing I noticed here was that NDepend won’t just tell you the underlying classes that contain these lists, it will shade in on the metric view ALL code effected by it. Even if the lists are wrapped and used elsewhere much higher up.

image

Related to the CQL, the Query Results window is one that I really wish was a dockable panel inside Visual Studio. By clicking on any member displayed here NDepend will just to the corresponding line of code. Very simple and easy to explore.

image

Metrics

The Metrics view was useful to provide an at a glance distribution of the current code query. It can also show the members that have changed when comparing multiple versions of an assembly. One of the projects I tried was a change comparison between DNN4.9.2 to 5 However, although the core libraries had significant change it did not drastically effect many of the public interfaces.

image

Visual Studio Integration

The plug-in for visual studio provides a large array of quick queries and lookups, I like to think of it as ‘Find all References’ on steroids because it gives so many more options and so much 'deeper' information. This starts to relate to things such as Efferent and Afferent coupling, knowing about these factors may definitely assist you when it comes to making refactoring decisions.

image

Code Comparisons

Code comparison of a slightly core modified version of DotNetNuke 4.9.1 to 5

# IL instructions    229 806 to 268 470      (+38 664   +16.8%)
# Assemblies    11
# Namespaces    95 to 110      (+15   +15.8%)
# Types    725 to 830      (+105   +14.5%)
# Methods    9 165 to 10 813      (+1 648   +18%)
# Fields    2 954 to 3 362      (+408   +13.8%)

Tier code used by the application:
# Tier Assemblies used    12
# Namespaces used    68 to 67      (-1   -1.5%)
# Types used    565 to 573      (+8   +1.4%)
# Methods used    1 671 to 1 750      (+79   +4.7%)
# Fields used    64

Viewing NDepend’s class browser in Code Comparison mode guides you through what’s changed. Everything from changes in the number of lines of IL, public methods, fields, namespaces, assemblies to test coverage. It may be nice to have these stats, however well structured release notes will do me much better than telling my a library has grown by 33%. I think the more important factor here is capturing changes to public interfaces and also test coverage %.

Getting to know your code…or someone elses

When you first come across a new codebase and start to familiarise yourself there are always a number of things that you may want to look at including

  • What are the most important namespaces, classes and methods; NDepend provides this this by a simple lookup then displays it visually. You can also make use of the ‘MethodRank’ feature to find the most used methods.
  • What are the classes with the highest coupling, not necessarily the most important classes. These are the ones to watch out for as they may be the ones doing ‘too much’. Kind of along the lines of the Single Responsibility Principle and even Separation of concerns.

Wishlist

I think in terms of ‘what’ NDepend does, all the information is there ready to be accessed, however there are a few suggestions I’d really love to see that would make having the data a little more ‘at your fingertips’.

More Visual Studio Integration, there are already some useful integration menus but I see a lot more potential for the information that NDepend can provide. If I had one feature request, it’d be to have that Query Results window as a Visual Studio dockable panel. The idea of not having to keep switching away from VS while I explore the results would be a good thing.

Although NDepend mostly has this covered, back in 2006 when I was trialing Parasoft’s .TEST one of the really handy concepts was to present you with 10 issues that you should fix today. So the idea of helping to progressively improve your codebase.

Thanks

Shout-out to Patrick Smacchia for giving me the opportunity to test drive NDepend.

I think I’ll continue to use NDepend going forward to see what else I am able to discover, and perhaps write a more advanced post. For now, I think it has shown that there are enough easy to use feature in there that even new uses can obtain some immediate value.

Links

NDepend Homepage
Your code via NDepend

posted @ Thursday, September 03, 2009 2:03 PM | Feedback (1)

Wednesday, August 19, 2009 #

CR_ClassCleaner now with Refactor key

On occasions I’m sure I’m one of many that take advantage of the CR_ClassCleaner plug-in for CodeRush.

For one reason or another the other day, I somehow managed to bork some of the shortcut keys which made calling ClassCleaner fairly impossible. On that note, I’ve always preferred the context-sensitive refactoring suggestions anyway. So with not a lot of effort I’ve added the RefactorProvider to CR_ClassCleaner. Here’s what you get when pressing the Refactor key on a class definition:

image

Feel free to download and try out the compiled dll, or grab the SVN patch to apply to your own source.

Downloads

Links

posted @ Wednesday, August 19, 2009 9:21 PM | Feedback (0)

Monday, August 17, 2009 #

Replace default DNN calendars with AJAX Toolkit Calendar Extender

Although DNN is a very capable CMS, one thing I’d really like to do is send this guy back to 1993:

image

While using a component we purchased (FormMaster), by simply ticking a box, you can call the default DNN calendar for any text field. While this is a cool feature to have it just so happens that the poor ‘ol default DNN Calendar looks like it’s been forgotten about for quite some time.

The first problem you find if you want to put this thing out of its misery is, you can’t. Navigating in the code to “DotNetNuke.Common.Utilities.Calendar” you find the following signature:

“Public Shared Function InvokePopupCal(ByVal Field As System.Web.UI.WebControls.TextBox) As String”. 
Is it a provider: no, so we can't just extend it easily.

One solution, besides modifying the core is to write another module which can ‘hijack’ the DNN Calendars and replace them with the AJAX Toolkit Extender.

Take it or leave it as a solution, here’s what I’ve done.

This piece of code may be considered a little angry, but essentially, it just loops through the controls on the page and looks for Calendar ‘asp:Hyperlinks’.

public static void FindNestedCalendarLinks(ControlCollection current, List<Control> foundCalendars)
{
    foreach (Control c in current)
    {
        if (c is HyperLink && ((HyperLink)c).NavigateUrl.StartsWith("javascript:popupCal('Cal'"))
        {
            foundCalendars.Add(c);
        }
        if (c.Controls != null)
            FindNestedCalendarLinks(c.Controls, foundCalendars);
    }
}

Next, I have a method which is called on the “Page.LoadComplete” event, which adds the AJAX Toolkit Calendar Extender:

public void ReplaceCalendars(ControlCollection controls)
{
    var foundCalendars = new List<Control>();
    FindNestedCalendarLinks(controls, foundCalendars);
    foreach (Control c in foundCalendars)
    {
        string dnnString = ((HyperLink)c).NavigateUrl;

        //extracts the UniqueID: dnn_ctr45232_FormMaster_ctl_e015a64a4a214eaf812836b9f40eb57d
        string textBoxId = matchTextBoxUniqueID.Replace(dnnString, "$1");
        //extracts the original control id: ctl_e015a64a4a214eaf812836b9f40eb57d
        Match textBoxMatch = matchTextBoxOriginalID.Match(textBoxId);

        if (textBoxMatch.Success)
        {
            AjaxControlToolkit.CalendarExtender cal = new AjaxControlToolkit.CalendarExtender();
            c.Parent.Controls.Add((Control)cal);

            //Set properties
            cal.CssClass = CalendarCssClass;
            cal.Format = DateFormat;
            cal.PopupButtonID = c.ID;
            cal.TargetControlID = textBoxMatch.Result("$1");
        }
    }
}

Just for good measure, there’s also a settings page, incase you need to change some of the properties of the Ajax calendars:

image

That’s pretty much the bulk of the work. The end result, a much nicer experience:

image

Downloads

Links

posted @ Monday, August 17, 2009 5:30 PM | Feedback (0)

Wednesday, July 29, 2009 #

Organisations and vision

Overview

I’d just like to share this small snippet from one of my masters Leadership assignments. To me one of the things that can mean the difference between ‘I’m only here because I get paid’ and ‘I’m here because I feel like I’m really making a difference’ can be a leader’s belief and sense of purpose. I believe this starts in the organisation’s own vision, mission and values.

Why have a meaningful vision?

Without going into the argument of why an organisation should have a true and meaningful vision and mission statement, Byrne & Rees (2006, p. 15) point out that “if an organizational mission statement is not ‘brought to life’ through the day-to-day activities of the organization, it may become a liability in that the staff will see it as a sham rather than as a motivator”.

Further to this “leaders can sustain their effectiveness only if they empower employees around a shared purpose. Leaders must convey passion for the business every day while maintaining clarity about the mission of the organisation” (George 2007). In some organisations, perhaps the meaning of the vision, mission, and values are there, they just may be portrayed awkwardly.

Even at a basic level any leader should be able to answer the phase “I love companyX because...”, “we give our customers a great family holiday at an affordable rate”, or even as simple as “we make accommodation easy”. Whatever the response, when leaders truly believe in a vision and and believe in making it an everyday reality, others will follow.

References

  • Byrne, J-AC & Rees, RT 2006, The Successful Leadership Development Program: How to Build it and How to Keep it Going, Pfeiffer, San Francisco.
  • George, B 2007, True North: Discover your Authentic Leadership, Jossey-Bass, San Francisco.

posted @ Wednesday, July 29, 2009 11:06 PM | Feedback (0)

Sunday, July 19, 2009 #

Create NHibernate classes using T4

Overview

Over the last little while there have been a raft of posts about using T4 templates, I think most of this seemed to be sparked from the drive to extend and gain more control over the Linq-to-Sql classes. So while there are a few good T4 templates to convert DBML files into classes there have been a number of drawbacks, some of these are pointed out here. The fact that L2S doesn’t support many-to-many relationships and the designer doesn’t let you specify the column lengths make using it for NHibernate (NH) related purposes fall a little short.

NHibernate XML Intellisense

On the next point, I know there has been a fair amount of hype around the Fluent NHibernate Mapping scene as well. I have never really found a few XML mapping files that hard to deal with. Here’s why:

image

Yep, once you’ve added the xsd definitions into Visual Studio’s schemas folder there’s intellisense and validation over any NH config.

T4 for Hbm.xml

If you’re creating a new project there is always the hassle of ensuring that your NH mappings have the same properties as your classes and all the methods and properties are virtual etc. So instead of converting a DBML file to NH mappings and classes, as mentioned before it is not really intended for this purpose. Here’s a small T4 template that you can use to convert .hbm.xml files into partial classes. So now, all you need to do is maintain an xml mapping file and let your class properties be automatically synchronised. My sample solution looks like this:

image

Inside the “BusinessObjectsGenerator.tt” is a simple generator that includes the desired business object structure and then specifies which xml files in the solution to generate partial classes for. The classes are partial so you can extend them with custom changes if needed in another file.

<#@ template language="C#v3.5" debug="True" hostspecific="True"  #>

<#@ include file="..\..\T4Templates\BusinessObjectsStructureTemplate.tt" #>
<#@ output extension="log" #>
<#

BusinessObjectStructureTemplate template = new BusinessObjectStructureTemplate();
var pathBase = new System.IO.FileInfo(Host.TemplateFile).DirectoryName;

BusinessObjectStructureTemplate.RenderClassFromHbm(pathBase, @"Mapping\Product.hbm.xml", template);
BusinessObjectStructureTemplate.RenderClassFromHbm(pathBase, @"Mapping\Order.hbm.xml", template);
BusinessObjectStructureTemplate.RenderClassFromHbm(pathBase, @"Mapping\Customer.hbm.xml", template);

#>

If you’ve previously downloaded and looked into Damien’s L2S templates they look fairly complex. The easiest way I’ve found to produce T4 is with the T4 toolbox, and also using the T4 Editor by Tangible Engineering. However, currently if you’ve download the T4Toolbox, I had to download and compile rev#34560 which corrects an error when having T4 templates in a project that is nested in a solution folder.

On the inside

Most of the work is done inside the “BusinessObjectsStructureTemplate.tt” file. What I’ve done to try and keep things simple is use NH’s own ‘MappingDocumentParser’ class to parse the Xml file, then simply iterate through the config to populate some custom data structures that are applied to the template. The reason for this is the custom data classes inside the T4 templates can be extended and changed later if more flexibility is needed, also meaning a new adapter could be written instead of the NH version.

Sourcecode

Visit the T4 repository

Choose one of these:

  • System.BusinessObjects version: BusinessObjectsStructureTemplate.tt
  • Generic POCO version: BusinessObjectsStructurePOCOTemplate.tt

And then include that file into the generator:

  • BusinessObjectsGenerator.tt

Links

Create NHibernate classes using T4

posted @ Sunday, July 19, 2009 11:00 AM | Feedback (4)

Sunday, July 12, 2009 #

The MethodLinq concept

There are now a lot of Linq providers around that do various different things. However, some interfaces were never meant to have linq. In fact there are particular APIs out there that we struggle to use without even thinking about adding linq.

The idea here is that what if there was a linq provider that was able to build and pass parameters into complex methods and interfaces. Why on Earth would you want to do this? Well, some interfaces, for example web services can end up with generate deeply nested properties, its nearly always a outright pain to build the required properties and objects to pass in. Another example would be a method that takes in a large number of complex types, in this case we might only be interested in setting a few properties on a few objects. And yes, you’re correct when you say ‘that’s what overloads are for’, so just hear me out and then judge for yourself.

Some examples

The method definition:

public List<buildingroomcategories> GetRates(Contact orderer, Contact travelAgent, Contact travelPoint, enumResChannel priceOwner, List<buildingroomcategories> buildings, enumRateRequestScope scope, int allotmentNumber, enumGuestRateType guestRateType, params RateRequestParameters[] rateRequestList) 

So as you can imagine, there is a lot of data and objects that need to be flying around in order to access this method.

Access via MethodLinq:

var rateQry = from rate in agent.Query().Rates where
                  rate.Building.ID == buildingId &&
                  rate.Parameters.FromDate == today &&
                  rate.Parameters.ToDate == today.AddDays(3) &&
                  rate.Parameters.PackageCode == "BAR"
              select rate;
var rateResponse = rateQry.Single();

Starting to get the idea? Don’t worry about the confusing method signature, just use the defined queryable properties to add what makes sense. Provided your destination method has a ‘design by contract’ implementation or even some basic null checking your in business.

Lets try another example, take the Paypal webservice. Method Definition:

SetExpressCheckoutResponse SetExpressCheckout(SetExpressCheckoutRequest request);

It looks easy enough, but the ‘SetExpressCheckoutRequest’ object turns out to be deeply nested. Using the .net3.5 constructors, this is what it takes to setup a request object:

var normalResponse = service.SetExpressCheckout(new PaypalAPI.SetExpressCheckoutRequest 
{ 
    RequesterCredentials = new PaypalAPI.CustomSecurityHeaderType 
    { 
        Credentials = new PaypalAPI.UserIdPasswordType 
        { 
            Username = "myaccount", 
            Password = "mypassword", 
            Signature = "signature" 
        } 
    }, 
    SetExpressCheckoutReq = new PaypalAPI.SetExpressCheckoutReq 
    { 
        SetExpressCheckoutRequest = new PaypalAPI.SetExpressCheckoutRequestType 
        { 
            SetExpressCheckoutRequestDetails = new PaypalAPI.SetExpressCheckoutRequestDetailsType 
            { 
                CallbackURL = "http://www.blah.com" 
            } 
        } 
    } 
});

And here is the same thing with MethodLinq:

var query = from item in service.Query().SetExpressCheckout 
            where 
            item.Request.RequesterCredentials.Credentials.Username == "myaccount" && 
            item.Request.RequesterCredentials.Credentials.Password == "mypassword" && 
            item.Request.RequesterCredentials.Credentials.Signature == "signature" && 
            item.Request.SetExpressCheckoutReq.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails.CallbackURL == "http://www.blah.com" 
            select item;

It does feel a little better, obviously at this stage its not perfect, but it does allow me to worry less about the crazy plethora of objects required to set the properties I want.

How its done.

Currently, it is possible to create MethodLinq access over a class’s methods with very few lines of code. So potentially, ANYONE can have a basic linq provider over their api in no time flat.

As an example, here is the mapping for the SetExpressCheckout method on the Paypal API. First it is necessary to create the following mapping class:

[QueryableMethodAttribute(MethodName = "SetExpressCheckout", Types = new Type[] { typeof(SetExpressCheckoutRequest) })]
public class LinqSetExpressCheckout : MethodQueryData<SetExpressCheckoutResponse>
{
    [QueryableMethodParameterAttribute(ParameterName = "request")]
    public SetExpressCheckoutRequest Request { get; set; }
}

This basically defines the method that is to be called, including the overloads (so we can find it via reflection), then the properties specified with ‘MethodParameterAttribute’ are those that you will use to query the method.

public class PaypalContext : MethodContext<PayPalAPIAAInterface>
{
    public PaypalContext(PayPalAPIAAInterface webservice)
        : base(webservice)
    {
        
    }

    public MethodLinqQuery<linqsetexpresscheckout> SetExpressCheckout { get { return new MethodLinqQuery<LinqSetExpressCheckout>(new MethodQueryProvider(base.OwnerClass)); } }
}

public static class PaypalContextExtensions
{
    public static PaypalContext Query(this PayPalAPIAAInterface service)
    {
        return new PaypalContext(service);
    }
}

From these few snippets of meta information the provider will then parse over the properties you’ve used and build the parameter objects for you, when this is done it puts the parameters in the correct order and finally invokes the desired function. It is also currently possible to have an anonymous expression on the ‘select’ if only a subset of the result is required.

Sourcecode

The sourcecode for this project can be viewed in the System.BusinessObjects.MethodLinq repository. Most of the existing unit tests I have for this project are based on a non-public api, it will probably take some additional time to write these against a mock interface.

As always, if you have any thoughts leave them below, hopefully this library will one day be able to unfuddle APIs and methods that require more work then they should.

posted @ Sunday, July 12, 2009 4:40 PM | Feedback (0)

Wednesday, December 31, 2008 #

Macbook Multi-touch Trackpad Driver update causes Blue Screen of Death

As happy as I was the other day that Apple has released an update for their windows trackpad driver, I've been getting plagued by BSODs caused by "applemtp.sys". I think I've narrowed the cause down to multi-touch operations (using 2 fingers at once), however here is a work-around...well, working for me so far..

image

Workaround:

As I've read on some of the support forums after the update there are now 2 mouse interface devices installed, after Disabling the "Apple Multitouch Mouse" I've not come across another BSOD.

Although I'm not sure yet, perhaps the other interface device is one left over from the previous mouse driver, or its an erroneous ugly twin from the new mouse driver. In either case Apple will need to fix their installer to remove it, or fix driver itself. Hopefully some more light is shed on this soon.

posted @ Wednesday, December 31, 2008 11:57 AM | Feedback (12)

Sunday, December 28, 2008 #

Macbook Multi-touch Trackpad Driver update

After recently updating to the latest aluminium macbook and loading back on Bootcamp with Windows Vista, it become very apparent that the existing drivers for the Trackpad are basically unusable. Apple's discussion forums where overflowing with threads complaining about poor compatibility, things such as even right-clicking or left-click-dragging becoming non-trivial. overview-hero20081014

This year I've also taken a summer uni semester to try and finish the Masters finished a little quicker. Finally I have a compatible version of mac:Word and Endnote, so I've spent the entire time in OSX, WOW! The multi-touch trackpad under OSX is sooo freak'n smooth, it really redefines how laptop mice 'should' work. The simple gestures and movements make a wide variety of common desktop tasks seamless and easy, some of these things include, Scrolling, Activating Expose, Zooming, etc.

The new drivers for Windows Vista and XP do not have the same sheen as using the trackpad under OSX however, they will at least allow use of the trackpad to get you out of trouble. Huge improvement, thanks to Apple for listening to the noise.

If you use bootcamp and an aluminium Macbook definitely download them from the Apple site immediately.

EDIT: Please see the next post if you experience blue screens from the update.

posted @ Sunday, December 28, 2008 9:15 AM | Feedback (0)

Saturday, October 04, 2008 #

ASP.NET + jQuery: What about PrototypeJS?

Well done jQuery

As everyone already knows, Microsoft has announced that jQuery will ship in the future with Visual Studio. I think this really is a step forward and will definitely complement all the exciting new developments going on with ASP.NET including the enhancements with ASP.NET Ajax and ASP.NET 3.5 + SP1.

But...

Here’s what I would like to know: Why did Microsoft choose jQuery? The only explanation I can come up with is: Well..why not?

I have ported JavaScript from jQuery to PrototypeJS and visa-versa, even emulated functionality I’ve seen in one with the other. After a while, I ended up settling into PrototypeJS, why? Well, honestly it’s probably not because of PrototypeJS itself, but because of script.aculo.us. Going back 12 months or so, the animations and effects in script.aculo.us to me appeared a little smoother and seemed to have more browser compatibility then the jQuery of the time.

I have recently been writing a client-side control extender using the ASP.NET Ajax libraries then using PrototypeJS+script.aculo.us to basically fill the gaps. And thus far these libraries are an exceptionally powerful and productive combination.

Battle tested

Lets also not forget that PrototypeJS + script.aculo.us are included as part of Ruby-on-rails, which basically means you can be assured that these JavaScript libraries have been deployed in a huge variety of websites in the Ruby community.

Taking a look at the warm-fuzzy real world client list on Prototype’s site and jQuery’s site, its obvious that both libraries are popular, there are a lot of big companies in each list, some are even listed in both. Funnily enough though Microsoft itself is listed only on the Prototype site.. :)

Conclusion?

Not really knowing where to get answers or reasons, I took a long shot and fired a tweet at Scott Hanselman…no pulse, but I didn’t expect anything. I’m just wanting to know what makes jQuery so special? It definitely has a better website then PrototypeJS. I’ve read forum comments that in some cases jQuery is only being used for it’s plugins, which are conveniently accessible from a link on the homepage. How many people even know that Scripteka has a collection of downloadable plug-ins for prototype!? I agree that the guys over at Prototype should look at a website refresh and start pulling the community together a bit.

The future 

In any respect I feel this is a step forward for Microsoft actually accepting and using Open Source products for .net instead of replicating them. And you never know, shipping NHibernate with Sql Server would be to me, a whole new level of respekt.

posted @ Saturday, October 04, 2008 11:14 PM | Feedback (5)