Monday, August 16, 2010

Html.ActionLink Displaying The Word Length In The URL - What?

Don't you just love crazy weirdness when you create urls? I sure do....NOT! Sometimes the smallest things can provide you with the biggest pain - especially when you are pressed for time. I ran across a crazy little problem in ASP.NET MVC 2 with an url I created using Html.Actionlink.

I wanted an url that looked like this -

http://www.mysite.com/Project/Pages/someGuidId.

I used the following Html.Actionlink -

<%= Html.ActionLink("View Project Pages", "Pages", "Project",
new { id = page.PageId })%>


This generated an url with a Length property at the end of it -

http:/www.mysite.com/Project/Pages?Length=7

What in the world is that? Length is NOT my friend! Fear not though! This error is very easy to solve with minimal effort. Adding one value makes the difference. I just needed to change my Html.Actionlink to the following:

<%= Html.ActionLink("View Project Pages", "Pages", "Project",
new { id = page.PageId },
null)%>

That nice little null does the trick quite nicely and makes everyone happy!

Smooches,

Kila

Problem:
<%= Html.ActionLink("View Project Pages", "Pages", "Project",
new { id = page.PageId })%>

generates http:/www.mysite.com/Project/Pages?Length=7

Solution:
<%= Html.ActionLink("View Project Pages", "Pages", "Project",
new { id = page.PageId },
null)%>

Saturday, August 14, 2010

NHibernate Not Saving And You Get A One Way To Fix Unexpected row count: 0; expected: 1 Error In NHibernate

I love NHibernate and I love Fluent NHibernate. Fluent NHibernate allows you to use NHibernate without the XML configuration files that would normally be required by NHibernate. In fact, by using the AutoMap feature of Fluent NHibernate, you can use NHibernate without writing ANY additional lines of code beyond adding virtual to your POCO classes. That sounds great.

Sometimes, however, NHibernate can give you error messages that aren't as intuitive as they could be. This is a small complaint because we software developers can always figure out how to do things....right? So you have created your classes, set up Fluent NHibernate and tried to save something only to find that NHibernate is not saving your entity. You try and try, but NHibernate will not save your entity. You look at the error message and you see the following:

Unexpected row count: 0; expected: 1

That message doesn't look good. Why won't NHibernate save? Whatever could the NHibernate problem be? Well I don't know all of the reasons that this error message might occur, but I do know one reason that I'm going to tell you about.

If you are using GUIDs or INTs as the primary key on your entity, NHibernate needs to see that entity id as empty so that it will know that the item you are saving is new. You will get the error shown above if you try to add the GUID or INT yourself. I know. I know. This is kind of counter to how you do things in Entity Framework, but isn't NHibernate smart? It can and will generate the id for you so you can sit back and relax (well you can't really relax, but NHibernate will create the id for you). To solve the problem, do not try to assign an int or Guid to your id. When NHibernate sees that the value is empty, NHibernate will recognize this to be a new item and perform a database Insert instead of an Update.

Wasn't that simple. I just told you to do nothing and I solved your problem.
Hope this saves you some time!

Smooches,

Kila

Problem:

System.MissingMethodException: No parameterless constructor defined for this object! Does This Error Really Mean What It Says?

System.MissingMethodException: No parameterless constructor defined for this object. What a great error message right? If you are using ASP.NET MVC, You may be fooled into thinking that receiving this message always means that you need to add something to your controllers. It doesn't! That's right - I said it doesn't always mean that. This message, which is about as helpful as a porcupine in your bathtub, can often point to an issue with the routes in your application.

Instead of going through a lengthy explanation about this error, I'm just going to get to the point. This error can be caused by having an incorrect route defined in your global.asax file. To troubleshoot this error, check your global.asax file and make sure that any parameter that is not a required parameter has the UrlParameter.Optional item. For example, id = UrlParameter.Optional. This error can occur if you have a route defined without an action and then you send in an url WITH the action. Making the action equal to UrlParameter.Optional can, in some instances, solve the problem.

Smooches,
Kila

Understanding Fluent NHibernate - The entity doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id)

The entity 'YourEntityName' doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id). Don't you just love Fluent NHibernate error messages?

So you have set up your database, got your tables together, created some classes and tried to use Fluent NHibernate to map and......you get the following - The entity 'YourEntityName' doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id). It seems like a straightforward error right? It looks like Fluent NHibernate is looking for an Id and you don't have it. But you think to yourself, "Self...you know you put that YourPropertyNameId in there. What could be going on?"

Well the truth is that the error is not as verbose as it seems. It means EXACTLY what it says. Let us say for a moment that you have a table named Projects. This Projects table has a primary key column called ProjectId. You are using Fluent NHibernate and NHibernate in ASP.NET MVC to automagically generate NHibernate mappings so that you don't have to do it by hand. Well, Fluent NHibernate expects to see that primary key column name displayed as Id NOT as ProjectId! What???? That is correct - Fluent NHibernate can't be expected to just "know" what everyone using it will name the primary key - soooo when you are using the AUTOMAPPING FEATURE that allows you to generate mapping files WITHOUT typing a line of code, you have to give those identity columns a nice GENERIC name of Id. Using something like {get; private set;} is not enough. If that naming convention doesn't work for you, you can do a few things. You can override the IsId feature. The override below, which would be placed in the configuration file, specifies that anything with the EntityNameId is the Id.


public override bool IsId(Member member)
{
return member.Name == member.DeclaringType.Name + "Id";
}


Now, that is the way to do it IF you are using configuration files. I don't.
I should because that was the suggested upgrade from Fluent NHibernate 1.0 to 1.1,
but I don't because the creator in his infinite wisdom still allows me to do it like this.



public ISessionFactory GetSessionFactory()
{
var connectionString = ConfigurationManager
.ConnectionStrings["YOUR_CONNECTION
_STRING_NAME_AS_DEFINED_
IN_YOUR_WEB_CONFIG_FILE
"]
.ConnectionString;

//Fluent NHibernate configurartion
var sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(x => x
.Is(connectionString)))
.Mappings(m => m.AutoMappings
.Add(AutoMap.AssemblyOf<YOUR_ENTITY_NAME>()
.Setup(cfg =>
{cfg.FindIdentity = member => member
.Name == member
.DeclaringType.Name + "Id";}
)))
.BuildSessionFactory();

return sessionFactory;
}


For
YOUR_ENTITY_NAME shown above, you can select ANY class in the directory that you want. Fluent NHibernate just uses that class to tell where ALL of your classes are so don't worry about which one to specify there. You can also use Fluent NHibernate to generate the actual mapping classes decorated with ClassMap and then make any adjustments . However, that means that you can't use the Automapping magical save-me-some-work feature.

Fluent NHibernate can make your life sooo much easier if you are using NHibernate, but you have to read the automapping area on the Fluent NHibernate Wiki if you really want to be able to use it to its fullest potential. READ IT HERE :-). No one likes to spend precious minutes/hours looking for why you get small issues like this, but if you read the wiki maybe you won't have to. I promise you that it won't hurt!

Smooches,
Kila

Problem:
When using Fluent NHibernate with the AutoMap feature, you get the following error - The entity 'YourEntityName' doesn't have an Id mapped. Use the Id method to map your identity property.

Solution:
Rename your primary key from whatever it was to Id or create the ClassMap files by hand and designate the column to be used as your primary key in that class. Don't forget to change your Fluent.Configure .Mappings area to something like this - .Mappings(x => x.FluentMappings.AddFromAssemblyOf() - so that you remove the Automap from the Mappings attribute.

You can also designate your column as a primary key by using the hbm.xml file structure, but that is too much work and you don't have type checking to make sure you didn't screw something up AND you defeat the purpose of Fluent NHibernate. Don't defeat the purpose people - just don't do it!

Monday, August 9, 2010

Use StructureMap To Create And Dispose Of NHibernate Sessions

If you are using StructureMap to manage sessions for NHibernate, you may have encountered situations where you would like to dispose of those sessions in a clean and efficient manner. You could create your own code to manage this (good luck with that) or you could use StructureMap to handle that too.

In the current version of StructureMap, you can use the following code placed in the Application_EndRequest event of your Global.asax file.

ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();

If you are using an old release of StructureMap, you can use the following code placed in the Application_EndRequest event of your Global.asax file.

HttpContextBuildPolicy.DisposeAndClearAll();

Either way, you can use StructureMap to manage the clean up of your sessions in NHibernate. I hope this knowledge makes your life easier!


Smooches,

Kila

Sunday, August 8, 2010

Learn How To Use Automapper To Make Your Life So Much Easier!

I love it when a tool actually DOES make my life easier! Don't you? As programmers, we are faced with a plethora of various tools to use for development. Some of them can really leave you wondering if you are really as smart as you think you are when you try to figure them out. In an effort to refine various processes I have in place for my .NET MVC development and to see how much more activity I can squeeze out of my development time, I decided some months ago to really dig into various programs designed for .NET. Those programs included dependency injectors, mapping tools, coding tools, etc.

A few months ago, I came across one tool that looked interesting. However, the tool didn't have what I considered to be enough documentation for me to dig into it - or so I thought. Perhaps I was being lazy or maybe I was on tool overload. I looked at it for a few minutes and really pushed it aside because I thought I didn't have the time to go figure out how to make it work. Boy was I wrong! That tool is called AutoMapper. The tool is designed to be a bridge between your domain model and the various representations of that model that you might need for your views - among other things. If that comment flew right over your head, don't worry because I'm going to explain what I mean.

Say that you have a domain model called Homes. This model describes all of the different types of homes that your client is going to be selling. You craft a beautiful domain model and now it is time to display some data from it in your view. You only want a few items from the Home domain in one view and different things in another. At this point, you are faced with a few choices. You could have your controller send the data DIRECTLY from your domain model to your view. However, there are or items that you don't need to display in certain views and there may be a particular way you want the data to display in certain views. You could format the display of the data INSIDE of your view - which isn't optimal because views shouldn't go around making decisions. You could modify the data in your controller OR (drum roll please......) you could create a view model specifically designed for your views that displays the data formatted exactly how you want it to be displayed. You can also apply all types of juicy validation in any way you want without effecting the underlying domain model in any way. AutoMapper lets you do that last few things I said quickly and easily.

After deciding to revisit this tool and for more documentation on it, I came across some great stuff that had been added to the project. In fact, I came across something that gave me that good old AHHHH HAAAAA moment and made me feel all warm and tingly inside. I came across a Silverlight video that walks you through a demo of AutoMapper! This video is located here at http://www.dnrtv.com/default.aspx?showNum=155. When I saw that Url I had to laugh - if ever there was a need for some good old fashioned MVC Url routing, that is it! Anyway, the video is absolutely excellent. There is too much talking in the first few minutes of it, but once Jimmy Bogard starts explaining the tool he developed, you will be hooked (well only if you are geeky and nerdy like me :-)). I also discovered that the video had been added to the documentation on CodePlex,. I didn't see that when I first looked at AutoMapper! Reminds me of that contact lens commercial where the woman tells the guy to look with his special eyes (go look it up on YouTube). Anyway, I'm thankful for it because it offers an in-depth look at some of the many things that AutoMapper can do.

AutoMapper is lightweight, easy to set up and makes the process of creating various view models from your domain model an absolute breeze. If you are really into separation of concerns then you need to be into AutoMapper.

Check out AutoMapper here - http://automapper.codeplex.com/.

Check out more about Jimmy Bogard, the creator of AutoMapper here - http://www.lostechies.com/blogs/jimmy_bogard/default.aspx.

Check out the video here - http://www.dnrtv.com/default.aspx?showNum=155.

Smooches,
Kila

ASP.NET MVC 2 & StructureMap Error - ASP.NET MVC 2 - GetControllerInstance(System.Type)': no suitable method found to override - OH NO!

Don't you just wish that when you port your applications from ASP.NET MVC 1 to ASP.NET MVC 2 and beyond that things just worked? If it did, I guess it would put some of us out of work. It is always nice to know that thanks to these updates and the technologies we employ to make our lives easier, we will always have jobs.

StructureMap and ASP.NET MVC 2 gave me a nice little error that you and others might run across. The solution is quick and easy - unless you don't know it (LOL). While moving one of my applications from MVC 1 to MVC 2, I came across the StructureMap error. Here is the offending StructureMap code I used in ASP.NET MVC 1.

CODE THAT DOES NOT WORK IN ASP.NET MVC 2
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null) return null;
try
{
return (IController)ObjectFactory.GetInstance(controllerType);
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
}

It looks like it should work right? Well it did work, but guess what? Times have changed....well StructureMap has changed. So now the code should look like the following:

CODE THAT WILL WORK IN ASP.NET MVC 2
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{

if (controllerType == null)
return base.GetControllerInstance(requestContext, controllerType);

try
{
return (IController)ObjectFactory.GetInstance(controllerType);
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
}
And there you have it! Changes, changes, changes! I hope this puts a smile on your face or at least lets you get back to work.

Smooches,
Kila