This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Friday, January 8, 2010

Lazy-Loading Web Page Components with ASP.NET MVC and jQuery

I am currently working in Visual Studio 2010 Beta 2
with .NET Framework version 4.0 Beta 2.

Here’s the scenario: you want a web page to return to the end user and render out as fast as possible, but you have some long-running parts to your page.  You’d like to get the page loading instantly, displaying a “please wait” message while you load the components.  If you program on ASP.NET, you’re in luck.

It seriously takes about 4 minutes to get yourself some fancy, fast, Ajax-enabled web pages, complete with lazy-loading sections that would typically slow down the page load for the end user.  With jQuery integration and support in Visual Studio 2010, master pages and the MVC Framework you are, in fact, already there without (maybe) knowing it.

Here’s everything you need to get to asynchronous web client bliss.

First Things First

Create a new project in Visual Studio 2010 (not a new web site).  Go the the ‘Web’ category of projects and select the 2.0 version of MVC for ASP.NET.

Add Script Support

Navigate to the Site.Master code file in the project.  It will be located under the Views\Shared folder.  Double-click to open it.

Next, expand the Scripts folder in Solution Explorer.  Drag the jquery-1.3.2.js file to the <head> section of Site.Master.

Blamo! jQuery support!

Rig up the Controller

In MVC, controllers contain the code that decides which view, or part of a view, is returned.  Open up the HomeController.cs file and add two new methods.  Both will be return type PartialViewResult, one named Peek and one named Poke.  Set both of them to sleep the thread for 3 seconds, then return a PartailView of the same name.  It should look like this:

image

The sleeping is just so that we can emulate some long-running function.  Imagine you’re dynamically building an image, or placing a reservation on a remote system.  In fact, do whatever you like, it’s your three seconds! ;o)

Sweet.  Controller’s all set.

“Make Mine an Easy View”

Sure, no worries.  Right-click on the methods in the controller that you just created and click on “Add View…”.  This will start a wizard to do some auto-generation for you.

image

Now, there’s a bunch of cool stuff in here, like strongly-typed views and whatnot, but we’re just going to make sure we have the partial view creation checked off and click on Add.  This creates the view for us that we need in the Views\Home folder.

Sweet.

All that’s left are some goofy comments in our ascx’s to try to make the readers laugh.  But first…

A Side Note…

…that’s entirely inline with the rest of this post.

Why did I choose PartialViews and ascx?  We don’t need to render a whole page here, just part of a page and that’s exactly what PartialViews do, and what ascx’s are.  If we try to return a full page it would also return all the HTML associated with that page and if the page uses Master Pages, it would also invoke the related classes for the master page and render the whole shebang.

We could also just put html pages on the server and request those, which you might argue would be simpler.  But, by going this route and creating methods on the controller – along with the related views – we’re able to leverage our models, existing web references, our repositories…everything that’s available to us through MVC (and the .NET Framework).

Back to the Story

In this sample, I’m actually going one step farther: the async bit we’re loading will make a call to another async bit as soon as it loads.

Page loads –> Peek is called –> Poke is called

We need to go to our View\Home\Index.aspx markup and add the part of the page that will be populated by the jQuery call.  All you need is a <div> with an ID.  Add the helper method jQuery load call, which makes a request to the web server and puts the result in the component you specify.  The $("#name") syntax is short-hand for returning the page element. 

The only other thing to note here is that I am telling jQuery to load “home/peek” and “home/poke”, which doesn’t look like web pages.  They aren’t.  These calls will be routed by MVC to the controller, and Peek and Poke will be found with reflection in the controller class.  That will invoke our methods and return the ascx components we created.

Put together, it all looks like the following:

Index.aspx (in the content tag): image

Peek.ascx: image

Poke.ascx: image

hehehe…get it? Polkalicious?!  Man, I’m funny.

A Simple Summary

Here’s all we have to do to get the thing running in a more abbreviated form:

  1. In a new ASP.NET MVC project, add the jQuery script to the head section of your Site.Master
  2. Add methods to your controller to handle the calls.  These will be of type PartialViewResult and return a PartialView
  3. Add the ascx files to the project by right-clicking on the controller methods and selecting to create partial views
  4. Add a <div> to the Views\Home\Index.aspx page and a piece of script after it to make the jQuery call.  Invoke the method on the controller through the routing features of MVC

And that’s everything you need to get partial lazy-loads going with jQuery and MVC. 

May the force be with you.

Microsoft SQL Server Wishlist

High on the list of designer and management features I would like to see in Microsoft SQL Server is the ability to create folders to group tables.

From an RDBMS perspective I would suggest that these tables be absolutely meaningless; I’m talking about pure user convenience.

Sure, we have filters support (through the context menu on Tables), but we don’t have a way to even save filters for later use.  Also, filters work great if you have common names and only by name do you wish to work with your tables, but it falls short if you want to work on a domain with variously named tables.

For instance, you might want to work on tables for customers, invoices and work orders, as well as the dozen or so history tables, the system data tables and others related to the domain.  No filter will easily be created to cover this gamut, and the filter is lost when you lose the connection to the server, restart Management Studio or decide you want to work with a different list of filtered tables.

Yeah, but “Work On” What?

What do I mean when I say work on?  I’m talking about when I’m authoring a diagram, or writing a stored proc (I make heavy use of the drag and drop features with tables and columns).  It’s just super handy to have a shorter list to work from.

How about this: instead of using folders, why not let me tag the tables?  Each tag you add could become a virtual folder and you apply as many tags as you like to each table.  That would be brilliant.

Microsoft SQL Server Management Studio – which is also the development environment of most ‘softies on the MS SQL stack – has come leaps and bounds in the last couple of builds, but compared to some of the features in other IDEs we work with daily there is still a lot of room for growth.

Here’s an old request I made: plug-ins.

Tuesday, January 5, 2010

Diving into Workflow Foundation 4.0 – Hiring Request

I am currently working in Beta 2 of Visual Studio 2010
with version 4.0 Beta 2 of the .NET Framework.

The first thing I’ll have to note in working with the Beta 2 samples in Windows Workflow Foundation 4.0 is that you’re not going to survive the sample as a passenger – at least not without a few notes on running it.

image If you want some tips on what the app is supposed to do, head to the end of this post.

The description of the sample is still a little lacking, which is understandable considering it’s in Beta. 

You’ll likely find this on your own, but the script required to run the application must be run from a command prompt with .NET environment variables loaded and run in a context with administrative privileges.

The HiringSample solution out-of-the-box does not work on 64bit systems because of the build settings.

Further, you’ll need to be aware of the service endpoint collisions that might occur if you try to debug from the a normal F5.

Lastly, I found that I had to manually create a folder used for request history in the data folder in order to get the application running.

Let’s start with the admin and 64 bit issues.

Configuring the DB and Loading the Services

First off, you need to get a prompt running with the .NET 4.0 environment variables set up.  In Vista or in Windows 7, simply hit your start button and type in “2010 prompt” (without the quotes) and it should be the first thing on your list.   If you need to locate it manually, check in Program Files –> Visual Studio 2010 –> Visual Studio Tools –> Visual Studio Command Prompt (2010). 

If you can’t find the prompt as a shortcut installed to your machine, check out my earlier post for that.

Next, navigate to the [samples root]\WF\Application\HiringRequestProcess\CS directory.  In there you’ll find the setup.bat and startservices.bat files.  Run setup.bat (this should be the only time you need to do this).

Next, open the HiringProcess.sln and build it (don’t run).

Pop back over to your command prompt and run the startservices.bat file to get everything fired up.

If you get an error at this point it may look something like this:

image

System.BadImageFormatException{"Could not load file or assembly 'HiringRequestProcess, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format."}

You may not see the error without attaching a debugger (or trying to run the project directly from the debugger) but I did get this message while trying to build.  To get around this – and again, I am on a 64 bit machine – I changed the HiringRequestProcessDefinition to target x86 machines (the HiringRequestProcess DLL project is set to target x86 and it is a dependency of the Definition project).  This allowed me to build the service projects and run them from the command prompt.

I initially made some progress and was able to get everything to compile by changing HiringRequestProcess to x64 and recompiling…except the web site, which starts throwing the same error as above.

Resolving DirectoryNotFoundException

The next bit was a little more tricky to get going.  You can’t debug the WebClient project directly through the solution as you get a host of other errors (endpoints already exist) with the WCF services.  This was a red herring of sorts as I tried to chase the other peripheral problems.

The issue at this point was that, while I could use the web site, persistence was not working and errors were not being reported to the WebClient.

I launched the web application per the instructions (right-click on the project, view in browser) and then attached to the process.  I also attached to HiringRequestProcessDefinition, which is where the XML persistence was failing.  This allowed me to expose the said exception.

To resolve this issue, simply add a directory called RequestHistory to the Data directory in the solution.

A Sample Overview

I couldn’t find a document that described the projects in any level of detail, so I’m writing a quick summary that it might help someone out there.

There are five projects in HiringRequest solution, the first listed in Solution Explorer being the WebClient.

WebClient has references to HiringRequestService, InboxService and OrgService, the three services that drive the overall project.  The web site is set up with a drop down box

InboxService has methods needed to fill out the default view in the web client as well as add and remove methods for inbox messages.

image

The OrgService is the human resource component of the application and handles pulling up corporate roles, lists of employees or specific employee details.  These are all readable with no write functionality.  The employee list and all supporting data is loaded on demand when the service is called and is not cached.

image

Note that in the solution OrgService and the IOrgService interface live in files named HRService and IHRService respectively.

The HiringRequestProcessDefinition is the last stop on the tour, along with its dependency on HiringRequestProcess. HiringRequestProcess contains the repository for requests and some base classes and constants used in the application.  The Definition project is actually two-part: the WF diagram (declarative) definition of the workflow and the HiringRequestProcess service.

A Few More Tips…

Make sure you read the MSDN help on getting the app to run.  There’s a lot said there that I didn’t say again.

If you set up the database on a non-default instance (meaning, if you’ve changed the default name of SQL Server Express on your machine) you’ll need to update the connection string used by the service in the  HiriringRequestProcessDefinition project.  You will get a confusing, misleading error if you don’t.  It is located in app.config as the second group of entries.

When you’re using the web client, there is a drop down box that lets you change who you’re “logged in” as.  There is no login procedure other than changing the dropdown.

image Make sure you keep the service windows open and in view when running the sample.  Someone in the organization of a certain role must act on hiring requests per the business rules and org structure.  The service console windows give you hints (employee ids) on who needs to do something next.

Hope this helps some!  Best of luck in exploring Windows Workflow Foundation 4.0.

Monday, January 4, 2010

OT: Epicilicious

May can’t come too soon:

Oh, yes, my friends.  This will be good.

I can’t wait for the upcoming SDK from Microsoft with the extension libraries to support the Iron Man suit (licensed from Stark Enterprises).  The Stark.MannedFlight namespace looks most interesting, but I’m also looking forward to using the Stark.FistsOfPower classes.

Sadly, it is rumoured to me a do-it-yourself kit for the suit.  I’ve got watches set up on eBay for cheap arc reactors.  Let me know if you find one.

Visual Studio 2010 Command Prompt

If you don’t do a full installation on Visual Studio 2010 (I’m on Beta 2 at the time of this posting) then you may not get the Visual Studio Command Prompt which loads up with all the environment variables needed to run framework applications and tools from the command line.

Thankfully, it’s easy to fix.

Grab the Beta 2 Web installer and run the Add or Remove Features command.

image

Next, drill into Visual C++ and select the compilers and tool option.

image

The web installer will have to go off and grab some bits from the Microsoft servers.  At my desk I am pulling down the package at 1178 KB/second (did I mention I like where I sit heheh). 

Go get a coffee. ;o) Your work at this point is pretty much done and it’ll take a bit for the download/install.

OK out of the install dialogue and you’re done!

image

Your Visual Studio 2010 command prompt should now be available from the Start Menu.

A Separate Tool?

I’m hoping in the final build that the Command Prompt is a separate option in the installer, broken out from the very large 2GB chuck that C++ is.  I guess in the grander scheme of things that 2GB is a trivial amount of space (a vendor gave us thumb drives of that size for Christmas), and if I wanted to I could rig up the environment variables myself.  Even still, all the work’s been done and an option in the installer would at least save the 2GB download.

Happy New Year All!

I have readers now in 75 countries and while we are all of different backgrounds, nationalities and mother tongues it is neat to be in a field of work that finds people passionate about their jobs around the world.

If you’re learning a new part of the .NET Framework, refining your skills or troubleshooting Visual Studio or MS SQL and have participated in this conversation that I have (mostly with myself), I wish the best to you and yours in this new year.

Peace and grace to you in 2010!

Thursday, December 24, 2009

Visual Studio 2010 Wishlist

It’s Christmas and so here’s a short list of things that I am asking Santa to bring me for Christmas (or in the March CTP) for the next build of Visual Studio 2010.

More Collapsible Regions

I would think this one would be easy enough because there is an implementation built in at a higher level.  Let’s also have the ability to collapse whiles, ifs, foreaches, switches and the like.

Collapsible Selections

I would like to be able to highlight a block of code and have that highlight turn into a collapsible region.  We are given collapsibles on certain blocks of functionality (methods, classes, comment regions) and if my first wish is granted than on other constructs as well, but not on selections.

While this is good:

image

…allowing me to collapse this would be even better:

image

…and by putting a image in the margin the team should be able to use the existing functionality they’ve implemented.

Intelligent Collapsible Regions – With Style!

Okay, so what if we could get those selections and regions collapsed?  We’d also like a way to preview those hidden bits, right?

Thankfully the editor is written in WPF now, so this shouldn’t be much more work than creating adorners for the collapsed hints.

And while they’re already doing it to some level (hover over the ellipses on a collapsed region) it is grey, without syntax highlighting and in a non-fixed-width font.  Let’s jazz it up.  In fact, let’s have two views: the first would reveal comments in the /// style and then an expander would animate open to reveal a little code browser.

There has got to be an intern working on the IDE team that could use a project like this as a learning experience ;o)

Code Browsing

Since we’re talking browsing, let’s hit my last item on the list for today: an alternative way to browse code.

If you don’t write them yourself, you likely work with someone who does: long code files.  I have a big monitor, so I am able to fit about 55 lines of code onscreen at a time.  But many of the classes I work in are 200+ lines of code (especially any DAL work). 

Other scenarios where traditional code browsing techniques break down are in tool-generated code.  When you’re looking through a LINQ to SQL generated class there can be literally thousands of lines of code.

Getting your head around ‘where’ you are in the file is not easy to do.

But what if you had a thumbnail view of the code?  That thumbnail could have highlighting for keys that you select in the legend. As you hover over the miniature version of the class, you get tooltips that reveal method names or a preview of a comment.  Clicking on the ‘map’ would take you to that place in your code.

There are about 100 different things you could implement in that, some of which would even be useful.

Or a Lump of Coal

image Visual Studio 2010 (I’m on Beta 2 as I write this) is loaded with treats and it runs fast…and the IDE team has already promised better performance in the next build we see.  If all I got for Christmas (even if it was a late gift) was a release copy of VS2010 I’d be a happy kid.

The .NET Framework 4.0 is a game-changer, and you’ll need Visual Studio 2010 to get in the game.  As the various parts of IDE continue to evolve, things like browsing code or manipulating the view of your code will become more and more integrated with your flow of development.

And when you see the above features show up, you can send me a Christmas Card. ;o)

Merry Christmas to everyone.  May you be blessed with the Joy, Peace, Love and Hope that this season was intended to bring.