2005年06月14日

Gentle.NETのサンプル

NHibernateとは別の.NET用O/Rマッピングツール「Gentle.NET」の
サンプルを紹介します。

以下のようなGentleSampleソリューションを考えます。

GentleSample
├─lib
│      FirebirdSql.Data.Firebird.dll
│      Gentle.Common.dll
│      Gentle.Framework.dll
│      Gentle.Provider.Firebird.dll
│      Gentle.Provider.Jet.dll
│      Gentle.Provider.MySQL.dll
│      Gentle.Provider.Oracle.dll
│      Gentle.Provider.OracleODP.dll
│      Gentle.Provider.PostgreSQL.dll
│      Gentle.Provider.SQLite.dll
│      Gentle.Provider.SQLServer.dll
│      Gentle.Provider.SQLServerCE.dll
│      Gentle.Provider.Sybase.dll
│      Gentle.Provider.SybaseASA.dll
│      log4net.dll
│      QuickGraph.Algorithms.dll
│      QuickGraph.dll
│     
├─sql
│      Users.sql
│     
└─src
    │  GentleSample.sln
    │ 
    └─Console
            App.config
            App.ico
            AssemblyInfo.cs
            Console.csproj
            Console.csproj.user
            ConsoleMain.cs
            Users.cs
           

このサンプルのファイル


Gentle.NETのバージョンは、1.2.3です。
主なファイルの内容は以下のようになっています。

App.config

<?xml version="1.0" encoding="utf-8" ?>

<!-- This file is a sample .NET configuration file. 
  To enable logging in Gentle you must either
  include this as your main configuration file or
  add the log4net section handler and log4net
  section to your own configuration file.
 
  Gentle itself will read settings from here if a 
  <gentle> section handler has been declared. If it
  is not present, Gentle will look for a file called 
  Gentle.config.
  You can specify the location and name of the
  stand-alone config file by adding an entry to the 
  AppSettings section of this file. Last, you can
  manually pass an XML fragment to Gentle's 
  Configurator class and force Gentle to use that. 
-->

<configuration>

 <!-- This section is used by the .NET framework to 
  identify which handler to use for which
  section in the XML confoguration file. -->
 <configSections>
  <!-- Register a section handler for Gentle (the
  <gentle> section) -->
  <section name="gentle" 
   type="Gentle.Common.GentleSectionHandler, 
    Gentle.Common" />
  <!-- Register a section handler for the log4net 
    section -->
  <section name="log4net" type="log4net.Config.Log4
NetConfigurationSectionHandler, log4net" />
 </configSections>

 <!-- This section contains the Gentle configuration 
  settings -->
 <gentle>
  <Gentle.Framework>
  
   <!-- See the API documentation for the 
     Gentle.Framework.GentleSettings class for
     detailed information on the keys available
     in the Options section -->
   <Options>
  
    <!-- the default timeout value in seconds for 
      IDbCommand instances created by Gentle -->
    <CommandTimeout>30</CommandTimeout>  

    <!-- whether to enable support for Gentle-managed 
      concurrency control columns -->
    <ConcurrencyControl>false</ConcurrencyControl>
    
    <!-- options: Attributes or XML (XML currently
      unused) -->
    <MasterDefinition>XML</MasterDefinition>
    <Analyzer>
     <!-- options: None, OnDemand (the default), 
        Full -->
     <Level>Full</Level>
     <!-- whether to warn about unmapped columns
        and other non-fatal errors -->
     <Silent>false</Silent>
    </Analyzer>

    <Cache>
     <!-- default cache strategy (use only Never
        or Temporary) -->
     <DefaultStrategy>Temporary</DefaultStrategy>
     <CacheStatements>true</CacheStatements>
     <CacheObjects>true</CacheObjects>
     <!-- when true Gentle will try to bypass query
        execution and compose
       the result from cached data alone -->
     <SkipQueryExecution>false</SkipQueryExecution>
     <!-- the scope within which to ensure uniqing
       options: Thread (default) or Application -->
     <UniqingScope>Thread</UniqingScope>
    </Cache>
    <Logging>
     <Verbosity>Debug</Verbosity>
     <Frailty>Debug</Frailty>
     <!-- "All" toggles all groups; use as first 
        option to turn all on or off -->
     <Category name="All" enabled="false" />
     <!-- Individual groups; use to selectively
        turn a group on or off -->
     <Category name="StatementExecution"
      enabled="true" />
     <Category name="Cache" enabled="true" />
     <Category name="Metadata" enabled="true" />
    </Logging>
   </Options>

   <!--   
   <NamespaceProviders>
    <Namespace namespace="Gentle.First"  
      provider="SQLServer" connectionstring="..." />
    <Namespace namespace="Gentle.Second" 
      provider="SQLServer" connectionString="..." />
   </NamespaceProviders>
   -->
   
   <DefaultProvider name="SQLServer" 
    connectionString="data source=127.0.0.1;
      initial catalog=Northwind;user id=mm;
      password=xxx;Connection Reset=false;
      packet size=4096" />

   <!--
   <DefaultProvider name="Firebird"
    connectionString="User=SYSDBA;
      Password=masterkey;Database=localhost 
        /3050:C:\Code\Gentle.NET\Source\Gen
        tle.Framework.Tests\Database Files\
        Gentle_Firebird.fdb;Dialect=3;
      Charset=UNICODE_FSS;Role=;Connection 
      lifetime=30;Pooling=true;Packet Size=8192;" />
   <DefaultProvider name="Jet" 
      connectionString="Provider=Microsoft.Jet.
      OLEDB.4.0;Data Source =C:\Code\Gentle.NET\
      Source\Gentle.Framework.Tests\Database 
      Files\Gentle_MSAccess.mdb;" />
   <DefaultProvider name="MySQL" 
      connectionString="Server=10.0.0.2;
      Database=test;User ID=xxx;Password=xxx" />
   <DefaultProvider name="PostgreSQL" 
      connectionString="Server=10.0.0.2;
      Database=Test;User ID=xxx;Password=xxx" />
   <DefaultProvider name="Oracle"
     connectionString="Data Source=kermit.
      symbiote.sporadicism.com,1521;
      User ID=gentle;password=xxx" />
   <DefaultProvider name="OracleODP" 
     connectionString="Data Source=kermit.
      symbiote.sporadicism.com,1521;
      User ID=gentle;password=xxx" />
   <DefaultProvider name="SQLite"
     connectionString="URI=file:c:/Code/Gentl
     e.NET/Source/Gentle.Framework.Tests 
     /Database Files/Gentle_SQLite/>
   <DefaultProvider name="SQLServer" 
    connectionString="data source=127.0.0.1;
     initial catalog=Test;user id=xxx;
     password=xxx;packet size=4096" />
   -->
  
   <Providers>
    <!-- list known provider assemblies; the
      assembly .dll suffix is optional
      <Provider name="CE" 
        assembly="Gentle.Provider.CE" /> 
    -->
    <Provider name="Firebird" 
      assembly="Gentle.Provider.Firebird" />
    <Provider name="Jet"
      assembly="Gentle.Provider.Jet" />
    <Provider name="MySQL"
      assembly="Gentle.Provider.MySQL.dll" />
    <Provider name="Oracle"
      assembly="Gentle.Provider.Oracle" />
    <Provider name="OracleODP"
      assembly="Gentle.Provider.OracleODP" />
    <Provider name="PostgreSQL"
      assembly="Gentle.Provider.PostgreSQL" />
    <Provider name="SQLite"
      assembly="Gentle.Provider.SQLite" />
    <Provider name="SQLServer"
      assembly="Gentle.Provider.SQLServer" />
    <Provider name="Sybase"
      assembly="Gentle.Provider.Sybase" />
    <Provider name="SybaseASA"
      assembly="Gentle.Provider.SybaseASA" />
   </Providers>
  </Gentle.Framework>
 </gentle>


 <!-- This section contains the log4net 
  configuration settings -->
 <log4net>
  <appender name="ConsoleAppender" 
    type="log4net.Appender.ConsoleAppender">
   <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern"
      value="%d [%t] %-5p %c (%P{hostname}) 
        [%x] - %m%n" />
   </layout>
  </appender>
  <appender name="RollingLogFileAppender" 
    type="log4net.Appender.RollingFileAppender">
   <param name="File" value="Gentle.NET.log"/>
   <param name="AppendToFile" value="true"/>
   <param name="MaxSizeRollBackups" value="10"/>
   <param name="MaximumFileSize" value="100MB"/>
   <param name="RollingStyle" value="Size"/>
   <param name="StaticLogFileName" value="true"/>
   <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern"
      value="%d [%t] %-5p %c [%x] - %m%n"/>
   </layout>
  </appender>
  <appender name="ChainsawFun" 
    type="log4net.Appender.RollingFileAppender">
   <param name="File" value="Gentle.NET.chainsaw.xml"/>
   <param name="AppendToFile" value="true"/>
   <param name="MaxSizeRollBackups" value="10"/>
   <param name="MaximumFileSize" value="100MB"/>
   <param name="RollingStyle" value="Size"/>
   <param name="StaticLogFileName" value="true"/>
   <layout type="log4net.Layout.XmlLayoutSchemaLog4j">
   </layout>
  </appender>
  <root>
   <level value="DEBUG" />
   <appender-ref ref="ConsoleAppender" />
   <appender-ref ref="RollingLogFileAppender" />
   <!-- appender-ref ref="ChainsawFun" / -->
  </root>
 </log4net>
</configuration>

ConsoleMain.cs

using System;

namespace GentleSample.Console
{
 class ConsoleMain
 {
  /// <summary>
  /// アプリケーションのメイン エントリ ポイントです。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   try
   {
    Users ford = new Users("user1");
    ford.Name = "user1_name";
    ford.Password = "user1_pass";
    ford.EmailAddress = "user1@gentle.sample.com";
    ford.LastLogon = DateTime.Now;
    ford.Persist(); // save the new user and assign an id value
    System.Console.WriteLine("追加成功");
   }
   catch(Exception ex)
   {
    System.Console.WriteLine(ex.ToString());
   }finally
   {
    System.Console.ReadLine();
   }
  }
 }
}

Users.cs

//=======================================================
// This file was generated using the MyGeneration tool in 
// combination
// with the Gentle.NET Business Entity template, $Rev: 44g $
//=======================================================
using System;
using System.Collections;
using Gentle.Framework;

namespace GentleSample.Console
{
 #region users
 /// <summary>
 /// This object represents the properties and methods
 /// of a Employee.
 /// </summary>
 [Serializable]
 [TableName("users")]
 public class Users : Persistent
 {
  #region Members
  private bool _changed = false;
  private static bool invalidatedListAll = true;
  private static ArrayList listAllCache = null;

  /***PRESERVE_BEGIN MANUAL_CODE_LogonID***/
  /***PRESERVE_END MANUAL_CODE_LogonID***/
  [TableColumn("LogonID", NotNull=true), 
   PrimaryKey(AutoGenerated=false)]
  protected string logonID;

  /***PRESERVE_BEGIN MANUAL_CODE_Name***/
  /***PRESERVE_END MANUAL_CODE_Name***/
  [TableColumn("Name", NotNull=false)]
  protected string name;

  /***PRESERVE_BEGIN MANUAL_CODE_Password***/
  /***PRESERVE_END MANUAL_CODE_Password***/
  [TableColumn("Password", NotNull=false)]
  protected string password;

  /***PRESERVE_BEGIN MANUAL_CODE_EmailAddress***/
  /***PRESERVE_END MANUAL_CODE_EmailAddress***/
  [TableColumn("EmailAddress", NotNull=false)]
  protected string emailAddress;

  /***PRESERVE_BEGIN MANUAL_CODE_LastLogon***/
  /***PRESERVE_END MANUAL_CODE_LastLogon***/
  [TableColumn("LastLogon", NotNull=false)]
  protected DateTime lastLogon;
  #endregion
   

  #region Constructors
 

  /// <summary>
  /// Create a new object using the minimum required
  /// information (all not-null fields except
  /// auto-generated primary keys).
  /// </summary>
  public Users(
    string LogonID)
  {
   _changed = true;
   invalidatedListAll = true;
   logonID = LogonID;
  }

   
  /// <summary>
  /// Create an object from an existing row of data.
  /// This will be used by Gentle to
  /// construct objects from retrieved rows.
  /// </summary>
  public Users(
    string LogonID,
    string Name,
    string Password,
    string EmailAddress,
    DateTime LastLogon)
  {
   logonID = LogonID;
   name = Name;
   password = Password;
   emailAddress = EmailAddress;
   lastLogon = LastLogon;
  }

  #endregion

  #region Public Properties
  
  public bool Changed
  { get { return _changed; } }
  
  public string LogonID
  {
   get{ return logonID; }
   set{ 
     _changed |= logonID != value;
     logonID = value;
     invalidatedListAll =  _changed;}
  }
  
  public string Name
  {
   get{ return name; }
   set{
     _changed |= name != value;
     name = value;
     invalidatedListAll =  _changed;}
  }
  
  public string Password
  {
   get{ return password; }
   set{
     _changed |= password != value;
     password = value;
     invalidatedListAll =  _changed;}
  }
  
  public string EmailAddress
  {
   get{ return emailAddress; }
   set{ 
     _changed |= emailAddress != value;
     emailAddress = value;
     invalidatedListAll =  _changed;}
  }
  
  public DateTime LastLogon
  {
   get{ return lastLogon; }
   set{
     _changed |= lastLogon != value;
     lastLogon = value;
     invalidatedListAll =  _changed;}
  }
  
 
  // generate a static property to retrieve all 
  //instances of a class that are stored in the
  //database
  static public IList ListAll()
  {
   if( listAllCache == null || invalidatedListAll )
   {
    listAllCache =
       Broker.RetrieveList( typeof(Users) ) 
       as ArrayList;
    invalidatedListAll = false;
   }
   return listAllCache;
  }
  
  #endregion

  #region Debug Properties
  /// <summary>
  /// Generated only when genDebug flag enabled in 
  /// MyGeneration template UI
  /// Returns number of items in internal cache
  /// </summary>
  public static int CacheCount
  {
   get{ return listAllCache == null ? 0 : listAllCache.Count;}
  }
  
  #endregion

  #region Storage and retrieval
   
  public static Users Retrieve(string id )
  {
   
   Key key = new Key( typeof(Users), true,
       "LogonID", id );
   return Broker.RetrieveInstance( typeof(Users),
       key ) as Users;
  }

  //Gentle.NET Business Entity script: Generation 
  // of complex retrieve function (multiple primary
  // keys)
  // is not implemented yet.

  public override void Persist()
  {
   if( Changed || !IsPersisted )
   {
    base.Persist();
    _changed=false;
   }
  }

  public override void Remove()
  {
   base.Remove();
   invalidatedListAll = true;
  }
  #endregion

  #region Relations
  // List of primary keys for this class table
  // Key: LogonID
  // List of foreign keys for this class table
  // List of selected relation tables for this
  // database
  #endregion

  #region ManualCode
  /***PRESERVE_BEGIN MANUAL_CODE***/
  /***PRESERVE_END MANUAL_CODE***/
  #endregion
 }

}
#endregion

Gentle.NETはマッピングファイルはなくクラスファイルだけを使用します。
Gentle.NETのクラスファイルもMyGenerationで作成できます。
(しかも、テンプレートが標準で添付されています)

【Gentle.NETのクラスファイルの作成方法】
1、まず、MyGenerationをインストールして、起動します。
(初回起動時で、設定画面が表示されたらデータベースの接続情報を入力して下さい)
2、File - Open - GentleNETフォルダを開く - BusinessEntity.csgenを開く。
3、Template - Executeを選ぶと、「C# Gentle.NET Business Entity」という
タイトルの画面が表示されます。
4、その画面で、出力先(output path)、名前空間(Namespace)、データベース、テーブル
を入力または選択して、OKをクリックします。

これで、出力先にGentle.NETクラスファイルが作成されます。
上記ソリューションでは「Users.cs」に該当します。

【サンプルの実行方法】
1、Users.sqlを実行しUsersテーブルを作成する。
2、GentleSample.zipをダウンロードし、適当な場所に解凍します。
3、GentleSampleをVisual Studio 2003で開き<DefaultProvider  name="SQLServer" connectionString="・・・"の部分(78行目)に接続文字列を記入します。
4、実行します。

「追加完了」と表示されれば成功です。

Gentle.NETは、マッピングファイルがないし、設定もコードを書かなくても読み込んでくれるのでNHibernateより便利な印象ですね。


人気blogランキング


posted by よっしぃ at 22:19 | Comment(0) | TrackBack(1) | O/R マッピング
この記事へのコメント
コメントを書く
お名前: [必須入力]

メールアドレス:

ホームページアドレス:

コメント: [必須入力]

認証コード: [必須入力]


※画像の中の文字を半角で入力してください。
この記事へのトラックバックURL
http://blog.seesaa.jp/tb/26983514

この記事へのトラックバック

Gentle.NETでトランザクションを使用する
Excerpt: 前回紹介したGentle.NETのサンプルをトランザクションを使用するものに変更しました。 変更したのはConsoleMain.csで、変更後は以下のようになっています。 ConsoleMain..
Weblog: よしぶろっIP
Tracked: 2006-11-30 22:02
×

この広告は1年以上新しい記事の投稿がないブログに表示されております。