HOME
User:
Anonymous
search for
in
Template Archives
Templates
Articles
Users
Login
Username:
Password:
Navigation
Registered User Functions:
Register New Account
Anonymous Functions:
Home
Users
Archives
Templates
Articles
MyGeneration Website
MyGeneration Forums
Categories
Application Type
Command Line
Graphical User Interface
Library
Sample
Web Application
Architecture Type
Client-Server
Distributed Computing
Multi-Tier
Peer-to-peer
Operating System
Linux
Win32
Programming Language
ASP
ASP.Net
C#
C++
Firebird SQL
J#
Java
Jet SQL
JScript
JSP
MySQL
Perl
PHP
PL/SQL
PostgreSQL
SQL
Transact-SQL
VB.Net
VBScript
XSLT
Template: NHibernate Object Mapping 1.2 by Serdar
Download Count:
12990
View Count:
4538
Template Properties
Unique ID:
158a7d34-a15e-40f9-8399-255f8f85f76c
Title:
NHibernate Object Mapping 1.2 by Serdar
Namespace:
NHibernate
Output Language:
C#
Mode:
Markup
Start Tag:
<%
End Tag:
%>
Template Body
Engine:
.Net Script
Language:
C#
<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization %><% public class GeneratedTemplate : DotNetScriptTemplate { private ArrayList _selectedTables; private ArrayList _selectedViews; private string _dbName; private string _tableName; private string _className; private string _exportPath; private string _fileName; private string _nameSpace; private string _assemblyName; private string _inheritFrom; private string _prefix; private string _licenseComment; private string _ide; private bool _createClassFiles; private bool _createXmlFiles; private bool _createReadOnly; private bool _generateEqualsHashCode; private bool _useNull; private bool _dontCreateFK; private bool _enableLazyClass; private bool _enableNullTypes; private bool _CreatingXML = false; private bool _createProjectFiles = false; private bool _createInternalAccessors = false; private bool _useFakeIDInViews = true; private StringBuilder _projectContentCS = new StringBuilder(); private StringBuilder _projectContentXML = new StringBuilder(); private string _NullSufix; public GeneratedTemplate( ZeusContext context ) : base( context ) {} public override void Render() { _dbName = input["chooseDatabase"].ToString(); _selectedTables = input["chooseTables"] as ArrayList; _selectedViews = input["chooseViews"] as ArrayList; _exportPath = input["outputPath"].ToString(); _nameSpace = input["classNamespace"].ToString(); _assemblyName = input["assemblyName"].ToString(); _inheritFrom = input["inheritFrom"].ToString(); _prefix = input["memberPrefix"].ToString(); _licenseComment = input["licenseComment"].ToString(); _ide = input["cmbIDE"].ToString(); _createClassFiles = (bool)input["chkClass"]; _createXmlFiles = (bool)input["chkMapping"]; _createReadOnly = (bool)input["chkReadOnly"]; _generateEqualsHashCode = (bool)input["chkEqualsHashCode"]; _useNull = (bool)input["chkUseNull"]; _dontCreateFK = (bool)input["chkDontCreateFK"]; _enableLazyClass = (bool)input["chkLazyClass"]; _enableNullTypes = (bool)input["chkEnableNullTypes"]; _createProjectFiles = (bool)input["chkProject"]; _createInternalAccessors = (bool)input["chkCreateInternalAccessors"]; _useFakeIDInViews = (bool)input["chkUseFakeIDInViews"]; _NullSufix = (_enableNullTypes ? "?" : ""); if( _licenseComment.Length > 0 ){ if( _licenseComment.StartsWith( "/*" )) _licenseComment = _licenseComment.Substring( 2 ); if( _licenseComment.EndsWith( "*/" )) _licenseComment = _licenseComment.Substring( 0, _licenseComment.Length - 2 ); } foreach( string _newTable in _selectedTables ) { ITable _workingTable = MyMeta.Databases[_dbName].Tables[_newTable]; _tableName = _workingTable.Alias.Replace( " ", "" ); _className = ToPascalCase( _tableName ); if( _createClassFiles ) { GenerateClassFile( _workingTable.Columns ); } if( _createXmlFiles ) { GenerateMappingFile( _workingTable.Columns ); } if( _createProjectFiles ) { AddProjectFileContent(); } } foreach( string _newView in _selectedViews ) { IView _workingView = MyMeta.Databases[_dbName].Views[_newView]; _tableName = _workingView.Alias.Replace( " ", "" ); _className = ToPascalCase( _tableName ); if( _createClassFiles ) { GenerateClassFile( _workingView.Columns ); } if( _createXmlFiles ) { GenerateMappingFile( _workingView.Columns ); } if( _createProjectFiles ) { AddProjectFileContent(); } } if( _createProjectFiles && ( _createClassFiles || _createXmlFiles )) GenerateProjectFiles(); %> Operation Successful.<% } //read guid of the existing project private string GetGuid( string fileName, string searchString ){ string guid = System.Guid.NewGuid().ToString().ToUpper(); if( File.Exists( fileName ) ){ TextReader tx = new StreamReader( fileName ); string txt = tx.ReadToEnd(); tx.Close(); int i = txt.IndexOf( searchString ); if( i > 10 ){ return txt.Substring( i + searchString.Length, 36 ); } } return guid; } private string GetSourceControl( int v ){ string fileName = Path.Combine( _exportPath, _assemblyName + ".csproj" ); if( !File.Exists( fileName ) ) return ""; TextReader tx = new StreamReader( fileName ); string txt = tx.ReadToEnd(); tx.Close(); switch(v){ case 2003: if(txt.Length > 20 && txt.Substring(0,21) != "<VisualStudioProject>") return ""; break; case 2005: if(txt.Length > 8 && txt.Substring(0,9) != "<Project ") return ""; break; } StringBuilder sb = new StringBuilder(); AddPrjPropVal(v, "SccProjectName", txt, sb); AddPrjPropVal(v, "SccLocalPath", txt, sb); AddPrjPropVal(v, "SccAuxPath", txt, sb); AddPrjPropVal(v, "SccProvider", txt, sb); return sb.ToString(); } private void AddPrjPropVal( int v, string prpName, string prjTxt, StringBuilder sb ){ int i = prjTxt.IndexOf( prpName ); if( i < 0 ) return; i = prjTxt.IndexOf(( v == 2003 ? "=" : ">" ), i + prpName.Length) + 1; switch(v){ case 2003: sb.Append( "\x000D\x000A " + prpName + " =" + prjTxt.Substring(i, prjTxt.IndexOf("\x000D", i) - i) ); return; case 2005: sb.Append( "\x000D\x000A <" + prpName + ">" + prjTxt.Substring(i, prjTxt.IndexOf("/>", i) - i) + "</" + prpName + ">" ); return; } } private void GenerateProjectFiles() { Directory.CreateDirectory( Path.Combine( _exportPath, "bin/Debug" )); Directory.CreateDirectory( Path.Combine( _exportPath, "bin/Release" )); Directory.CreateDirectory( Path.Combine( _exportPath, "obj/Debug" )); Directory.CreateDirectory( Path.Combine( _exportPath, "obj/Release" )); switch(_ide){ case "2003": %><VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{<%=GetGuid( Path.Combine( _exportPath, _assemblyName + ".csproj" ), "ProjectGuid = \"{" )%>}"<%=GetSourceControl(2003)%> > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "<%=_assemblyName%>" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "<%=_assemblyName%>" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "..\..\..\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "..\..\..\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "..\..\..\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" BuildAction = "Compile" /><%=_projectContentCS.ToString().Replace("*"," ")%> </Include> </Files> </CSHARP> </VisualStudioProject> <% break; case "2005": Directory.CreateDirectory( Path.Combine( _exportPath, "Properties" )); %><Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>8.0.50727</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{<%=GetGuid( Path.Combine( _exportPath, _assemblyName + ".csproj" ), "<ProjectGuid>{" )%>}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace><%=_assemblyName%></RootNamespace> <AssemblyName><%=_assemblyName%></AssemblyName><%=GetSourceControl(2005)%> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Properties\AssemblyInfo.cs" /><%=(_projectContentCS.ToString() + _projectContentXML.ToString()).Replace("*"," ")%> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project><% break; } output.save( Path.Combine( _exportPath, _assemblyName + ".csproj" ), false ); output.clear(); switch(_ide){ case "2003": %>using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the "project output directory". The location of the project output // directory is dependent on whether you are working with a local or web project. // For local projects, the project output directory is defined as // <Project Directory>\obj\<Configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // For web projects, the project output directory is defined as // %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj\<Configuration>. // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] <% output.save( Path.Combine( _exportPath, "AssemblyInfo.cs" ), false ); break; case "2005": %>using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("<%=_assemblyName%>")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("<%=_assemblyName%>")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("<%=GetGuid( Path.Combine( _exportPath, "Properties/AssemblyInfo.cs" ), "[assembly: Guid(\"" ).ToLower()%>")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] <% output.save( Path.Combine( _exportPath, "Properties/AssemblyInfo.cs" ), false ); break; } output.clear(); } private void AddProjectFileContent() { if(!( _createClassFiles || _createXmlFiles ))return; switch(_ide){ case "2003": if( _createClassFiles ) _projectContentCS.Append( @" ****************<File ********************RelPath = """ ).Append( _className ).Append( @".cs"" ********************SubType = ""Code"" ********************BuildAction = ""Compile"" ****************/>" ); if( _createXmlFiles ) _projectContentCS.Append( @" ****************<File ********************RelPath = """ ).Append( _className ).Append( @".hbm.xml"" ********************BuildAction = ""EmbeddedResource"" ****************/>" ); break; case "2005": if( _createClassFiles ) _projectContentCS.Append( @" ****<Compile Include=""" ).Append( _className ).Append( @".cs"" />" ); if( _createXmlFiles ){ if( _projectContentXML.Length == 0 ) _projectContentXML.Append( @" **</ItemGroup> **<ItemGroup>" ); _projectContentXML.Append( @" ****<EmbeddedResource Include=""" ).Append( _className ).Append( @".hbm.xml"" />" ); } break; } } private void GenerateClassFile( IColumns Columns ) { _CreatingXML = false; %>/* <%=( _licenseComment.Length == 0 ? "insert license info here" : _licenseComment )%> */ using System; namespace <%= _nameSpace %> { /// <summary> /// Generated by MyGeneration using the Serdar's NHibernate Object Mapping 1.1 template (based on Gustavo's) - serdar@argelab.net /// </summary> [Serializable] public <%=(_enableLazyClass ? "" : "sealed ")%>class <%= _className %> <% if (_inheritFrom.Length > 0) { %> : <%=_inheritFrom%> <% } %> { <% BuildPrivateMembers( Columns ); %> <% BuildDefaultConstructor( Columns ); if( _createInternalAccessors ){%> <% BuildInternalAccessors( Columns ); }%> <% BuildPublicAccessors( Columns ); %> <% BuildPublicFunctions( Columns ); %> <% if( _generateEqualsHashCode ) BuildEqualsHashCodeOverrides( Columns ); %> } } <% _fileName = _className + ".cs"; output.save( Path.Combine( _exportPath, _fileName ), false ); output.clear(); } private void GenerateMappingFile( IColumns Columns ) { _CreatingXML =true; BuildHBMDefinition( Columns ); _fileName = _className + ".hbm.xml"; output.save( Path.Combine( _exportPath, _fileName ), false ); output.clear(); } private void BuildDefaultConstructor( IColumns Columns ) { %>#region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public <%= _className %>() {<% foreach( IColumn field in Columns ) { string fieldName = ColumnToMemberVariable( field ); string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey && !_dontCreateFK ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) ); if( fieldType.EndsWith( "[]" ) ) { %> <%= fieldName %> = new <%= fieldType %>{}; <% } else { switch( fieldType ) { case "string":%> <%= fieldName %> = <% if(_useNull){ %>null; <% } else {%> String.Empty; <% } break; case "DateTime":%> <%= fieldName %> = DateTime.MinValue; <% break; case "bool":%> <%= fieldName %> = false; <% break; case "decimal": case "float": case "double": case "byte": case "short": case "int": case "long":%> <%= fieldName %> = 0; <% break; default:%> <%= fieldName %> = <% if(_useNull){ %> null; <% } else {%> new <%= fieldType %>(); <% } break; } } }%> } #endregion // End of Default ( Empty ) Class Constuctor<% } private void BuildRequiredConstructor( IColumns Columns ) { if( CountRequiredFields( Columns ) > 0 && CountNullableFields( Columns ) < Columns.Count ) { %>#region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public <%= _className %>(<% bool first = true; foreach( IColumn col in Columns ) { if( !col.IsNullable ) { if( !first ) output.write( ", " ); output.write( ColumnToNHibernateType( col ) + " " + ColumnToArgumentName( col ) ); first = false; } } %>) {<% foreach( IColumn col in Columns ) { if( !col.IsNullable ) { %> <%= ColumnToMemberVariable( col ) %> = <%= ColumnToArgumentName( col ) %>; <% } else { if( ColumnToNHibernateType( col ).EndsWith( "[]" ) ) { %> <%= ColumnToMemberVariable( col ) %> = new <%= ColumnToNHibernateType( col ) %>{}; <% } else { switch( ColumnToNHibernateType( col ) ) { default:%> <%= ColumnToMemberVariable( col ) %> = null; <% break; case "string":%> <%= ColumnToMemberVariable( col ) %> = <% if(_useNull){ %>null; <% } else {%> String.Empty; <% } break; case "DateTime":%> <%= ColumnToMemberVariable( col ) %> = DateTime.MinValue; <% break; case "bool":%> <%= ColumnToMemberVariable( col ) %> = false; <% break; case "decimal": case "double": case "float": case "byte": case "short": case "int": case "long":%> <%= ColumnToMemberVariable( col ) %> = 0; <% break; } } } } %> } #endregion // End Required Fields Only Constructor<% } } private void BuildFullConstructor( IColumns Columns ) { %>#region Full Constructor /// <summary> /// full constructor /// </summary> public <%= _className %>(<% bool first = true; foreach( IColumn field in Columns ) { if( !first ) output.write( ", " ); output.write( ( field.IsInForeignKey && !field.IsInPrimaryKey && !_dontCreateFK ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) ) + " " + ColumnToArgumentName( field ) ); first = false; }%>) {<% foreach( IColumn col in Columns ) { %> <%= ColumnToMemberVariable( col ) %> = <%= ColumnToArgumentName( col ) %>; <% } %> } #endregion // End Full Constructor<% } private void BuildEqualsHashCodeOverrides( IColumns Columns ) { %> #region Equals And HashCode Overrides /// <summary> /// local implementation of Equals based on unique value members /// </summary> public override bool Equals( object obj ) { if( this == obj ) return true; if( ( obj == null ) || ( obj.GetType() != this.GetType() ) ) return false; <%= _className %> castObj = (<%= _className %>)obj; <% if( CountUniqueFields( Columns ) == 0 ) {%> return castObj.GetHashCode() == this.GetHashCode()<% } else {%> return ( castObj != null )<% foreach( IColumn c in Columns ) { if( c.IsInPrimaryKey ) { %> && ( this.<%= ColumnToMemberVariable( c ) %> == castObj.<%= ColumnToPropertyName( c ) %> )<% } } } %>; } /// <summary> /// local implementation of GetHashCode based on unique value members /// </summary> public override int GetHashCode() { <% if( CountUniqueFields( Columns ) == 0 ) { %>return this.GetType().FullName.GetHashCode(); <% } else {%> int hash = 57; <% foreach( IColumn c in Columns ) { if( c.IsInPrimaryKey ) { %> hash = 27 * hash * <%= ColumnToMemberVariable( c ) %>.GetHashCode();<% } } %> return hash; <% }%> } #endregion <% } private void BuildPrivateMembers( IColumns Columns ) { if( Columns.Count > 0 ) { %>#region Private Members private bool <%= _prefix %>isChanged; private bool <%= _prefix %>isDeleted;<% foreach( IColumn field in Columns ) { if( field.IsInForeignKey && !field.IsInPrimaryKey && !_dontCreateFK) {%> private <%= ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) %> <%= ColumnToMemberVariable( field ) %>; <% } else {%> private <%= ColumnToNHibernateType( field ) %> <%= ColumnToMemberVariable( field ) %>; <% } } %> #endregion<% } } private void BuildInternalAccessors( IColumns Columns ) { if( Columns.Count > 0 ) { %>#region Internal Accessors for NHibernate <% foreach( IColumn field in Columns ) { string fieldAccessor = ColumnToNHibernateProperty( field ); string fieldName = ColumnToMemberVariable( field ); string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey && !_dontCreateFK ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) ); %> /// <summary> /// <%= field.Description %> /// </summary> internal <%=(_enableLazyClass ? "virtual" : "")%> <%= fieldType %> <%= fieldAccessor %> { get { return <%= fieldName %>; }<% if( !_createReadOnly ) { %> set { <%= fieldName %> = value; }<% } %> } <% } %> #endregion // Internal Accessors for NHibernate <% } } private void BuildPublicAccessors( IColumns Columns ) { if( Columns.Count > 0 ) { %>#region Public Properties <% foreach( IColumn field in Columns ) { string fieldAccessor = ColumnToPropertyName( field ); string fieldName = ColumnToMemberVariable( field ); string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey && !_dontCreateFK ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) ); %> /// <summary> /// <%= field.Description %> /// </summary> public <%=(_enableLazyClass ? "virtual" : "")%> <%= fieldType %> <%= fieldAccessor %> { get { return <%= fieldName %>; }<% if( !_createReadOnly ) { //if(!((field.IsInPrimaryKey && field.IsAutoKey) || field.IsComputed)) //{ switch( fieldType ) { default:%> set { <%= _prefix %>isChanged |= (<%= fieldName %> != value); <%= fieldName %> = value; }<% break; case "byte[]": %> set { if( value != null && value.Length > <%= field.CharacterMaxLength.ToString() %>) throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString()); <%= _prefix %>isChanged |= (<%= fieldName %> != value); <%= fieldName %> = value; } <% break; case "string": %> set { if ( value != null ) if( value.Length > <%= field.CharacterMaxLength.ToString() %>) throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString()); <%= _prefix %>isChanged |= (<%= fieldName %> != value); <%= fieldName %> = value; }<% break; } //} }%> } <% } %> /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public <%=(_enableLazyClass ? "virtual " : "")%>bool IsChanged { get { return <%= _prefix %>isChanged; } } /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public <%=(_enableLazyClass ? "virtual " : "")%>bool IsDeleted { get { return <%= _prefix %>isDeleted; } } #endregion <% } } private void BuildPublicFunctions( IColumns Columns ) {%> #region Public Functions /// <summary> /// mark the item as deleted /// </summary> public <%=(_enableLazyClass ? "virtual " : "")%>void MarkAsDeleted() { <%= _prefix %>isDeleted = true; <%= _prefix %>isChanged = true; } #endregion<% } private void BuildHBMDefinition( IColumns Columns ) { if( Columns.Count > 0 ) { output.writeln( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" ); output.writeln( NHibernateMappingTag() ); output.writeln( "\t" + NHibernateClassTag( Columns ) ); output.writeln( "\t\t" + NHibernatePrimaryKeysTag( Columns ) ); output.writeln( "\t\t" + NHibernateProperties( Columns ) ); output.writeln( "\t</class>" ); output.writeln( "</hibernate-mapping>" ); } } private string NHibernateMappingTag() { //// can't handle external mappings ?!? ////string xml = "<hibernate-mapping xmlns=\"http://nhibernate.sourceforge.net/schemas/nhibernate-mapping-2.0.xsd\""; //string xml = "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.0\""; //// handle schemas, cascade, import, and access methods? //return xml + ">"; return "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.0\">"; } private string NHibernateClassTag( IColumns Columns ) { //ITable t = Columns[0].Table; //IView v = Columns[0].View; //string desc = ( t == null ) ? v.Description : t.Description; StringBuilder xml = new StringBuilder(); xml.Append( "<class name=\"" ).Append( _nameSpace ).Append( "." ).Append( _className ).Append( "," ); if (_assemblyName.Length > 0) xml.Append( _assemblyName ).Append( "\"" ); else xml.Append( _nameSpace ).Append( "\"" ); xml.Append( " table=\"" ).Append( _tableName ).Append( "\"" ); if(_enableLazyClass) { xml.Append( " lazy=\"true\"" ); } if( _createReadOnly || (Columns.Count > 0 && Columns[0].View != null)) { xml.Append( " mutable=\"false\"" ); } // handle schema override, dynamic insert & update, and proxies? xml.Append( ">\r\n" ); return xml.ToString(); } private string NHibernatePrimaryKeysTag( IColumns Columns ) { StringBuilder xml = new StringBuilder(); int i = 0; foreach( IColumn c in Columns ) { if( c.IsInPrimaryKey ) { i++; } } if( i == 0 ) { //add fake id for views if( Columns.Count > 0 && Columns[0].View != null && _useFakeIDInViews ) { IColumn c = Columns[0]; xml.Append( "<id name=\"" ).Append( ColumnToPropertyNameNH( c ) ).Append( "\" column=\"" ); xml.Append( c.Alias ).Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" ); xml.Append( ">\r\n\t\t\t<generator class=\"native\"/>\r\n\t\t</id>" ); return xml.ToString(); } else return " <!-- could not find a primary key for this table/view. NHibernate requires an 'id' element, so you'll have to define one manually. -->"; } if( i == 1 ) { foreach( IColumn c in Columns ) { if( c.IsInPrimaryKey ) { xml.Append( "<id name=\"" ).Append( ColumnToPropertyNameNH( c ) ).Append( "\" column=\"" ); xml.Append( c.Alias ).Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" ); switch( ColumnToNHibernateType( c ) ) { case "decimal": case "float": case "double": case "short": case "int": case "long": xml.Append( " unsaved-value=\"0\">\r\n" ); break; default: xml.Append( ">\r\n" ); break; } xml.Append( "\t\t\t<generator class=\"" ); xml.Append( ( c.IsAutoKey || c.IsComputed ) ? "native" : "assigned" ); xml.Append( "\"/>\r\n\t\t</id>" ); } } } if( i > 1 ) { xml.Append( "<composite-id access=\"field\">" ); xml.Append( "\r\n\t\t\t" ); foreach( IColumn c in Columns ) { if( c.IsInPrimaryKey ) { xml.Append(" <key-property name=\"").Append( ColumnToPropertyNameNH( c ) ).Append( "\" column=\"" ); xml.Append( c.Alias ).Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" ); switch( ColumnToNHibernateType( c ) ) { case "decimal": case "float": case "double": case "short": case "int": case "long": xml.Append( " />\r\n" ); break; default: xml.Append( "/>\r\n" ); break; } xml.Append( "\t\t\t" ); } } xml.Append( "\r\n\t\t</composite-id>\r\n\t\t" ); xml.Append( "<!-- Composite primary key is experimental. View the documentation for syntax. -->" ); xml.Append( "<!-- problems: gustavohe@gmail.com -->" ); } return xml.ToString(); } private string NHibernateProperties( IColumns Columns ) { StringBuilder xml = new StringBuilder(); bool ff = true; foreach( IColumn c in Columns ) { if( (!c.IsInPrimaryKey) && (!(ff && Columns.Count > 0 && Columns[0].View != null && _useFakeIDInViews)) ) { // create sets & such for foreign keys !!! if( c.IsInForeignKey && !_dontCreateFK) { if( c.ForeignKeys.Count > 1 ) { xml.Append( "<!-- more than one foreign column is mapped to " ).Append( c.Name ).Append( " - you're on your own. -->\r\n\t\t" ); } else { IForeignKey fk = c.ForeignKeys[0]; xml.Append( "<many-to-one name=\"" ).Append( ColumnToPropertyNameNH( c ) ).Append( "\" column=\"" ).Append( c.Name ); xml.Append( "\" class=\"" ).Append( _nameSpace ).Append( "." ).Append( ToPascalCase( fk.PrimaryTable.Alias.Replace( " ", "" ) ) ).Append( "," ).Append( _nameSpace ).Append( "\" />\r\n\t\t" ); } } else { xml.Append( "<property column=\"" ).Append( c.Name ); xml.Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" ); if( _createReadOnly ) { xml.Append( " access=\"field\" name=\"" ).Append( ColumnToMemberVariable( c ) ).Append( "\"" ); } else { xml.Append( " name=\"" ).Append( ColumnToPropertyNameNH( c ) ).Append( "\"" ); } if( !c.IsNullable ) { xml.Append( " not-null=\"true\"" ); } if( c.LanguageType == "string" || c.DataTypeName == "binary" || c.DataTypeName == "binaryobject" ) { xml.Append( " length=\"" ).Append( c.CharacterMaxLength ).Append( "\"" ); } xml.Append( " />\r\n\t\t" ); } } ff = false; } return xml.ToString(); } private string ConvertNHibernate( string Type ) { string retVal = Type; switch( Type ) { case "bool": retVal = "Boolean"; break; case "byte": retVal = "Byte"; break; case "sbyte": retVal = "SByte"; break; case "char": retVal = "Char"; break; case "decimal": retVal = "Decimal"; break; case "double": retVal = "Double"; break; case "float": retVal = "Single"; break; case "int": retVal = "Int32"; break; case "uint": retVal = "UInt32"; break; case "long": retVal = "Int64"; break; case "ulong": retVal = "UInt64"; break; case "short": retVal = "Int16"; break; case "ushort": retVal = "UInt16"; break; case "string": retVal = "String"; break; case "byte[]": retVal = "BinaryBlob"; break; } return retVal; } private string ColumnToMemberVariable( IColumn Column ) { return ToLower( _prefix + UniqueColumn( Column ) ); } private string ColumnToPropertyName( IColumn Column ) { return ToPascalCase( UniqueColumn( Column ) ); } private string ColumnToPropertyNameNH( IColumn Column ) { return ( _createInternalAccessors ? "_" : "" ) + ToPascalCase( UniqueColumn( Column ) ); } private string ColumnToArgumentName( IColumn Column ) { return ToLower( UniqueColumn( Column ) ); } private string ColumnToNHibernateProperty( IColumn Column ) { return /*_prefix +*/ "_" + ToPascalCase( UniqueColumn( Column ) ); } private string UniqueColumn( IColumn Column ) { string c = Column.Alias.Replace( " ", "" ); if( Column.Table != null && Column.Table.Alias.Replace( " ", "" ) == c ) { c += "Name"; } if( Column.View != null && Column.View.Alias.Replace( " ", "" ) == c ) { c += "Name"; } return c; } // nhibernate doesn't have these, so use the existing types private string ColumnToNHibernateType( IColumn Column ) { string retVal = Column.LanguageType; switch( retVal ) { case "sbyte": retVal = "byte"; break; case "uint": retVal = "int"; break; case "ulong": retVal = "long"; break; case "ushort": retVal = "short"; break; case "bool": case "decimal": case "double": case "float": case "byte": case "short": case "int": case "long": if (!_CreatingXML){ if(Column.IsNullable) { retVal = retVal + _NullSufix; } } break; } if( Column.DataTypeName == "binary" || Column.DataTypeName == "binaryobject" ) retVal = "byte[]"; return retVal; } private string ToLeadingCaps( string name ) { char[] chars = ToLower( name ).ToCharArray(); chars[0] = ToUpper( chars[0] ); return new string( chars ); } private string ToLeadingLower( string name ) { char[] chars = name.ToCharArray(); chars[0] = ToLower( chars[0] ); return new string( chars ); } private string ToPascalCase( string name ) { string notStartingAlpha = Regex.Replace( name, "^[^a-zA-Z]+", "" ); string workingString = ToLowerExceptCamelCase( notStartingAlpha ); workingString = RemoveSeparatorAndCapNext( workingString ); return workingString; } private string RemoveSeparatorAndCapNext( string input ) { string dashUnderscore = "-_"; string workingString = input; char[] chars = workingString.ToCharArray(); int under = workingString.IndexOfAny( dashUnderscore.ToCharArray() ); while( under > -1 ) { chars[ under + 1 ] = ToUpper( chars[ under + 1 ] ); workingString = new String( chars ); under = workingString.IndexOfAny( dashUnderscore.ToCharArray(), under + 1 ); } chars[ 0 ] = ToUpper( chars[ 0 ] ); workingString = new string( chars ); return Regex.Replace( workingString, "[-_]", "" ); } private string ToLowerExceptCamelCase( string input ) { char[] chars = input.ToCharArray(); for( int i = 0; i < chars.Length; i++ ) { int left = ( i > 0 ? i - 1 : i ); int right = ( i < chars.Length - 1 ? i + 1 : i ); if( i != left && i != right ) { if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ left ] ) && Char.IsUpper( chars[ left ] ) ) { chars[i] = ToLower( chars[i] ); } else if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ right ] ) && Char.IsUpper( chars[ right ] ) ) { chars[i] = ToLower( chars[i] ); } else if( Char.IsUpper( chars[i] ) && !Char.IsLetter( chars[ right ] ) ) { chars[i] = ToLower( chars[i] ); } } } chars[ chars.Length - 1 ] = ToLower( chars[ chars.Length - 1 ] ); return new string( chars ); } private int CountRequiredFields( IColumns Columns ) { return Columns.Count - CountNullableFields( Columns ); } private int CountNullableFields( IColumns Columns ) { int i = 0; foreach( IColumn c in Columns ) { if( c.IsNullable ) { i++; } } return i; } private int CountUniqueFields( IColumns Columns ) { int i = 0; foreach( IColumn c in Columns ) { if( !c.IsNullable && c.IsInPrimaryKey ) { i++; } } return i; } private char ToLower( char c ) { c = Char.ToLower( c, CultureInfo.InvariantCulture ); return ( c != 305 ) ? c : 'i'; } private string ToLower( string s ) { return s.ToLower().Replace( "\u0131", "i" ); } private char ToUpper( char c ) { c = Char.ToUpper( c, CultureInfo.InvariantCulture ); return ( c != 304 ) ? c : 'I'; } private string ToUpper( string s ) { return s.ToUpper().Replace( "\u0130", "I" ); } } %>
Dynamic Interface:
Engine:
.Net Script
Language:
C#
<%#REFERENCE System.Windows.Forms.dll %> <%#NAMESPACE System, System.Text, System.Collections, Zeus, Zeus.UserInterface, Zeus.DotNetScript, Microsoft.Win32 %> public class GeneratedGui : DotNetScriptGui { public GeneratedGui( ZeusGuiContext context ) : base( context ) {} GuiTextBox classNamespace; GuiTextBox assemblyName; GuiTextBox inheritFrom; GuiTextBox licenseComment; GuiTextBox outputPath; GuiTextBox memberPrefix; GuiCheckBox chkUseNull; GuiCheckBox chkDontCreateFK; GuiCheckBox chkEqualsHashCode; GuiCheckBox chkReadOnly; GuiCheckBox chkClass; GuiCheckBox chkMapping; GuiCheckBox chkLazyClass; GuiCheckBox chkEnableNullTypes; GuiCheckBox chkProject; GuiCheckBox chkCreateInternalAccessors; GuiCheckBox chkUseFakeIDInViews; GuiComboBox cmbIDE; public override void Setup() { RegistryKey reg ; reg = Registry.CurrentUser; reg = reg.CreateSubKey("Software"); reg = reg.CreateSubKey("Serdar"); reg = reg.CreateSubKey("nHibernateScript"); if ( !input.Contains( "chooseTables" ) || !input.Contains( "txtPath" ) || ( !input.Contains( "chkClass" ) && !input.Contains( "chkNaming" ) ) ) { ui.Title = "Serdar's NHibernate Object Mapping - serdar@argelab.net"; ui.Width = 790; ui.Height = 695; ui.StartPosition = "Manual"; ui.Left = 130; ui.Top = 20; // Grab default output path string sOutputPath = ""; if( input.Contains( "defaultOutputPath" ) ) { sOutputPath = input["defaultOutputPath"].ToString(); } // Locates the folder in the register reg = Registry.CurrentUser; reg = reg.OpenSubKey("Software\\Serdar\\nHibernateScript"); /**************************************************************************************************/ // Section Title GuiLabel lblMappingSection = ui.AddLabel( "lblMappingSection", "Hibernate Mapping Settings", "Hibernate Mapping Settings" ); lblMappingSection.Top = 10; lblMappingSection.Left = 10; lblMappingSection.Width = 150; lblMappingSection.Bold = true; // Create Mappings Checkbox chkMapping = ui.AddCheckBox( "chkMapping", "Create mapping files.", getBool(reg.GetValue("Mapping", "true")), "Create an XML file for each table or view selected. (*.hbm.xml)" ); chkMapping.Top = lblMappingSection.Top; chkMapping.Left = lblMappingSection.Left + 220; chkMapping.Width = 135; // Set Assembly Name Label GuiLabel lblAssemblyName = ui.AddLabel("lblAssemblyName", "Class Assembly: ", "Enter the class assembly name." ); lblAssemblyName.Top = lblMappingSection.Top + 25; lblAssemblyName.Left = lblMappingSection.Left; lblAssemblyName.Width = 130; // Set Assembly Name Textbox assemblyName = ui.AddTextBox( "assemblyName", "NHibernate", "Enter the class assembly name." ); assemblyName.Top = lblAssemblyName.Top; assemblyName.Left = lblAssemblyName.Left + lblAssemblyName.Width; assemblyName.Width = 200; assemblyName.Text = (string)reg.GetValue("assemblyName", "NHibernate"); // Set Namespace Label GuiLabel lblNamespace = ui.AddLabel( "lblNamespace", "Class Namespace: ", "Enter your objects namespace." ); lblNamespace.Top = assemblyName.Top; lblNamespace.Left = 420; lblNamespace.Width = lblAssemblyName.Width; // Set Namespace Textbox classNamespace = ui.AddTextBox( "classNamespace", "NHibernate.DAL", "Enter your objects namespace." ); classNamespace.Top = lblNamespace.Top; classNamespace.Left = lblNamespace.Left + lblNamespace.Width; classNamespace.Width = assemblyName.Width; classNamespace.Text = (string)reg.GetValue("classNamespace", "NHibernate"); /**************************************************************************************************/ /**************************************************************************************************/ // Section Title GuiLabel lblClassSection = ui.AddLabel( "lblClassSection", "Hibernate Class Settings", "Hibernate Class Settings" ); lblClassSection.Top = classNamespace.Top + classNamespace.Height + 15; lblClassSection.Left = 10; lblClassSection.Width = 150; lblClassSection.Bold = true; // Create Classes CheckBox chkClass = ui.AddCheckBox( "chkClass", "Create class files.", getBool(reg.GetValue("Class", "true")), "Create a class file for each table or view selected. (*.cs)" ); chkClass.Top = lblClassSection.Top; chkClass.Left = lblClassSection.Left + 220; chkClass.Width = 120; // Set member variable prefix label GuiLabel lblMemberPrefix = ui.AddLabel( "lblMemberPrefix", "Member variable prefix: ", "Enter a prefix for member variables." ); lblMemberPrefix.Top = lblClassSection.Top + 25; lblMemberPrefix.Left = lblClassSection.Left; lblMemberPrefix.Width = 130; // Set member variable prefix Textbox memberPrefix = ui.AddTextBox( "memberPrefix", "_", "Enter a prefix for member variables." ); memberPrefix.Top = lblMemberPrefix.Top; memberPrefix.Left = lblMemberPrefix.Left + lblMemberPrefix.Width; memberPrefix.Width = 200; memberPrefix.Text = (string)reg.GetValue("memberPrefix", "_"); // Set inherit from label GuiLabel lblInheritFrom = ui.AddLabel( "lblInheritFrom", "Inherit from: ", "Enter a namespace for all generated classes to inherit from." ); lblInheritFrom.Top = memberPrefix.Top + 25; lblInheritFrom.Left = lblClassSection.Left; lblInheritFrom.Width = lblMemberPrefix.Width; // Set inherit from textbox inheritFrom = ui.AddTextBox( "inheritFrom", "", "Enter a namespace for all generated classes to inherit from." ); inheritFrom.Top = lblInheritFrom.Top; inheritFrom.Left = lblInheritFrom.Left + lblInheritFrom.Width; inheritFrom.Width = memberPrefix.Width; inheritFrom.Text = (string)reg.GetValue("inheritFrom", ""); // Set license comment label GuiLabel lblLicenseComment = ui.AddLabel( "lblLicenseComment", "License Comment: ", "Enter license information for the header of class files." ); lblLicenseComment.Top = lblClassSection.Top + 25; lblLicenseComment.Left = 420; lblLicenseComment.Width = lblMemberPrefix.Width; // Set license comment textbox licenseComment = ui.AddTextBox( "licenseComment", "", "Enter license information for the header of class files." ); licenseComment.Top = lblLicenseComment.Top; licenseComment.Left = lblLicenseComment.Left + lblLicenseComment.Width; licenseComment.Width = memberPrefix.Width; licenseComment.Multiline = true; licenseComment.Height = 60; licenseComment.Text = (string)reg.GetValue("licenseComment", ""); /**************************************************************************************************/ /**************************************************************************************************/ // Section Title GuiLabel lblProjectSection = ui.AddLabel( "lblProjectSection", "VS Project Settings", "Visual Studio Project Settings" ); lblProjectSection.Top = inheritFrom.Top + inheritFrom.Height + 15; lblProjectSection.Left = 10; lblProjectSection.Width = 150; lblProjectSection.Bold = true; // Create Project CheckBox chkProject = ui.AddCheckBox( "chkProject", "Create project files.", getBool(reg.GetValue("Project", "true")), "Create .csproj & AssemblyInfo.cs files" ); chkProject.Top = lblProjectSection.Top; chkProject.Left = lblProjectSection.Left + 220; chkProject.Width = 120; // Set target ide label GuiLabel lblIDE = ui.AddLabel( "lblIDE", "Target IDE: ", "Select your Visual Studio version to generate project files." ); lblIDE.Top = lblProjectSection.Top + 25; lblIDE.Left = lblProjectSection.Left; lblIDE.Width = 130; // Set target ide combobox cmbIDE = ui.AddComboBox("cmbIDE", "Select your Visual Studio version to generate project files."); cmbIDE.Top = lblIDE.Top; cmbIDE.Left = lblIDE.Left + lblIDE.Width; cmbIDE.Width = 200; cmbIDE["2003"] = "Visual Studio.Net 2003"; cmbIDE["2005"] = "Visual Studio.Net 2005"; cmbIDE.SelectedValue = (string)reg.GetValue("cmbIDE", "2003"); /**************************************************************************************************/ /**************************************************************************************************/ // Section Title GuiLabel lblOptionsSection = ui.AddLabel( "lblOptionsSection", "Generation Options", "Options specific to generated classes and mappings." ); lblOptionsSection.Top = lblIDE.Top + lblIDE.Height + 15; lblOptionsSection.Left = 10; lblOptionsSection.Width = 150; lblOptionsSection.Bold = true; /******************************************/ // Lazy Loading CheckBox chkLazyClass = ui.AddCheckBox( "chkLazyClass", "Enable Lazy Loading.", getBool(reg.GetValue("LazyClass", "true")), "Enable Lazy Loading." ); chkLazyClass.Top = lblOptionsSection.Top + 20; chkLazyClass.Left = lblOptionsSection.Left; chkLazyClass.Width = 175; // Allow null checkbox chkUseNull = ui.AddCheckBox( "chkUseNull", "Use null in the Constructor", getBool(reg.GetValue("UseNull", "true")), "User type = null in the Constructor." ); chkUseNull.Top = chkLazyClass.Top + 20; chkUseNull.Left = chkLazyClass.Left; chkUseNull.Width = 175; /******************************************/ // Don't Create FK checkbox chkDontCreateFK = ui.AddCheckBox( "chkDontCreateFK", "Don't create foreign key reference.", getBool(reg.GetValue("DontCreateFK", "false")), "Don't create foreign key class reference." ); chkDontCreateFK.Top = lblOptionsSection.Top + 20; chkDontCreateFK.Left = chkLazyClass.Left + chkLazyClass.Width + 10; chkDontCreateFK.Width = 200; // Create Equals() CheckBox chkEqualsHashCode = ui.AddCheckBox( "chkEqualsHashCode", "Create Equals and GetHashCode.", getBool(reg.GetValue("EqualsHashCode", "true")), "Generate Equals and GetHashCode methods." ); chkEqualsHashCode.Top = chkDontCreateFK.Top + 20; chkEqualsHashCode.Left = chkDontCreateFK.Left; chkEqualsHashCode.Width = 200; /******************************************/ // Enable Nullable Types checkbox chkEnableNullTypes = ui.AddCheckBox( "chkEnableNullTypes", "Enable nullable types.", getBool(reg.GetValue("EnableNullTypes", "false")), "Enable nullable types. Works with .net 2.0." ); chkEnableNullTypes.Top = lblOptionsSection.Top + 20; chkEnableNullTypes.Left = chkDontCreateFK.Left + chkDontCreateFK.Width + 10; chkEnableNullTypes.Width = 175; /******************************************/ // Read-Only checkbox chkReadOnly = ui.AddCheckBox( "chkReadOnly", "Create as read-only.", getBool(reg.GetValue("ReadOnly", "false")), "Create object and mapping to have read-only access." ); chkReadOnly.Top = lblOptionsSection.Top + 20; chkReadOnly.Left = chkEnableNullTypes.Left + chkEnableNullTypes.Width + 10; chkReadOnly.Width = 175; /******************************************/ // Create internal accessors checkbox chkCreateInternalAccessors = ui.AddCheckBox( "chkCreateInternalAccessors", "Create NHibernate Accessors", getBool(reg.GetValue("CreateInternalAccessors", "false")), "Create NHibernate accessors to fix IsChanged state problem (arises after loading data)." ); chkCreateInternalAccessors.Top = chkDontCreateFK.Top + 20; chkCreateInternalAccessors.Left = chkDontCreateFK.Left + chkDontCreateFK.Width + 10; chkCreateInternalAccessors.Width = 175; /******************************************/ // Use fake id for views checkbox chkUseFakeIDInViews = ui.AddCheckBox( "chkUseFakeIDInViews", "Use fake id in views", getBool(reg.GetValue("UseFakeIDInViews", "true")), "Use the first column of view as fake id." ); chkUseFakeIDInViews.Top = chkDontCreateFK.Top + 20; chkUseFakeIDInViews.Left = chkEnableNullTypes.Left + chkEnableNullTypes.Width + 10; chkUseFakeIDInViews.Width = 175; // Blank spacer GuiLabel spacer = ui.AddLabel( "spacer", "", ""); spacer.Top = chkReadOnly.Top + 20; spacer.Left = chkReadOnly.Left; spacer.Width = 1; /**************************************************************************************************/ /**************************************************************************************************/ // Section Title GuiLabel lblOutputPath = ui.AddLabel( "lblOutputPath", "Output Path: ", "Select the output path for generated content." ); lblOutputPath.Top = chkUseNull.Top + 30; lblOutputPath.Left = 10; lblOutputPath.Width = 70; // Output folder Textbox and File Picker outputPath = ui.AddTextBox("outputPath", sOutputPath, "Select the output path for generated content."); outputPath.Top = lblOutputPath.Top; outputPath.Left = lblOutputPath.Left + lblOutputPath.Width; outputPath.Width = 400; outputPath.Text = (string)reg.GetValue("outputPath", sOutputPath); GuiFilePicker selectPath = ui.AddFilePicker( "selectPath", "Browse", "Select a directory to output generated content.", "outputPath", true ); selectPath.Top = outputPath.Top; selectPath.Left = outputPath.Left + outputPath.Width + 10; selectPath.Width = 52; /**************************************************************************************************/ /**************************************************************************************************/ // Section Title GuiLabel lblDatabaseMappings = ui.AddLabel( "lblDatabaseMappings", "Database Mappings", "Select database mappings below." ); lblDatabaseMappings.Top = outputPath.Top + 35; lblDatabaseMappings.Left = 10; lblDatabaseMappings.Width = 150; lblDatabaseMappings.Bold = true; // Set Database DropDown GuiLabel lblChooseDatabase = ui.AddLabel("lblChooseDatabase", "Source Database: ", "Select a database to generate content from." ); lblChooseDatabase.Top = lblDatabaseMappings.Top + 25; lblChooseDatabase.Left = lblDatabaseMappings.Left; lblChooseDatabase.Width = 100; GuiComboBox chooseDatabase = ui.AddComboBox( "chooseDatabase", "Select a database to generate content from." ); chooseDatabase.Top = lblChooseDatabase.Top; chooseDatabase.Left = lblChooseDatabase.Left + lblChooseDatabase.Width; chooseDatabase.Width = classNamespace.Width; // Setup Tables selection multi-select listbox. GuiLabel lblTableSelect = ui.AddLabel( "lblTableSelect", "Select tables:", "Select tables from the listbox below." ); lblTableSelect.Top = chooseDatabase.Top + 25; lblTableSelect.Left = lblDatabaseMappings.Left; lblTableSelect.Width = lblDatabaseMappings.Width; GuiListBox chooseTables = ui.AddListBox( "chooseTables", "Select tables." ); chooseTables.Top = lblTableSelect.Top + 20; chooseTables.Width = 350; chooseTables.Height = 200; // Setup Views selection multi-select listbox. GuiLabel lblViewSelect = ui.AddLabel( "lblViewSelect", "Select views:", "Select views from the listbox below." ); lblViewSelect.Top = lblTableSelect.Top; lblViewSelect.Left = 420; lblViewSelect.Width = lblTableSelect.Width; GuiListBox chooseViews = ui.AddListBox( "chooseViews", "Select views." ); chooseViews.Top = lblViewSelect.Top + 20; chooseViews.Left = lblViewSelect.Left; chooseViews.Width = chooseTables.Width; chooseViews.Height = chooseTables.Height; // Attach the onchange event to the cmbDatabases control. setupDatabaseDropdown( chooseDatabase ); chooseDatabase.AttachEvent( "onchange", "chooseDatabase_onchange" ); /**************************************************************************************************/ GuiButton btnSave = ui.AddButton("btnSave", "Save Settings", "Save all changes."); btnSave.AttachEvent("onclick", "btnSave_onclick"); ui.ShowGui = true; } else { ui.ShowGui = false; } } public void setupDatabaseDropdown( GuiComboBox Databases ) { try { if( MyMeta.IsConnected ) { Databases.BindData( MyMeta.Databases ); if( MyMeta.DefaultDatabase != null ) { Databases.SelectedValue = MyMeta.DefaultDatabase.Alias; bindTables( Databases.SelectedValue ); bindViews( Databases.SelectedValue ); } } } catch { } } public void bindTables( string sDatabase ) { int count = 0; GuiListBox lstTables = ui["chooseTables"] as GuiListBox; try { IDatabase db = MyMeta.Databases[sDatabase]; lstTables.BindData( db.Tables ); } catch { } } public void bindViews( string sDatabase ) { int count = 0; GuiListBox lstViews = ui["chooseViews"] as GuiListBox; try { IDatabase db = MyMeta.Databases[sDatabase]; lstViews.BindData( db.Views ); } catch { } } public void chooseDatabase_onchange( GuiComboBox control ) { int count = 0; GuiComboBox cmbDatabases = ui["chooseDatabase"] as GuiComboBox; bindTables( cmbDatabases.SelectedText ); bindViews( cmbDatabases.SelectedText ); } private bool getBool(object valor){ return Boolean.Parse((string) valor); } public void btnSave_onclick(GuiButton btnSave) { RegistryKey reg ; reg = Registry.CurrentUser; reg = reg.CreateSubKey("Software"); reg = reg.CreateSubKey("Serdar"); reg = reg.CreateSubKey("nHibernateScript"); reg.SetValue("classNamespace", classNamespace.Text); reg.SetValue("outputPath", outputPath.Text); reg.SetValue("memberPrefix", memberPrefix.Text); reg.SetValue("DontCreateFK", chkDontCreateFK.Value.ToString()); reg.SetValue("UseNull", chkUseNull.Value.ToString()); reg.SetValue("EqualsHashCode", chkEqualsHashCode.Value.ToString()); reg.SetValue("ReadOnly", chkReadOnly.Value.ToString()); reg.SetValue("Class", chkClass.Value.ToString()); reg.SetValue("Project", chkProject.Value.ToString()); reg.SetValue("Mapping", chkMapping.Value.ToString()); reg.SetValue("LazyClass", chkLazyClass.Value.ToString()); reg.SetValue("EnableNullTypes", chkEnableNullTypes.Value.ToString()); reg.SetValue("assemblyName", assemblyName.Text); reg.SetValue("inheritFrom", inheritFrom.Text); reg.SetValue("licenseComment", licenseComment.Text); reg.SetValue("cmbIDE", cmbIDE.SelectedValue); reg.SetValue("CreateInternalAccessors", chkCreateInternalAccessors.Value.ToString()); reg.SetValue("UseFakeIDInViews", chkUseFakeIDInViews.Value.ToString()); } }
Copyright © 2004 MyGeneration Software. All rights reserved.
Feedback:
feedback@mygenerationsoftware.com
Support:
support@mygenerationsoftware.com