Thursday, December 16, 2010

Why Do I Love Cheating On Dot Net As Much As I Do With.....Ruby(LOL)!

I try to keep this site clear of anything other than my love for .Net, but I am the biggest cheater I have ever known. You know why? I really, really love Ruby on Rails! There.... I said it! I mean I REALLY love Ruby on Rails! I'm telling you this for a few reasons. First, as you move through the programming world, it is important to keep your mind open. A programmer should know multiple languages. It helps you on a number of levels. Professionally, it helps if you can demonstrate your flexibility in learning new things. Second, if you ever need to find a new job, you have more than one programming language under your belt which can open up more programming opportunities for you. Third, knowing more than one language helps you to see deficiencies more clearly in the languages you use. I can tell you from experience that learning .Net and then learning Ruby made me clearly see some key deficiencies in .Net - even though I still love .Net.

I'm not saying that you need to learn every language under the sun, but knowing additional languages can only be a good thing. If you are a .Net programmer, I HIGHLY suggest that you add Ruby on Rails to your arsenal. As a plus, you can likely create a fully functioning program in Ruby in less time than it took you to read this.

Smooches,

Kila

Friday, November 12, 2010

Finding The .SQL Mime Type SQL Server Mime Type

OMG! Why are some things so much more difficult than they need to be? I am creating a database application to make my life simpler. The application allows you to enter class file information once and then the application automatically, or should I say automagically, creates the class .cs file, Fluent NHibernate mapping files in your choice of AutoMap or ClassMap files (AutoMap and overrides are my preference) and the database .sql script. Creating the files and saving them to the database is simple. The problem came when I needed to download the files from the database. The system was adding a .txt file to the end of the file - Example: FileName.sql.txt. This was making me very sad.

I decided to get the actual mime type for a sql file so that the file would download appropriately without adding .txt to the file. Well you would think that I was trying to find how to get into Fort Knox or something. The general consensus is that most people just want to use text/plain. Not I said the mouse! Well I decided to use something I had used before - the Gnome Mime Type database. This database had allowed me to find a mime type that worked properly with some other Microsoft files that I was saving and retrieving from a database (for example, the mime type for a .cs file in the Gnome library is text/c-sharp and it works perfectly). Sooooo back to my good old friend.

The mime type for a .sql file is text/x-sql. The Gnome mime library is pretty extensive. The goal is to be a resource and standard way of using and finding mime types.

This is a simple thing, but since Google wasn't the easiest resource for finding the mime type for .sql files, I thought you might find this useful.

PROBLEM:
What is the .sql mime type? Where can I find the .sql mime type? Should I use text/plain or another mime type for .sql files?

SOLUTION:
You can use text/x-sql and you can use the Gnome library to find out more mime types as needed.

Smooches,

Kila Morton

Friday, October 22, 2010

How To Solve System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' and no extension method 'RenderPartial'

Sometimes there are errors when you build in ASP.NET MVC that just make you want to shoot your own computer! You resist the urge of course (I hope), but the desire is still there! While I was creating an extension helper in ASP.NET MVC using Visual Studio 2010, I came across this error:

How To Solve System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' and no extension method 'RenderPartial' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

Ummm.....NO I am NOT missing a using directive or assembly reference - thank you very much! Well actually I was - LOL. I'm using MVC2. It seems that it wants an additional reference to reference RenderPartial now.

Here is a list of the usings I was using
(notice that wording - "usings I was using" - that makes me laugh - I crack myself up sometimes!) -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
using System.Reflection;

The using statements above SHOULD be enough to allow me to use RenderPartial. Unfortunately, I had to add ONE MORE using statement to make it work -

using System.Web.Mvc.Html;

That solved the issue! Why does Microsoft change little things like this? Do they do it just to drive people crazy?

Smooches,

Kila


PROBLEM:
How To Solve System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' and no extension method 'RenderPartial' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

SOLUTION:
Make sure you are referencing MVC in your web.config, make sure you have a mvc using statements listed above in your file and make sure you add the following item to that list of using statements.

using System.Web.Mvc.Html;

Sunday, October 10, 2010

Problems With The HP ZD8000!

There are very few products that I actually can say that I hate, however, HP has managed to make two products that are on my list.

A few years ago, I was given an HP zd8000 as a gift. I know the person that gave this thing to me cares for me very much so I don't hate them, but this laptop has to be one of the worst pieces of technology I have EVER owned. If this was my only laptop, I would be really, really angry right now. As it stands, it is one of many. However, since I just had to spend more time than I care to admit upgrading it to Windows7, I'm going to just list the problems I have had to date.

The computer is now 3 years old. However, I have been having many of these issues for a while now.

1.) The keyboard misses, skips and does not register some keystrokes. It happens to all of the keys. You will go along typing with a smile on your face only to realize that half the letters you typed were not registered by the keyboard. I used to have a USB keyboard attached to this laptop so I didn't notice this problem. It makes you want to scream!

2.) Several of the USB ports have DISCONNECTED from whatever they are connected to inside of the computer. I'm pretty handy with a screwdriver so I can correct this one, but it should not have happened in the first place.

3.) The computer overheats to the point that it could cause a fire! I have handled this issue with a Belkin cooling fan underneath the laptop. I hope this will help.

4.) The DVD RW drive stopped recognizing DVDs. This was OK after an upgrade to Windows 7. Well let me say that it MIGHT be OK. I say MIGHT because I JUST upgraded the machine from XP to Windows 7 TODAY! However, so far so good on that issue.

5.) The laptop battery no longer works. The system will not register that there is a battery. This is my FOURTH battery! There is a recall on this issue, so maybe it will work now.

6.) The power supply stopped working. It seems like it is the power supply connector that is the issue. I had to use some electrical tape to keep it connected and still.

7.) The middle of the touch pad has worn down to the point that I can see the green circuit board underneath it.

Of course, the warranty is gone so the best I can do is replace the parts myself. I wasn't angry about these things until I did a search and discovered that these are major issues for MANY ZD8000 owners! In fact, I saw MANY people talking about and suggesting class action lawsuits over the ZD8000 issues.

It makes me feel sick to my stomach that a company like HP would make computers like this without the thorough testing needed to make sure that they will work consistently and it really makes me sick to know that HP won't make things right!

Sunday, September 26, 2010

How To Get Fluent NHibernate, NHibernate And Castle To Work Using Medium Trust

There are times when open source projects can give you incredible joy. Then there are other times when you just want to go find the developers of a particular open source project and yell at them just a little bit. The truth is that we should all be thankful that open source developers care enough to create fantastic open source projects, but sometimes things can get hairy and scary. I had one such situation with NHibernate, Fluent NHibernate, Castle and StructureMap when I tried to get everything working in a medium trust environment. I'm going to tell you how to solve the problem so that you can have an easier go of things than I had.


I created a beautiful project using NHibernate, Fluent NHibernate , the part of Castle that NHibernate relies on and StructureMap. Everything worked perfectly in development and I was super happy and all smiles. Instead of just releasing the project, I decided to create a coming soon page for it. The coming soon page can be seen here - http://www.thedesigncoders.com/comingsoon. That page has a contact form on it that uses NHibernate to persist the data. This page looked and worked great on my development machine, but I got a rude awakening after deploying it. That rude awakening was an error - System.Security.SecurityException: That assembly does not allow partially trusted callers. What? OMG! Here was the first lesson for me - always run your project on dev using the same trust level as your production environment. Doing this would have shown me the error well before deployment. OK. Lesson learned.

Now I was in a pickle. The error was occurring in Castle according to the error message. I used Google to investigate the issue. There were a whole lot of different things that people tried. One of them was to disable lazy loading. I nearly lost my lunch when I read that! I had set up Fluent NHibernate using its AutoMap feature and I had an EXTENSIVE database system with a lot of interconnected many to one, one to one and one to many relationships. Disabling lazy loading would basically mean that I might as well remove NHibernate and Fluent NHibernate and use Entity Framework. That, however, would have taken me a long time to do and it simply wasn't anything I even wanted to think about. I don't have anything against Entity Framework, but it took effort for me to set up NHibernate, Fluent NHibernate and StructureMap and I wasn't about to abandon my beautifully done project because of one stupid error. I was GOING to figure this out.

OK. So after viewing some blogs AND the NHibernate website, which suggested that I would need to go through hell and high water to get things to work, I decided to keep searching. Here are some of the articles I came across.


  1. Use NHibernate Proxy Generators
    http://nhforge.org/blogs/nhibernate/archive/2008/09/23/introducing-nhibernate-proxygenerators.aspx
    This would be good, but I'm using Fluent NHibernate's AutoMap feature so I don't use mapping files. That means that this is useless to me and it is likely unnecessary for you.

  2. Disable Lazy Loading, Disable Reflection Optimization & Change Web.Config Permissions
    http://nhforge.org/wikis/howtonh/run-in-medium-trust.aspx
    No, no and NOOOOOOOOOOOO!!!!!!! Fluent NHibernate's AutoMap feature makes things REALLY easy for me. If I had to disable lazy loading on my project given how large the database is and how much work Fluent NHibernate saves me from doing, I would have a fit. This just WAS NOT an option. In fact, it was a beyond useless idea to me.

  3. Rebuilding The Castle Project, NHibernate and Fluent NHibernate
    http://blog.yeticode.co.uk/2010/03/running-nhibernate-in-medium-trust/
    Hmmmm....this sounds good...... or so I thought! I would SIMPLY download all three projects, change the assembly in Castle to AllowPartiallyTrustedCallers, build it and use the dlls to then rebuild everything else. Great! I download the latest version of Castle and I start down that road. God/Allah/Jehovah/Jesus/Messiah/ HELP ME!!! It is times like these that make you feel stupid. I did all of that without thinking about ONE important (very important) thing - I didn't initially pay attention to the various versions of the files! Doooh!! Things did not match up! This version needed that version and that version needed this version and so on and so on. The problem wasn't JUST the versioning. Castle rolled its Dynamic Proxy into Castle.Core. It used to be its own project, but they changed this in the latest version. This meant that I had to change various parts of NHibernate. NHibernate was looking for a reference to Castle.Core AND Castle.DynamicProxy. I was starting to think about looking for a drink - and that says a lot because I have never had a drink of alcohol in my life! Fortunately, I figured out a different way.

I started thinking about the problem. The problem was that I couldn't set this project up on my chosen host because they don't allow people's apps to use full trust and the components I was using required full trust to do certain things. Surely I wasn't the only person who had this issue. In fact, I was positive I wasn't the only person with this issue because Google told me so (lol). Therefore, someone else had to have come up with a solution. I found that someone or a group of someones (I know this isn't proper grammar) had already solved the problem for their project. That project is called Cuyahoga. That brings me to solution number 4 -


    4. When In Doubt, Use The Files Of Someone Else To Work It Out! (I love that rhyme)

    Yeah! Now that is my kind of solution. After pulling out my hair by the root, this “solution” left me with 5 strands left! Cuyahoga is using NHibernate with Castle. Since they have already conquered the medium trust issue, I knew that their latest files should be sufficient for me. They don't use Fluent NHibernate (shame on them), but I knew that it would be nothing for me to download the latest source of Fluent NHibernate, add the dlls I took from Cuyahoga to the src and then compile everything. That is what I did and it worked like a charm. I swapped out the dlls in my project and I didn't have to disable or change anything else. Yes! Yes! Yes!

    Here is the link to the Cuyahoga files.

    https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/lib

There you have it! Using those files will allow you to get everything running in a medium trust environment!


There are a couple of things that I found during my search that troubled me. There have been a lot of people who have had this issue. I would think that the open source project creators, especially NHibernate, would create source code that works in a medium trust environment. They won't. Making people do it themselves isn't necessarily a bad thing, but everyone doesn't want to spend time struggling to get things done. That is one of the things that makes Entity Framework appealing to the masses - for the most part, it just works.


Here is a link to one particularly onerous discussion surrounding the issue involving users and the Nhibernate developers. I found the whole character of the discussion to be completely distasteful. It shouldn't be so hard to do something that is so easy.

http://groups.google.com/group/nhusers/browse_thread/thread/dbfa6840d42f4c12/0db76f949568f947?lnk=gst&q=medium+trust#0db76f949568f947


If you have this issue, don't fret, worry or drive yourself insane. Just get those files and make it happen. Do not, I repeat, do not disable lazy loading for NHibernate to make it work in a medium trust environment. That defeats the whole purpose of the tool.

Smooches,

Kila

Friday, September 24, 2010

How To Tell What Happened When Publish Failed In ASP.NET MVC

This is a simple one. If you use the Publish feature in Visual Studio, you might be wondering how you can tell why a publish fails. The reason could be anything from an image file not being loaded in a project, to something more serious. To find out, you can click on View and then select Output to see exactly why the publish failed. Wasn't that simple?
Smooches,
Kila

Wednesday, September 22, 2010

How To Uninstall Internet Explorer 9 Beta

I made a mistake. I should have known better than to install a Microsoft Beta product. I love Microsoft, but their Beta products have some real quirks sometimes (I know....hence the term Beta). I usually wait - never wanting to be first in that arena. However, I decided to take a chance on Internet Explorer 9 Beta. The install SEEMED to go smoothly. The computer restarted, but I would get an error when I tried to use IE9. Every single time I clicked on it, I got the dreaded Windows has an error message and then Windows is checking for a solution message. Over and over. I tried all of the instructions provided by Microsoft to fix it, but I finally decided that I didn't and don't have the time to work through the issues. I need IE for development purposes and it HAS to work for me so I did an uninstall. However, when I went to do my uninstall, I couldn't find IE9! Since anything that is added has to have a way to be removed, I started searching to find it. I did and here is the solution so you won't have to spend as much time as I did.
On Windows 7 here is what you do:
  1. Go to Control Panel
  2. Select Programs And Features
  3. In the upper left hand corner, select View Installed Updates
  4. You will be provided with a list of updates, but you will likely not see Windows Internet Explorer 9 clearly in the list
  5. To find Windows Internet Explorer 9, go to the search box in the upper right hand corner and type in Windows Internet Explorer 9
  6. Windows Internet Explorer 9 will magically appear and you should select it and then hit the Uninstall button.
  7. The computer will uninstall the components and then ask you to restart.
  8. Once you restart, you will need to set up some attributes of Internet Explorer 8 again, but you will be rid of Internet Explorer 9 and ready to rock and roll.

Whew....lets not EVER do that again until IE9 is ready - lol!

Smooches,

Kila

Monday, September 6, 2010

How To Solve A SQL Server Database Marked As Suspect Mode

I'm going to keep this short and to the point. You may log into SQL Server some day and find that some of your databases have an exclamation point along with being marked with the following: DatabaseName (Suspect). That just makes you frown. Well I'm going to show you how to turn your frown upside down!

The solution is listed below.

Smooches,

Kila

Problem:
SQL Server marks your database as (Suspect). It won't open and you don't know what to do.

Solution:
To solve the problem, run the following in query analyzer.


EXEC sp_resetstatus 'YourDatabaseName';

ALTER DATABASE YourDatabaseName SET EMERGENCY

DBCC checkdb('YourDatabaseName')

ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DBCC CheckDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS)

ALTER DATABASE YourDatabaseName SET MULTI_USER

After you run this, right click on the database and hit Refresh. There you go! Now your frown is turned upside down!

Thursday, September 2, 2010

Primary Keys Do Not or Should Not Equal Clustered Index....Repeat After Me...Learn How To Add A Clustered Index On A Non Primary Key Column

Today I'm going to tell you about a novel concept that I just had to demonstrate to one of my employees who didn't know/believe that it was possible. Before I tell you about this concept, I need to give you a little bit of background information. If you are using SQL Server, you know that when you create a table and add a primary key, a clustered index is automagically created for you on the primary key column. However, the problem with that is that the primary key you create may not be the clustered index you are looking for. There can be only one clustered index on a table. SO what are YOU going to do if the clustered index on your primary key is not on the column you want? What are you going to do if you need to add a clustered index on a column that is not the primary key? The answer to those questions is to change the clustered index first and then create your primary key. In order to change your clustered index, you need to remember a few things.


  1. A primary key is not an index. Primary keys uniquely identify columns in your table - nothing more and nothing less. You don't have to use them for indexing.
  2. A clustered index, reorders the physical rows of your table. So if you are consistently doing searches on a particular column AND it is unique in your table, you can use that column in a clustered index. Don't forget this. I always use the example of a telephone book. Clustered Indexes are like telephone books. Why would you want to have a telephone book ordered by a randomly generated Primary Key? The answer is that you wouldn't. Instead, you need a real world way to order your information.
  3. You SHOULD NOT let SQL Server decide the clustered index for you. It happens by default, but accounting for this is part of good database design.
  4. Setting up a clustered index that IS NOT your primary key is easy to do.

I love #4.... I love #4....repeat after me....

So with all of those things in mind, let me give you an example. Lets say that you have a table called Options. Your table is defined like this.



CREATE TABLE [dbo].[Options](
[OptionId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Options_OptionId] DEFAULT (newid()),

[OptionName] [nvarchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[OptionDisplayName] [nvarchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[OptionDescription] [nvarchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[OptionStatus] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF_Options_OptionStatus] DEFAULT ('ACTIVE'),

[LastStatusChangeDate] [datetime] NOT NULL CONSTRAINT [DF_Options_LastStatusChangeDate] DEFAULT (getdate()),

[CreatedBy] [uniqueidentifier] NOT NULL,

[DisplayOrder] [int] NOT NULL,

[DateAdded] [datetime] NOT NULL CONSTRAINT [DF_Options_DateAdded] DEFAULT (getdate())

) ON [PRIMARY]



Here is what this table looks like in the flesh without a key:


Looks good right? Now what? Well if you are like most people, your next step is to add the primary key! But this isn't correct. Adding the primary key will automatically create a clustered index. INSTEAD, we are going to create the clustered index FIRST! That's right! I said FIRST! You create the clustered index first and then you add the primary key after the fact.

Here is what you end up with.

You didn't see it, but the table is now physically ordered by the Display Order column - NOT the OptionId column. As you can see, we have a Clustered Index AND a Primary Key column which is unique, yet non-clustered. How did we do that? We did it by remembering to do the following:

  1. Create your Clustered Index FIRST - before you add a Primary Key!
  2. Add your unique Primary Key after you have added the Index.

This will allow you to have the clustered index set on the column that you actually should have it on instead of using the default set up that SQL Server offers you.

Problem:
You don't know how to add a non primary key column as a clustered index in SQL Server.

Solution:
Add the clustered index first on the column the table should be ordered on and then add the primary key.

* Note - Always remember to add your Clustered Index and then save and then add your primary key and then save AND THEN add your relationships. If you are using the SQL Database Diagram feature, don't try to add your clustered index and then use the diagram to add your primary key and relationships without saving the primary key BEFORE YOU ADD RELATIONSHIPS. If you add the clustered index and then go to the diagram to add the primary key and relationships WITHOUT SAVING the primary key before you add the relationships, when you save the primary key and relationships, the system will remove your custom clustered index and try to add the clustered index on the primary key only. This seems to be a quirk of using the database diagram feature.

Always remember the order -
  1. Add clustered index on your column
  2. Save
  3. Add primary key
  4. Save
  5. Add relationships
  6. save

Smooches,

Kila Morton

Saturday, August 28, 2010

How To Do A One To One Mapping In Fluent NHibernate Using HasOne! It Is So Easy! (Lets Map A One To One With Fluent NHibernate..YEAH!!)

I am going to give you a solid example of a One to One Fluent NHibernate mapping. Fluent NHibernate can be a fabulous tool once you learn how to use it. Once you get the hang of it, it is so much simpler than Entity Framework. I know that your eyes may bulge at that statement because what could be easier than dragging and dropping on a GUI. Automapping in Fluent Nhibernate is really even easier than that - ONCE YOU UNDERSTAND HOW TO DO CERTAIN THINGS. One of the ways you can learn more about Fluent NHibernate is by reading the documentation, however, sometimes that is not enough. One of the things that I found when trying to figure out how to do a one to one mapping using .HasOne is that the documentation on using .HasOne is sparse at best. What I found, over and over, was that there were no EASY, reasonable, concrete, full examples of exactly how you should map a one-to-one in Fluent NHibernate using .HasOne. So, I sat down and invested some time in figuring out how to do a one-to-one mapping in Fluent NHibernate using .HasOne and now I'm going to make things easier for you by telling you how to do it without adding all kinds of crazy things to your code and without pulling out your hair.

Since I like to give clear and concise examples, lets go through this step by step. This example is extremely simple, but it illustrates the point beautifully.

We are going to map two tables - TestUser and TestFullName. In this example, every user needs to have a full name saved with them. There can be only one name for each user. The two tables are connected on the UserId so TestUser.UserId = TestFullName.UserId. OK. Lets get all Fluenty (I made that word up)!

Step 1 - The Database Tables

You can create the two tables in any way you deem appropriate. The tables should have the columns specified in the following image:
(CLICK ON THE IMAGE TO SEE A BIG VERSION OF IT)

Notice the one to one key designation. Also, as you can see, each table has UserId as the primary key, which is the key feature of a one to one mapping in Fluent NHibernate. As you can also see, a relationship has been defined on the two tables. That relationship establishes the TestUser table as being the Primary Key table and the TestFullName table as being the Foreign Key table. This is EXTREMELY important in the mapping. If you accidently set the mapping up using reverse syntax, your mapping will not save and you will sit in front of the screen banging on your head asking yourself, "WHY GOD WHY WON'T THIS SAVE?" Now that we have the tables created, the primary keys assigned and the relationship mapped, we are going to go to step 2 and create the classes.

Step 2 - The Classes

public class TestUser
{
public virtual Guid UserId
{ get; set; }
public virtual string Username
{ get; set; }
public virtual TestFullName FullName
{ get; set; }
}


public class TestFullName
{
public virtual Guid UserId
{ get; set; }
public virtual string FullName
{ get; set; }
public virtual TestUser TestUser
{ get; set; }

public virtual void AssignUser(TestUser user)
{
TestUser = user;
user.FullName = this;
}
}

As you can see, I have a property in both tables that references the other table. Notice also that there is no IList mapping in there because this is a true one to one. Do you see how I created a property that allows you to assign a user?

Step 3 - The Actual Mappings

NOW, here is where it gets pretty guys and gals. Why do I say that? Well if you have been looking for how to do a one to one mapping using Fluent NHibernate, you have likely seen example after example of hacks that just don't feel correct due to the convoluted nature of the answers. It isn't as bad as you thought it would be. I am using the AutoMap feature of Fluent NHibernate to do a one to one mapping, so the code below includes the Override keyword. With the AutoMap feature you don't have to worry about class maps - unless of course you want to. Here is the mapping.

.Override
(map => map.Id(f => f.UserId))
.Override
(map => map
.HasOne(x => x.FullName)
.Class()
.Constrained())

.Override
(map => map.Id(f => f.UserId)
.GeneratedBy.Foreign("TestUser"))
.Override
(map => map
.HasOne( x => x.TestUser)
.Class()
.Cascade.All()
))

OOOhhhhhh Yeah! Doesn't that look great? Of course it does. Let me explain a little bit about why I did things this way.

First, you will notice that I map the Id. This is because the Id is not clear to Fluent NHibernate. Since UserId isn't intuitive based on the table names, I had to use the map feature to add an Id. Notice that I also use .GeneratedBy.Foreign. This tells Fluent NHibernate where the Id is coming from. Next, you can see that I've thrown Constrained() in there. That tells NHibernate that there is a Foreign key constraint on TestUser that refers to the primary key in TestFullName. On the other side I use a Cascade since things like Updates, Deletes, etc. should be persisted across both entities. There is one additional very important thing to notice here. I use .HasOne on BOTH sides of the mapping. All of these things ensure that you each instance saved will have the same primary key value across both tables.

I'm not showing you how exactly how to save things because I don't know how you have everything set up, but here is the outline of what you do.

Step 4 - Saving Things

  1. Assign a new user to a name using the handy-dandy .AssignUser method we created in Step 2.
  2. Save the name.
  3. Save the user
These things need to be done in order to avoid conflicts.


That's it! Aren't I great, super, fantastic and wonderful? Of course I am! This is how to easily map a one to one relationship in Fluent NHibernate using .HasOne. Now remember, don't go getting yourself confused about what a one to one is. James Gregory has spent so much of his time telling people on Stack Overflow and the Fluent NHibernate group that they want a many to one and not a one to one that I'm surprised he isn't in a straight jacket sitting in a padded room somewhere (Maybe He Is...). So read the documentation on Fluent NHibernate and use this example of how to map a one to one in Fluent NHibernate so you can look super smart.

Smooches,

Kila Morton


Problem:
You can't map a one to one in Fluent NHibernate using .HasOne OR you need to know how to do a one to one mapping in Fluent NHibernate.

Solution:
I won't list it here. You have to read everything above on this one!

As a side note, James Gregory is one of the creators of Fluent NHibernate. I think he has likely rubbed the skin off of his fingers due to how many times he has had to explain that many of the mappings that people consider to be one to one are actually many to one. You can take a look at his post here. We have a true one to one Fluent NHibernate mapping here so I don't think that we will get on James Gregory's bad side.

Tuesday, August 24, 2010

One Solution To The Fluent NHibernate Error "The given key was not present in the dictionary."

Problem:
You have set up some mappings and you get the following Fluent NHibernate error - "The given key was not present in the dictionary."

Solution:
This error can be generated for multiple reasons. One of the reasons is that you forget to map an entity. Before you go any further, check that you have mapped EVERY entity and check that you have registered every entity if you are using something like StructureMap or any other IOC.

Smooches,

Kila

Thursday, August 19, 2010

How To Handle The Following Error When Using StructureMap With ASP.NET MVC -The controller for path was not found or does not implement IController.

{"The controller for path 'main_bg.gif' was not found or does not implement IController."} Doesn't that error look great? If you say yes then I know that you don't have enough to do. When you are working with StructureMap, or really any dependency injector, to handle the creation of your controllers, you might run into a situation where you get the following error :

{"The controller for path 'main_bg.gif' was not found or does not implement IController."}

Of course, /Content/images/main_bg.gif won't be in YOUR error message, but some image you are using will likely be in your message. As you can see, StructureMap seems to be looking for a controller for the path of one of my image files. Well isn't that great? Now what? Fear not my friends, the solution to this problem is very, very simple - I promise. Before I tell you the answer, I'm going to ask you a question. What area can you use in MVC to tell your program to ignore or follow certain paths? .........1..........2.........3........Give up? It is the RegisterRoutes area of the global.asax. In this case, you just need to tell your code to ignore the route to your beautiful graphic and StructureMap will stop giving you the error. See, I told you it was simple!

Smooches,
Kila

Problem:
You are receiving the following error when you are debugging your ASP.NET MVC application in Visual Studio.
{"The controller for path 'main_bg.gif' was not found or does not implement IController."}
(You might also see something like the following:
{"The controller for path '/' was not found or does not implement IController."})

Solution:
Change your global.asax RegisterRoutes routine to ignore the offending path.

Example: routes.IgnoreRoute("{*ignoregifs}", new { ignoregifs = @".*\.gif(/.*)?" }); This will ignore all gifs.

If your issue is some other type of file or "/", you simply adjust the regular expression accordingly.

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

Friday, July 30, 2010

Fix For Client-Error-Not-Possible Brother HL 2140 Problem On A Mac

OK. I know what you are thinking - this is a .Net Crazy blog - not a Mac/Apple blog. I admit that you are right, but (AND THIS IS A BIG BUT) I have just spent more time than I care to admit (OK - about an hour really) trying to get my handy dandy Brother HL-2140 to print after hooking it up to my iMac. Yes I know.....I'm a PC girl, but I do have many computers running various things and I do have a Mac in the family. Everyone is welcome where I come from!

Anyway, I have been using this printer with my PCs without a problem. I hooked it up to my iMac, download the latest drivers for it from the Brother website and tried to print. Nothing! What? Isn't hooking a printer up to the mac supposed to be super easy (hahaha)? Nope! I uninstalled and reinstalled (the PC thing to do) and still nothing. I kept getting a client-error-not-possible error! What in the world is that? Talk about obscure errors! Ghhheeshhhhh! I researched the issue. Many people have had the same issue, but there was no resolution displayed. OK. Lets start playing around.

I decided to try to see if it was the printer driver causing the problem or the printer. I selected a variety of different types of print drivers to see if I could get the printer to have a reaction. I used various CUPS drivers for different Brother printers since that is what the actual driver for the HL-2140 is. I came up short! Then I used a Gutenprint driver for one of the other Brother printers. Guess what? I got a reaction! The printer "pretended" to print - it spit out paper, but didn't print the text. OOOOKKKKK.....now what?

Since I did get a reaction when I used a Gutenprint driver, I realized that the issue was driver related (see how smart I am?). I decided to try a different approach. I went back to the Brother website and I downloaded an OLD driver for the HL-2140. I have an iMac with OS 10.5.8 (as of today) and I downloaded the HL-2140 driver for OS 10.4. I went through the process of installing - blah,blah,blah - followed directions - blah,blah,blah and tried to print. Guess what? It worked!!!! Success, success, success! I AM as smart as I think I am (I hope :-)).

Anyway, that solved the problem and I could print on my Brother HL-2140 using my iMac running OS 10.5.8. Hopefully this saves you time and allows you to just get on with things.

If this helps you, write a comment and tell me how wonderful I am. If it DOESN'T help you, write a comment and tell me know how wonderful I am.

Smooches,

Kila

Problem: Brother HL 2140 printer will not print when connected to an iMac running OS 10.5.8

Solution: Download the old drivers for OS 10.4 from the Brother website and install it per the instructions. After the install and reboot, the printer should now print using the old drivers.