Noah Blumenthal's Blog

October 25, 2009

Blog moved

Filed under: Uncategorized — noahblu @ 1:01 am

Head over to for the new blog.  I’m not sure how long I’ll keep this one up, so update your bookmarks!

September 25, 2009

When (not) to use volatile

Filed under: Uncategorized — noahblu @ 4:07 pm

I was banging my head against a wall when I found this post by Jerome Laban about the volatile keyword.  I made the mistake of thinking that volatile would be sufficient in this situation:

   1: private volatile int _counter = 0;

   2: ...

   3: private void SomeMethodThatIsCalledByMultipleThreads()

   4: {

   5:     _counter++;

   6: }

and I was surprised when some of my unit tests were not running correctly (on a side note, I usually unit test multi-threading issues by issuing a command 100 or 1000 times.  I’m interested in hearing how you test that kind of stuff).

Turns out that if I thought about it a little more I would have realized that this won’t do what you (might) expect.  You see the volatile keyword just tells the system never to cache this variable – that’s especially important in multi-processor systems (and who doesn’t have at least 2 cores nowadays?) where each processor might have a different cache of the variable value.

So by using the volatile keyword you’re telling the processor to always get the latest version of the variable from memory.  So why is the above code not thread safe?

Well, remember that the incrementing a variable is a multi-step process:

  1. load variable into a register
  2. increment
  3. save back from the register

Now the thread might pause at any point in this process!  What happens if Thread A does step 1 and then gets paused, then Thread 2 does step 1?  After both threads run, _counter will only have incremented by 1!  So even though you’re always reading the current value, your increment isn’t thread safe.

So this is where you say “hey – I don’t really need the volatile keyword here.  I need a lock instead”.  And you’d be right:

   1: private volatile int _counter = 0;

   2: private object _myLocker = new object();

   3: ...

   4: private void SomeMethodThatIsCalledByMultipleThreads()

   5: {

   6:     lock(_myLocker)

   7:         _counter++;

   8: }

September 17, 2009

When Rexex is EVIL (or how to lock up an app/server with simple regex)

Filed under: Uncategorized — noahblu @ 2:05 pm

Terrific powerpoint on ReDoS over here

It is believed that Regex performance is fast, but the truth is that the Regex worst case is exponential.  In this presentation we will show how an attacker can easily exploit the Regex worst case and cause an application DoS.

September 16, 2009

Rendering ViewPage to random stream (or not)

Filed under: Uncategorized — noahblu @ 3:09 pm

I had this crazy idea.

My company has some Response Filters that replace tokens in the outputted HTML into some other data.  Now that we’re moving over to MVC I figured hey — maybe I can do a better job with these.  You see, these Filters have inline HTML — that is, they use a StringBuilder to create the necessary HTML to replace the token.  That’s no fun — first of all it’s not too pretty, but also, what happens when the designer wants to make a change?

My crazy idea was to call an Action from within the Filter.  I figured this would have a couple benefits:

  1. Decouple UI from the data (that’s what MVC’s all about right?)
  2. Provide 1 stop for this information (so now the same method can be called from within the web app, without the need for a token, and the same method will be called from the filter to replace the token)

I figured the process would go something like this:

  1. Create a StreamWriter that points to a MemoryStream
  2. Create a faux Response object that uses this StreamWriter
  3. Have the ControllerFactory.Current create the controller
  4. Invoke the Action on the Controller using the in-memory Response
  5. Since the output will be sent to MemoryStream, just read it from there and replace the token

Sound simple, right?  It’s not!

First of all, HttpContext is a magical, super-inter-dependent beast.

   1: IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

   2: // I need an HttpRequest    

   3: HttpRequest httpRequest = new HttpRequest(HttpContext.Current.Request.FilePath, HttpContext.Current.Request.Url.AbsoluteUri, string.Empty);

   4: // Here's the stream I'm going to put the response into

   5: MemoryStream memStream = new MemoryStream();

   6: // I need a Response to hold the stream

   7: HttpResponse response = new HttpResponse(new StreamWriter(memStream));

   8: // I need an HttpContextBase, which wraps the HttpContext, which requires the Request & Response

   9: HttpContextBase httpContext = new HttpContextWrapper(new HttpContext(httpRequest, response));

  10: // I need a RequestContext to feed into the Execute method on my Controller

  11: RequestContext requestContext = new RequestContext(httpContext, new RouteData()

  12: {

  13:     Values = { { "controller", "Home" }, { "action", "SomeAction" } }

  14: });

  15: IController controller = factory.CreateController(requestContext, "Home");

  16: controller.Execute(requestContext);

Man, that was a lot of work!  And you know what?  It doesn’t even work!

That’s right, get used to it because this post is all about things not working.  If you’re looking for a quick fix, you might want to visit google because you won’t find it in this post.  The above code generates the following Exception on line 16:

The SessionStateTempDataProvider requires SessionState to be enabled.

And a quick peek at Reflector tells me this is because the HttpContext (that I’m passing in) has a Session object that’s null.

Ok, so I came up with another, simpler and more elegant way of accomplishing this, if not a little more dependent:

   1: // Queue up all my HttpContext dependencies

   2: HttpRequest httpRequest = new HttpRequest(HttpContext.Current.Request.FilePath, HttpContext.Current.Request.Url.AbsoluteUri, string.Empty);

   3: MemoryStream memStream = new MemoryStream();

   4: HttpResponse response = new HttpResponse(new StreamWriter(memStream));

   5: HttpContextBase httpContext = new HttpContextWrapper(new HttpContext(httpRequest, response));


   7: // In reality I'd use reflection for this, but as you'll see the code won't work anyway so why bother?

   8: HomeController homeController = new HomeController();

   9: ControllerContext controllerContext = new ControllerContext(httpContext, new RouteData(){

  10:     Values = {{ "controller", "Home"}, { "action", "SomeAction"}}

  11: }, homeController);


  13: // Again, I would use reflection but it's a waste of time

  14: ActionResult result = homeController.SomeAction();

  15: result.ExecuteResult(controllerContext);

Looks pretty good, right?  What I’m doing is creating the Controller (in a non proof-of-concept I’d use reflection to queue that up) and then calling the necessary Action which returns an ActionResult.  I’m then running the ExecuteResult method on said ActionResult passing in my ControllerContext which has a reference to my HttpContext which in turn writes data to my MemoryStream.

However, this also doesn’t work as (I) expected.  What ends up happening is that the MemoryStream length remains 0 but the output from the ActionResult ends up on the calling page – at the top of the page.

I debugged against the MVC source code and you want to see the culprit?  ViewPage.cs, line 110:

   1: public virtual void RenderView(ViewContext viewContext) {

   2:     ViewContext = viewContext;

   3:     InitHelpers();

   4:     // Tracing requires Page IDs to be unique.

   5:     ID = Guid.NewGuid().ToString();

   6:     ProcessRequest(HttpContext.Current);

   7: }

Notice the last line there:


So, no matter what you do, you’ll still be passing the HttpContext.Current (with its StreamWriter) back to the Page to get rendered.  Damn!

So what are the options here? 

I could inherit from ViewPage and override the RenderView.  That might work, but could cause other bugs because HttpContext is still super duper dependent and to debug I’ll have to head on over to the .NET Framework code (which, luckily, is available).  I’ll also probably want to create a new class for my Controllers (which we already have, actually) to inherit from Controller so that I can create some sort of View method that will return my special inherited ViewPage that calls this overridden RenderView.

This no longer strikes me as quite the elegant solution I first assumed it would be.

I’m not quite sure the direction I’m going to take this now.

August 24, 2009

MCTS Test Information

Filed under: Uncategorized — noahblu @ 4:12 pm

I passed the MCTS last week and figured people might want to know a little about the test and what I did to pass.

First of all, I used the Microsoft Press Self Paced study guide for the 70-562 test (available on Amazon).  It is a BIG book, but a lot of it is fluff (like lesson reviews and such), and there’s plenty you can skip if you feel comfortable with the material.  The book comes with a 15% off test voucher making the test $106 or so (down from $125).

It’s not a bad idea to take tons of practice tests from different places — I saw a link from MS that says they’ll pay for your second test if you fail the first time, but why take them up on the offer?

Regarding the test itself, it’s pretty straight forward save for a couple things.  For the most part, it’s multiple choice with 4 choices (though some questions have a bunch of checkboxes and you might have to choose 2 or 3 options out of the lot).  Now on every multiple-choice question there are 2 answers that if you aren’t completely brand new to ASP.NET you can throw out right away; that leaves 2 possible choices for each question.

Sometimes they are kind of tricky like if they ask something where you have 2 code snippets that look EXACTLY the same except one reads has something about “DataSource=” and one has “DataSourceID=”.  When there’s a lot of filler above and below that line it’s hard to see that line though.  That kind of stuff is what I mean by tricky.  Especially because the test is kind of new, that kind of thing made me think “wait, is there a mistake here?  these two answers are exactly the same!” until I re-read and re-read and re-read.

One of my biggest complaints about the practice tests I took was in regards to the questions that ask you to choose multiple answers.  The test tells you how many to choose (e.g. there are 7 options, choose 2), but some practice tests don’t do this.

Also, there was definitely 1 question on the test that was easy.  I mean really easy.  Too easy actually.  And having 4 choices I was very tempted to double-guess myself because it was just too easy.  You figure MS is tricking you.  But the test in that regard is pretty straight forward.  I got that one right by not over analyzing, so just keep that in mind.  If it’s the answer, it’s the answer.

August 18, 2009


Filed under: Uncategorized — noahblu @ 5:47 pm

Passed the 70-562 this morning.  Officially Microsoft Certified Technology Specialist in ASP.NET 3.5

August 3, 2009

Noah Blumenthal is an MCP

Filed under: Uncategorized — noahblu @ 5:12 pm

I’m now a Microsoft Certified Professional!  I took the 70-536 (.NET Framework Application Development Foundation) test this morning and aced it :).  Next up, 70-562 I think…

I’m excited!

July 27, 2009

jQuery $.extend() method with plugin called multiple times (note to self: RTFM!)

Filed under: Uncategorized — noahblu @ 4:22 pm


jQuery’s $.extend() method is used to merge two (or more) objects.  It’s very useful in plugin development since it can be used to merge user defined options with default options for a plugin.  I ran into an issue today trying to debug a plugin I wrote (jquery inline row editor) whereby settings were getting all screwed up if it was used multiple times on a page (ie a page with multiple editable tables).  I’m ashamed to say it, but it took me a while of debugging before realized what the issue was.  Note to self: RTFM!!!

Take the following snippet:

   1: $.fn.inplacerowedit = function(options) {

   2:     var ops = $.extend($.fn.inplacerowedit.defaults, options);

   3:     .....

   4: }

Now what I didn’t take into account is that the $.extend() method doesn’t just spit out a merged object based on all the parameters, it merges all objects sent in as parameters into the first parameter.  So in this example above, ops == $.fn.inplacerowedit.defaults which itself is a combination of what it started out as and the options parameter.  Well that now makes sense why things got screwed up when this was called multiple times, huh?

So the solution was to set the first parameter of the $.extend() method to a blank object {} and have jQuery append EVERYTHING to that and set THAT to ops like so:

   1: $.fn.inplacerowedit = function(options) {

   2:     var ops = $.extend({}, $.fn.inplacerowedit.defaults, options);

   3:     .....

   4: }

OR I suppose you could just declare ops and then use that as the first parameter.

July 10, 2009

Retrieve OR Instantiate ModelBinder

Filed under: Uncategorized — noahblu @ 2:25 am

Sometimes you want your model binder to retrieve an object if it exists or instantiate it if it doesn’t.  For instance I have a create page and an edit page for my models so on the create page I want the model to be instantiated but I also have an edit page that posts back the ID of the model and I’d love the entity to be retrieved from the DB for further edits.  SO…..

I created a ModelBinder that actually takes two different model binders and tries to bind with each.  If it works the first time, great, otherwise try the backup.  In my case that’s Retrieval with a backup of Instantiate.  This could be used for many different purposes though, so don’t let the class name throw you off:

   1: public class RetrieveOrInstantiateModelBinder : IModelBinder

   2: {

   3:     private IModelBinder _retrievalBinder;

   4:     private IModelBinder _instantiationBinder;

   5:     public RetrieveOrInstantiateModelBinder(IModelBinder retrievalBinder, IModelBinder instantiationBinder)

   6:     {

   7:         _retrievalBinder = retrievalBinder;

   8:         _instantiationBinder = instantiationBinder;

   9:     }

  10:     #region IModelBinder Members


  12:     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

  13:     {

  14:         object obj = _retrievalBinder.BindModel(controllerContext, bindingContext);

  15:         if (obj == null)

  16:             obj = _instantiationBinder.BindModel(controllerContext, bindingContext);


  18:         return obj;

  19:     }


  21:     #endregion

  22: }

Model Binder that retrieves from DB

Filed under: Uncategorized — noahblu @ 2:20 am

Many times I need a model binder that will retrieve my model from a repository so that I can perform updates.  Here’s what I came up with.

   1: public class EntityRetrievalBinder<T, TRepository> : IModelBinder

   2:     where TRepository : IRepository<T>

   3: {

   4:     #region IModelBinder Members


   6:     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

   7:     {

   8:         var name = bindingContext.ModelName + ".ID";

   9:         ValueProviderResult idResult;

  10:         try

  11:         {

  12:             if (bindingContext.ValueProvider.TryGetValue(name, out idResult))

  13:             {

  14:                 Guid id = new Guid(idResult.AttemptedValue);

  15:                 var repository = StructureMap.ObjectFactory.GetInstance<TRepository>();

  16:                 T obj = repository.FindById(id);

  17:                 if (obj == null)

  18:                     throw new ArgumentException("Object not found");

  19:                 return obj;

  20:             }

  21:         }

  22:         catch (Exception e)

  23:         {

  24:         }

  25:         return null;

  26:     }

I changed a couple things for this post, but basically the logic is simple.  What this does is just retrieve the repository from StructureMap and then try to run the Find() method which takes a Guid ID as its only parameter.  Either this will return a null (if no ID was posted) or an object of type T OR it might throw an exception if the user posted an ID but that ID was not found.  I’ll show you in the next post how I tie everything together.

Next Page »

Create a free website or blog at