Click here to Skip to main content
Click here to Skip to main content

NHibernate Templates for Smart Code Generator

By , 11 Dec 2007
 
Screenshot - img1.png

Introduction

To learn more about Smart Code please read the next article, by clicking here.

The sample code and templates, are based in the next article NHibernate Best Practices with ASP.NET . In this excellent article, Billy McCafferty, describes best practices for leveraging the benefits of NHibernate 1.2, ASP.NET.

For this article we'll try to be original.....and we'll use the Northwind database as sample, but these examples will work with any databases

Bug Fix on ASPX templates, loading page by ID method

Code Generation, a brief overview

The Smart Code tool makes possible the automatic generation of programs and components that interact with database systems. It works by reading a database schema, allowing the user to set certain extended properties for tables and columns, and applying templates to each table in order to generate code. The templates are themselves programs that access the Smart Code Object Model to produce tailored programs and components. Although Smart Code comes with a set of basic templates, users may edit these or create their own to suit their particular project needs. Moreover, templates may be written in C# or VB.NET (or theoretically in any .NET language that supports the creation of dynamic-link libraries).

Quick Start Guide

Smart Code is a very powerful tool, and perhaps the best way to learn how to use it is to see a sample application running and then go back and examine which features of Smart Code were responsible for the application's functionality.

  • On the web.config and modify the connection.connection_string value
  • Play with the application, open up different pages and entering some data.
  • Open the Newin.scp project with the last release of Smart Code.
  • Compile the NHibernateTemplates and WebTemplates and Load the dlls into Smart Code.
  • Change some properties in Newin.scp project, this will show you the effect of different attribute settings and template assignments.

The NHibernate Template Libraries

The Sample package comes with one set of template libraries for generating 3- tier, web-form-based solutions that use NHibernate to access and modify data. This set of libraries is for generating code in C#; (future releases will support generating code in VB.NET).

In addition, the Sample package includes sample Northwind project in Visual Studio.NET to work with these sets of libraries, so that the generated code may simply be dragged-and-dropped into them.

The Domain Layer

For a description about the domain layer, click here

The Domain layer describing the data access objects and the classes of objects used to transport data between the tiers

Generating the Separated Interface, IDAOFactory

The IDAOFactory Interface provide methods to get objects as DAOs. This class serves as the abstract data. The template to generate the IDAOFactory for all entities in the Smart Code project is the IDaoFactory class in the NHibernateTemplates project.

IDAOFactory Interface

Notice, if you check the Item it Template run only one time, because it is an project level template.

The Code Generated for the IDAOFactory look like this:

 
using System;
using System.Collections.Generic;

namespace Northwind.Core.DataInterfaces
{
    public interface IDaoFactory
    {
        ICategoryDao GetCategoryDao();
        ICustomerCustomerDemoDao GetCustomerCustomerDemoDao();
        ICustomerDemographicDao GetCustomerDemographicDao();
        ICustomerDao GetCustomerDao();
        IEmployeeDao GetEmployeeDao();
        IEmployeeTerritoryDao GetEmployeeTerritoryDao();
        IOrderDetailDao GetOrderDetailDao();
        IOrderDao GetOrderDao();
        IProductDao GetProductDao();
        IRegionDao GetRegionDao();
        IShipperDao GetShipperDao();
        ISupplierDao GetSupplierDao();
        ITerritoryDao GetTerritoryDao();
    }
}
 

The Data Interfaces

The template DataInterfaces generate code for supporting each one concrete DAO factory. Each factory is an is a database-independent implementation, where the implementations will be database specific.

The Template used to generate the DataInterfaces is shwon in the next figure:

The Data Interfaces

And the code generated, for the Product Table look like this

using System;
using System.Collections.Generic;
using Northwind.Core.Domain;

namespace Northwind.Core.DataInterfaces
{
    /// Since this extends the IDao{TypeOfListItem, IdT} behavior, it's a good idea to 
    /// place it in its own file for manageability.  In this way, it can grow further without
    /// cluttering up IDaoFactory.
    public interface IProductDao : IDao<Product, System.Int32>
    {

    }
}

Mapping the Domain to the Database, HBM-XML files

The NHibernateTemplates project provide a class NHibernateHbm, to generate mapping files for NHibernate

Mapping the Domain to the Database, HBM-XML files

This Template generate the HBM files, for tables with single and composite Key and linking tables which will be recognised and the appropriate many-to-one or many-to-many mapping created

Hbm for Table with single key:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Northwind.Core" namespace="Northwind.Core.Domain">
  <class name="Product" table="Products" >
    <id name="ID" type="System.Int32" column="ProductID">
      <generator class="identity"/>
    </id>
    <property name="ProductName" column="ProductName" type="System.String" not-null="true" length="40"/>
    .............
    <many-to-one name="CategoryIDCategories" column="CategoryID" class="Category"  update="0"  insert="0" />
    <many-to-one name="SupplierIDSuppliers" column="SupplierID" class="Supplier"  update="0"  insert="0" />
    <bag name="OrderDetailses" table="Order Details" inverse="true" lazy="true" cascade="delete">
      <key column="ProductID" />
      <one-to-many class="OrderDetail"/>
    </bag>
  </class>
</hibernate-mapping>

Hbm for Table with composite key:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Northwind.Core" namespace="Northwind.Core.Domain">
    <class name="EmployeeTerritory" table="EmployeeTerritories" >
    <composite-id name="ID" class="Northwind.Core.Domain.EmployeeTerritory+DomainObjectID">
        <key-property type="System.Int32" name="EmployeeID" column="EmployeeID" />
        <key-property type="System.String" name="TerritoryID" column="TerritoryID" />
    </composite-id>
    <many-to-one name="EmployeeIDEmployees" column="EmployeeID" class="Employee"  update="0"  insert="0" />
    <many-to-one name="TerritoryIDTerritories" column="TerritoryID" class="Territory"  update="0"  insert="0" />
 </class>
</hibernate-mapping>

The many-to-one and bag are created from the Foreing Key relationship between the tables (InReferences and OutReferences) these references are created when you build the Domain, the next figure shown this concept:

InReferences and OutReferences

Both tables Products and Territories are related by Out References (OutReferences), with the EmployeeTerritories (InReferences).

Generating the C# class

The NHibernateTemplates project provide the class NHibernateClass, to generate the C# class for NHibernate

Generating the C# class

As the mapping, the NHibernateClass support single and composite key, about the IDs please refeer to Generic IDs and Object Comparisons section in the NHibernate Best Practices with ASP.NET Article.

The next code shows a sample how the code for composite keys are generated:

using System;
using System.Collections.Generic;

namespace Northwind.Core.Domain
{
    /// <span class="code-SummaryComment"><summary>
</span>
    /// EmployeeTerritory object for NHibernate mapped table EmployeeTerritories.
    /// <span class="code-SummaryComment"></summary>
</span>
    [Serializable]
    public class EmployeeTerritory : DomainObject<EmployeeTerritory.DomainObjectID>
    {

        [Serializable]
        public class DomainObjectID
        {
            private System.Int32 _EmployeeID;
            private System.String _TerritoryID;

            public DomainObjectID() { }
            
            public DomainObjectID(System.Int32 employeeID, System.String territoryID)
            {
                _EmployeeID = employeeID;
                _TerritoryID = territoryID;
            }

            public System.Int32 EmployeeID
            {
                get { return _EmployeeID; }
                protected set { _EmployeeID = value; }
            }

            public System.String TerritoryID
            {
                get { return _TerritoryID; }
                protected set { _TerritoryID = value; }
            }

            public override bool Equals(object obj)
            {
                if (obj == this) return true;
                if (obj == null) return false;

                DomainObjectID that = obj as DomainObjectID;
                if (that == null)
                {
                    return false;
                }
                else
                {
                    if (this.EmployeeID != that.EmployeeID) return false;
                    if (this.TerritoryID != that.TerritoryID) return false;
                    return true;
                }
            }

            public override int GetHashCode()
            {
                return EmployeeID.GetHashCode() ^ TerritoryID.GetHashCode();
            }
        }

        private Employee _EmployeeIDEmployees;
        private Territory _TerritoryIDTerritories;

        public EmployeeTerritory()
        {
        }

        public EmployeeTerritory(DomainObjectID id)
        {
            base.id = id;
        }

        public virtual System.Int32 EmployeeID
        {
            get { return base.id.EmployeeID; }
        }

        public virtual System.String TerritoryID
        {
            get { return base.id.TerritoryID; }
        }

        public virtual Employee EmployeeIDEmployees
        {
            get { return _EmployeeIDEmployees; }
            set { _EmployeeIDEmployees = value; }
        }

        public virtual Territory TerritoryIDTerritories
        {
            get { return _TerritoryIDTerritories; }
            set { _TerritoryIDTerritories = value; }
        }

        public override int GetHashCode()
        {
            return ID.GetHashCode();
        }
    }
}

Where EmployeeTerritory+DomainObjectID overrides the Equals and GetHashCode Methods.

Web Forms for Listing Records

SmartCode IDE

These templates generate Web Forms for listing records. All of them display records in an ASPGrid, 20 records at a time (by default), with controls for browsing the grid's contents; also, column headers may be clicked to sort rows and paging.

SmartCode IDE

Each row in the grid has hyperlinks to edit and view the corresponding record, and the pages include a "Add" button to create a new record. The grid is automatically populate when the page is loaded

Web Forms for Editing Records

SmartCode IDE

These templates generate Web Forms for creating and editing records.

SmartCode IDE

Moreover, these templates recognize attributes like the Control property has been set to ComboBox or Check Box.

SmartCode 
       IDE

The ComboBox control combinated with LOV property, produce custom DataTextField properties in the dropDown Web Control.

SmartCode 
       IDE

Summary

The possibilities for Smart Code templates are unlimited. Smart Code is an exceptionally powerful developer productivity tool. Coupled with the NHibernate templates you can write the base code for your application in a matter of minutes.

Web Application Project

The Sample Code uses the Web Application Project type of website for building web applications. This kind of web site is very similar to the .Net Framework 1.1 model.

You can get the installer for Web Application Projects at http://download.microsoft.com/download/9/0/6/906064ce-0bd1-4328-af40-49dca1aef87c/WebApplicationProjectSetup.msi. After downloading it you can just run it.

Changelog

  • Minor bug fix in composite-key definition

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Danilo Mendez
Web Developer
United States United States
Danilo is the creator of SmartRules, a Business Rules Engine. He is an industry consultant working primarily with companies interested in implementing dynamic rules programming concepts to add flexibility to their architectures on web, CE, and desktop platforms. He operates his own website, Kontac, where you will find more information.
 
To contact Danilo, email him at danilo.mendez@gmail.com.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralUnable to download any thingmemberjustintimberlake29-Aug-09 17:06 
Hi i am unbale to donwnload any thing related to this article
 
It leads to this page http://www.kontac.net/site/SmartCode/Download/tabid/64/Default.aspx and nothing happens even when i click on second level menu download :(
QuestionSmartCode version problemmemberFrancesca Nardi28-Apr-09 5:23 
I have a problem with SmartCode version.
Template project use 2.0 version, but version download of SmartCode Studio use 3.0 and I have an error on load NHibernateTemplate.dll
 
Can you help me!
 
Thank
QuestionSmartCode version problemmemberFrancesca Nardi28-Apr-09 5:31 
I receive this error message on load library
 
Le informazioni su come richiamare il debug JIT (Just-In-Time) anziché questa finestra
sono riportate in fondo al messaggio.
 
************** Testo dell'eccezione **************
System.Exception: Couldn't load Templates from library: NHibernateTemplates
Impossibile caricare uno o più tipi richiesti. Per ulteriori informazioni, recuperare la proprietà LoaderExceptions.
in Kontac.Net.SmartCode.Engine.Implementation.CodeEngine.GetEntityTemplates(LibraryInfo library)
in Kontac.Net.SmartCode.Studio.CodeGenerationDlg.AddTemplateNodes(LibraryInfo libray, TreeNode libraryNode)
in Kontac.Net.SmartCode.Studio.CodeGenerationDlg.AddAssemblyButton_Click(Object sender, EventArgs e)
in System.Windows.Forms.Control.OnClick(EventArgs e)
in System.Windows.Forms.Button.OnClick(EventArgs e)
in System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
in System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
in System.Windows.Forms.Control.WndProc(Message& m)
in System.Windows.Forms.ButtonBase.WndProc(Message& m)
in System.Windows.Forms.Button.WndProc(Message& m)
in System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
in System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
in System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
 

************** Assembly caricati **************
mscorlib
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
mscorlib.resources
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
SmartCode.Studio
Versione assembly: 3.0.1.28906
Versione Win32: 3.0.1.*
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/SmartCode.Studio.exe
----------------------------------------
System.Windows.Forms
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
WeifenLuo.WinFormsUI.Docking
Versione assembly: 2.2.2864.18696
Versione Win32: 2.2.0.0
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/WeifenLuo.WinFormsUI.Docking.DLL
----------------------------------------
System.Configuration
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Windows.Forms.resources
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms.resources/2.0.0.0_it_b77a5c561934e089/System.Windows.Forms.resources.dll
----------------------------------------
System.Web.Services
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System.Web.Services/2.0.0.0__b03f5f7f11d50a3a/System.Web.Services.dll
----------------------------------------
nbnwvd_o
Versione assembly: 3.0.1.28906
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
SmartCode.SchemaProvider
Versione assembly: 1.0.0.0
Versione Win32: 1.0.0.0
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/SmartCode.SchemaProvider.DLL
----------------------------------------
SmartCode.Model
Versione assembly: 3.0.0.0
Versione Win32: 3.0.0.0
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/SmartCode.Model.DLL
----------------------------------------
WizardLib
Versione assembly: 0.0.0.0
Versione Win32: 0.0.0.0
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/WizardLib.DLL
----------------------------------------
System.Data
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_32/System.Data/2.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Transactions
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_32/System.Transactions/2.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.EnterpriseServices
Versione assembly: 2.0.0.0
Versione Win32: 2.0.50727.3053 (netfxsp.050727-3000)
Base di codice: file:///C:/Windows/assembly/GAC_32/System.EnterpriseServices/2.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
SmartCode.Engine
Versione assembly: 1.0.0.0
Versione Win32: 1.0.0.0
Base di codice: file:///C:/Program%20Files/Kontac/SmartCode/SmartCode.Engine.DLL
----------------------------------------
NHibernateTemplates
Versione assembly: 1.0.0.0
Versione Win32: 1.0.0.0
Base di codice: file:///C:/Users/Michele/Sviluppo%20Software/Helper%20%20%26%20Add-inns/SmartRules/NHibernate/NHibernate/NHibernate/obj/Release/NHibernateTemplates.dll
----------------------------------------
AnswerRe: SmartCode version problemmemberDanilo Mendez Gamonal30-Apr-09 9:33 
Please download the last SmartCode setup from
http://www.kontac.net/site/SmartCode/tabid/55/Default.aspx
 
The setup create several projects, between them and usually in 'C:\Program Files\SmartCode\Source\
the project named 'NHibernate Best Practices'. Open and compile with the dll's located in C:\Program Files\SmartCode\
and finally create a new project with the download SmartRules
 
Danilo
GeneralCannot compile mapping documentmemberbrenor6-Apr-09 6:28 
Hi,
My domain is quite similar to what you've described in your article.
 
I'm wondering if the syntax
 class="Northwind.Core.Domain.EmployeeTerritory+DomainObjectID"
is correct, as i get the 'could not compile the mapping document..'
GeneralStart using SmartCodememberMarcoFIerro4-Feb-09 11:17 
Hi,
 
I am very interested in using a code generation tool, and SmartCode seems to be very interesting.
 
But ... I can't make it work or even load the sample project (Newin.scp) provided in http://www.codeproject.com/KB/cs/NHibernate_Templates.aspx.
 
Also, I cannot find any documentation describing, step by step, how to use the product.
 
Could anyone help me?
 
Thanks in advance.
 
marco
GeneralRe: Start using SmartCodememberLeonelCorso3-Apr-09 9:54 
Hey Marco
 
I'm having the same problem. Were you able to solve it?
 
Leonel
GeneralCombine it with a visual designermemberElGuroProgramador30-Jul-08 7:17 
Nice tool.
Bit the missing part in a larger project is the designer, to have an overview about the classes.
 
szenario 1)
DB exists, no problem for the current template, works!
 
szenario 2)
new project, new DB. Many tabels, many changes, no overview without visual designer.
Possible class design tools are Visio and Visual Studio.
- Is there is visio template anywhere to generate hbm files and classes?
 
- In Visual Studio designer i can design the classes and constraints.
Now i get my classes, but now? How can i get the hbm and class files to map it with nhibernate?
GeneralSQL Create statementsmemberElGuroProgramador30-Jul-08 7:08 
Nice codegen template to generate the classes an hbm files.
 
I know that nhibernate can generate the database tables, but it is not useable if some tables exits and only a few tables are new.
So it would be nice to have a generated class.sql file also, to minimize the error between generated code / hbm / and database.
 
Is there a way to generate this with the template?
GeneralI can not download the studiomembersonnywong29-Jun-08 23:19 
The third link is not available
GeneralI don't get code for Stored ProceduresmemberGerardo Palazuelos G.16-Jan-08 12:00 
Hi,
Excellent tool!.
 
Sorry I don't get it, but I try out your tool but I don't get any code for Stored Procedures.
 
Could you help me?
GeneralRe: I don't get code for Stored ProceduresmemberDanilo Mendez17-Jan-08 10:24 
Gerardo
 
Unzip the source code and search into next directory
'SourceCode\Templates\StoreProcedures' for the StoreProcedures-style templates
 
Danilo
Me alegra que te sea util esta herramienta
Questionhow nhibernate-mapping.xsd was createdmemberThanks for all the fish12-Dec-07 8:12 
or how to generate nhibernate-mapping.xsd?
GeneralRe: how nhibernate-mapping.xsd was createdmemberDanilo Mendez12-Dec-07 10:31 
use the templates attached into code generator source
 
Danilo
GeneralDomain Model VS Domain Tablesmemberomarvr7212-Dec-07 4:20 
Hello,
 
Excellent article and content.
 
Just a note:
Sometimes when we think level domain, we may want to create two objects domain associated with a single table in the database.
 
Did not thought about any of this for this generation tool?
 
Thanks
Omar
GeneralRe: Domain Model VS Domain TablesmemberDanilo Mendez12-Dec-07 10:31 
Omar
May be you can add a new property to the relationship between 2 tables (domain) and play with them....
 
Danilo
QuestionHow to debug templatesmembergiammin20-Sep-07 5:35 
I used to generate code by mygeneration but your app is really better!!
 
i'm custumizing some template and i found exceptions due to my code error.
 
there is a easy way to debug template?
 
thanks
AnswerRe: How to debug templatesmemberDanilo Mendez20-Sep-07 5:55 
Do it...
1. In VS 2005, Set your break point into dll source code.
2. Run Smart Code Studio
3. Goto debug menu and select attach, on the new windows, locate the smartcode.exe process and select it.
4. Generate code with smart code, obviusly, select at least one time the template choose for debug.
5. Done

GeneralRe: How to debug templatesmembergiammin20-Sep-07 6:11 
Thanks
i did so but i didn't set any breakpoint and becouse of exception handling i thought vs2008 didn't attach to process.
 
i resolved
 
thanks
GeneralProject template checkboxmembergiammin19-Sep-07 8:09 
Sorry but i don't understand what is it for....
 
you says: " Notice, if you check the Item it Template run only one time, because it is an project level template."
 
please could you explain me the usage of Project template checkbox
 
GREAT APP!!
GeneralRe: Project template checkboxmembergiammin19-Sep-07 9:59 
no problem! i find out!
GeneralRe: Project template checkboxmemberDanilo Mendez20-Sep-07 5:47 
Nice,
NewsVisual Studio Web Applications Projects is now part of VS 2005 SP1 [modified]memberAbel Braaksma11-Sep-07 12:45 
The information at the beginning of this article is out of date: W-A-P as separate download is no longer supported by Microsoft. Instead of downloading the Web Application Projects, you'll need to download Service Pack 1 for Visual Studio 2005. They added it to in June 2007 and since then, they discourage downloading the separate package.
 
If you have Web Application Projects already installed previously, you must uninstall it before installing SP1.
 
This was explained here and this is the actual download for Visual Studio 2005 SP1 (it is huge: 430+MB).
 
Keep up the good project, Very nice!
 
Cheers,
-- Abel Braaksma
http://abelleba.metacarpus.com
 

-- modified at 2:48 Thursday 13th September, 2007
Generalcannot assign views to templatememberukungx15-Aug-07 4:18 
views don't appear in object list so i cannot assign view to template, i have added views before clicked generate icon, i also checked the checkbox under objects list pane but the views still doesnt appear so i cannot assign view to the template
 
i use nhibernate/web template from example including in this article
 
thank you for your smart code, its make life happier Smile | :)
QuestionRe: cannot assign views to templatememberukungx19-Aug-07 21:38 
anybody please help me how to assign views to a template since views doesn't appear when i started generate process (views doesn't appear in Setting Code Generation pop-up window so i cannot to assign views to a template)
AnswerRe: cannot assign views to templatememberDanilo Mendez5-Sep-07 1:17 
This bug was fixed in the last release, please download and try again
 
Danilo
GeneralFor those who prefer Mapping.Attributes....memberDamonCarr14-Aug-07 3:09 

Nice work! You should also consider the software factory approach here.. It fits your model far better (the GAT, DSL, etc..). Someday when I am bored I am going to sit dowe and extend the Microsoft Web Client software factory for this.
 
I have modified this in a number of significant ways (good work by the way... Just what I needed).
 
Most importantly, this generates only Attributes, never hbm files. For those who have made the switch to attribute based mapping, most never go back in my experience. It is far easier in 95% of the cases (yes there are some caveats but the RawXML attribute clears them up almost 100%). It is very rare indeed to ever NOT do a large project with 100% attributes for my firm and I.
 
Anyhow, if there is interest I would consider making this new template (also HEAVILY refactored) into open source on CodePlex or wherever.
 
Kind Regards,
Damon Carr, CTO
agilefactor
GeneralRe: For those who prefer Mapping.Attributes....memberDanilo Mendez14-Aug-07 4:57 
Hello Damon
 
Well I am new in NHibernate, but I read in someone site that there are extensions for replace the hbm files with attributes and you confirmed that is possible.
It look that you've done a great deal of good work for your side, modifing the original templates to generate Attributes for NHibernate mapping.
I am sure that the community will be thanks, if you share your set of templates with them (and me Smile | :) ). I offer to you add your CodePlex account to the SmartCode developer's Team and add your templates to the core setup of SmartCode. Also I want to create a new SmartCode Template Projects to separate the SmartCode project from Templates projects, because both are differents projects ( If I fix a bug in any templates I need make a new setup of All project).
 
Danilo Mendez
Smart Rules Architect
www.kontac.net
danilo.mendez@kontac.net
GTalk, MSN: danilo.mendez@gmail.com
Technology That Understands Business.
GeneralRe: For those who prefer Mapping.Attributes....memberDamonCarr20-Aug-07 6:09 
Excellent! I actually have started a codeplex project doing exactly that so I propose my team simply joins your team.
 
This is up and running and we are using it in production. Here are some items we really need:
 
(perhaps this is all possible):
 
1) Ability to invoke this application as a command line application (or at least pass the project file as a parameter to the main GUI)
 
2( Ability to integrate this such that we can make this a Visual Studio 2005+ Addin to automatically add files to the project you select.
 
This would also mean allowing the user in your tool to see the Visual Studio project layout and select the folder they want code to go to (for each item).
 

There is a lot more but that should be good for now.
 
We are doing a lot more as well.... Generation of TestFixtures with Mocks, etc.
 
My email is damon@agilefactor.com and the project is : NHibernate Attributes Power Toys.
 
Thanks,
Damon Carr, CTO
agilefactor
GeneralSome Changes to Make it work for mememberAndi Baso11-Aug-07 19:09 
I makes some change for NHibernate Template and WebTemplates, Refer to Billy Comment in NHibernate BestPractices
In NHibernate Template DomainObject.cs
1.change namespace:
WriteLine(@"namespace {0}.Core.Domain", Helper.PascalCase(Domain.Code));
2. Change visibility:
WriteLine(@" protected IdT id = default(IdT);");
3.Change to virtual :
WriteLine(@" public virtual IdT ID {");
WriteLine(@" get { return id; }");
WriteLine(@" protected set { id = value; }");
WriteLine(@" }");

public virtual bool IsTransient() {
return ID == null || ID.Equals(default(IdT));
}

In WebTemplateProject, line 128 file EditCodeBehind.cs, place it at line 110, so it look like this :
foreach (ColumnSchema column in primaryKeyColumns)
{
WriteLine(@" ui{0}.{1} = Request.QueryString[""{0}""];", column.Code, Helper.GetValueOrText(column));
}
if (primaryKeyColumns.Count == 1)
{
WriteLine(@" {0} ID = {1};", primaryKeyColumns[0].NetDataType, Helper.GetConvertToNETType(primaryKeyColumns[0], "ui" + primaryKeyColumns[0].Code + "." + Helper.GetValueOrText(primaryKeyColumns[0])));
}
else
{
foreach (ColumnSchema column in primaryKeyColumns)
{
if (domainObjectIDArgs != "")
{
domainObjectIDArgs += ", ";
}
domainObjectIDArgs += Helper.GetConvertToNETType(column, "ui" + column.Code + "." + Helper.GetValueOrText(column));
}
}
 
W();

I'm using oracle and makes some changes in SmartCode Studio and rebuild it to make sure Oracle DataType Mapping Correctly. Nice Jobs Danilo.
 
andibaso
GeneralRe: Some Changes to Make it work for mememberDanilo Mendez13-Aug-07 12:22 
Hello andi
 
Thanks for provide the changes for the templates, I will update the code at soon as possible.
 
Danilo Mendez.
GeneralRe: Some Changes to Make it work for mememberAndi Baso13-Aug-07 16:45 
i'm forget, i prefer using Convert.ToString() than ToString() because i found error Error: Object reference not set to an instance of an object when string is null, so i change WebTemplates on EditCodeBehind.cs line 157, so it look like this :
WriteLine(@" ui{0}.{1} = Convert.ToString(entity.{0});", column.Code, Helper.GetValueOrText(column));.
CMIIW
GeneralOracle connection problemmemberVladimirCh16-Jul-07 22:10 
Hi
I was not able to make it connect to Oracle
Let's say I have a TNS entry:
ORA10_GKNTEST =
   (DESCRIPTION =
      (ADDRESS_LIST =
         (ADDRESS = (PROTOCOL = TCP)(HOST = BALORA10)(PORT = 1521))
      )
      (CONNECT_DATA =
         (SERVICE_NAME = GKNTEST)
      )
   )
 
I tried every combination possible:
oracle/[username]:[pass]@ora10_gkntest - "URL cannot be parsed", then "Object reference not set to an instance of an object."
oracle/[username]:[pass]@balora10/ora10_gkntest - "Connection attemp successful.", then "Specified cast is not valid."
oracle/[username]:[pass]@localhost/ora10_gkntest - "Connection attemp successful.", then "Specified cast is not valid."
oracle/[username]:[pass]@xxx.xxx.xxx.xxx/ora10_gkntest - "Connection attemp successful.", then "Specified cast is not valid."
 
Is there any way to make it work?
GeneralRe: Oracle connection problemmemberDanilo Mendez17-Jul-07 1:32 
The "Specified cast is not valid." message is caused by the provider, it work fine in Oracle 8 and 9 I am not tested it with Oracle 10. Can you Debug the source code?
 
Danilo Mendez
GeneralRe: Oracle connection problemmemberghollins20-Jul-07 5:31 
I am having the same issue except I get No data exists for the row or column. Can you help?
GeneralRe: Oracle connection problemmemberVladimirCh20-Jul-07 5:40 
I've sent the author the fixed code for OracleSchemaExtractor, but haven't received any reply from him yet. The code had been actually very raw.
I guess you have to wait for the next release, or you can download the sources and build it yourself.
 
I can supply you with the fixed sources (not sure that all the bugs've been fixed, kinda short of time now).
 
Just write here of you need it.
GeneralRe: Oracle connection problem [modified]memberDanilo Mendez20-Jul-07 6:13 
Thanks Vladimir,
This weekend I'll update the Smart Code setup
 
Thanks
Danilo
 


GeneralRe: Oracle connection problemmemberghollins20-Jul-07 6:40 
Can you send me the fixed src?
 
Thanks

GeneralRe: Oracle connection problemmemberghollins20-Jul-07 6:47 
Thats ok I've fixed it.
GeneralRe: Oracle connection problemmemberDanilo Mendez21-Jul-07 7:40 
Bug fixed by Vladimir, please download the last release of SmartCode
 
Danilo.
 

GeneralI can't open your site:http://www.kontac.net/WelcomeSC.aspxmemberpaulyuan7-Jul-07 21:53 
could you give me a release?
 
yuanxhsoft@126.com
 
thanks!
GeneralRe: I can't open your site:http://www.kontac.net/WelcomeSC.aspxmemberDanilo Mendez Gamonal8-Jul-07 0:54 
Try
 
http://www.codeplex.com/smartcode/Release/ProjectReleases.aspx?ReleaseId=4354
 
Danilo
GeneralRe: I can't open your site:http://www.kontac.net/WelcomeSC.aspxmemberpaulyuan9-Jul-07 21:52 
Thanks !
 
it's a really great tool!
 
Paul
GeneralFew ItemsmemberStevieGen4-Jul-07 16:04 
Not sure if you are basing on the Enterprise for Billy:
 
NHibernateDaoFactory
 
Can you include the :
 
private string sessionFactoryConfigPath;
 
public NHibernateDaoFactory(string sessionFactoryConfigPath)
{
Check.Require(sessionFactoryConfigPath != null, "sessionFactoryConfigPath may not be null");
SessionFactoryConfigPath = sessionFactoryConfigPath;
}
 

 
protected string SessionFactoryConfigPath
{
get { return sessionFactoryConfigPath; }
set { sessionFactoryConfigPath = value; }
}
 

also:
for example:
public IAuthorDao GetAuthorDao()
{
return new AuthorDao(sessionFactoryConfigPath); <--- set this
}
 
--
for the web:
create the CustomHttpHandler for Windsor
 
Also - config files? ie. CastleConfig and NHibernateConfig ?
 
Any plans for Presenters and Views ?
 
---
 
For each Dao: ie.
 
namespace Blog.Data
{
public class BlogDao : AbstractNHibernateDao, IBlogDao
{
public BlogDao(string sessionFactoryConfigPath)
: base(sessionFactoryConfigPath)
{
}
}
}
 
Currently missing the constructor?
 

Great tool so far - enjoying it!!!
GeneralRe: Few ItemsmemberDanilo Mendez Gamonal4-Jul-07 16:39 
The sample is based in the "BasicSample" provided for Billy article, btw you can port the templates to the EE, making some minor changes to the templates.
 
...Danilo
QuestionJava/HibernatememberThe Wizard of Doze4-Jul-07 7:56 
Can Smart Code generate Java code for Hibernate (this is a serious question)? What would I need to do in order to make it work for Java/Hibernate?

AnswerRe: Java/HibernatememberDanilo Mendez Gamonal4-Jul-07 8:39 
Sure, it is an serious response Smile | :) ...you can generate any text, e.g. Stored procedure, Jsp code, java code, VB Code, inclusive some friends mine are using SmartCode to generate code to PHP applications.
 
To generate java/NHibernate code, modify the templates included in the article to create the java classes.
 
Danilo Mendez
Smart Rules Architect
www.nrules.com
danilo.mendez@kontac.net
Technology That Understands Business.
 

GeneralRe: Java/HibernatememberThe Wizard of Doze4-Jul-07 10:18 
Danilo Mendez Gamonal wrote:
you can generate any text, e.g. Stored procedure, Jsp code, java code, VB Code, inclusive some friends mine are using SmartCode to generate code to PHP applications.

 
Cool! Thank you very much! Smile | :)

GeneralConnection StringmemberStevieGen3-Jul-07 14:41 
I use sql express and my string would look like:
 
./SQLEXPRESS
 
It doesn't appear that the tool supports this type of string?
 
ie. the format is mssql2005/(local)/Northwind
 
I need to have something like mssql2005/./SQLEXPRESS/Northwind ?
 
Can I just put a standard connection string in the dialog?
GeneralRe: Connection StringmemberDanilo Mendez Gamonal3-Jul-07 14:53 
try to use the IP of your Computer, or....try
 
mssql2005/.\SQLEXPRESS/Northwind
 
Good luck!
 
Danilo

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 11 Dec 2007
Article Copyright 2007 by Danilo Mendez
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid