Unable to update the EntitySet ” because it has a DefiningQuery and no <> element exists in the <> element to support the current operation.

Silly thing this.

Found this link.

In my case this was caused by not selecting the primary key for the table in SQL Server I was generating the entity set against and then attempting to call the Entity Framework AddObject method with the generated entity. I’m pretty sure that this sort of error will occur though with just about any operation you try against the DB with the entity if you haven’t defined a primary key.

reCAPTCHA with ASP.NET MVC 3 RAZOR using Microsoft.Web.Helpers and jQuery

My goal was to put a reCAPTCHA onto my registration page. I’m building the site using ASP.MVC using the Razor view engine.

This is a holy hellish bitch to figure out how to get working the first time with all the conflicting posts from people on it and then of course some of it just straight up doesn’t work because of bugs in how the packages are installed.

Obviously you could just use Javascript and roll your own reCAPTCHA with MVC, but since all these folks have gone to great lengths to figure out how to do this within the MVC Framework using HtmlHelpers and what not you would think I could just throw a few references in and a couple of lines of code and get it going. Why reinvent the wheel right? No, it’s not that simple.

The first page you might have found is this one.

Now it all looks great and probably worked fine with ASP.NET MVC 2, but with Razor all the HTML elements that are output are escaped. So you end up with <script> instead of an actual script tag. I could not for the life of me figure out how to get around this and I’m sure it is something really simple, but there are few detailed syntax references for Razor out there.

So, now I found another page indicating that Microsoft has their own set of Helpers for this and the library can be added using NuGet.

Of course he highlights the System.Web.Helpers library as the one that is added by this package installer when in reality the library doing the work is Microsoft.Web.Helpers so don’t try looking for your helper method in System.Web.Helpers.

The other issue is that the NuGet package installer for microsoft-web-helpers is messed up (as of this writing) and doesn’t install all the references that are required to use it so if you try to run your web site after installing this package you get a lovely yellow screen error.

To solve this you need to follow this fellow’s instructions to add the missing references.

Once you have that done, you can then add

@using Microsoft.Web.Helpers

to the top of your view and then your call to

@ReCaptcha.GetHtml(publicKey:"YOUR KEY", theme: "red")

should work. At least it did for me.

Also, once you get this all done it’s fairly trivial to make this work properly with jQuery. All you need to do is submit the two recaptcha fields to your controller method that is doing your validation along with the rest of your form fields.

$('#FORMID').submit(function (event) {
            if ($(this).valid()) {
                event.preventDefault();
                $.post('/CONTROLLER/ACTION', { recaptcha_challenge_field: $("input#recaptcha_challenge_field").val(), recaptcha_response_field: $("input#recaptcha_response_field").val()},
                function (data) {
                    $('#result').html(data);
                });
            }
        });

Edit: Today (March 1) I found this page that describes the syntax for outputting raw HTML in Razor. Looks like it just got posted a day before I was working on this. Syntax is below in case you wanted to use the code embedded in the ReCaptcha DLL from Google Code.

@Html.Raw(Html.GenerateCaptcha())

I didn’t actually try this out yet, so YMMV.

Updating Entity Framework EDMX when changes are made to the database.

This isn’t obvious, at least it wasn’t to me and for some reason when I searched for this I didn’t come up with the answer either.

To update the Entity Framework EDMX and sync it with your DB changes you double click on the EDMX in the VS2010 Solution Explorer. This brings up the designer (Model Browser window apparently is what it’s called) with a class layout of your entities. Right click anywhere on the designer surface and you’ll see an option in the dialog to “Update Model from Database.” Click on this and you get brought into the Update Wizard where you can choose the database objects you want to Add (if new), but by default it refreshes existing objects.

One thing the wizard doesn’t seem to do is delete columns from existing objects. Probably some sort of safety mechanism, but if you deleted the column from the database, do you really want to keep it in your entity? Ah well, who knows.

EDIT: Of course right after I write this post I find this page, which still isn’t particularly clear about how you get to the “Model Browser window,” but maybe I’m just dumb.

jQuery UI Slider and IE8 Compatibility Mode / IE7

After implementing the slider control from jQuery UI with our video player I was quite happy with the overall performance and the look and feel, unfortunately I experienced some headaches when it was deployed as the setup I had implemented did not work with IE8 in the compatibility mode. Now, thankfully the app was for internal use where I can tell people not to use IE8 in the compatibility mode, but obviously some were using it that way otherwise I would not have had any complaints.

The whole thing irked me a bit so I figured out how to make it work properly.

The first issue was that the slider did not slide. The Javascript was reporting back that the width of the element was 2 rather than 500 as it did in IE8. I tracked that down to needing to specifically set the size of the DIV that contained the DIV that the player was in. So it ended up as…

I did already have elements within that container div that had a width set to 500px, but the slider in IE7 mode did not expand properly without giving the container it was in a specific width. YMMV.

The other problem I encountered was that while using a UI theme with the slider and having it report progress using the single slider and a background value (in this case a background image) the image would often expand to 100% of the height of the page (though only downward, not up) so you would end up with the progress bar of the slider expanded as a giant block over whatever was below it.

The solution to this was to override these particular styles and give them a fixed height rather than the 100% they are set to by default. In my case I changed them to 2.0em as that fit with the other changes I made to the height of the slider.


Threading and ManualResetEvent vs Thread.Sleep

Found this really interesting post on StackOverflow that clarified the performance difference between using events and the more obvious but less efficient Thread.Sleep().

We have a real-time messaging app that we wanted to wait on calling back the client if a message was not queued up for delivery (to avoid unnecessary callbacks if messages were not being sent). The original implementation used a while loop with a call to thread.sleep, but after a few hundred users were utilizing the system we would get some strange behaviors and performance issues. Not all the time, but some of the time.

Currently the code is being revised to utilize the ManualResetEvent class. The event driven model (not related in this case to .net events) for having the thread wait on certain actions would be the better way to do this and obviously if I knew anything about thread programming in .NET at the time I would have seen this right away, but we live and learn.

In the case of a ManualResetEvent you utilize the Set and Reset calls in combination with the WaitOne() call to indicate that where threads will wait and when they can continue. The Reset event signals the start of the wait for whatever activity needs to be waited on and the Set event indicates when threads can proceed.

Javascript for in statement usage.

I don’t know why I forget the syntax for things like this.

var cars = ["Ferrari","Subaru","Mazda"];

for ( var i in cars )
{
    alert( cars [i] );
}

And since objects in Javascript are also associative arrays you can do things like this.

var object = new Object;

object.FirstName = "Harvey"
object.LastName = "Meeker"
object.Hobby = "Cars"

for (var item in object)
{
   document.write(item + " " + object[item] + "
") }

Switching between C#, Javascript and all the rest it’s the simple things my brain dumps out.

WordPress Google Syntax Highlighting with XHTML

Well, I set up this blog and then wanted a code syntax highlighter, because those are nifty. I installed this plugin and all seemed well. Then though I noticed the little XHTML link on the right side of the blog that is installed there by default and I clicked on it and it went over to the W3C validator where my new blog validated improperly! And all due to my new syntax highlighting plugin.

Well, it seems that this plugin is based on an older version of the Google Syntax Highlighter which doesn’t conform to standards.

http://code.google.com/p/syntaxhighlighter/wiki/Usage

The new one apparently works a bit differently in how it selects DOM elements.

http://alexgorbatchev.com/wiki/SyntaxHighlighter:Usage

The old one uses a pre tag with a “name” attribute as the selector and XHTML 1.0 doesn’t know from a name attribute in a pre tag.

function FindTagsByName(list, name, tagName)
	{
		var tags = document.getElementsByTagName(tagName);

		for(var i = 0; i < tags.length; i++)
			if(tags[i].getAttribute('title') == name)
				list.push(tags[i]);
	}

So I altered the selector code a little so it finds by the “title” attribute instead. Perhaps I’ll just update the plugin code to use the new version of the SyntaxHighlighter, but for now this seems to work fine.

Winforms, DataGridViews and overriding events.

WinForms are archaic and outdated with the new hotness that is WPF (not really), but I still use them.  Not often enough to know much in detail about them, but enough to get myself into trouble.

I made a small app with a data entry/update form and then on another tab added a DataGridView that would display the entered data.  The nice thing about the DataGridView in WinForms as opposed to working with web controls is that you get things like sorting for free when you click on a column header.

My problem came about when I wanted to give the user the ability to click on a row in the grid and have that record load itself into the entry form on the other tab.  I overrode the CellMouseClick event and loaded the record based on the key from that row, but that in turn killed the auto-sorting of the grid when you clicked on the header.

private void emplGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            gridSelection = emplGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
            tabControl1.SelectTab("tabPage1");
            FindLoadEmployee(sender);
        }

Luckily I came to the quick conclusion that I could tell when the header cells were being clicked based on their row index and in that case a simple return statement took care of the problem.

private void emplGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            gridSelection = emplGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
            tabControl1.SelectTab("tabPage1");
            FindLoadEmployee(sender);
        }

There’s probably a better way to do this or a better event to utilize given that I’m not really a WinForms developer and just sort of hack away at this, but this seemed to work for me without much issue.