I have received some flack for my lack of blog posting. To defend myself let me state that for the past year I have been busy. Really busy. There were many days where I didn’t have time to eat or sleep, much less blog.

After April 12th all that changed. I took a vacation and recharged my batteries a little. Now that I am “not so busy” I have decided to start blogging again. Looking back it wasn’t that I didn’t have interesting things to share, it is just that I didn’t have time to write them up properly. In Word Press and OneNote combined I have over 70 drafts of blog entries. So I am making a public commitment – 10 blog entries a month for the next 3 months to try and catch up.

I have decided to back date any blogs which were started so that they make sense chronologically to me. For example my first entry is going to be about updating the blog to use HTML5 and CSS3. I performed a demo of doing that for the spring quarter UCSD Extension ASP.NET MVC class. So I am going to file it as if I was able to write it up at that time, because that is where I did the research. However some of the entries are really just titles and a couple of bullet points, so those will get new dates.

Here I go…

[Update: Adding Converting Blog to CSS3 on May 3rd]

When I started doing more complicated things with ASP.NET MVC it was using Razor. In some ways that was unfortunate because some of these things were actually a little easier in prior versions. It starts to get complicated when you start composing partial views and multiple javascript files. First some Javascript files depend on other javascript files. And secondly partial views need certain scripts to be included that the main page doesn’t necessarily know about. The problem is that Razor doesn’t really deal with these things very well.

For this blog entry I am going to focus on getting JavaScript files included from partial views. This question has been asked numerous times on Stack Overflow

  • http://stackoverflow.com/questions/863436/is-it-bad-practice-to-return-partial-views-that-contain-javascript
  • http://stackoverflow.com/questions/912755/include-javascript-file-in-partial-views
  • http://stackoverflow.com/questions/4707982/how-to-include-javasscript-from-a-partial-view-in-asp-net-mvc3
  • http://stackoverflow.com/questions/5376102/mvc-partial-views-and-unobtrusive-jquery-javascript
  • http://stackoverflow.com/questions/7556400/injecting-content-into-specific-sections-from-a-partial-view-asp-net-mvc-3-with
  • http://stackoverflow.com/questions/11098198/is-it-ok-to-put-javascript-in-partial-views

In fact, I bet if you put all of the questions in 1 it would have quite a point total. But it is spread into so many slightly different questions that it is tough to quantify.

So first to define the problem. The ideal place for scripts is right before the close of the body tag. The default template’s master/layout view contains a scripts section for this purpose. Unfortunately sections can only be defined, not added to. So that means that the main view is the only one that can place script files in that section. It can get very awkward if there are script files that are very specific to the partial view, especially if the main view includes a number of partials. Basically the master view has to maintain the list of scripts needed by the entire tree of partial views.

Let’s make the problem more concrete. Let’s say I have three main view that include a partial view. That partial view uses another partial view. I change the leaf partial view so that I need some JavaScript. I have to find out where all of the views are that include me (but of course no view includes me directly), and add the script to those views. In short – YUCK.

While researching a solution to the problem, I came across a couple of promising solutions, namely:

http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/

And

http://forloop.co.uk/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc

The first didn’t take into account paths, and the second was way too complicated in terms of how to use them, so I came up with this nice simple hybrid of the two solutions.

Here is an example of its use
Either at the top of the file or the web config, need to use the namespace

@using PartialsWithScripts.Helpers

To include a script in a partial view simple add it like so:

@{ Html.MyAddScriptFile("~/Scripts/App/contact.js"); }

Here is the code

public static class ScriptHelpers
{
    const string ScriptContextKey = "ScriptContext";

    public static void AddScript(this HtmlHelper htmlHelper, string path)
    {
        var scriptContext = GetScriptContext(htmlHelper);
        scriptContext.Add(path);
    }

    public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
    {
        var scriptContext = htmlHelper.ViewContext.HttpContext.Items[ScriptContextKey] as HashSet<string>;
        if (scriptContext != null)
        {
            var builder = new StringBuilder();
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
            foreach (var scriptFile in scriptContext)
            {
                builder.AppendLine("<script type='text/javascript' src='" + urlHelper.Content(scriptFile) + "'></script>");
            }
            return new MvcHtmlString(builder.ToString());
        }
        return MvcHtmlString.Empty;
    }

    private static HashSet<string> GetScriptContext(HtmlHelper htmlHelper)
    {
        var scriptContext = htmlHelper.ViewContext.HttpContext.Items[ScriptContextKey] as HashSet<string>;
        if (scriptContext == null)
        {
            scriptContext = new HashSet<string>();
            htmlHelper.ViewContext.HttpContext.Items[ScriptContextKey] = scriptContext;
        }
        return scriptContext;
    }
}

…for Data based services

There are two basic problems with using WCF to expose data services and both boil down to producing too many methods
1) You have to create a minimum of 5 methods per type that you want to expose (CRrUD)
This is basically – “I have too many types of things to expose”
2) You have to create a new method every time a client comes up with a different way to query the data
a. Get Orders by Product
b. Get Orders by Customer
c. Get Order By OrderId
d. Get Orders by Category
e. Etc
This is basically “There are too many ways to query my data”

There is one other reason that is sometimes overlooked, which is you have to modify all those methods when you want to do something across the board, like service side paging or filtering out rows based on the current customer. These use cases are difficult to apply in an aspect oriented fashion and often require the modification of many different pieces of code.

While teaching my fall MVC class, I was under a space constraint on both my e-mail and my hard drive. (Since then both have been cleaned out and upgraded). Anyway I was receiving these huge files containing a whole bunch of packages that I already have on my machine, and could easily download again. So I decided to make a video to demonstrate how to use NuGet to fix the problem.

You can watch the video on my YouTube channel

I use WordPress for my blog. I wanted to update the bog to use HTML5 and CSS3. It wasn’t like I was using tables for layout or anything but there were three things that I didn’t really like the look of.

The first thing I wanted to fix was the Web font. I was using JavaScript to produce the font, and it was not giving good results in all browsers. I searched for and found the Whiteboard regular font I was using. Unfortunately not all font files are supported in all of the browsers. To support all browsers you need at least 2 files. I downloaded and copied all of the necessary files (ttf, eot, woff, and svg). Then I edited my main stylesheet and added this to the top

/* @font-face kit by Fonts2u (http://www.fonts2u.com) */ 
@font-face
{
	font-family:"Whiteboard";
	src: url("House_Whiteboard_font_by_callsignKateJones.eot");
	src: url("House_Whiteboard_font_by_callsignKateJones.eot?#iefix") format("embedded-opentype"),
	url("House_Whiteboard_font_by_callsignKateJones.woff") format("woff"),
	url("House_Whiteboard_font_by_callsignKateJones.ttf") format("truetype"),
	url("House_Whiteboard_font_by_callsignKateJones.svg#Whiteboard") format("svg");
	font-weight:normal;font-style:normal;
}

I removed the typeface.js scripts and the extraneous styles, and voila, I now had working fonts in all browsers.

The next thing I wanted to focus on was the text on the sticky note. I wanted it to look written on. For this I needed the new CSS3 rotate transform

.sticky
{
	-webkit-transform:rotate(-9deg);
	-moz-transform:rotate(-9deg);
	-o-transform:rotate(-9deg);
	/* filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=-0.1); */
	-ms-transform:rotate(-9deg);
}

The last thing I didn’t like was the whiteboard boarder. It looked alright in Chrome (which was my default browser, but not so good in IE. I tried a couple of things including border gradients and background gradients, but I couldn’t get it to look right. Finally I had to resort to JavaScript which sucks.

I missed the first session because of lack of sleep and the fact that I hadn’t finished my slides for the day’s second talk. I came in at the end of Bret Stateham’s talk on Getting Started on Azure. I didn’t expect anyone to show up for my talk on Azure Tricks and Tips because of the advanced nature of the talk and that not many people are doing Azure yet. I was pleasantly surprised to find 10-15 people there, which was a great number for that kind of talk. The talk was well received and there were lots of good questions. I have uploaded the slides for the talk.

Afterwards I went to lunch with the DM gang. After I came back I was going to check out David Pallmann’s talk but I was about five minutes late, and it was in the same room as mine, so it was hot stuffy and crowded. Instead I ventured over to John Bowen’s talk on the Future of XAML for XAML Developers, which was in a much nicer room. I wanted to be in the same room for the talk after the next one, and Llewellyn assured me that it was going to be crowded, so instead of heading over to several other talks I just hung out in the same room and suffered through Fundamentals of Metro Style Applications. Then it was time for my favorite talk of the day – Michael Palermo’s HTML5 for the Real World. The crazy thing was that it was my favorite talk despite knowing all the material! His dynamic and engaging style was simply fun to listen to. After that was over I headed over to a fairly good talk by Paul Mendoza on Writing Maintainable JavaScript.

The Geek dinner was great – Lllewellyn was congratulated on the schedule, and I met a few people and had some interesting conversations on the CAP theorem and light particles as well as digitizing old film.

I was undecided as to which topic to attend first the next morning. On a whim I decided to attend the Hacking Your Memory session. Much to my surprise that became my favorite session of the entire camp – It Was Awesome! The speaker (Gary Hoffman) did a great job, the slides were well prepared, the topic was interesting and the audience was really engaged. Check out the site if you are interested.

Next I was trying to decide between WordPress Ninja!, and .NET TDD Kickstart. by Barry Stahl whom I had met two nights previously. I made the wrong choice and attended the WordPress Ninja! talk, which should have been renamed WordPress Beginnner!. During lunch Llewellyn talked me into doing the afternoon sessions that was supposed to be with Woody Zuill, but due to family emergencies Woody had to cancel. I begged out of the first one to attend a Node.js talk. I then trekked back over and helped give the talk on Testing EF, ASP.NET and ASP.NET MVC. I stayed in the room to attend the final talk User Driven Development which had some interesting discussion.

Great conference as always. Kudos to Woody Pewitt, Bret Stateham, Llewellyn Falco, and the rest of the volunteers for their efforts.

I am by no means an expert on Workflow. But after e-mailing back and forth with Jim Bears and Dave McCarter about a possible talk for the July meeting of the San Diego Developers Group, we concluded that not many people understand, use, or appreciate workflow. This could be due to bad experiences they have had in prior versions. Since the 4.0 version has addressed a lot of those shortcomings, we decided that it would be a great topic for discussion at a user group.

As per usual, I was too busy to prepare for the talk more than a day in advance. But I put together some slides, and formed a pretty good idea of the demo I wanted to do before I went in.

The first hour of the talk went pretty well. It was when I got into the unrehearsed part of the demo that things started to go awry. I had packaged up the first demo into a custom activity, and was trying to reuse that in a flowchart activity. Also I was switching from a WorkflowInvoker to running the workflow from a WorkflowApplication. At the same time I was adding persistence. I noted that I was still passing in the custom activity and not the workflow that contained the Flowchart, but I knew that something else was going on. I eventually found it (I was forgetting to call Run on the WorkflowApplication). Once I fixed that however, I forgot to go back and switch to the outer activity. That’s was the reason that nothing else was working.

This morning before I went to work, I fixed that problem, and corrected a couple of typos in the slides. Now that I am back home, I am going to finish the rest of the demo. That was always my plan, because I didn’t think that I would have time to do everything live.

I had already created one event – the completed event. But now that I allow the workflow to persist I want to capture another event – the PeristableIdle event

Here is an example of hooking that up:

app.PersistableIdle = e =>
{
	Console.WriteLine("Persisting...");
	_persistingEvent.Set();
	return PersistableIdleAction.Persist;
};

then I want to change my main from this:

WorkflowApplication app = CreateNewWorkflow();
app.Run();
_completedEvent.WaitOne();

to this:

WorkflowApplication app = CreateNewWorkflow();
app.Run();
_persistingEvent.WaitOne();
app.ResumeBookmark("readPrizeCode", Console.ReadLine());
_completedEvent.WaitOne();

Run it again, and everything works, but now what happens if I close the console application after receiving the prize code?
I need someway of loading the existing workflow, but I don’t have anything that I can load it by. As I mentioned last night there are a couple of ways to do this:
1) by using Promotable properties so that some of your properties are persisted along with the workflow.
2) Just tracking the mapping between your custom property and the instance ID from another table

I chose the second option, and added in the DataAccessLayer to do this already, but to take advantage of this feature I need to add the mapping record when it goes idle and take out the mapping when it completes. The final result looks something like this:

static readonly ManualResetEvent _completedEvent = new ManualResetEvent(false);
static readonly ManualResetEvent _persistingEvent = new ManualResetEvent(false);
static readonly ManualResetEvent _unloadedEvent = new ManualResetEvent(false);

static void Main(string[] args)
{
	string email = null;
	while (string.IsNullOrWhiteSpace(email))
	{
		Console.WriteLine("Enter your e-mail address:");
		email = Console.ReadLine();
	}

	bool done = false;
	while (!done)
	{
		WorkflowApplication app = CreateNewWorkflow(email);

		Guid instanceId;
		using (var session = new EfSession())
		{
			instanceId = session.Workflows.GetWorkflowInstance(email);
		}
		if (instanceId != Guid.Empty)
		{
			app.Load(instanceId);

			string prizeCode = null;
			while (string.IsNullOrWhiteSpace(prizeCode))
			{
				Console.WriteLine("Enter your prize code:");
				prizeCode = Console.ReadLine();
			}

			app.ResumeBookmark("readPrizeCode", prizeCode);
			_completedEvent.WaitOne();
			done = true;
		}
		else
		{
			app.Run();
			_unloadedEvent.WaitOne();
		}
	}
}

public static WorkflowApplication CreateNewWorkflow(string email)
{
	IDictionary<string, object> outputs = null;
	var app = new WorkflowApplication(
		new QuestionForPrize());
	app.Completed += e =>
	{
		outputs = e.Outputs;
		Console.WriteLine("Removing instance {0}...", app.Id);
		using (var session = new EfSession())
		{
			var instances =
				from wi in session.Workflows.All
				where wi.EmailAddress == email && wi.WorkflowInstanceId == app.Id
				select wi;
			var instance = instances.SingleOrDefault();
			if (instance != null)
			{
				session.Workflows.Delete(instance);
				session.Save();
			}
		}
		_completedEvent.Set();
	};
	app.PersistableIdle = e =>
	{
		Console.WriteLine("Persisting instance {0}...", app.Id);
		var wi = new WorkflowInstance
		{
			EmailAddress = email,
			WorkflowInstanceId = app.Id,
		};
		using (var session = new EfSession())
		{
			session.Workflows.Add(wi);
			session.Save();
		}
		_persistingEvent.Set();
		return PersistableIdleAction.Unload;
	};

	app.Unloaded = e =>
	{
		Console.WriteLine("Instance {0} has been unloaded", app.Id);
		_unloadedEvent.Set();
	};

	app.InstanceStore = GetInstanceStore();
	return app;
}

private static InstanceStore GetInstanceStore()
{
	var instanceStore = new SqlWorkflowInstanceStore(
		ConfigurationManager.ConnectionStrings["Workflow"].ConnectionString)
	{
		HostLockRenewalPeriod = TimeSpan.FromSeconds(1)
	};

	InstanceHandle handle = instanceStore.CreateInstanceHandle();
	InstanceView view = instanceStore.Execute(
		handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
	handle.Free();
	instanceStore.DefaultInstanceOwner = view.InstanceOwner;
	return instanceStore;
}

Here are the slides and demos for the talk. Thanks everyone for coming!

This was my fourth year presenting at the San Diego Code Camp (and the 5th year attending).

On Saturday I went to see Dustin Davis speak on Aspect Oriented Programming with PostSharp because we had been e-mailing back and forth about combining our possible AOP talks. I then stopped by to see Mark Rotenburg speak about NetDuino which I hadn’t really played with but after that talk I really wanted to.

After lunch I tried to get in to see Jon Galloway speak about MVC 3, but the place was so packed I went next door to see Brad Cunningham speak about “Becoming a better ninja”.

Ike Ellis and I spoke next about Sql Azure vs. Amazon RDS. This was probably the easiest talk I have ever given with no preparation. Ike and I interact with one another quite a lot and it was really no different in front of an audience as it was front of a group of company developers.

Unfortunately I was peppered with questions after the talk, so I missed the final session.

On Sunday I was the first talk on Aspecting EF And WCF. I was glad to see that I was given a bigger room this year. Jim Houghton and Mark Taparauskas from DevelopMentor were also there. I was nervous because of the large amount of material I had to cover, but I think the talk went well considering how advanced the topic was. In the hour talk I managed to go over the WCF extensibility model, write an IOperationInvoker, discuss the EF provider model, plug in a custom provider, discuss how lambdas can be used to call services in a type safe manner, describe the decorator pattern, talk about how to bundle up reusable calling logic, and switch the calling model of my existing client. There were three demos, on aspecting WCF on the service side, EF on the client side, and WCF on the client side.

After my talk I headed over to see Alex Shah talk about PhoneGap. Having done a little phone development myself I found the topic interesting, although the talk could have used a little polish.

I went to lunch with Mark, and when I got back Llewellyn was waiting to prepare our talk on Reactive Extensions. My original talk had ben introducing some concepts and then building a couple of nifty demos. When Llewellyn joined he wanted to show the Koans for each particular set of functions. So we wrote up the demo slides that followed every slide of what I wanted to cover with the name of a method two from the Koans. We finished early but unfortunately not in time to catch the talk before ours, so we just hung out until the end and gave the final talk.

During the talk Bart texted to say that Run was now called ForEach? Not sure if I agree with that rename, but there it is. The final demos were on Drag and drop with Silverlight, and throttling text event to issue web service calls. We had one question at the end around Throttle which I will post when I get a chance.

I love the Reactive Framework, I will get to why in a minute. I even did a talk on it at the Guerrilla.NET class in May. That talk didn’t go so well because they keep changing the freakin’ API! Every single time I upgrade I have to fix things. This last class unfortunately I didn’t even realize that I was upgrading. I made the mistake of creating a project from scratch and using NuGet to pull down the latest version of Reactive. All of the Demo code that I was using broke in subtle ways that I couldn’t quite figure out live, so I had to pull out a project that I had built a week prior. I just now had the time to sift through the changes and make everything work again.

There are still two major ways to subscribe to UI events. The API used to be called FromEvent, now it is FromEventPattern, even though FromEvent still exists for some reason. The important part isn’t whether th API is called FromEvent or FromEventPattern. The distinguishing feature is whether you pass one generic type argument or two. If you just pass one you get access to use the old string method like this:

var mousemoves1 =
	from evt in Observable.FromEventPattern<MouseEventArgs>(rect, "MouseMove")
	select evt.EventArgs.GetPosition(LayoutRoot);

If you pass in two arguments (the first being the delegate type, and the second being the EventArgs type) you get to use the more confusing, but more flexible API. It makes sense after you think about it for a while. That one looks like this:

var mousemoves2 =
	from evt in Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(
		h => MouseMove += h, h => MouseMove -= h)
	select evt.EventArgs.GetPosition(LayoutRoot);

The reason you can’t simple pass MouseMove is because the add_ and remove_ methods for the event aren’t exposed directly.

Anyway, one of the best features of Reactive is the fact that you can transform a set of UI specific events that can only be handled by the UI to a set of events that can be handled by anyone, a ViewModel for instance.

var textChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
				h => textBox.TextChanged += h,
				h => textBox.TextChanged -= h);
var stringsChanging = 
	from tc in textChanged
	select ((TextBox)tc.Sender).Text;

// Now that we have transformed these events we can pass 
// them safely into the ViewModel
// which will still know nothing of how they were generated
viewModel.SetupSubscription(stringsChanging);

The idea of transforming an passing around events is one of the main reasons why I still love Reactive even though they break me every month or so…

I just finished a Guerrilla.NET in Boston with Michael Kennedy and Mark Smith. Here are the topics we covered.

  • Introduction to WPF and Silverlight
  • ASP.NET MVC 3.0: Beyond the Basics
  • LINQ to Objects and LINQ to XML
  • Entity Framework
  • Model-View-ViewModel for WPF and Silverlight
  • PFx: Task and The Parallel Class
  • Thread Safety and Concurrent Data Structures
  • Building WCF REST Services
  • C# 3.0, 4.0, and 5.0
  • Entity Framework and the Repository Pattern
  • jQuery
  • Cloud Computing for the .NET Developer: IaaS, PaaS, and Patterns
  • The NoSQL Movement, LINQ, and MongoDB
  • iOS Programming with .NET and MonoTouch
  • Design Patterns for Testability (DI, IoC, and unit testing)
  • Reactive Framework for .NET (Rx)
  • WCF Data Services
  • Power Debugging with WinDBG

I had a great time, and as an added bonus I learned some things. I was monkeying for Mark while he was doing the “Entity Framework and the Repository Pattern”. He did two things that I thought were better than I had done in the past. But first some background…

I used to structure my repositories using an interface similar to this:

IEnumerable<T> GetAll() // or sometimes returning an IList
T GetById(TKey id)  // sometimes just taking an object
void Add(T t)
void Delete(TKey id) // sometimes taking a T
void Save()

I may have other interfaces which specialize a particular IRepository to contain additional query methods.
Sometimes when I am implementing the repository pattern I combine it with a session object. This is especially nice when using NHibernate or doing Web work (where the controller method creates the session and closes it before returning). The session will hang on to the context so that different repositories can be called together in a transaction.

Mark pointed out two things that work differently in Entity Framework and LINQ than in other ORMs.
1) Save() doesn’t need to go on the individual repositories anymore it can be moved up into the Session object. This is because SaveChanges() commits all changes across anything using the same context.
2) If you change the All method to return an IQueryable you can remove all of the other Get methods, because they can be built using LINQ.

So the new IRepository looks like:

IQueryable<T> All
void Add(T t)
void Delete(T t)

That is a good simplification, thanks Mark.