Monday, April 16, 2012

Nhibernate simple tutorial with Northwind and fluent nhibernate

I had a tough time configuring and setting up NHibernate with the configuration that I wanted. This is what I wanted to do:

1. Database first
2. Fluent Nhibernate

I know this kind of looks like the basic stuff that every one wants to do. But I wanted code for fluent Nhibernate to be generated by some tool. Finally I got hold of NHibernate Mapping Generator. A very simple to use mapping generator and free :). You can find it here: Nhibernate Mapping Generator.

The only problem that I faced with this tool is that if a table has a space in its name the code generator will add and space in the class name which breaks everything. So before you use this tool to generate the mapping classes make sure you remove any spaces from the table name. I never add spaces when I am creating a table but Northwind database has tables with spaces in table name.

These are the steps that I followed for NHibernate Mapping Generator:


  1. Downloaded NHibernate Mapping Generator
  2. After running NHibernateMappingGenerator.exe from the dowloaded zip file I entered the connection string pointing to my local Northwind database. (Make sure to remove spaces from table name)
  3. select the path where I want the generated files to be placed.
  4. In preferences make sure the Fluent Nhibernate is selected.
  5. Hit Generate All


Using the generated files in Visual studio:

I created a solution with a class library "DataLayer" and added two folders "Entities" and "Mapping".


I added one more file NhibernateSession for maintaining a single session just to keep things simple. Also to test the generated classes I added a test project which is a console application.

I added three references to the "DataLayer" & "Test" project: FluentNhibernate, NHibernate, NHibernate.ByteCode.Castle.

These are the contents of NhibernateSession class:


public class NhibernateSession
    {
        private static ISessionFactory _sessionFactory;
 
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();
                return _sessionFactory;
            }
        }
 
        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(@"Server=.;Database=Northwind;Trusted_Connection=True;").ShowSql())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Order>())
                .BuildSessionFactory();
        }
 
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }


The Test project contains a single file Program.cs and its content are as follows:


class Program
    {
        static void Main(string[] args)
        {
            TestRead();
        }
 
        private static void TestRead()
        {
            using (var session = NhibernateSession.OpenSession())
            {
                var makeQuery = (from product in session.Query<Product>()
                                 select product).First();
 
                Console.WriteLine("Product Name: " + makeQuery.ProductName);
                Console.ReadLine();
            }
        }
    }


Thats it. Hit run and enjoy. NHibernate setup in may be 10 minutes :).

If you need source code for this sample project write in comments. I figured its just too simple for the need to include any source code.

Sunday, March 18, 2012

Separate Web application into multiple projects

I read a number of blogs on how to do this. Most of them were for VS 2005 but none for VS 2010 (It doesn't matter though). Also all the blogs involved using IIS instead of IISExpress which we use for development. This is the link that was the most useful http://support.microsoft.com/default.aspx?scid=kb;EN-US;307467

It really doesnt matter what folder structure you use or where the sln file is placed. This is the structure that we have.

Red Line: Folder structure
Blue Line: Project References

You can have multiple Child Web Application. We have 3 child web applications currently.

These are the steps to create the project structure:

  1. Create the parent web application. 
  2. Create child web applications.
  3. If you are converting an existing web site to web application and moving your App_Code outside of the web application then create a Class Library project and move everything from App_Code in the website to the new App_Code class library project.
  4. Add reference of App_Code class library project to all web application. (If there are any web applications you can surely avoid adding this reference)
  5. Create Common User Controls library (if needed). This can even include Web User Controls.
  6. If you have separated your User Controls in step 3 (Common User Controls child Web App in the diagram) into a separate web application then you will have to add the reference of this project in every child project that uses this User Controls.
  7. Add reference for each child web application in parent web application. If parent web application uses the user controls even add reference of Common User Controls in parent we application.
  8. If your web config includes tagprefix then ideally you should keep the web.config. This gives you two advavatages: 1. You wont see any annoying error messages on aspx pages coz visual studio wont be able to find the reference for the tagprefix. 2. If you have web deployment projects it wont compile.

Steps to build and run the project:

There are two ways in which we can do this. With either treating the child web applications as virtual folders in IISExpress or having a post build step to copy .aspx and .ascx files to where they were originally.

Case 1: Virtual folders (My way)

In applicationhost.config file for IISExpress find your site. This is what visual studio adds for parent web application:


This is what you will have to add for each of your child projects:


Case 2: Post build step

I have never tried this. But it should work. In the post build step of each child web application project add a copy step to copy in the parent directories physical location. You wont need to make any changes in the IISExpress configuration.

I think I have covered all the steps that I know. :)

Monday, March 5, 2012

Addons / extensions for Visual Studio (Free :) )

The first step that i take after installing a new version of Visual Studio is installing all the basic extensions.

It all starts with

VSCommands 2010


http://visualstudiogallery.msdn.microsoft.com/d491911d-97f3-4cf6-87b0-6a2882120acf

Just add this. I use so many of the features from this tool. Locate in solution, Reload All, Collapse all projects(even better than Power Commands), Group items.

Ever had that annoying commit from some one which modified a lot of project files and had to click on reload project quite a few time. Not any more. Reload all projects does the trick.

Code assistance, build assistance (cancel build when first project fails).

PowerCommands for Visual Studio 2010

http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99

Cant live without the Collapse all projects from this tool. I work in a project which has atleast 50 projects in a solution. So Collapse All is must for me.

The other feature that I use a lot is Edit project file. I know not many do this but dealing with lot of branches and creating automated build makes me use this feature a lot.

Format document on save. You will love to use this if you are working on a new project.


Productivity Power Tools


http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef

Add Reference dialog is awsome. This feature alone makes this tool must have.


This adds the annoying but useful Find tool which will be the default in VS 11. Its good but has some bugs. Still better then than legacy find for daily use.

If you ever wanted legacy scrolling this is it.

Has the new Solution Navigator which again will be part of VS 11. Dont use this if you have as many projects as I have in my solution.

Browser styled tabs.

Ctrl+Click. I use this a lot to go to definition instead of the traditional F12

NuGet


Its the number one tool on VS Extensions you should have it any ways. :). A great tool to manage external assemblies.




Web site to Web application without loosing tfs history


We tried to follow most of what’s written in this link:


However “Copying Files to the Web Application Project” step requires you to copy files from Website to Web application project which would add files. This results in loosing of TFS history which didn’t meet our criteria. 


These are the steps we followed to convert as far as I recollect:


  1. Create an empty web application project with name “UIWebApp” (Obviously any name you want).
  2. Close solution in visual studio but keep visual studio open.
  3. Open Source control explorer or visual studio command prompt. Our website was in folder UI. We moved all the files from folder “UI” to folder “UIWebApp” using the following command 
  4. tf.exe rename "$/PROJECT/UI/*.*" "$/PROJECT/UIWebApp/". Rename operation guarantees TFS history will be preserved. To Do this from Source control explorer you will have to individually right click on each file and move it to its new location. We had over 10,000 files I guess, so it was difficult for us to do this from Source control explorer. Check In.
  5. After this step we opened the solution went in “UIWebApp” project, selected show all files and included all the files we moved in the previous step and used the “Include in project” option. 
  6. Select all files in APP_CODE in the web app project and in properties make sure the build action is set to compile. (We moved all the files from APP_CODE in a seprate library and added a reference to that library in the web app project. This link tells more about this step http://vishaljoshi.blogspot.com/2009/07/appcode-folder-doesnt-work-with-web.html)
  7. We removed the website “UI” from the solution and also cleared all the related files and folders from TFS. This will help if you want to rename your app to same name as your website which in our case we did rename it to “UI”. Check In.
  8. Make sure that the references for the user controls are correct. 
  9. Now right click on the Web Application project in solution explorer and click convert to Web Application. This step could take several hours if your website was huge. Took us hours. It adds designer files for each aspx and ascx page and fixes all the changes keyword Codefile to Codebehind. Check In.
  10. If your deploy included web config transformation that should now be done in Web.config.Release. Follow the examples in the Web.config.Release. 
  11. Build. This should be it for conversion.


Other than maintaining history we faced problems with our automated deploying since we decided to separate some folders into separate Web Applications for ease of maintenance and maintaining these Web Apps as virtual folders. You can read my blog for separating web applications at http://abhighag.blogspot.com/2012/03/separate-web-application-into-multiple.html

If your conversion doesn’t involve creating separate web apps then you won’t need any change in builds. Also before we used to use Web application deploy projects for deploying with websites but we switched to msbuild since that makes sure that the web config tranforms are handled correctly.

This is the command line we used for auto deployment:
msbuild .\WebApp\Www\XY\XY.csproj "/p:Platform=AnyCPU;Configuration=Release;WebProjectOutputDir=..\..\..\Source\en\XY" /t:_WPPCopyWebApplication

If you get "Projects have recently been added to this solution" or "Some of the properties associated with the solution could not be read" when you open the solution then follow this link