ross dickinson: web and desktop software developer

If you're using Microsoft's unobtrusive ajax library with your MVC3 project, you might come across a problem if you're trying to add an error handler to one of your Ajax.BeginForm or Ajax.ActionLink calls.

The problem lies in the library's handling of the data-ajax-failure attribute that gets added to an ajax form/link. Basically, the library just doesn't execute the method after finding it. The problem line of code is line 98 of jquery.unobtrusive-ajax.js:

$.extend(options, {
    // other handler code removed
    error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
});

To fix this, you need to change line 98 to this:

 

$.extend(options, {
    error: function() {
        getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"]).apply(this, arguments);
    }
});

Operation could destabilize the runtime

by Ross on December 2, 2011 at 3:54 PM under .NET

If you've been using linq to sql then you may have come across this baffling error before:

[VerificationException: Operation could destabilize the runtime.]
Read_SomeEntityClass(ObjectMaterializer`1 )
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext()
System.Linq.Buffer`1..ctor(IEnumerable`1 source)
System.Linq.Enumerable.ToArray(IEnumerable`1 source)

It would be a little nicer if the error message explained what operation could destablize the runtime and why, but alas, it does not.

So, what's causing the problem?

At least in some instances, this error will pop up because your entity class has a readonly field being used for storage. When linq to sql attempts to set a value on that field, it can't, so that error is thrown. If you want to be technical about it, you can set a readonly field's value through reflection, but it's bad practice. It's a good thing linq to sql doesn't do that, but the error it throws could be far more helpful.

IE7 Adds White Space and Line Breaks After Hidden Input Fields

by Ross on November 30, 2011 at 12:39 PM under

If you've ever worked with hidden fields in IE7, you may have stumbled across this when viewing code like this:

<form>
    <input type="hidden" />
    <span>Hi, I'm text!</span>
</form>

You expected to see this: But you end up with this:
Hi, I'm text!
Hi, I'm text!

This is due to a bug with how IE7 handles hidden input tags directly inside a form element. For whatever reason, when IE7 sees a hidden input tag with any white space or line breaks between the end of its tag and the beginning of the next tag, it adds an empty line to the rendered version. This seems to only effect direct descendents of the form element, though.

You can fix this in a few ways:

  1. The "Hacky Fragile" way: Remove any white space between the hidden input tag and the next tag.
  2. The "Meh" Way: Put all your hidden inputs at the end of the form tag.
  3. The "Recommended" way: Wrap the hidden inputs inside of another tag, like a div.

The Problem with Microsoft's ASP.NET Forums

by Ross on November 23, 2011 at 4:17 PM under ASP.Net

As an ASP.NET developer, most people end up at the ASP.NET Forums at one time or another. While I'm sure Microsoft wants their forums to be the be-all end-all of ASP question-and-answer sites, the truth is that the advice given is generally lacking in quality and coherency. Now, I am generalizing a bit. I primarily hang out in the Web Forms subsection, so my experience is limited to this area.

So, what's wrong with the forums?

The replies always strike me as a case of "firsties!", with other users clamoring to get their answer in first. They see their personal user point count, displayed on every single post, as something of pride. I'm all for getting your answer in first, assuming it's right. Frequently, the first several answers to a post can be blatantly wrong. Either the user didn't understand the original question to begin with, or they post code samples with error laden syntax. I get the impression that the user who wrote the answer didn't actually see if the answer they supplied would work.

There's also the issue of users who do nothing but link to other sites that "might help them". I'm all for referencing external resources, except:

  1. Far too often, and this is a problem that's global to pretty much any web forum, links become stale and no longer work. What could have been an answer for another user months/years later is now lost since the user didn't post anything but a link.
  2. The person answering should atleast summarize what the link is about. At least indicate that they understand what the information in the link was talking about. I've seen people who just haphazardly link to things without even reading it, including links to WinForms documentation(wrong part of the framework), or even links to java documentation(not even remotely useful for the question at hand, which specifically had to do with capabilities of csharp and the .NET framework).

Microsoft would really benefit from having moderators who can cleanup the painfully wrong answers from the site. Or even, instead of only allowing the original poster to mark a post as the answer, let everyone else upvote and downvote posts in terms of quality. I can't think of how often I've seen the accepted answer not actually work, but a post further along actually does.

In the mean time, I stick to StackOverflow in order to get quality responses to questions. Though, I do try to help out on the ASP.Net forums.

ASP MVC's EditorFor and DisplayFor Templates

by Ross on November 18, 2011 at 1:23 PM under ASP.Net

I was wracking my brain the other day while trying to figure out how to get an editor template to properly bind to the ViewModel when using Html.EditorFor(m => m.ModelProperty). On the clientside it seemed to visually render ok, but something was amiss. What was wrong?

  1. The rendered input tag was missing the unobtrusive validation attributes that I was expecting.
  2. The name value of the input tag wasn't "ModelProperty" like I was expecting, but "ModelProperty.ModelProperty".

So why was this happening? Apparently, when inside an editor or display template, calling methods like Html.TextBox or Html.Label with the model's property name in it causes the template to bind to the dynamic ViewModel created for that template's instance, instead of the original ViewModel that the property originally came from.

To get around this, all you need to do from your template is call Html.TextBox(""), Html.Label(""), or any of the other helper methods. Just passing in an empty string fixes the problem!

EnsureID, ClientID and ClientIDMode

by Ross on September 16, 2011 at 11:39 AM under ASP.Net

Noticed this annoying quirk today while working on a custom WebForms control. Calling EnsureID will not populate the ClientID property if the control's effective ClientIDMode is set to Static. No idea why! EnsureID will still populate the ID properties, but if you need the ClientID for client-side javascript, you'll need to find other ways around. I opted to go this route:

public override string ClientID
{
    get
    {
        EnsureID();
        if (!string.IsNullOrWhiteSpace(ClientID))
        {
            return ClientID;
        }
        if (!string.IsNullOrWhiteSpace(ID))
        {
            return ID;
        }
        throw new InvalidOperationException("Where's the ClientID for this DateTimePicker?");
    }
}

Preventing Unnecessary DataBinding in ASP.Net

by Ross on June 29, 2011 at 2:02 PM under ASP.Net

If you're looking to reduce the amount of sql calls your ASP WebForms page uses, you may wanna check that you're not calling the Controls property on any class that inherits from CompositeDataBoundControl. The Controls getter does the following:

  1. Calls EnsureChildControls.
  2. Calls CreateChildControls.
  3. Calls EnsureDataBound.
  4. Performs whatever data binding needs to occur.

This can eat up resources if you have a data source that's returning hundreds of thousands of rows prior to setting limiting parameters!

Canceling Remote Desktop File Transfers

by Ross on April 7, 2011 at 10:05 PM under

Every so often when I'm transferring files over remote desktop from one Windows 7 desktop to another, I'll need to cancel the transfer. Sometimes, the "Transferring Files" dialog will get stuck on the "Cancelling..." screen and never make any further progress. Quickest way to fix this is to kill the rdpclip process on the remote machine.

ASP.Net 4 ClientIDMode and Validators

by Ross on March 24, 2011 at 1:51 PM under .NET | ASP.Net

Just a quick note. ASP validators(like RequiredFieldValidator) do not work when validator's ClientIDMode is set to a value other than AutoID. This happens either by explicitly setting a value, or the validator inheriting it from a parent control. The only work around, so far, is to make sure your validator has AutoID set.

VirtualPathProvider and ScriptManager conflict.

by Ross on January 25, 2011 at 8:05 PM under .NET | ASP.Net | Programming

I spent this afternoon working on a custom VirtualPathProvider for two websites we have at work. We need to share resources(master pages, themes, scripts, etc) between the two and I figured embedding resources in a separate project would be the best bet. The VirtualPathProvider implementation takes any old path its given(like "/resources/style.css") and looks to see if there's an embedded resource that matches. This worked out great after I got around some annoying implementation details(MSDN documentation on VirtualPathProvider is kind of terrible).

Then I got stumped. On some pages everything would work as expected. The page would include all the referenced embedded resources and load without a hitch. On other pages, though, the same reference would result in an "Directory not found" HttpException for no apparent reason. After tearing my hair out trying to find something wrong with my VirtualPathProvider, I went to look at the full stacktrace of what was wrong. I probably should have done that in the first place seeing as my problem wasn't specifically being thrown by my VirtualPathProvider class.

[HttpException (0x80070003): Directory 'C:\Solutions\Website\Resources\Dir' does not exist. Failed to start monitoring file changes.]
System.Web.FileChangesMonitor.FindDirectoryMonitor(String dir, Boolean addIfNotFound, Boolean throwOnError)
System.Web.FileChangesMonitor.StartMonitoringPath(String alias, FileChangeEventHandler callback, FileAttributesData& fad)
System.Web.Caching.CacheDependency.Init(Boolean isPublic, String[] filenamesArg, String[] cachekeysArg, CacheDependency dependency, DateTime utcStart)
System.Web.Caching.CacheDependency..ctor(String[] filenames)
System.Web.Script.Services.WebServiceData.GetWebServiceData(HttpContext context, String virtualPath, Boolean failIfNoData, Boolean pageMethods, Boolean inlineScript)
System.Web.Script.Services.PageClientProxyGenerator.GetClientProxyScript(HttpContext context, IPage page, Boolean debug)
System.Web.UI.ScriptManager.RegisterServices()
System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e)
System.Web.UI.Page.OnPreRenderComplete(EventArgs e)
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

What's ScriptManager doing? Beats me, but I looked into it and came across this: HttpException when serving a page with a ScriptManager using a Virtual Path Provider

It turns out that, prior to ASP 4.0, the ScriptManager control has a bug that causes it to ignore any custom VirtualPathProvider classes whenever it does whatever it does internally. This only happens when the ScriptManager's EnablePageModes property is set to true. Setting this to false immediately fixed my problem. That may not solve everyone's problem, though. There's a hotfix available for this specific issue, though I can't vouch for it.

 

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github