Feed Subscribe
Exception has been thrown by the target of an invocation.


Match foreign key property with navigation property in Entity Framework metadata

by ondrejsv 31. August 2010 17:04

Entity Framework 4 brought a new way of dealing with references – directly through their foreign key value. While it takes off some abstraction, it’s more friendly to common situations in practice (e.g. selecting from drop down lists) and also it enables you to change a reference without having to load either the old referenced entities or the new one. Also note that this feature is optional; you won’t have your model polluted with foreign keys if you do not want.

This brings some new challenges in my scripts and old code dealing with EF metadata. Now I have to differentiate between “ordinary” simple properties and foreign key properties. Fortunately, it’s not that difficult.

You can get the matching foreign key property to a given navigation property by calling the GetDependentProperties() method which returns exactly entity properties which are dependent ones in the relationship. Note that we’re playing in the conceptual model area (which is what I want) and the foreign key column as implemented in the database could have different name. Also note that if there is a foreign key property, the method should return only value. If there isn’t (maybe you unchecked the “Include foreign key columns in the model” option in the Data Model Wizard), the collection will be empty.

And as usual some code for demonstration. It just outputs the list of all navigation properties in all entities and their corresponding foreign key property names:

var cx = new ModelContainer(); var mw = cx.MetadataWorkspace; var entities = mw.GetItems<EntityType>(DataSpace.CSpace); foreach (var en in entities) { Console.WriteLine(en.FullName); foreach (var np in en.NavigationProperties) { Console.WriteLine("- navigation property found: " + np.Name); if (np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One) { Console.WriteLine("-- is to one"); Console.WriteLine("--- its FK property is " + np.GetDependentProperties().ToList()[0].Name); } } }

Tags:

When BeginForm is not BeginForm<T>

by ondrejsv 30. August 2010 16:03

or why the ASP.NET MVC 2 client validation fails when you use Microsoft.Web.Mvc (aka MvcFutures)?

There’s an incredibly useful set of extension methods in the MvcFutures called BeginForm<T>. These methods provide an alternative type-safe way of building MVC forms instead of the old string based BeginForm. Instead of:

<% using (Html.BeginForm("Submit", "ThreadedInputController")) { %>

you just write

<% using (Html.BeginForm<ThreadedInputController>(c => c.Submit()) { %>

No strings here, everything type-safe.

But when you enable fantastic client side validations with the BeginForm<T> constructed form you end with a JavaScript error “Object Required” somewhere deep inside the MicrosoftMvcValidation.js:

image

on the line:

formElement[Sys.Mvc.FormContext._formValidationTag] = this;

The cause of this is that the new BeginForm<T> and the old BeginForm do not have a common implementation; in fact they are completely separated. The client side validation model requires all HTML forms have an ID value and also the framework expects this ID value to be set in the FormContext.FormId property of the current ViewContext. The original BeginForm does exactly this. If you don’t provide the form ID yourself, it will generate one in the form “formN” where N is the sequence number of the form.

It’s nothing difficult to fix the implementation but you must rename your extension methods to avoid conflict with the MvcFutures implementation or directly fix it in the MvcFutures and build your own version.

Here’s the fix (I renamed methods to the BeginFormA<T>):

private static readonly object _lastFormNumKey = new object(); private static int IncrementFormCount(IDictionary items) { object lastFormNum = items[_lastFormNumKey]; int newFormNum = (lastFormNum != null) ? ((int)lastFormNum) + 1 : 0; items[_lastFormNumKey] = newFormNum; return newFormNum; } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an Extension Method which allows the user to provide a strongly-typed argument via Expression")] public static MvcForm BeginFormA<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method, IDictionary<string, object> htmlAttributes) where TController : Controller { TagBuilder tagBuilder = new TagBuilder("form"); if (helper.ViewContext.ClientValidationEnabled && htmlAttributes["id"] == null) { // forms must have an ID for client validation int formNum = IncrementFormCount(helper.ViewContext.HttpContext.Items); var formId = String.Format(CultureInfo.InvariantCulture, "form{0}", formNum); tagBuilder.GenerateId(formId); } tagBuilder.MergeAttributes(htmlAttributes); string formAction = Microsoft.Web.Mvc.LinkExtensions.BuildUrlFromExpression(helper, action); tagBuilder.MergeAttribute("action", formAction); tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method)); helper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); var theForm = new MvcForm(helper.ViewContext); if (helper.ViewContext.ClientValidationEnabled) { helper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"]; } return theForm; }

You can download the whole static class with the extension methods.

Note: This bug is still not fixed in the ASP.NET MVC 3 Preview 1.

Tags: ,

Globalization is not an enemy 2 (N2CMS case)

by ondrejsv 28. August 2010 21:11

Some time ago I wrote an article about failures to properly write code concerning globalization, i.e. to write the code in such a way that it does not crash and works as intended when running in environments with regional settings you have not anticipated.

I’m playing with the wonderful N2CMS project these days. So far I’ve really enjoyed it. One of my first attempts to get known with it was to create a simple page with a date time field. They have an out-of-the-box date time control to render the field. As you can guess, I don’t have the en-US regional settings. Here’s the field:

image

One text box with a small nice calendar button for the date part and another text box sitting next for the time part. Let’s choose a date with the calendar.

image

It even recognizes the Slovak date pattern (DD. MM. YYYY):

image

So far so good. Let’s save the page and again open for edit. Bump:

image

Something very wrong happened. After some researching I found the DatePicker control’s source and there’s a quite ugly code :-):

if(value != null) { string[] dateTime = value.Split(' '); DatePickerBox.Text = dateTime[0]; if (dateTime.Length > 1) TimePickerBox.Text = dateTime[1].EndsWith(":00") ? dateTime[1].Substring(0, dateTime[1].Length - 3) : dateTime[1]; else TimePickerBox.Text = string.Empty; if (dateTime.Length > 2) TimePickerBox.Text += " " + dateTime[2]; // This could be AM/PM } else { DatePickerBox.Text = string.Empty; TimePickerBox.Text = string.Empty; }

I don’t know the reason behind that but parsing a datetime string on your own devices is a very bad idea.

And fix is simple. Just rely on the .NET Framework to do all the magic:

if(value != null)
{
    DateTime parsed;
    if (DateTime.TryParse(value, out parsed))
    {
        DatePickerBox.Text = parsed.ToShortDateString();
        if (parsed.Second == 0)
            TimePickerBox.Text = parsed.ToShortTimeString();
        else
            TimePickerBox.Text = parsed.ToLongTimeString();
    }
}
else
{
DatePickerBox.Text = string.Empty;
TimePickerBox.Text = string.Empty;
}

Disclaimer: My goal is not to whine about the N2CMS quality. No, I think that N2CMS is really a wonderful project and I’m a fan of it :-) Give it a try!

Tags:

It’s time to throw away greedy Firefox

by ondrejsv 28. August 2010 14:47

A quick quiz for today. What application that ate 1,3 GB of my memory and 50 % CPU I forcefully ended in the Task Manager to give me such a picture?:

image

Yes, Mozilla Firefox. What I dared to do? Download 3 files 300 MB each in size. Apparently Firefox Download Manager holds them in the memory until it downloads them and only then flushes them to disk! Complete fail. I had to switch to the Internet Explorer 8 to download them all (without any problem).

(Yes, I know about 3rd party download managers, I use one of them, but not for such small files.)

Tags:

VS2010 Bug: Entity Data Model Wizard disappears after selecting “Generate from Database”

by ondrejsv 6. June 2010 17:55

Today I found another annoying bug in Visual Studio 2010. I often work connected to my company LAN via VPN and I have generated some entity data models from databases over the wire in the past. Entity Data Model Wizard which runs when you add a new “ADO.NET Entity Data Model” item in Visual Studio has a “nice feature” that it remembers all connections you entered into it. Of course, if you disconnect from LAN, those connections are not available. If you are unlucky enough, one of those connections may be the first one and default in the combobox where you can select an existing connection to base your EDMX on. Visual Studio probably tries to get information on tables or whatever from the database but if the database is not reachable, it fails very silently and closes the window instead of letting you to select another connection or create a new one. #fail

Fortunately, these connections are the same you see in the Data Connections node of the Server Explorer. So delete all of those which are remote and you have no connection to them any more and the Data Model Wizard would behave properly.

Tags: