<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>orm &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/orm/</link>
	<description>Feed of posts on WordPress.com tagged "orm"</description>
	<pubDate>Mon, 13 Oct 2008 06:52:17 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Hibernate Tutorial : Part 2]]></title>
<link>http://rufflog.wordpress.com/?p=50</link>
<pubDate>Thu, 09 Oct 2008 09:58:41 +0000</pubDate>
<dc:creator>Hadzrul</dc:creator>
<guid>http://rufflog.pt-br.wordpress.com/2008/10/09/hibernate-tutorial-part-2/</guid>
<description><![CDATA[Now we continue on the next step (go through Part 1 before reading this). Here I will explain about ]]></description>
<content:encoded><![CDATA[<p>Now we continue on the next step (go through <a href="http://rufflog.wordpress.com/2008/10/08/hibernate-tutorial-part-1/" target="_self">Part 1</a> before reading this). Here I will explain about the configurations and how to work with Hibernate.</p>
<p><!--more--></p>
<p>Hibernate is designed to operate in different types on environment, thus there are a lots of configuration parameters. For this tutorial, we only use some basic configuration parameters just to make it work. There are 3 types of configurations (programmatic configuration, XML configuration and properties file configuration). Here, we will use XML configuration. The configuration file need to be placed in the root of your CLASSPATH and named with "<em><strong>hibernate.cfg.xml</strong></em>".</p>
<p>[sourcecode language='xml']<?xml version="1.0" encoding="UTF-8"?><br />
<!DOCTYPE hibernate-configuration PUBLIC<br />
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"<br />
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"></p>
<p><hibernate-configuration><br />
    <session-factory></p>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hbm</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/training/Risk.hbm.xml"/>
<mapping resource="com/training/Policy.hbm.xml"/>
<mapping resource="com/training/Client.hbm.xml"/>
<mapping resource="com/training/Batch.hbm.xml"/>
    </session-factory></p>
<p></hibernate-configuration>[/sourcecode]</p>
<p>The most important thing here is your session factory.  A global <em><strong>SessionFactory </strong></em>object will be instantiated and used by Hibernate to do the database operations. Inside the session factory, we need to define the <strong>data source</strong> and your mapping file location (you can add more configurations if needed). <em><strong>SessionFactory </strong></em> object will only be instantiated once. It can open new <em><strong>Session</strong></em> that represents a single-threaded unit of work.</p>
<p>In order to instantiate the session factory, we need a helper class (named as <em>HibernateUtil.java</em>) that handle the startup and makes accessing a <em><strong>SessionFactory </strong></em>convenient.</p>
<p>[sourcecode language='java']public class HibernateUtil {<br />
    private static final SessionFactory sessionFactory;<br />
    static {<br />
        try {<br />
            sessionFactory = new Configuration().configure().buildSessionFactory();<br />
        } catch (Throwable ex) {<br />
            // Make sure you log the exception, as it might be swallowed<br />
            System.err.println("Initial SessionFactory creation failed." + ex);<br />
            throw new ExceptionInInitializerError(ex);<br />
        }<br />
    }</p>
<p>    public static Session getSession() {<br />
        return sessionFactory.openSession();<br />
    }<br />
}[/sourcecode]</p>
<p>Here, we will use a <strong>Data Access Object</strong> <strong>(DAO) </strong>to abstract and encapsulate all  access to the data source. The DAO manages the connection with the data  source to obtain and store data. The DAO implements the access mechanism required to work with the data  source. Below is the implementation of the DAO that we be used.</p>
<p>[sourcecode language='java']public class PolicyDAOImpl implements PolicyDAO {</p>
<p>    public void add(Policy policy) {<br />
        Session session = HibernateUtil.getSession();<br />
        try{<br />
            Transaction tx = session.beginTransaction();<br />
            session.save(policy);<br />
            tx.commit();<br />
        }finally{<br />
            session.close();<br />
        }<br />
    }</p>
<p>    public void update(Policy policy) {<br />
        Session session = HibernateUtil.getSession();<br />
        try{<br />
            Transaction tx = session.beginTransaction();<br />
            session.update(policy);<br />
            tx.commit();<br />
        }finally{<br />
            session.close();<br />
        }<br />
    }</p>
<p>    public void delete(Policy policy) {<br />
        Session session = HibernateUtil.getSession();<br />
        try{<br />
            Transaction tx = session.beginTransaction();<br />
            session.delete(policy);<br />
            tx.commit();<br />
        }finally{<br />
            session.close();<br />
        }<br />
    }</p>
<p>    public Policy get(int policyNo) {<br />
        Session session = HibernateUtil.getSession();<br />
        Policy policy = null;</p>
<p>        try{<br />
            Transaction tx = session.beginTransaction();<br />
            policy = (Policy)session.get(Policy.class, new Integer(policyNo));<br />
            Hibernate.initialize(new Integer(policy.getPolicyNo()));<br />
            tx.commit();<br />
        }finally{<br />
            session.close();<br />
        }</p>
<p>        return policy;<br />
    }</p>
<p>    public List getAll() {<br />
        Session session = HibernateUtil.getSession();<br />
        Transaction tx = null;<br />
        List result = null;<br />
        try {<br />
            tx = session.beginTransaction();<br />
            Query q = session.createQuery("from Policy");<br />
            result = q.list();<br />
            tx.commit();<br />
        }<br />
        catch (HibernateException he) {<br />
            if (tx!=null) tx.rollback();<br />
            throw he;<br />
        }<br />
        finally {<br />
            session.close();<br />
        }<br />
        return result;<br />
    }<br />
}[/sourcecode]</p>
<p>As you can see here, all method need to get new <em><strong>Session </strong></em>from <em><strong>SessionFactory</strong></em>. To shield our code from the actual underlying transaction system (in this case plain JDBC, but it could also run with JTA) we use the Transaction API that is available on the Hibernate Session. When the transaction ends, either committed or rolled back, Hibernate also unbinds the <em><strong>Session </strong></em>from the thread and closes it for you.</p>
<p>I want to highlight something here. What we do for <em>getAll() </em>method is use an <strong>HQL (Hibernate Query Language)</strong> query to load all existing <em><strong>Policy</strong></em> objects from the database. Hibernate will generate the appropriate SQL (based on your specified dialect), send it to the database and populate <em><strong>Policy</strong></em> objects with the data. You can create more complex queries with HQL, of course.</p>
<p>Now, we can start working with Hibernate. You can create a class with a <em>main()</em> method to test the DAO.</p>
<p>Source code: <a href="http://rapidshare.com/files/152308093/hibernate.rar.html" target="_blank">Get it here</a></p>
<p>Reference: <a href="http://www.hibernate.org/hib_docs/reference/en/html/" target="_blank">Hibernate Reference Documentation</a></p>
<p><strong>-HADZRUL-</strong></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate Tutorial : Part 1]]></title>
<link>http://rufflog.wordpress.com/?p=20</link>
<pubDate>Wed, 08 Oct 2008 09:55:24 +0000</pubDate>
<dc:creator>Hadzrul</dc:creator>
<guid>http://rufflog.pt-br.wordpress.com/2008/10/08/hibernate-tutorial-part-1/</guid>
<description><![CDATA[For Hibernate tutorial, I will cover the basic configurations and functions that have been provided ]]></description>
<content:encoded><![CDATA[<p>For Hibernate tutorial, I will cover the basic configurations and functions that have been provided by Hibernate. Part 1 will explain about hibernate mappings and persistent classes. Ok, let's start.</p>
<p><!--more--></p>
<p>First, we need to design some environment to work on. Let say we create a simple environment that consist of 4 entities. The main entity that we will use is <strong><em>Policy </em></strong>(like insurance policy). Who will make a policy? Of course we will have an entity called <em><strong>Client </strong></em>(like a person that bought an insurance). Then, we have entity called <em><strong>Batch </strong></em>(policy need to group by batch). And the last one, we will have <em><strong>Risk </strong></em>(people - how many people that will be covered).</p>
<p style="text-align:center;"><img class="aligncenter size-medium wp-image-30" title="Entity Diagram" src="http://rufflog.wordpress.com/files/2008/10/untitled2.jpg?w=300" alt="" width="300" height="139" /></p>
<p>Hibernate architecture consist of 3 base elements:</p>
<ul>
<li>Persistent classes - ordinary JavaBeans/POJOs; create short-lived, single threaded objects containing persistent state and business function.</li>
<li>Mapping files - files that map tables and columns in XML format. It tells Hibernate what table to be access in the database and what column should be use.</li>
<li>Hibernate properties - application settings (database connection, mapping files location, etc.).</li>
</ul>
<p>Now we need to prepare all the persistent classes and mapping files. My example here will involve hibernate associations. Hibernate will handle all the associations automatically, but we need to customize some POJOs and mapping files. I will briefly explain what we should do for each entity.</p>
<pre>Batch.java</pre>
<div style="background:#FFFBCC;border:solid;border-width:thin;padding:2px 20px;">
<pre>package com.training;

public class Batch implements java.io.Serializable {
   private int batchId;
   private String batchDesc;

   public int getBatchId() {
      return this.batchId;
   }

   public void setBatchId(int batchId) {
      this.batchId = batchId;
   }

   public String getBatchDesc() {
      return this.batchDesc;
   }

   public void setBatchDesc(String batchDesc) {
      this.batchDesc = batchDesc;
   }
}</pre>
</div>
<pre>Batch.hbm.xml</pre>
<div style="background:#E5E5E5;border:solid;border-width:thin;padding:2px 20px;">
<pre>&#60;hibernate-mapping&#62;
    &#60;class name="com.training.Batch" table="batch"&#62;

        &#60;id name="batchId" type="int"&#62;
            &#60;column name="batch_id" /&#62;
            &#60;generator class="identity" /&#62;
        &#60;/id&#62;

        &#60;property name="batchDesc" type="string"&#62;
            &#60;column name="batch_desc"/&#62;
        &#60;/property&#62;
    &#60;/class&#62;
&#60;/hibernate-mapping&#62;</pre>
</div>
<p>For <em><strong>Batch</strong></em>, we don't have any association involved. This is because, Batch will not refer to any entity but I will be referred by other entities. As you can see, the <em>Batch.hbm.xml</em><strong> </strong>is a mapping file. It map all the properties inside the Batch class. Mapping classes <strong>must </strong>declare an identifier (defined as &#60;id&#62; element in mapping file). Identifier represents the primary key column in database. Now, we move to <em><strong>Risk</strong></em>.</p>
<pre>Risk.java</pre>
<div style="background:#FFFBCC;border:solid;border-width:thin;padding:2px 20px;">
<pre>package com.training;

public class Risk implements java.io.Serializable {

   private int riskId;
   private String name;
   private Policy policy;

   public int getRiskId() {
      return this.riskId;
   }

   public void setRiskId(int riskId) {
      this.riskId = riskId;
   }

   public String getName() {
      return this.name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public Policy getPolicy() {
      return policy;
   }

   public void setPolicy(Policy policy) {
      this.policy = policy;
   }
}</pre>
</div>
<pre>Risk.hbm.xml</pre>
<div style="background:#E5E5E5;border:solid;border-width:thin;padding:2px 20px;">
<pre>&#60;hibernate-mapping&#62;
    &#60;class name="com.training.Risk" table="risk"&#62;
        &#60;id name="riskId" type="int"&#62;
            &#60;column name="risk_id" /&#62;
            &#60;generator class="identity" /&#62;
        &#60;/id&#62;
        &#60;property name="name" type="string"&#62;
            &#60;column name="name" /&#62;
        &#60;/property&#62;
        &#60;many-to-one name="policy" class="com.training.Policy"
         fetch="select"&#62;
        	&#60;column name="policy_no" /&#62;
        &#60;/many-to-one&#62;
    &#60;/class&#62;
&#60;/hibernate-mapping&#62;</pre>
</div>
<p>What we have here is a bit different than <em><strong>Batch</strong></em>. <em><strong>Risk </strong></em>(as a child) has a relationship with <em><strong>Policy </strong></em>(as a parent). A<em><strong> </strong><strong>Policy </strong></em>can have many <em><strong>Risks</strong></em>. So, <em><strong>Risk </strong></em>will have <strong>many-to-one</strong> association with <em><strong>Policy</strong></em>. <em><strong>Risk </strong></em>need to hold its' parent instance. Inside the class, we need to declare one extra property to hold parent's instance. For the mapping file, we need to add &#60;many-to-one&#62; element that will map the extra property to the database by specifying the column name. In database, it will take an identifier of the parent to be stored.</p>
<pre>Policy.java</pre>
<div style="background:#FFFBCC;border:solid;border-width:thin;padding:2px 20px;">
<pre>package com.training;

import java.util.HashSet;
import java.util.Set;

public class Policy implements java.io.Serializable {

   private int policyNo;
   private Integer classification;
   private Integer subClass;
   private Client client;
   private Batch batch;

   private List risk = new ArrayList();

   public int getPolicyNo() {
      return this.policyNo;
   }

   public void setPolicyNo(int policyNo) {
      this.policyNo = policyNo;
   }

   public Integer getClassification() {
      return this.classification;
   }

   public void setClassification(Integer classification) {
      this.classification = classification;
   }

   public Integer getSubClass() {
      return this.subClass;
   }

   public void setSubClass(Integer subClass) {
      this.subClass = subClass;
   }

   public Batch getBatch() {
      return batch;
   }

   public void setBatch(Batch batch) {
      this.batch = batch;
   }

   public Client getClient() {
      return client;
   }

   public void setClient(Client client) {
      this.client = client;
   }

   public List getRisk() {
      return risk;
   }

   public void setRisk(List risk) {
      this.risk = risk;
   }
}</pre>
</div>
<pre>Policy.hbm.xml</pre>
<div style="background:#E5E5E5;border:solid;border-width:thin;padding:2px 20px;">
<pre>&#60;hibernate-mapping&#62;
    &#60;class name="com.training.Policy" table="policy"&#62;
        &#60;id name="policyNo" type="int"&#62;
            &#60;column name="policy_no" length="100" /&#62;
            &#60;generator class="assigned" /&#62;
        &#60;/id&#62;
        &#60;list name="risk" cascade="all,delete-orphan"
         fetch="select" lazy="false"&#62;
	    &#60;key column="policy_no"/&#62;
	    &#60;index column="seq"/&#62;
	    &#60;one-to-many class="com.training.Risk"/&#62;
	&#60;/list&#62;
        &#60;property name="classification" type="java.lang.Integer"&#62;
            &#60;column name="classification"/&#62;
        &#60;/property&#62;
        &#60;property name="subClass" type="java.lang.Integer"&#62;
            &#60;column name="sub_class"/&#62;
        &#60;/property&#62;
        &#60;many-to-one name="batch" class="com.training.Batch"&#62;
            &#60;column name="batch_id" /&#62;
        &#60;/many-to-one&#62;
        &#60;one-to-one name="client" cascade="all"/&#62;
    &#60;/class&#62;
&#60;/hibernate-mapping&#62;</pre>
</div>
<p><em><strong>Policy </strong></em>is the main entity here. It has relationships with other entities. We will go through one by one. Let's focus on <em><strong>Risk</strong></em>. Just now, we already set many-to-one association to its' mapping file. So, inside <em>Policy.hbm.xml</em>, we need to set the opposite (<em><strong>one-to-many</strong></em> association). Remember that a policy can have many risk? Then, we need to put a collection of <em><strong>Risks</strong></em> inside the <em><strong>Policy</strong></em> object. So, if retrieve a policy, Hibernate will help to retrieve all the risks (child) automatically. Easy right? For one-to-many association, a collection (for this example, I choose <strong>List</strong> as collection) need to add as a new property at the parent class (Policy class). Inside the mapping file, &#60;list&#62; element has been used to map to the property.</p>
<div style="border:thin solid;background:#eaf3fa none repeat scroll 0 50%;width:180px;padding:2px 20px;">
<pre>&#60;key column="policy_no"/&#62;</pre>
</div>
<p>This <strong>key column</strong> will map to <em>policy_no</em> column in Rate table. Means, this is the key that connect to the parent (foreign key).</p>
<div style="border:thin solid;background:#eaf3fa none repeat scroll 0 50%;width:155px;padding:2px 20px;">
<pre>&#60;index column="seq"/&#62;</pre>
</div>
<p>When we use List as collection, we need to provide one column called "<span style="color:#0000ff;"><em><strong>seq</strong></em></span>". Just need extra column in database (Risk table), and no modification at its' class and mapping file. This column used for sorting your item inside the List. Don't worry, Hibernate will handle this.</p>
<p>Remember that policies need to group by <em><strong>Batch</strong></em> ? One policy can only be under one batch. But one batch can have many policies inside.  So, we need to put <strong>many-to-one</strong> association to <em><strong>Policy</strong></em>. Since this situation is similar to <em><strong>Risk</strong></em>, I don't need to repeat again.</p>
<p>Ok, now we move to last entity that we've not covered yet.</p>
<div style="border:thin solid;background:#eaf3fa none repeat scroll 0 50%;width:285px;padding:2px 20px;">
<pre>&#60;one-to-one name="client" cascade="all"/&#62;</pre>
</div>
<p>Before we move on, this is the mapping to <em><strong>Client</strong></em>. One extra property need to be included inside the Policy object to hold the <em><strong>Client</strong></em>. Let's say one client can ONLY have one policy (I just want to show one-to-one relationship). When comes to <strong>one-to-one</strong> association, both side need to have information of each other. But the child (Client) need to use its' parent (Policy) id as identifier (primary key).</p>
<pre>Client.java</pre>
<div style="background:#FFFBCC;border:solid;border-width:thin;padding:2px 20px;">
<pre>package com.training;

public class Client implements java.io.Serializable {

   private int clientId;
   private String name;
   private String nric;
   private Policy policy;

   public int getClientId() {
      return this.clientId;
   }

   public void setClientId(int clientId) {
      this.clientId = clientId;
   }

   public String getName() {
      return this.name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getNric() {
      return this.nric;
   }

   public void setNric(String nric) {
      this.nric = nric;
   }

   public Policy getPolicy() {
      return policy;
   }

   public void setPolicy(Policy policy) {
      this.policy = policy;
   }
}</pre>
</div>
<pre>Client.hbm.xml</pre>
<div style="background:#E5E5E5;border:solid;border-width:thin;padding:2px 20px;">
<pre>&#60;hibernate-mapping&#62;
    &#60;class name="com.training.Client" table="client"&#62;
        &#60;id name="clientId" column="client_id"&#62;
	    &#60;generator class="foreign"&#62;
	        &#60;param name="property"&#62;policy&#60;/param&#62;
	    &#60;/generator&#62;
	&#60;/id&#62;
        &#60;one-to-one name="policy" constrained="true"/&#62;
        &#60;property name="name" type="string"&#62;
            &#60;column name="name" length="150" /&#62;
        &#60;/property&#62;
        &#60;property name="nric" type="string"&#62;
            &#60;column name="nric" length="50" /&#62;
        &#60;/property&#62;
    &#60;/class&#62;
&#60;/hibernate-mapping&#62;</pre>
</div>
<p>Just need to add a property of its' parent (Policy) here. That's all. Oh, don't forget the association inside the mapping file.</p>
<p><a href="http://rufflog.wordpress.com/2008/10/09/hibernate-tutorial-part-2/" target="_self">Continue to Part 2</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Data Access Test with Sqlite]]></title>
<link>http://hendryluk.wordpress.com/?p=160</link>
<pubDate>Tue, 07 Oct 2008 11:19:14 +0000</pubDate>
<dc:creator>hendryluk</dc:creator>
<guid>http://hendryluk.pt-br.wordpress.com/2008/10/07/data-access-test-with-sqlite/</guid>
<description><![CDATA[I have mentioned briefly in previous post about 5 different approaches to write unit-test for data-a]]></description>
<content:encoded><![CDATA[<p>I have mentioned briefly in previous post about <a href="http://hendryluk.wordpress.com/2008/09/08/unit-testing-data-access-code/">5 different approaches to write unit-test for data-access code</a>. So now I will try to cover the first method in more detail. And among the 5, this method seems to be the most common one so far.<br />
I will be using <a href="http://sqlite.org">Sqlite</a> as in-memory database. Some other arguably better alternative is available, that is if you are happy to fork out some extra bucks on <a href="http://vistadb.net">VistaDB</a>.<br />
So let's reemphasize the desired characteristics of a good unit test, especially in the context of data-access code.<br />
<strong>1. Isolated.</strong> Database (by definition) persists any change to its state. However, this is usually not desirable in unit-test. A good test case runs in complete isolation from any changes made in other test-cases. I.e., any changes to the database from one test case should not be visible from other test-cases.<br />
<strong>2. Repeatable.</strong> Regardless how many times a unit test is executed, a consistent result is expected. For this to happen, unit-test should not rely on presumption on external condition, especially shared database.<br />
<strong>3. Fast. </strong>If your test fixture cannot be executed in every several minutes or so, there is only one thing that can possibly happen: developers will start abandoning it. And unfortunately, this is usually the case if you are connecting to database system from test code, where the whole test-suite can take up to an hour to execute, if you are lucky. No one can run it frequent enough to make it useful, and hence no one will keep on maintaining it.</p>
<p><strong>IN MEMORY DATABASE</strong><br />
The main reason why using in-memory database for unit-test is that it is incredibly fast! Both in restoring zero state, execution, and cleaning up. Speaking of which, let's take a look on typical cycle of in memory database in unit-test.<br />
We are going to have NHibernate to build the database schema from scratch before each test case, and dispose it at the end of the test case. Then start again with building the schema on clean database again for the next test-case. This way, we always have an empty sheet to work on for each test-case without affecting (or being affected by) any database changes in other test-cases.<br />
Here is some NUnit test case example using NHibernate.<br />
[code lang="c#"]<br />
[TestFixture]<br />
public class CustomerRepositoryTest: InMemoryDBTestFixture<br />
{<br />
	private ISession session;<br />
	private CustomerRepository repository;</p>
<p>	[TestFixtureSetuUp]<br />
	public void FixtureSetUp()<br />
	{<br />
		InitialiseNHibernate(typeof(Customer).Assembly);<br />
	}</p>
<p>	[SetUp]<br />
	public void SetUp()<br />
	{<br />
		this.session = this.CreateSession();<br />
		this.repository = new CustomerRepository(<br />
			new FakeSessionManager(session));<br />
	}</p>
<p>	[TearDown]<br />
	public void TearDown()<br />
	{<br />
		this.session.Dispose();<br />
	}</p>
<p>	[Test]<br />
	public void CanQueryCustomerByLastname()<br />
	{<br />
		var customers = new List<Customer>(){<br />
			new Customer(){<br />
				FirstName="Peter",<br />
				LastName="Griffin"},<br />
			new Customer(){<br />
				FirstName="Other",<br />
				LastName="Lads"},<br />
			new Customer(){<br />
				FirstName="Meg",<br />
				LastName="Griffin"},<br />
			new Customer(){<br />
				FirstName="Yet Another",<br />
				LastName="Bloke"}};</p>
<p>		foreach(var cus in customers)<br />
			session.Save(cus);<br />
		session.Flush();<br />
		foreach(var cus in customers)<br />
			session.Evict(cus);</p>
<p>		var loaded = repository.QueryByLastname("Griffin");</p>
<p>		Assert.That(loaded.Count, Is.EqualTo(2));<br />
		AssertLoadedDataEqual(loaded[0], customers[0]);<br />
		AssertLoadedDataEqual(loaded[1], customers[2]);<br />
	}<br />
	private static void AssertLoadedDataEqual(Customer loaded, Customer saved)<br />
	{<br />
		AssertThat(loaded, Is.NotEqualTo(saved)); // Make sure it's not cached data</p>
<p>		Assert.That(loaded.ID, Is.EqualTo(saved.ID));<br />
		Assert.That(loaded.FirstName, Is.EqualTo(saved.FirstName));<br />
		Assert.That(loaded.LastName, Is.EqualTo(saved.LastName));<br />
	}<br />
}<br />
[/code]<br />
The plumbing for initializing NHibernate and building in-memory database is managed by base-class InMemoryDBTestFixtureBase. It is a very common practice to have this kind of base class for all database test-fixtures within a project, so we we can turn our back on setting up test database and concentrate on testing what we care about. Let's take a look at the base class code.<br />
[code lang="c#"]<br />
public abstract class InMemoryDBTestFixtureBase<br />
{<br />
	protected static ISessionFactory sessionFactory;<br />
	protected static Configuration configuration;</p>
<p>	public static void InitialiseNHibernate(params Assembly [] assemblies)<br />
	{<br />
		if(sessionFactory!=null)<br />
			return;</p>
<p>		var prop = new Hashtable();<br />
		prop.Add("hibernate.connection.driver_class", "NHibernate.Driver.SQLite20Driver");<br />
		prop.Add("hibernate.dialect", "NHibernate.Dialect.SQLiteDialect");<br />
		prop.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");<br />
		prop.Add("hibernate.connection.connection_string", "Data Source=:memory:;Version=3;New=True;");</p>
<p>		configuration = new Configuration();<br />
		configuration.Properties = prop;</p>
<p>		foreach (Assembly assembly in assemblies)<br />
			configuration = configuration.AddAssembly(assembly);<br />
		sessionFactory = configuration.BuildSessionFactory();<br />
	}</p>
<p>	public ISession CreateSession()<br />
	{<br />
		var session = sessionFactory.OpenSession();<br />
		new SchemaExport(configuration)<br />
			.Execute(false, true, false, true, session.Connection, null);<br />
		return session;<br />
	}<br />
}<br />
[/code]<br />
This base class takes care of configuring NHibernate with Sqlite in-memory provider, and registering all the assemblies where our hbm files are located. CreateSession method will load the new session with a fresh in-memory database, and it gets NHibernate to build it with the schema from those hbm files.</p>
<p><strong>BOTTOM LINE</strong><br />
We have achieved our 3 objectives for isolation, repeatability, and speed. Additionally, compared to the other 4 unit-test approaches, in-memory database offers a unique advantage.<br />
Each test-case is self sufficient: specifying its own pre-condition (initial data), and verifying the final outcome. Each test case is self explanatory in revealing the intention of the test. Test readers will find it remarkably easy to follow each of the test-cases independently without having to switch back and forth between Visual Studio and database IDE or dataset XML (as in the case with nDbUnit).<br />
Having self-sufficient test-case might as well come as a disadvantage considering how bloated the test-code ends up, even for this rather simplistic example. In practice, this can get worse since you have to deal with populating the data for all chain of unrelated tables as well only to satisfy foreign key constraints when setting up initial data. Not to mention the frustration when the database schema changes every now and then. It is very likely that data initialization would typically take up majority of the test code, just to support mere couple lines of real test logic that we really care about.<br />
Another disadvantage is that not all functionalities will work (or behave the same way) between in-memory and targetted database. Not to mention various subtle idiosynchracies with Sqlite.<br />
And if you don't use data-access framework that offers cross database portability (like NHibernate does), this approach is not even an option.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[det är inte mig du är rädd för]]></title>
<link>http://mymlanthereal.wordpress.com/?p=1431</link>
<pubDate>Mon, 06 Oct 2008 19:59:24 +0000</pubDate>
<dc:creator>mymlan</dc:creator>
<guid>http://mymlanthereal.pt-br.wordpress.com/2008/10/06/det-ar-inte-mig-du-ar-radd-for/</guid>
<description><![CDATA[plötsligt slog det mig
det är inte mig du är rädd för
det är sanningen
du upplever sanningen s]]></description>
<content:encoded><![CDATA[<p>plötsligt slog det mig</p>
<p>det är inte mig du är rädd för</p>
<p>det är sanningen</p>
<p>du upplever sanningen som så hotfull att när den slingrar sig runt dina fötter sparkar du vilt omkring dig som vore den en giftig orm</p>
<p>du offrar vänner, kärlek, ja till och med din egen sinnesro för att inte sanningen ska komma fram</p>
<p>det skrämmer mig</p>
<p>vet du vilken egenskap jag tycker bäst om hos mig själv, som gör att jag inte slutar älska mig?</p>
<p>det är den att jag är sann</p>
<div class="zemanta-pixie" style="margin-top:10px;height:15px;"><a class="zemanta-pixie-a" title="Zemified by Zemanta" href="http://reblog.zemanta.com/zemified/5b0d8f11-2206-4ad5-8233-8f5958cab291/"><img class="zemanta-pixie-img" style="border:medium none;float:right;" src="http://img.zemanta.com/reblog_e.png?x-id=5b0d8f11-2206-4ad5-8233-8f5958cab291" alt="Reblog this post [with Zemanta]" /></a></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Tempelhuggorm,(Tropidolaemus wagleri), Bako nationalprk, Borneo]]></title>
<link>http://byalvan.wordpress.com/?p=142</link>
<pubDate>Wed, 01 Oct 2008 16:15:44 +0000</pubDate>
<dc:creator>byalvan</dc:creator>
<guid>http://byalvan.pt-br.wordpress.com/2008/10/01/tempelhuggormtropidolaemus-wagleri-bako-nationalprk-borneo/</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<p><a href="http://byalvan.files.wordpress.com/2008/10/red-img_0535.jpg"><img class="aligncenter size-full wp-image-143" title="Tempelhuggorm 2" src="http://byalvan.wordpress.com/files/2008/10/red-img_0535.jpg" alt="" width="496" height="372" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Javascript ORM]]></title>
<link>http://alessioma.wordpress.com/?p=34</link>
<pubDate>Wed, 01 Oct 2008 13:10:10 +0000</pubDate>
<dc:creator>bayois</dc:creator>
<guid>http://alessioma.pt-br.wordpress.com/2008/10/01/javascript-orm/</guid>
<description><![CDATA[Bene bene é arrivato anche un nuovo ORM Javascript per Gears&#8230;saranno molto contenti Hibernate]]></description>
<content:encoded><![CDATA[<p>Bene bene é arrivato anche un nuovo ORM Javascript per Gears...saranno molto contenti Hibernate e Propel.<br />
Ecco alcuni esempi presi da <a href="http://www.urielkatz.com/archive/detail/introducing-jstorm/">JStORM</a></p>
<p><code><br />
var Person = new JStORM.Model({<br />
  name:"Person",<br />
  fields:<br />
  {<br />
     firstName:new JStORM.Field({type:"String",maxLength:25}),<br />
     lastName:new JStORM.Field({type:"String",maxLength:25}),<br />
  },<br />
  connection:"default"<br />
});<br />
</code></p>
<p>For example to print all the persons in the database:<br />
<code><br />
Person.all().each(function(person)<br />
{<br />
  console.log(person.firstName);<br />
});<br />
</code></p>
<p>What the all function do is to create a new instance of JStORM.Query for Person model.<br />
Other function that return a query is filter,filter return a query filtered by a criteria,for example:<br />
<code><br />
var katzFamily = Person.filter("lastName = ?","Katz");<br />
katzFamily.each(function(person)<br />
{<br />
  console.log(person.firstName);<br />
});<br />
</code></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ignited Record for CodeIgniter]]></title>
<link>http://shahjahanrussell.wordpress.com/?p=11</link>
<pubDate>Wed, 01 Oct 2008 08:04:03 +0000</pubDate>
<dc:creator>Shahjahan Russell</dc:creator>
<guid>http://shahjahanrussell.pt-br.wordpress.com/2008/10/01/ignited-record-for-codeigniter/</guid>
<description><![CDATA[ 
What is IgnitedRecord?
IgnitedRecord is a relation handling ORM library, made for the PHP framewo]]></description>
<content:encoded><![CDATA[<p> </p>
<h1>What is IgnitedRecord?</h1>
<p>IgnitedRecord is a relation handling <abbr title="Object Relational Mapping" />ORM library, made for the PHP framework <a href="http://www.codeigniter.com/">CodeIgniter</a>.</p>
<p>The goal of <a class="wiki_link" href="http://shahjahanrussell.wordpress.com/wiki/show/IgnitedRecord/IgnitedRecord">IgnitedRecord</a> is to provide an easy to use, easily customizeable, ORM library to <a class="wiki_link" href="http://shahjahanrussell.wordpress.com/wiki/show/IgnitedRecord/CodeIgniter">CodeIgniter</a>.</p>
<h1>Features at a glance</h1>
<ul>
<li>Easily configurable</li>
<li>Uses default values if settings are not explicitly set</li>
<li>Relations:
<ul>
<li>Belongs to</li>
<li>Has Many</li>
<li>Has One</li>
<li>Has And Belongs To Many (shorted to habtm)</li>
</ul>
</li>
<li>When fetching related objects, it is possible to filter, order and modify the query in a large quantity of ways</li>
<li>Belongs To and Has One relations can be fetched easily through a JOIN with the help of join_related()</li>
<li>Behaviours, which can add and modify the functionality of IgnitedRecord</li>
<li>Hooks and triggers where you can put your own code</li>
<li>Complete support for PHP 4, no "hacks" or anyting else is required for IgintedRecord to work under PHP 4.</li>
<li>Method Chaining under PHP 5</li>
<li>Nested WHERE statements and subqueries, with help from <a class="wiki_link" href="http://shahjahanrussell.wordpress.com/wiki/show/IgnitedRecord/IgnitedQuery">IgnitedQuery</a></li>
<li>Partial support for multiple primary keys (relations are not supported, yet)</li>
</ul>
<h1>Benefits</h1>
<ul>
<li>Repetitious work is minimized.</li>
<li>You have a finished model base to builld on.</li>
<li>You don't have to write SQL if you don't want to.</li>
<li>The choice between updates and inserts is automatically determined.</li>
<li>The result resources are automatically cleaned up, to improve speed and lower memory consumption.</li>
<li>The code is easier to read, take this as an example:<br />
$posts = $user-&#62;related('posts')-&#62;order_by('name', 'desc')-&#62;get();<br />
// instead of:<br />
$posts = $this-&#62;db-&#62;from('posts')-&#62;where('user_id', $user-&#62;id)-&#62;order_by('name', 'desc')-&#62;get()-&#62;result();<br />
The difference will be even more obvious when more advanced queries are used.</li>
</ul>
<p>Download location:</p>
<p><a class="alignleft" title="Download latest version of Igniter Record" href="http://www.assembla.com/spaces/IgnitedRecord/documents" target="_blank">download latest version of Igniter Record</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Technology stack.]]></title>
<link>http://roosst.wordpress.com/?p=29</link>
<pubDate>Mon, 29 Sep 2008 19:18:54 +0000</pubDate>
<dc:creator>James</dc:creator>
<guid>http://roosst.pt-br.wordpress.com/2008/09/29/technology-stack/</guid>
<description><![CDATA[The proof of concept for Roosst has existing on my dev environment for a few weeks now.  Right from]]></description>
<content:encoded><![CDATA[<p>The proof of concept for Roosst has existing on my dev environment for a few weeks now.  Right from the first line of code I had to have a rough idea what technology the site would be written in.  Of course being a non-trivial website I'm going to need to serve HTML, utilise server-side scripting, and store stuff in a database.  There's a multitude of tools out there to choose from, and being the only person working on a greenfield project I have the luxury of selecting every product and language myself.  That is a priveldge for a dev.  Rarely, when working in a team environment do you get such a complete level of control.</p>
<p>In making my choices I had to weigh up a lot of variables.  I had to consider how I could leverage my own skillset, how I could get things done quickly, how I could make my site accessible to as many people as possible, and last-but-not-least; cost.  Not forgetting how I can <em>attempt(!)</em>, to make my site cool.  The web can be a trendy place, and adversely it can be a political place.  Technologies and companies fly in and out of fashion and tools and companies can find themselves turning from zero to hero - or reverse - almost overnight.  Initially I actually found myself considering if by choosing one technology a whole set of users might just switch off.  I certainly hope not and I've decided to have more faith in the world!  I trust that a website will be judged on its merit, and not on the whim of some perpetual slanging match between opposing development communities.</p>
<p><strong>Principals</strong></p>
<p>I set myself some early guiding principals:</p>
<p><em>Minimise Vendor Lock In:</em></p>
<p>I wanted to minimize vendor lock in.  I decided that the easiest way to do this laid firmly with the overall architecture.  So the distinction between each tier must be well defined.  Each tier must have clearly defined boundaries and interfaces, and must be interoperable with its adjacent tier, regardless of each tiers' technology.  If this is adhered to then each tier should be supplant-able at some point the future.</p>
<p><em>Leverage Skills:</em></p>
<p>Being a one man band means time and money is limited.  To get things done quickly I need to leverage my existing skill-set as much as possible.  Which means at some point I'm going to be using .Net.  .Net is a technology I've been working with extensively since its early days, and .Net 3.5 and C# allow a lot of good code to get written fast.</p>
<p><em>High Availability:</em></p>
<p>Finally, I want my website available to all.  Whatever tools are used, they're no good if they alienate users.</p>
<p><strong>Client</strong></p>
<p>My website is to be quite active on the client.  So Flash, Silverlight, Javascript are all in contention.  My current flash skills are limited (to zero) and it doesn't really do what I want it do do.  Silverlight is certainly interesting but how much penetration into the wide world it will achieve is still an unknown.  Finally, Javascript, the staple client scripting language of all active websites, but how will it fare going forward?  What's interesting here is how the 'browser wars' seem to have reignited.  For a long time Microsoft were chased around anti-competitive courts over their Internet Explorer bundling.  Then suddenly Firefox comes along and blows things wide open.  Barely has the dust settled and Nintendo are putting Opera in the family living room, Safari arrives, and then Google drop Chrome on an unsuspecting world.  All of these speak the international language of love...er...Javascript.  Not only is Javascipt universal but Javascript engines are getting faster and faster.  The choice is made.</p>
<p><strong>More Client</strong></p>
<p>Fairly early on into my prototyping I had to accept that I can't spend hours, days, weeks playing around with Javascript plumbing, when I should be using Javascript to implement functionality.  Again, being a one man team on a budget I can't spend days analysing the various Javascript frameworks out there.  After a few hours scouring the Internet for opinions and snippets and desided to try out the dojo toolkit.  It rocks, and I recommend it.  I've not had reason to switch to another framework.</p>
<p><strong>Server</strong></p>
<p>To me, this wasn't a hard decision.  ASP.Net/IIS/C#.  Technology I know my way around well, and it has no bearing on what browsers can access the page.  This is where I can leverage my existing skill-set and make up time.  Still, I have set my principal of clear layer separation and this means classic ASP.Net paradigms such as post back event handling, and ATLAS wont really feature in Roosst.</p>
<p><strong>Database</strong></p>
<p>Oracle and SQL Server are databases I work with regularly.  Both cost money, and both were therefore pretty much immediately discounted.  With MySQL obviously being free, and a web stalwart, it seemed like an obvious contender.  My last experience with MySQL was in the pre stored procedure era, but with these and triggers now available the decision was made.  I'm not going to get into the long running stored procedures vs. inline SQL debate, but with one of my core principals being the need to easily supplant a layer the ability to define a distinct interface on the database is a pointer as to which direction I'll be taking.</p>
<p><strong>Summary</strong></p>
<p>So as it stands right now that's my core technology stack:</p>
<ul>
<li>Javascript &#38; dojo</li>
<li>IIS/.Net/C#</li>
<li>MySQL</li>
</ul>
<p>It's not ground-breaking news, but it's an insight on where I'll be spending the next few months.</p>
<p>Will it change?  Hell yes!  Plans are flexible and being on my own I have the luxury of being able to change!  How Gears and Silverlight play out over the coming months will be something I'll be keeping a keen eye upon.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ny dag, jobbig natt och sjuklingar på rummet]]></title>
<link>http://mathiaskarlsson.wordpress.com/2008/09/28/ny-dag-jobbig-natt-och-sjuklingar-pa-rummet/</link>
<pubDate>Sun, 28 Sep 2008 14:07:29 +0000</pubDate>
<dc:creator>mathiaskarlsson</dc:creator>
<guid>http://mathiaskarlsson.pt-br.wordpress.com/2008/09/28/ny-dag-jobbig-natt-och-sjuklingar-pa-rummet/</guid>
<description><![CDATA[Igår kväll så käkade vi på ett riktigt mysigt ställe. Ett lokalt matställe. Billigt och bra. ]]></description>
<content:encoded><![CDATA[<p>Igår kväll så käkade vi på ett riktigt mysigt ställe. Ett lokalt matställe. Billigt och bra. Förrätt: varma mackor med tok mycket smält ost, heta kycklingvingar. Huvudrätt: Texas ribs, med pommes. Självklart free refill när det gällde colan. Det märktes vem som var amerikanaren i vårt sällskap då Jonathan hade druckit 4 stora Cola innan jag ens fattade att det var gratis påfyllning. Vi tänkte dricka några öl efter maten, men det var totalt omöjligt. Jag här nog aldrig varit så mätt i hela mitt liv! Efter maten åkte vi tillbaka till hotellrummet där Lotta fick en trevlig överaskning. När hon öppnade hotellrummet så ramlade en liten svart orm ned på golvet efter att ha träffat henne på armen. Det var en liten helsvart skit som var jävligt aggresiv då den högg mot Jonathan när han försökte ta bort den med toalettpapper. Han fick ut den tillslut med hjälp av en tidning. Efter detta så var det bara att söka igenom rummen efter fler, men som tur var, utan resultat. Vi hittade iofs varsin kackerlacka som jag fick jaga med en kaffekopp. Tydligen ska man inte döda dem då lukten lockar till sej fler.<br />
Nu till natten. Tilde hostar som sjutton på natten. Hon är aspigg på dagen men hostig på natten. Hon fick sova intill mej inatt på högar med kuddar. Sophie har inte alls varit pigg i natt. Feber, hostat och haft alla möjliga influensasymptom. Feber 39.5. Just nu sover hon efter en frukost bestående av donuts. Nedan ser ni ett kort på Tilde när hon får sin jordgubbssmakande medicin. More to come .....</p>
<p><a href="http://mathiaskarlsson.files.wordpress.com/2008/09/p-640-480-b78eb645-cdef-4fbb-a0b3-5f8314d46825.jpeg"><img class="alignnone size-full wp-image-364" src="http://mathiaskarlsson.files.wordpress.com/2008/09/p-640-480-b78eb645-cdef-4fbb-a0b3-5f8314d46825.jpeg" alt="" width="225" height="300" /></a></p>
<p><a href="http://mathiaskarlsson.files.wordpress.com/2008/09/p-640-480-5d4dc608-2fbb-4290-bf09-7d677e8d14fb.jpeg"><img class="alignnone size-full wp-image-364" src="http://mathiaskarlsson.files.wordpress.com/2008/09/p-640-480-5d4dc608-2fbb-4290-bf09-7d677e8d14fb.jpeg" alt="" width="225" height="300" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[How to use custom audit fields with SubSonic]]></title>
<link>http://jamesewelch.wordpress.com/?p=328</link>
<pubDate>Thu, 25 Sep 2008 01:13:01 +0000</pubDate>
<dc:creator>Jim</dc:creator>
<guid>http://jamesewelch.pt-br.wordpress.com/2008/09/24/how-to-use-custom-audit-fields-with-subsonic/</guid>
<description><![CDATA[SubSonic uses a few audit fields by default - you don&#8217;t need to write any code. However, the f]]></description>
<content:encoded><![CDATA[<p><a href="http://subsonicproject.com/" target="_blank">SubSonic</a> uses a few audit fields by default - you don't need to write any code. However, the field names that are used are coded into the source code. You can modify the source code and generate a new assembly, but if you're like me and would rather not edit the <a href="http://subsonicproject.com/getting-at-the-subsonic-svn-subversion-repository/" target="_blank">source code</a> (so you don't need to update the code at every release), then you'll be looking for an alternative approach.</p>
</p>
<p><!--more-->
</p>
<h3>SubSonic default audit fields</h3>
<p>First, by <a href="http://subsonicproject.com/setup/subsonic-conventions/" target="_blank">default SubSonic</a> uses the following database field names:</p>
<ul>
<li>CreatedBy  </li>
<li>CreatedOn  </li>
<li>ModifiedBy  </li>
<li>ModifiedOn  </li>
<li>Deleted  </li>
<li>IsDeleted  </li>
<li>IsActive </li>
</ul>
<p>I'm only going to focus on CreatedBy, CreatedOn, ModifiedBy, and ModifiedOn in this example, but you can insert the others into the code if you need.</p>
<h5>What happens when you have differing field names?</h5>
<p>The problem arises when you have database field names that differ from the above field names. In my database, I've very close but we use a different naming standard that uses underscores to make the field names more readable without relying on camel casing the field names.</p>
<p>Here's how my field names match up with SubSonic's defaults:</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<thead>
<tr>
<th valign="top" width="117">My field name </th>
<th valign="top" width="281">SubSonic default field name</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top" width="117">Created_By</td>
<td valign="top" width="281">CreatedBy</td>
</tr>
<tr>
<td valign="top" width="117">Created_On</td>
<td valign="top" width="281">CreatedOn</td>
</tr>
<tr>
<td valign="top" width="117">Modified_By</td>
<td valign="top" width="281">ModifiedBy</td>
</tr>
<tr>
<td valign="top" width="117">Modified_On</td>
<td valign="top" width="281">ModifiedOn</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<h3>The Three Options</h3>
<ol>
<li>
<p>Modify SubSonic source code</p>
</li>
<li>
<p>Use partial classes for each table</p>
</li>
<li>
<p>Create a custom template and base class</p>
</li>
</ol>
<p>The advantages and disadvantages to each option is shown below. I'm sure there's a few more advantages and disadvantages, so if you think of one, let me know in the comments section.</p>
<p>&#160;</p>
<h5>Option 1: Modify SubSonic source code</h5>
<p>You can modify the SubSonic source code to use your database field names.</p>
<table cellspacing="0" cellpadding="2" width="486" border="0">
<tbody>
<tr>
<td valign="top" width="209"><strong>Advantages</strong></td>
<td valign="top" width="275"><strong>Disadvantages</strong></td>
</tr>
<tr>
<td valign="top" width="209">
<ul>
<li>Less coding </li>
</ul>
</td>
<td valign="top" width="275">
<ul>
<li>Requires maintaining project's source code  </li>
<li>Must maintain multiple copies of source code for each differing set of field names per application/database </li>
</ul>
</td>
</tr>
</tbody>
</table>
<h5>Option 2: Use Partial classes for each table</h5>
<table cellspacing="0" cellpadding="2" width="486" border="0">
<tbody>
<tr>
<td valign="top" width="208"><strong>Advantages</strong></td>
<td valign="top" width="276"><strong>Disadvantages</strong></td>
</tr>
<tr>
<td valign="top" width="208">
<ul>
<li>Easy to code </li>
</ul>
</td>
<td valign="top" width="276">
<ul>
<li>Duplicate code for each table/class  </li>
<li>Must add partial classes and code for every table/class </li>
</ul>
</td>
</tr>
</tbody>
</table>
<h5>Option 3: Create a custom template and base class</h5>
<table cellspacing="0" cellpadding="2" width="486" border="0">
<tbody>
<tr>
<td valign="top" width="208"><strong>Advantages</strong></td>
<td valign="top" width="276"><strong>Disadvantages</strong></td>
</tr>
<tr>
<td valign="top" width="208">
<ul>
<li>No code duplication  </li>
<li>Automatically configured for any new tables/classes </li>
</ul>
</td>
<td valign="top" width="276">
<ul>
<li>Must create a code generation template project </li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<h3>Option 1: Modifying the SubSonic source code</h3>
<p>The first solution is the modified SubSonic's source code as stated by <a href="http://forums.subsonicproject.com/forums/p/3552/14534.aspx#14534" target="_blank">yitzchok</a>:</p>
<blockquote><p>Get the source code of SubSonic and modify <strong><a href="http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Constants.cs" target="_blank">SubSonic\Constants.cs</a></strong> to the names you want</p>
<p>&#160;&#160;&#160; public class ReservedColumnName<br />&#160;&#160;&#160; {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string CREATED_BY = "CreatedBy";<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string CREATED_ON = "CreatedOn"; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string DELETED = "Deleted";<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string IS_ACTIVE = "IsActive";<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string IS_DELETED = "IsDeleted";<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string MODIFIED_BY = "ModifiedBy";<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; public const string MODIFIED_ON = "ModifiedOn"; <br />&#160;&#160;&#160; }</p>
</blockquote>
<p>In this code, you would just insert your field names as the string literals. Then you would rebuild the project and use the new SubSonic modified assemblies.</p>
<p>If you choose to go this route, then you don't need to follow any further. I choose to go a different route, because I didn't want to modify and maintain the source (when updates are available) and have to worry about merging any of my changes back into the source.</p>
<p>&#160;</p>
<h3>Option 2: Using partial classes</h3>
<h5>Step 1: Creating your partial classes</h5>
<p>Add a new partial class to your source code. For example, if your table was called "Product" and you had generated a SubSonic class called "Product", then your partial class would look something like:</p>
<pre class="code"><span style="color:rgb(0,0,255);">namespace</span> MyProject.DAL
{
    <span style="color:rgb(0,0,255);">public</span> <span style="color:rgb(0,0,255);">partial</span> <span style="color:rgb(0,0,255);">class</span> <span style="color:rgb(43,145,175);">Product
</span>    {</pre>
</p>
<pre class="code">    }</pre>
</p>
<pre class="code">}</pre>
<p>The namespace and class should match exactly what is generated by SubSonic. You are just adding another source code file to your DAL project. I usually structure my SubSonic DAL project as such:</p>
<p>/MyProject/DAL</p>
<p>/MyProject/DAL/Custom</p>
<p>/MyProject/DAL/Generated</p>
<p>The automatically generated class files go into "DAL/Generated" and my partial classes go into "DAL/Custom".</p>
<h5>Step 2: Overriding BeforeInsert and BeforeUpdate</h5>
<p>To automatically set the created_on, created_by, modified_on, and modified_by values. I need to override the BeforeInsert and BeforeUpdate methods. You can paste the below code within the Product class above. You may need to modify parts of the code to fit your database design.</p>
<p>Here, I check to see if this table has a database field named "Created_On" and if it does, then I set the database column to DateTime.Now. Then I just repeat that same logic for the other fields.</p>
<pre class="code"><span style="color:rgb(0,0,255);">protected</span> <span style="color:rgb(0,0,255);">override</span> <span style="color:rgb(0,0,255);">void</span> BeforeInsert()
{
   <span style="color:rgb(0,0,255);">string</span> userName = <span style="color:rgb(0,0,255);">string</span>.Empty;
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(43,145,175);">HttpContext</span>.Current != <span style="color:rgb(0,0,255);">null</span>)
      userName = <span style="color:rgb(43,145,175);">HttpContext</span>.Current.User.Identity.Name;
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">this</span>.GetSchema().Columns.Contains(<span style="color:rgb(163,21,21);">"Created_On"</span>))
      <span style="color:rgb(0,0,255);">this</span>.SetColumnValue(<span style="color:rgb(163,21,21);">"Created_On"</span>, <span style="color:rgb(43,145,175);">DateTime</span>.Now);
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">this</span>.GetSchema().Columns.Contains(<span style="color:rgb(163,21,21);">"Created_By"</span>))
      <span style="color:rgb(0,0,255);">this</span>.SetColumnValue(<span style="color:rgb(163,21,21);">"Created_By"</span>, userName);
   <span style="color:rgb(0,0,255);">base</span>.BeforeInsert();
}

<span style="color:rgb(0,0,255);">protected</span> <span style="color:rgb(0,0,255);">override</span> <span style="color:rgb(0,0,255);">void</span> BeforeUpdate()
{
   <span style="color:rgb(0,0,255);">string</span> userName = <span style="color:rgb(0,0,255);">string</span>.Empty;
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(43,145,175);">HttpContext</span>.Current != <span style="color:rgb(0,0,255);">null</span>)
      userName = <span style="color:rgb(43,145,175);">HttpContext</span>.Current.User.Identity.Name;
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">this</span>.GetSchema().Columns.Contains(<span style="color:rgb(163,21,21);">"Modified_On"</span>))
      <span style="color:rgb(0,0,255);">this</span>.SetColumnValue(<span style="color:rgb(163,21,21);">"Modified_On"</span>, <span style="color:rgb(43,145,175);">DateTime</span>.Now);
   <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">this</span>.GetSchema().Columns.Contains(<span style="color:rgb(163,21,21);">"Modified_By"</span>))
      <span style="color:rgb(0,0,255);">this</span>.SetColumnValue(<span style="color:rgb(163,21,21);">"Modified_By"</span>, userName);
   <span style="color:rgb(0,0,255);">base</span>.BeforeUpdate();
}</pre>
<p>You can also replace the string literals used above ("Created_By", etc.) with constants.</p>
<h5>Step 3: The end</h5>
<p>You'll need to create partial classes and override the two methods in each of your tables that you want to automatically maintain your audit fields.</p>
<p>Finally, build and test your code.</p>
<p>&#160;</p>
<h3>Option 3: Creating code templates</h3>
<h5>Step 1</h5>
<p>First, make a copy of the templates provided with the SubSonic installation. We are going to modify those templates to inherit from a custom class that we'll create.</p>
<p>The templates are located in your installation folder and consists of several ASPX files. The SubSonic web site shows you how to create a template project and get the build process to work. So you should make sure that you have a project with the ASPX files and you are able to do a successful build before continuing.</p>
<ul>
<li><a href="http://subsonicproject.com/customization/creating-your-own-code-gen-templates/" target="_blank">Webcast: Creating&#160; Your Own Code Gen Templates</a> by Rob Connery 
</li>
<li><a href="http://subsonicproject.com/customization/code-generation-how-to-customize-our-templates/" target="_blank">Code Generation: How To Customize Our Templates</a> </li>
</ul>
<p>&#160;</p>
<h5>Step 2: Modifying the template</h5>
<p>Open the CS_ClassTemplate.aspx file.</p>
<p>Scroll down about 25 lines and insert the following bold code (middle line with comment) between the shown lines:</p>
<pre class="code">  <span style="color:rgb(0,0,255);">string</span> baseClass = tbl.Provider.TableBaseClass;
<strong>  <span style="color:rgb(0,0,255);">string</span> baseClassCustomized = baseClass;</strong><span style="color:rgb(0,128,0);"><strong> // this is new!</strong>
</span>  <span style="color:rgb(0,0,255);">string</span> collectionBaseClass = <span style="color:rgb(43,145,175);">String</span>.Format(<span style="color:rgb(163,21,21);">"List&#60;{0}&#62;"</span>, className);</pre>
<p>Here we are adding a new variable named "baseClassCustomized" to store the name of our new base class that we'll implement later.</p>
<p>Next, scroll down to about line 40 and insert the following bold code (last line with comment) between the shown lines:</p>
<pre class="code">{
 baseSuffix = <span style="color:rgb(163,21,21);">"IActiveRecord"</span>;
 collectionBaseClass = <span style="color:rgb(43,145,175);">String</span>.Format(<span style="color:rgb(163,21,21);">"ActiveList&#60;{0}, {0}Collection&#62;"</span>, className);
 baseClassCustomized =  <span style="color:rgb(43,145,175);">String</span>.Format(
     <span style="color:rgb(163,21,21);">"MyProject.DAL.ActiveRecordCustomized&#60;{0}&#62;, {1}"</span>,
     className,
     baseSuffix);<span style="color:rgb(0,128,0);"><strong> // this is new!</strong></span>
}</pre>
<p>I'm just updating the base class for ActiveRecord. You will need to use the full class name with namespace to the class that we haven't created yet.&#160; In this example, our newly created class name will be "<strong>MyProject.DAL.ActiveRecordCustomized.</strong>" You should put your namespace and class name here.</p>
<p>Finally, scroll down to around line 117 and update the code to generate the class information as shown below. We are changing baseClass to use baseCusomizedClass.</p>
<pre class="code">  public partial class &#60;%=className%&#62; : &#60;%=baseCustomizedClass%&#62;</pre>
<p>You'll need to update your web.config and/or app.config as shown by Rob in the webcast and SubSonic documentation linked above in Option 2: Step 1. Also, make sure you can build the template project as shown in the webcast.</p>
<p>&#160;</p>
<h5>Step 3: Adding our new customized base class</h5>
<p>Create a new class within the namespace used for the previous step. You must make sure this class and namespace match what we've used in the previous step or you will get build errors.</p>
<pre class="code"><span style="color:rgb(0,0,255);">namespace</span> MyProject.DAL
{
    <span style="color:rgb(0,0,255);">public</span> <span style="color:rgb(0,0,255);">class</span> <span style="color:rgb(43,145,175);">ActiveRecordCustomized</span>&#60;T&#62; : <span style="color:rgb(43,145,175);">ActiveRecord</span>&#60;T&#62;
        <span style="color:rgb(0,0,255);">where</span> T : <span style="color:rgb(43,145,175);">ReadOnlyRecord</span>&#60;T&#62;, <span style="color:rgb(0,0,255);">new</span>()<span style="color:rgb(0,128,0);">
</span>    {</pre>
</p>
<pre class="code">    }</pre>
</p>
<pre class="code">}</pre>
<h5>Step 4: Override BeforeInsert and BeforeUpdate</h5>
<p>Finally, you just need to override the BeforeInsert and BeforeUpdate methods to add in your audit field data.</p>
<p><em>See Option 2: Step 2 for source code.</em></p>
<p>&#160;</p>
<h5>Step 5: The end</h5>
<p>Finally, build and test your code.</p>
<p>&#160;</p>
<p>
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fjamesewelch.wordpress.com%2f2008%2f09%2f24%2fhow-to-use-custom-audit-fields-with-subsonic%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fjamesewelch.wordpress.com%2f2008%2f09%2f24%2fhow-to-use-custom-audit-fields-with-subsonic%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Bir kaza haberi de Erzincan'dan: 3 ölü]]></title>
<link>http://yurdumturkiye.wordpress.com/?p=164</link>
<pubDate>Wed, 24 Sep 2008 21:35:03 +0000</pubDate>
<dc:creator>Yazar</dc:creator>
<guid>http://yurdumturkiye.pt-br.wordpress.com/2008/09/25/bir-kaza-haberi-de-erzincandan-3-olu/</guid>
<description><![CDATA[24 09 2008 23:10
Erzincan&#8217;ın Tercan ilçesindeki trafik kazasında, 3 kişi öldü, 3 kişi y]]></description>
<content:encoded><![CDATA[<p><strong>24 09 2008 23:10</strong><br />
Erzincan'ın Tercan ilçesindeki trafik kazasında, 3 kişi öldü, 3 kişi yaralandı.</p>
<p><!--more--></p>
<p><img class="alignleft" style="margin:2px;" src="http://image.haber7.com/haber/haber7/photos/974620080914085007546.jpg" alt="3 ölü" width="272" height="204" /><span style="font-family:Arial;">Erzincan-Tercan kara yolunun 85. kilometresindeki Tüneller mevkisinde, Ali Yılmaz'ın kullandığı 74 AP 706 plakalı otomobille, sürücüsü henüz tespit edilemeyen 24 AE 371 plakalı kamyonet çarpıştı.</span></p>
<p><span style="font-family:Arial;">Kazada, otomobil sürücüsü Ali Yılmaz (36) ile Sakine (37) ve Deniz Yılmaz (5) olay yerinde ölürken,  kamyonette bulunan Mustafa Turan ve Emin Erdem'le, otomobildeki Muhammet Ali Yılmaz yaralandı.</span></p>
<p><span style="font-family:Arial;">Yaralılar, Erzurum'daki hastanelere gönderildi.</span></p>
<p>AA</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Hakkari'de çatışma: 1 terörist ölü]]></title>
<link>http://yurdumturkiye.wordpress.com/2008/09/25/hakkaride-catisma-1-terorist-olu/</link>
<pubDate>Wed, 24 Sep 2008 21:28:20 +0000</pubDate>
<dc:creator>Yazar</dc:creator>
<guid>http://yurdumturkiye.pt-br.wordpress.com/2008/09/25/hakkaride-catisma-1-terorist-olu/</guid>
<description><![CDATA[24 09 2008 22:16
Hakkari Valiliği, Çukurca ilçesinde güvenlik güçleri ile teröristler arasın]]></description>
<content:encoded><![CDATA[<p><strong>24 09 2008 22:16</strong><br />
Hakkari Valiliği, Çukurca ilçesinde güvenlik güçleri ile teröristler arasında çıkan çatışmada 1 teröristin ölü olarak ele geçirildiğini bildirildi.</p>
<p><!--more--></p>
<p><img class="alignleft" style="margin:2px;" src="http://image.haber7.com/haber/haber7/photos/208520080919061822930.jpg" alt="1 terörist ölü" width="272" height="204" /><span style="font-family:Arial;">Hakkari Valiliği'nden yapılan yazılı açıklamada, "23 Eylül 2008 günü saat 21.30 sıralarında Hakkari'nin Çukurca ilçesinde Irak'tan ilçemize yasadışı yollarla girmeye çalışan teröristler tarafından sınır güvenliğini sağlamakla görevli güvenlik kuvvetleri unsurlarına saldırı girişiminde bulunulmuş, çıkan çatışmada 1 terörist ölü olarak ele geçirilmiştir. Diğer teröristlerden bir kısmının yaralı olarak Irak topraklarına geri kaçtıkları tespit edilmiştir. Güvenlik kuvvetlerimizin zayiatı bulunmamaktadır.</span></p>
<p><span style="font-family:Arial;">Bölgede operasyonlar aynı azim ve kararlıkla sürdürülmektedir" denildi.</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Fatih Sultan Mehmet Han ( II.Mehmed - Osmanlı Sultani)]]></title>
<link>http://videow.wordpress.com/?p=637</link>
<pubDate>Tue, 23 Sep 2008 14:39:56 +0000</pubDate>
<dc:creator>sorularlaislamiyet</dc:creator>
<guid>http://videow.pt-br.wordpress.com/2008/09/23/fatih-sultan-mehmet-han-iimehmed-osmanli-sultani/</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<p>[googlevideo=http://video.google.com/videoplay?docid=4197865340101543030&#38;ei=ff_YSJb0M5bC2gLY7vy3Ag&#38;q=fatih+sultan+mehmet&#38;hl=tr]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Keloglan Kurbaga Prens]]></title>
<link>http://videow.wordpress.com/?p=635</link>
<pubDate>Tue, 23 Sep 2008 14:35:42 +0000</pubDate>
<dc:creator>sorularlaislamiyet</dc:creator>
<guid>http://videow.pt-br.wordpress.com/2008/09/23/keloglan-kurbaga-prens/</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<p>[googlevideo=http://video.google.com/videoplay?docid=-4131263331945299309&#38;ei=sP3YSMTUMZCsiAK1gpzEAg&#38;q=%C3%A7izgi]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Nhibernate-4]]></title>
<link>http://yahyakoc.wordpress.com/?p=59</link>
<pubDate>Mon, 22 Sep 2008 19:26:19 +0000</pubDate>
<dc:creator>Yahya KOÇ</dc:creator>
<guid>http://yahyakoc.pt-br.wordpress.com/2008/09/22/nhibernate-4/</guid>
<description><![CDATA[Evet dizimizin son yazısına gelmiş bulunuyoruz.
Önceki Yazılar

Nhibernate-1
Nhibernate-2
Nhibe]]></description>
<content:encoded><![CDATA[<p>Evet dizimizin son yazısına gelmiş bulunuyoruz.</p>
<h3>Önceki Yazılar</h3>
<ul>
<li><a href="http://yahyakoc.wordpress.com/2008/09/10/nhibernate-1/">Nhibernate-1</a>
<li><a href="http://yahyakoc.wordpress.com/2008/09/22/nhibernate-2/">Nhibernate-2</a>
<li><a href="http://yahyakoc.wordpress.com/2008/09/22/nhibernate-3/">Nhibernate-3</a>
</ul>
<p><strong>Nullable</strong><br />
Nullable tipler Nhibernate kullanımı için çok önemli bir ayrıntıdır.Bir nesne kaydettiğimizi düşünelim.Nesnenin integer tipte alanları olsun.Siz o alana bir değer atamadığınız sürece o alanlar "0" dır. Nhibernate bu durumda bu değerin sizin tarafınızdan mı atandığını yoksa başlangıç değeri mi olduğunu kestiremez ve veritabanına o alanlar için 0 yazar.Nhibernate, nesnenin alanlarının kullanıcı tarafından set edilip edilmediğini o alanların değerinin "null" olup olmadığına bakarak karar verir.Bu durumda nesnelerimizin veritabanında karşılığı "allow null" olan alanları için nullable tipler kullanmalıyız.Nullable ya da int? gibi..Bu durum Datetime gibi tipler için de geçerlidir.Normal Datetime tipi kullanırsanız ve o alana atama yapmazsanız Nhibernate veritabanına 01/01/1900 yazar. O alanın boş geçilememesi gibi bir şartımız varsa bu durumda nullable tipler yerine normal tipleri kullanabiliriz.<br />
<!--more--><br />
<strong>Nhibernate ve Exception</strong><br />
Nhibernate exception fırlattığında .net ortamında aldığınız hata genelde generic hatalardır.Bunun yerine hatanın derinlerine inip “inner excepiton” da ne yazdığına mutlaka bakın.Yani “Lazy laoding” hatası alırsınız ama innerexception içinde “Ad” alanı bulunamadı yazabilir.Aslında “Ad” alanı bulunumadığı için lazy loading hatası alırsınız ama bunu ilk etapta farkedemeyebilirsiniz.Bu yüzden innerexception içinde yazan mesajı baz alarak problemlerinizi çözmeye çalışın.</p>
<p><strong>SetMaxResult</strong><br />
Sorgumuza döndürmesini istediğimiz maksimum kayıt sayısını bildirebiliyoruz.<br />
[sourcecode language="csharp"]<br />
criteria.SetMaxResult(25);<br />
[/sourcecode]</p>
<p><strong>IgnoreCase</strong><br />
Oracle ve örnek uygulamamızda da kullandığımız SQLite gibi case-sensitive veritabanlarında insensitive sorgulama yapabilmemiz için IgnoreCase metodunu kullanırız.<br />
[sourcecode language="csharp"]<br />
Expression.Eq("Ad", "Hasan").IgnoreCase();<br />
[/sourcecode]</p>
<p><strong>Subcriteria, Sum,Avg</strong><br />
Şimdi count,avg gibi sql fonksiyonların ve alt sorguların  nhibernate ile nasıl gerçeklendiğini inceleyelim:</p>
<p>=&#62;Öğrenci numarası Hasan’ın öğrenci numarasını alalım.<br />
[sourcecode language="csharp"]<br />
ICriteria criteria = session.CreateCriteria(typeof (Ogrenci));<br />
criteria.Add(Expression.Eq("Ad", "Hasan"));<br />
criteria.Add(Expression.Eq("Soyad", "Fehmi"));<br />
criteria.SetProjection(Projections.Property("OgrenciId"));<br />
IList<string> liste= criteria.List<string>();<br />
[/sourcecode]<br />
Bu tür spesifik sonuçlar döndürmeye yönelik sorgularımız bir ya da bir kaç hesaplanmış alan döndüreceği için listemizin dönüş tipi artık üzerinde sorgu yaptığımız nesnenin tipinde değil de “string” tipindedir.Çünkü artık nesnesinin tamamını döndürmüyoruz.</p>
<p>=&#62;Öğrenci numarası Hasan’ın öğrenci numarasından büyük olan öğrencileri  bulalım.<br />
[sourcecode language="csharp"]<br />
ICriteria criteria = session.CreateCriteria(typeof (Ogrenci));<br />
DetachedCriteria dtCriteria1 = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria1.Add(Expression.Eq("Ad", "Hasan"));<br />
dtCriteria1.Add(Expression.Eq("Soyad", "Fehmi"));<br />
dtCriteria1.SetProjection(Projections.Property("OgrenciId"));</p>
<p>DetachedCriteria dtCriteria = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria.SetProjection(Projections.Avg("OgrenciId"));<br />
criteria.Add(Subqueries.PropertyGe("OgrenciId", dtCriteria1));<br />
IList<Ogrenci> liste = criteria.List<Ogrenci>();<br />
[/sourcecode]<br />
Bu sorguda bazı şartları sağlayan öğrencileri döndürdüğümüz için liste tipimiz artık “Ogrenci”.</p>
<p>=&#62;Öğrenci numarası Hasan’ın öğrenci numarasından büyük olan öğrencileri yada adında “is” karakteri geçen öğrencileri  Ad sırasına göre getiriyoruz.<br />
[sourcecode language="csharp"]<br />
 ICriteria criteria = session.CreateCriteria(typeof (Ogrenci));<br />
DetachedCriteria dtCriteria1 = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria1.Add(Expression.Eq("Ad", "Hasan"));<br />
dtCriteria1.Add(Expression.Eq("Soyad", "Fehmi"));<br />
dtCriteria1.SetProjection(Projections.Property("OgrenciId"));</p>
<p>DetachedCriteria dtCriteria = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria.SetProjection(Projections.Avg("OgrenciId"));<br />
criteria.Add(Expression.Or<br />
                           (<br />
                            Subqueries.PropertyGe("OgrenciId",dtCriteria),<br />
                            Expression.Like("Ad","%İs%"))<br />
                           );<br />
criteria.AddOrder(Order.Asc("Ad"));<br />
IList<Ogrenci> liste = criteria.List<Ogrenci>();<br />
[/sourcecode]</p>
<p>=&#62;Şimdi olayı biraz daha karmaşık hale getirelim. Öğrenci numarası Hasan’ın öğrenci numarasından büyük olan öğrencileri yada adında “is” karakteri geçen öğrencileri   adlarına göre gruplayıp her grubun elaman sayısını  ve OgrenciId ortalamasını getiriyoruz.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
ICriteria criteria = session.CreateCriteria(typeof(Ogrenci));<br />
DetachedCriteria dtCriteria1 = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria1.Add(Expression.Eq("Ad", "Hasan").IgnoreCase());<br />
dtCriteria1.Add(Expression.Eq("Soyad", "Fehmi").IgnoreCase());<br />
dtCriteria1.SetProjection(Projections.Property("OgrenciId"));</p>
<p>DetachedCriteria dtCriteria = DetachedCriteria.For(typeof(Ogrenci));<br />
dtCriteria.SetProjection(Projections.Avg("OgrenciId"));<br />
dtCriteria.Add(Expression.Or<br />
                            (<br />
                              Subqueries.PropertyGe("OgrenciId ", dtCriteria),<br />
                              Expression.Like("Ad", "%İs%").IgnoreCase()<br />
                            )<br />
              );<br />
criteria.SetProjection(Projections.ProjectionList()<br />
                                  .Add(Projections.GroupProperty("Ad"),"Sayi")<br />
                                  .Add(Projections.Count("Ad"),"Ad")<br />
                                  .Add(Projections.Avg("OgrenciId"),"Ortalama")<br />
               );<br />
IList<object[]> list = criteria.List<object[]>();<br />
[/sourcecode]<br />
Dönüş tipimiz artık bir dizi listesi.Çünkü her sonucun kendi içinde bir dizisi  var.Bu gelen sonucu bir grid’e bağlayacağımızı farzedelim.Bu durumda IList tipindeki listemizi anlamlı bir tipe çevirelim.Örrneğin çok sevdiğimiz DataTable’a çevirelim.</p>
<p>[sourcecode language="csharp"]<br />
DataTable dt = new DataTable();<br />
ProjectionList pl = (ProjectionList)criteria.GetType().GetProperty("Projection").GetValue(criteria, null);</p>
<p>foreach (string str in pl.Aliases)<br />
{<br />
         DataColumn dc = new DataColumn(str);<br />
         dt.Columns.Add(dc);<br />
}</p>
<p>foreach (object[] objarray in list)<br />
{<br />
         DataRow dr = dt.NewRow();<br />
         int i = 0;<br />
foreach (object obj in objarray)<br />
   	{<br />
      	   dr[i] = obj.ToString();<br />
         i++;<br />
      }<br />
    dt.Rows.Add(dr);<br />
}<br />
return dt;<br />
[/sourcecode]</p>
<p>[sourcecode language="csharp"]<br />
.Add(Projections.GroupProperty("Ad"),"Sayi")<br />
.Add(Projections.Count("Ad"),"Ad")<br />
.Add(Projections.Avg("OgrenciId"),"Ortalama")<br />
[/sourcecode]<br />
Yukarıda gördüğünüz “Sayi”, “Ad”, “Ortalama” ifadeleri bağlayacağımız gride datafield olarak tanıtacağımız alias serisi..<br />
Grid bağladıktan sonra ortaya aşağıdaki gibi bir sonuç çıkar.<br />
<img src="http://yahyakoc.wordpress.com/files/2008/09/groupby-1.jpg" alt="" title="groupby-1" width="280" height="265" class="alignnone size-full wp-image-378" /></p>
<p><strong>Distinct</strong><br />
Nhibernate içinde distinct şu şekilde kullanılır.<br />
[sourcecode language="csharp"]<br />
.Add(Projections.Distinct(Projections.Property("OgrenciId")));<br />
[/sourcecode]<br />
OgrenciId alanı üzerinden distinct yapacağımıız bildiriyoruz.</p>
<p><strong>Örnek uygulama</strong><br />
Yazı dizimizin en başında bahsettiğimiz örnek uygulamaya <a href="http://rapidshare.com/files/147515085/sanalokul.rar.html">buradan</a>  erişebilirsiniz. Veri tabanı olarak SQLite seçtim.Böylece veritabanı bağlantıları ile uğraşmadan uygulamayı indirir indirirmez çalıştırabileceksiniz.Kodlama VS2008 ortamında c# ile yapıldı.</p>
<p>Böylece Nhibernate yazı dizimizi ana başlıklara değinerek bitirmiş olduk.Vaktimiz olursa ActiveRecord ile alakalı bir yazı yazmayı düşünüyorum.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Nhibernate-3]]></title>
<link>http://yahyakoc.wordpress.com/?p=55</link>
<pubDate>Mon, 22 Sep 2008 19:26:11 +0000</pubDate>
<dc:creator>Yahya KOÇ</dc:creator>
<guid>http://yahyakoc.pt-br.wordpress.com/2008/09/22/nhibernate-3/</guid>
<description><![CDATA[Merhaba bu yazımızda Nhibernate ile veritabanı sorgulama metodlarını inceleyeğiz.
Hql
Hibernat]]></description>
<content:encoded><![CDATA[<p>Merhaba bu yazımızda Nhibernate ile veritabanı sorgulama metodlarını inceleyeğiz.<br />
<strong>Hql</strong><br />
Hibernate Query Language(hql) bildiğimiz ansi-sql’e çok benzeyen hibernate için özelleştirilmiş bir  sorgulama dilidir.<br />
Hemen bir örnek yapalım:</p>
<p>[sourcecode language="csharp"]<br />
OkulDAONHibernate _dao = new OkulDAONHibernate();<br />
IList<Ogrenci> liste= _dao.GetOgrenciByAdSoyadHQL("İsmail", "Koç");</p>
<p>...............<br />
public IList<Ogrenci> GetOgrenciByAdSoyadHQL(string strAd,string strSoyad)<br />
        {<br />
            ISession session = NHibernateHttpModule.CurrentSession;<br />
            return session.CreateQuery("select from Ogrenci o where o.Ad=:AD and o.Soyad=:SOYAD")<br />
                .SetString("AD", strAd)<br />
                .SetString("SOYAD", strSoyad)<br />
                .List<Ogrenci>();<br />
        }<br />
[/sourcecode]<br />
<!--more--><br />
<strong>Sql</strong><br />
İlla da Sql! Sql’den vazgeçmem diyenler için:<br />
[sourcecode language="csharp"]<br />
OkulDAONHibernate _dao = new OkulDAONHibernate();<br />
IList<Ogrenci> liste= _dao.GetOgrenciByAdSoyadSQL("İsmail", "Koç");</p>
<p>............................<br />
    public IList<Ogrenci> GetOgrenciByAdSoyadSQL(string strAd, string strSoyad)<br />
        {<br />
            ISession session = NHibernateHttpModule.CurrentSession;<br />
            return session.CreateSQLQuery("select * from OGRENCI  where Ad=:AD and Soyad=:SOYAD")<br />
                .AddEntity(typeof(Ogrenci))<br />
                .SetString("AD", strAd)<br />
                .SetString("SOYAD", strSoyad)<br />
                .List<Ogrenci>();<br />
        }<br />
[/sourcecode]<br />
Hemen iki fark göze çarpmalı<br />
=&#62;CreateQuery metodu yerine CreateSqlQuery metodunu kullandık.<br />
=&#62;CreateSqlQuery metoduna fazladan AddEntity metodunu ekledik.Takdir edersinizki Nhibernate sql cümlesi içerisinde gönderdiğiniz tablo adı/adlarının hangi sınıfa karşı geldiğini bilmez.Bu yüzden sorguda kullanılacak sınıfın Ogrenci olduğunu belirtiyoruz.<br />
“Ben bu yöntemi  ‘select * from Ogrenci’  şeklinde değil de “select ad from Ogrenci’ şeklinde kullanmak istiyorum” diyenler olabilir  ama bu şekilde kullanım geçersizdir.Zira tablodaki satır tamamen geldiğinde bir sınıfa karşılık gelir.”Sadece iki kolonu çeksin ve bunları da nesnenin o iki propety’sine set etsin” diyebiliriz ama Nhibernate  bu yöntemi desteklemiyor.</p>
<p><strong>Expressions</strong><br />
Expression kullanma yöntemi bu üç yöntemden benim tercih ettiğim yöntem...İzlenebilir olması ve içerisinde  string ifadeler bulanmaması(select * from ,inner join....) tercih edilmesinin sebeplerinden...<br />
Hemen örneklerimize başlayalım</p>
<p>1)Soyadı “Koç” olan öğrencileri bulalım.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return   session.CreateCriteria(typeof(Ogrenci))<br />
                     .Add(Expression.Eq("Soyad","Koç"))<br />
                     .List<Ogrenci>();<br />
[/sourcecode]<br />
Gördüğünüz gibi burda Expression sınıfını kullanıyoruz.Bu sınıf içinde işimize yarayan bir çok metod bulunuyor.(Expression.Gt,Ge,Lt,Le,In,IsEmpty,Like,InsensitiveLike...).Hemen aklıma gelmişken hatırlatayım  veritabanı olarak oracle kullanıyorsak oracle case sensitive olduğu için expressionlar içine verdiğiniz değerlere dikkat etmeliyiz.”KOÇ” ile “koç” biribirinden farklı değelerdir.</p>
<p>2)Adında “a” harfi geçen öğrencileri soyadlarına göre azalan sırada sıralayalım.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return   session.CreateCriteria(typeof(Ogrenci))<br />
                    .Add(Expression.Like("Ad","%a%"))<br />
                    .AddOrder(Order.Desc("Soyad"))<br />
                    .List<Ogrenci>();<br />
[/sourcecode]</p>
<p>3)Adı “ismail” ya da “taner” olan öğrencileri soyadlarına göre artan sırada sıralayalım.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return   session.CreateCriteria(typeof(Ogrenci))<br />
                    .Add(<br />
                          Expression.Or(<br />
                                            Expression.Eq("Ad","İsmail"),<br />
                                            Expression.Eq("Ad","Taner")<br />
                                            )<br />
                          )<br />
                   .AddOrder(Order.Asc("Soyad"))<br />
                   .List<Ogrenci>();<br />
[/sourcecode]</p>
<p>4)Adı “İsmail”  ve soyadı alanı boş olmayan öğrencileri getirelim.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return   session.CreateCriteria(typeof(Ogrenci))<br />
                     .Add(<br />
                            Expression.And(<br />
                                             Expression.Eq("Ad","İsmail"),<br />
                                             Expression.IsNotEmpty("Soyad")<br />
                                          )<br />
                            )<br />
                          .List<Ogrenci>();<br />
[/sourcecode]</p>
<p>5)Adı “ismail” olan soyadı “koç” yada “kılıç” olan öğrencileri getirelim.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return   session.CreateCriteria(typeof(Ogrenci))<br />
                     .Add(Expression.Eq("Ad","İsmail"))<br />
                     .Add(<br />
                             Expression.Or(<br />
                                                Expression.Eq("Soyad","Koç"),<br />
                                                Expression.Eq("Soyad","kılıç")<br />
                                               )<br />
                           )<br />
                           .List<Ogrenci>();<br />
[/sourcecode]</p>
<p><strong>Example</strong><br />
Diğer bir yöntemimiz de örnek nesne kullanıp sorgulama yapma yöntemidir.</p>
<p>1)Adı “İsmail” olan öğrencileri çekelim.<br />
[sourcecode language="csharp"]<br />
Ogrenci ogr=new Ogrenci();<br />
ogr.Ad = "ismail";<br />
           ...............<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
return session.CreateCriteria(typeof(Ogrenci))<br />
                   .Add(Example.Create(ogr))<br />
                   .List<Ogrenci>();<br />
[/sourcecode]</p>
<p>2)Sınıfı 9B(id=7) olan öğrencileri example kullanarak bulalım.<br />
[sourcecode language="csharp"]<br />
ISession session = NHibernateHttpModule.CurrentSession;<br />
Sinif snf = session.CreateCriteria(typeof(Sinif))<br />
                        .Add(Expression.Eq("SinifId",7))<br />
                        .List<Sinif>()[0];<br />
         ..............<br />
Ogrenci ogr=new Ogrenci();<br />
ogr.Sinif = snf;<br />
         ..............<br />
return session.CreateCriteria(typeof(Ogrenci))<br />
                   .Add(Example.Create(ogr))<br />
                        .CreateCriteria("Sinif")<br />
                        .Add(Example.Create(ogr.Sinif))<br />
                   .List<Ogrenci>();<br />
[/sourcecode]<br />
5)Önce 7B sınıfını getirdik.<br />
8)Sonra bir öğrenci nesnesi oluşturup “Sinif” property’sine getirdiğimiz snf nesnesini atadık.<br />
10)Daha sonra Ogrenci tipinden bir criteria oluşturduk.<br />
12)Sorgumuzun “Sinif ilişkisi” üzerinden olacağını belirttik.<br />
Yani iç içe iki example vermiş olduk.</p>
<p>Bu örnekleri bu şekilde uzatabiliriz.Bir sonraki yazımızda having,count,sum  gibi metodları ve subcriteria sınıfını inceleyeğiz.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Nhibernate-2]]></title>
<link>http://yahyakoc.wordpress.com/?p=51</link>
<pubDate>Mon, 22 Sep 2008 19:26:00 +0000</pubDate>
<dc:creator>Yahya KOÇ</dc:creator>
<guid>http://yahyakoc.pt-br.wordpress.com/2008/09/22/nhibernate-2/</guid>
<description><![CDATA[Yazımızın ikinci bölümünde Nhibernate’in derinliklerine doğru yol alalım.Uzunca girizgahla]]></description>
<content:encoded><![CDATA[<p>Yazımızın ikinci bölümünde Nhibernate’in derinliklerine doğru yol alalım.Uzunca girizgahlara hiç gerek yok.Hemen başlayalım.</p>
<p><strong>Load()</strong>,<strong>Get()</strong><br />
Id’sini bildiğimiz nesneleri çekmek için kullanılır.Criteria oluşturmaya gerek yoktur.<br />
[sourcecode language="csharp"]<br />
Ogrenci ogr=new Ogrenci();<br />
ogr=(Ogrenci)session.Load(typeof(Ogrenci),242);<br />
ogr=(Ogrenci)session.Get(typeof(Ogrenci),242);<br />
[/sourcecode]<br />
Birinci kullanımda nesnenin veritabanında karşılığı yoksa exception fırlatır.Get metodunu kullandığımızda nesnenin veritabanında karşılığı yoksa metod null değeri döndürür.<br />
<!--more--><br />
<strong>Lazy</strong><br />
Lazy kavramına daha sonra değinmeyi planlıyordum ama sonraki örneklerde bolca lazım olacağı için anlaşılması gereken bir kavram.Nhibernate’in işinin aslında nesneler(tablolar) arası ilişkileri yönetmek olduğundan bahsetmiştik.Bir önceki yazının son kısmında yaptığımız örnekte veritabanından bir Okul nesnesi çekmiş onun Siniflar listesinin içine dallanmıştık.Şimdi okul sınfıını çektiğimizde onun yavru kayıtlarını o kayıtların da yavru kayıtlarını çektiğimizi hayal edin.İyi ilişkilendirimiş bir veritabanımız varsa nerdeyse tüm veritabanını çekmeye kalkıyoruz demektir.Öyleyse bu işleme bir yerde dur demeliyiz.Burda “lazy” devreye giriyor.Lazy=true ifadesinin ana kaydın collection’ında kullandığımızda “Bu collection’ı doldurma.İhtiyacım olduğunda getir” demiş oluyoruz.Peki nhibernate bizim bu listeye ihtiyacımız olduğundan nasıl haberdar oluyor:Kod satırında nesneyi yazıp o nesnenin bahsi geçen listesine ulaştığımız an Nhibernate o listeyi bizim için dolduruyor.Aşağıdaki sqlserverprofiler aracı ile çalışan sql cümlelerini inceleyelim.</p>
<p>=&#62;Lazy=false değeri set edilmediği durumda<br />
[sourcecode language="csharp"]<br />
IList<Okul> liste= _dao.TumOkullariGetir();<br />
[/sourcecode]</p>
<p><img class="alignnone size-full wp-image-269" title="profiler-1" src="http://yahyakoc.wordpress.com/files/2008/09/profiler-1.jpg" alt="" width="640" height="163" /><br />
Gördüğünüz gibi hem Okul sorgusu hem de Sinif sorgusu çalıştı.</p>
<p>=&#62;Lazy=true değeri set edilmediği durumda<br />
[sourcecode language="csharp"]<br />
IList<Okul> liste= _dao.TumOkullariGetir();<br />
[/sourcecode]</p>
<p><img class="alignnone size-full wp-image-272" title="profiler-2" src="http://yahyakoc.wordpress.com/files/2008/09/profiler-2.jpg" alt="" width="640" height="88" /></p>
<p>Sadece okul sorgusu çalıştı.<br />
Gelen sonucu watch edip “Sınıflar” listesini açtığımızda</p>
<p><img class="alignnone size-full wp-image-273" title="watch-11" src="http://yahyakoc.wordpress.com/files/2008/09/watch-11.jpg" alt="" width="747" height="231" /><br />
<img class="alignnone size-full wp-image-274" title="profiler-3" src="http://yahyakoc.wordpress.com/files/2008/09/profiler-3.jpg" alt="" width="640" height="112" /></p>
<p>GetAllOkul metedomuzu tekrar gözden geçirelim.Açtığımız session’ı kapatmadık.Şu şekilde olmalıydı.<br />
[sourcecode language="csharp"]<br />
     public IList<Okul> GetAllOkul()<br />
        {<br />
            ISession session = _sessionFactory.OpenSession();<br />
            ICriteria criteria = session.CreateCriteria(typeof(Okul));<br />
            IList<Okul> liste = criteria.List<Okul>();<br />
            <em>session.close(); </em><br />
            return liste;<br />
        }<br />
[/sourcecode]<br />
Kodumuzu bu şekilde değiştirdikten sonra presenter sınıfımızdaki kodumuza geri dönelim.<br />
[sourcecode language="csharp"]<br />
IList<Okul> liste= _dao.GetAllOkul();<br />
Sinif sinif=liste[0].Siniflar[0];<br />
[/sourcecode]</p>
<p>Üçüncü satıra dikkat edelim.Gelen okulların ilkinin ilk sınıfını almaya çalışıyoruz.Bu arada lazy=true ve session kapatıldı.<br />
<img src="http://yahyakoc.wordpress.com/files/2008/09/watch-3.jpg" alt="" /></p>
<p>Hatırlayacağınız gibi <strong>lazy=true</strong> ifadesi bize listeye ihtiyacımız olduğu zaman listeyi gidip dolduruyordu.GetAllOkul metodundan çıkıldığı zaman session’ı kapattık.Çok daha sonra Siniflar listesine erişmek istediğimizde açık session olmadığı hatasını aldık.Öyleyse session’ımızın sürekli açık olması gerekiyor.Sesion’ı ve sessionfactory’yi bir yerlerde saklamak gerekiyor.Bunun için bir HTTPModule kullanıyoruz.Bunun için aşağıdaki gibi iki yapı kullanıyoruz.</p>
<p>Önce OKULDAO sınıfının yapıcısında yazdığımız Nhibernate konfigurasyonunu kaldırıyoruz.Çünkü bu nesneden instance alındığında aşağıdaki kod bloğu çalışıyor.Her seferde sessionfactory oluşturuluyor.Bu çok maliyetli bir yaklaşım.Bunun yerine sessionfactory bir defa oluşturulup pekala ASP.Net session’da saklanabilir.<br />
[sourcecode language="csharp"]<br />
private static ISessionFactory _sessionFactory;<br />
public OkulDAONHibernate()<br />
{<br />
     Configuration config =new Configuration().Configure();<br />
     _sessionFactory = config.BuildSessionFactory();<br />
}<br />
[/sourcecode]<br />
İki sınıfımız bize bu konuda yardımcı olacak: SessionHelper ve NhibernateHttpModule.<br />
[sourcecode language="csharp"]<br />
public class SessionHelper<br />
    {<br />
    private static ISessionFactory _sessionFactory = null;<br />
        private static ISessionFactory SessionFactory<br />
        {<br />
            get<br />
            {<br />
                if (_sessionFactory == null)<br />
                {<br />
                    Configuration config = new Configuration().Configure();<br />
                    _sessionFactory = config.BuildSessionFactory();<br />
                    if (_sessionFactory == null)<br />
                        throw new InvalidOperationException("Could not build SessionFactory");<br />
                }<br />
                return _sessionFactory;<br />
            }<br />
        }<br />
        public static ISession OpenSession()<br />
        {<br />
            ISession session;<br />
            session = SessionFactory.OpenSession();<br />
            if (session == null)<br />
                throw new InvalidOperationException("Cannot open session");<br />
            return session;<br />
        }<br />
    }<br />
[/sourcecode]<br />
Gördüğünüz gibi _SessionFactory bir kere oluşturulup static bir değişkene atılıyor.<br />
NhibernateHttpModule sınıfı çok önemli o yüzden ayrıntılı incelemenizi tavsiye ederim.<br />
[sourcecode language="csharp"]<br />
  public class NHibernateHttpModule : IHttpModule<br />
     {<br />
         public const string KEY ="_TheSession_";<br />
         private static ISession _session;</p>
<p>         private void context_BeginRequest(object sender, EventArgs e)<br />
         {<br />
             HttpApplication application = (HttpApplication)sender;<br />
             HttpContext context = application.Context;<br />
             context.Items[KEY] = SessionHelper.OpenSession();<br />
         }</p>
<p>         private void context_EndRequest(object sender, EventArgs e)<br />
         {<br />
             HttpApplication application = (HttpApplication)sender;<br />
             HttpContext context = application.Context;</p>
<p>             ISession session = context.Items[KEY] as ISession;<br />
             if (session != null &&  session.IsOpen)<br />
             {<br />
                 try<br />
                 {<br />
                     session.Flush();<br />
                     session.Close();<br />
                 }<br />
                 catch { }<br />
             }<br />
             context.Items[KEY] = null;<br />
         }</p>
<p>         public static ISession CurrentSession<br />
         {<br />
             get<br />
             {<br />
                 if (HttpContext.Current == null)<br />
                 {<br />
                     if (_session != null)<br />
                         return _session;</p>
<p>                     _session = SessionHelper.OpenSession();<br />
                     return _session;<br />
                 }<br />
                 HttpContext currentContext = HttpContext.Current;<br />
                 ISession session = currentContext.Items[KEY] as ISession;<br />
                 if (session == null)<br />
                 {<br />
                     session = SessionHelper.OpenSession();<br />
                     currentContext.Items[KEY] = session;<br />
                 }<br />
                 return session;<br />
             }<br />
         }<br />
         #region IHttpModule Members<br />
         public void Init(HttpApplication context)<br />
         {<br />
             context.BeginRequest += new EventHandler(context_BeginRequest);<br />
             context.EndRequest += new EventHandler(context_EndRequest);<br />
         }<br />
[/sourcecode]<br />
59.-60.) Bu iki satır IHttpModule sınıfınından implement ettiğimiz metodlar.Böylece “open session per request” yapımızı kurmuş olacağız.Her istek geldiğinde (11.) SessionHelper yardımı ile Sessionfactory üzerinden bir session açıyoruz.İstek sonlandığında (24.) session’ımızı flush ediyoruz.Böylece arada kalmış, veritabaınına güncellenmemiş nesnelerimiz kalmıyor.<br />
Bu yapının web uygulamamız tarafından kullanılabilmesi için webconfig ayarlarını aşağıdaki gibi değiştiriyoruz.<br />
[sourcecode language="xml"]<br />
<system.webServer><br />
    <modules><br />
      <add type="SanalOkul.DAO.NHibernateHttpModule,SanalOkul.DAO" name="NhibernateHttpModule"/><br />
   </modules><br />
[/sourcecode]<br />
Şimdi OkulDAO sınıfımızın son haline göz atalım.<br />
[sourcecode language="csharp"]<br />
  public IList<Okul> GetAllOkul()<br />
        {<br />
            ISession session = NHibernateHttpModule.CurrentSession;<br />
            ICriteria criteria = session.CreateCriteria(typeof(Okul));<br />
            IList<Okul> liste = criteria.List<Okul>();<br />
            return liste;<br />
        }<br />
[/sourcecode]<br />
Gördüğünüz gibi artık sessionfactory oluşturma session açma,kapatma işlemleriyle biz uğraşmıyoruz.</p>
<p><strong>save(),update(),SaveorUpdate(),SaveorUpdateCopy(),delete()</strong></p>
<p>Save metodunun kullanımına örnek<br />
[sourcecode language="csharp"]<br />
Ogrenci ogr=new Ogrenci();<br />
ogr.Ad = "taner";<br />
ogr.Soyad = "bozdemir";<br />
session.Save(ogr);<br />
session.Flush();<br />
session.Refresh(ogr);<br />
[/sourcecode]<br />
5.)Nesneyi session’ımıza yolluyoruz.Henüz id alanı set edilmedi.<br />
6.)Session’in içinde yer alan nesne(ler) veritabanına yazılıyor.Burada dikkat etmemiz gereken bir nokta var.Flush metodu sadece ogr nesnesi için çalışmaz.O anda session’da yer alan ve <em>değişikliğe uğramış </em>tüm nesneleri veritabanında güncellemeye çalışır.Daha önce de belirttiğimiz gibi Nhibernate nesneleri id alanalrından tanır.Load ettiği nesneleri session kapanana kadar takip eder.Isdirty diye bir alan üzerinden nesnenin değişikliğe uğrayıp uğramadığını takip eder.<br />
7.)Nesnenin son halini veritabanından alır.veritabanında trigger türü veri üzerinde değişiklik yapacak yapılar bulunuyorsa nesnesinin son halini almak için birebirdir.Şahsen veritabanında stored procedure,function,trigger türü yapıların kullanılmasını pek benimsemiyorum.Bu tür işlemlerin business logic içerisinde gerçekleştirilmesi taraftarıyım.</p>
<p>Update metodunun kullanımına örnek<br />
[sourcecode language="csharp"]<br />
Ogrenci ogr=new Ogrenci();<br />
session.Load(ogr,242);<br />
ogr.Soyad = "bozdemir";<br />
session.Update(ogr);<br />
session.Flush();<br />
[/sourcecode]<br />
5.)Bu satıra aslında gerek yok çünkü hemen alt satırdaki session.flush() metodu değişen nesneleri belirleyip bunları veritabanında güncelleyecektir.</p>
<p>SaveorUpdate ve SaveorUpdateCopy metodları save ve update metodlarının yerine kullanılır.Eğer nesnenin veritabanında karşılığı varsa(persistent) Nhibernate bu nesneyi günceller.Eğer yeni bir kayıt(Transient) ise nesneyi veri tabanına kaydeder.</p>
<p>[sourcecode language="csharp"]<br />
Ogrenci ogr=new Ogrenci();<br />
session.Load(ogr,242);<br />
ogr.Soyad = "bozdemir";<br />
session.SaveOrUpdateCopy(ogr);<br />
session.Flush();<br />
[/sourcecode]</p>
<p>5.)242 id’li bir kayıt veritabanında varsa güncellenir,kayıt yoksa yeni bir kayıt olarak veritabanına işlenir.SaveorUpdateCopy, SaveorUpdate metodundan farklı olarak kaydettiği nesnenin bir kopyasını geri döndürür.Ayrıca Update ve SaveorUpdate kullanıldığında aynı id değerini taşıyan başka bir nesne session içerisinde yer alıyorsa “<strong>different object with the same identifier value</strong>” hatası alırız.SaveorUpdateCopy metodu yeni oluşturlan nesnenin tüm durumunu zaten session içerisinde yer alan aynı id’ye sahip nesnenin üzerine giydirir böylece tek nesne haline getirir.Bu yüzden save/update işlemlerinizde SaveorUpdateCopy metodunu kullanmanızı tavsiye ederim.Bu metodun Hibernate’deki karşılığı da bildiğim kadarıyla “<strong>merge</strong>” metodur.</p>
<p>Şimdi de Asp.net Session ile Nhibernate’i birlikte kullanalım.Presenter sınıfımızı bir anlığına aradan çıkardığımızı,view'in dao'ya direk eriştiğini varsayalım örneğin daha kolay anlaşılabilmesi için...<br />
[sourcecode language="csharp"]<br />
public partial class _Default : System.Web.UI.Page<br />
{<br />
    protected void Page_Load(object sender, EventArgs e)<br />
    {<br />
        if (!IsPostBack)<br />
        {<br />
           OkulDAONHibernate _dao = new OkulDAONHibernate();<br />
           Okul okl = _dao.GetById(1);<br />
           okl.Adres += " Türkiye Dünya";<br />
          _dao.Update(okl);<br />
           Session["okl"] = okl;<br />
         }<br />
     }<br />
    protected void Button1_Click(object sender, EventArgs e)<br />
    {<br />
       OkulDAONHibernate _dao=new OkulDAONHibernate();<br />
       Okul okl = (Okul) Session["okl"];<br />
       Sinif snf= okl.Siniflar[0];<br />
       snf.SinifAdi = "11D";<br />
      _dao.Update(okl);<br />
     }<br />
}<br />
[/sourcecode]<br />
8.)Id’si 1 olan okulu getiriyoruz.<br />
9.-10.)Adres alanını güncelliyoruz.<br />
11.)Nesneyi Asp.Net Session’a atıyoruz.<br />
17.)Buton eventi altında nesneyi Asp.Net Session’ınından geri alıyoruz.<br />
18.)Siniflar listesine ulaşıp ilk sınıfı alıyoruz.<br />
19.-20.)O sınıfın adını “11D” olarak güncelliyoruz.</p>
<p>Peki bu kod düzgün çalışır mı?Hemen söyleyelim çalışmaz.<br />
=&#62;Page_Load eventi altında okul nesnemizi veritabanından çekiyoruz.(buraya dikkat! Siniflar listesi lazy=true)<br />
=&#62;Okul nesnemizin adresini güncelliyoruz.<br />
=&#62;Nesneyi Asp.Net Session’a atıyoruz.<br />
=&#62;PageLoad eventi bitiyor ve NhibernateHttpModule içindeki <strong>context_EndRequest</strong> metodu çalışıyor.<br />
=&#62;Buton eventi başlıyor <strong>context_BeginRequest </strong>metodu çalışıyor ve yeni bir session açılıyor.<br />
=&#62;18.satırda kapanan session’a ait nesnemizi geri alıyoruz.<br />
=&#62;19.satırda nesnenin lazy olan listesine erişmek isityoruz.Nhibernate devreye girip listeyi bizim için çekmeye kalkıyor ama bu nesnenin listesi kapanan bir session’a ait.Vee çok sevdiğimiz hatamız gene karşımızda: <strong>failed to lazily initialize a collection - no session</strong></p>
<p>Bu durumda elimizde üç seçenek var:<br />
=&#62;Listeyi lazy=false yapmak ama bu değişkeni kontrollü kullanmak lazım zira çok büyük listeler performansı dibe çeker.<br />
=&#62;Page Load eventi altında değiştirmek istediğimiz sınıfın ait olduğu okulu değil de “Sinif” nesnesinin kendisini Asp.Net Session içine gömüp aşağıda gerekli değişikliği yapıp güncelleme yaparız.<br />
=&#62;Okul nesnesini Page Load eventi altında session’a atıp Buton event’i altında erişerek o nesneyi id’siyle yeniden veritabanından getirterek sinifları üzerinde işlem yapmak.</p>
<p>[sourcecode language="csharp"]<br />
protected void Button1_Click(object sender, EventArgs e)<br />
{<br />
    OkulDAONHibernate _dao=new OkulDAONHibernate();<br />
    Okul okl = (Okul) Session["okl"];<br />
    okl=_dao.GetById(okl.OkulId);<br />
    Sinif snf= okl.Siniflar[0];<br />
    snf.SinifAdi = "11Z";<br />
   _dao.UpdateSinif(snf);<br />
}<br />
[/sourcecode]</p>
<p>6.)Bu satırda önceki sesssion’a kalan nesnemizi bu sessionda tekrar çekiyoruz.Nhibernate bu işlem için <strong>Refresh()</strong> metodunu sunuyor.<br />
[sourcecode language="csharp"]<br />
protected void Button1_Click(object sender, EventArgs e)<br />
{<br />
     OkulDAONHibernate _dao=new OkulDAONHibernate();<br />
     Okul okl = (Okul) Session["okl"];<br />
     _dao.RefreshOkul(okl);<br />
     Sinif snf= okl.Siniflar[0];<br />
     snf.SinifAdi = "11Z";<br />
    _dao.UpdateSinif(snf);<br />
}<br />
[/sourcecode]</p>
<p>5.)Bu satırdaki RefreshOkul metodunun içeriği de şöyle<br />
[sourcecode language="csharp"]<br />
public void RefreshOkul(Okul okl)<br />
{<br />
    ISession session = NHibernateHttpModule.CurrentSession;<br />
    session.Refresh(okl);<br />
}<br />
[/sourcecode]</p>
<p>Şimdi biraz daha kapsamlı bir örnek yapalım.Bir Okul oluşturalım.Ona bağlı iki sınıf ve o sınıflara bağlı birer öğrenci kaydedelim.<br />
[sourcecode language="csharp"]<br />
     OkulDAONHibernate _dao = new OkulDAONHibernate();<br />
     Okul okl=new Okul();<br />
     okl.OkulAdi = "Refet Bele Lisesi";<br />
     okl.Adres = "Tuzla/İstanbul";</p>
<p>     Sinif snf1=new Sinif();<br />
     snf1.Okul = okl;<br />
     snf1.SinifAdi = "9A";<br />
     Sinif snf2=new Sinif();<br />
     snf2.Okul = okl;<br />
     snf2.SinifAdi = "9B";</p>
<p>     Ogrenci ogr1=new Ogrenci();<br />
     ogr1.Ad = "İsmail";<br />
     ogr1.Soyad = "Koç";<br />
     ogr1.Sinif = snf1;</p>
<p>     Ogrenci ogr2 = new Ogrenci();<br />
     ogr2.Ad = "Emrah";<br />
     ogr2.Soyad ="Bozdağ";<br />
     ogr2.Sinif = snf2;</p>
<p>     snf1.Ogrenciler.Add(ogr1);<br />
     snf2.Ogrenciler.Add(ogr2);<br />
     okl.Siniflar.Add(snf1);<br />
     okl.Siniflar.Add(snf2);</p>
<p>   _dao.Insert(okl);<br />
[/sourcecode]<br />
Üst taraftaki kodda dikkatinizi çekmiş olmalı okul nesnesinin siniflar listesine yeni sinif eklemeden önce o sınıfın okul property’sini set ediyoruz.<br />
[sourcecode language="csharp"]<br />
    snf2.Okul = okl;<br />
    okl.Siniflar.Add(snf2);<br />
[/sourcecode]</p>
<p>Üstteki örneğimizde gördüğünüz gibi Okul,Sinif ve Ogrenci nesnelerini okul üzerinden kaydettik.Yani ilişkinin en başındaki nokta üzerinden kaydettik.Bir de olaya tersten bakalım:</p>
<p>[sourcecode language="csharp"]<br />
     OkulDAONHibernate _dao = new OkulDAONHibernate();<br />
     Okul okl=new Okul();<br />
     okl.OkulAdi="Beşiktaş Anadolu Lisesi";</p>
<p>     Sinif snf=new Sinif();<br />
     snf.SinifAdi="7A";<br />
     snf.Okul=okl;<br />
     okl.Siniflar.Add(snf);<br />
     snf.Insert();<br />
[/sourcecode]</p>
<p>Bu kodu çalıştırdığımızda şöyle bir hata alırız:<strong>Object references an unsaved transient instance-save transient object before flushing:SanalOkul.Domain.Okul</strong></p>
<p>Türkçesi "snf nesnesini kaydetmeye çalışıyorsun, bir ilişki vermişsin ama bu ilişkiye konu alan nesne(okul) veritabanında yok(transient). Önce onu kaydet ondan sonra gel <img src="http://yahyakoc.wordpress.com/files/2008/09/icon_smile.gif" /><br />
Bu durumda önce okl nesnemizi kaydetmeliyiz sonra snf nesnemizi kaydedebiliriz.<br />
[sourcecode="csharp"]<br />
    _okulDao.Insert(okl);<br />
    _oklDao.Insert(snf);<br />
[/sourcecode]</p>
<p>Aradaki fark anlaşıldı umarım..</p>
<p>Bir yazımızın daha sonuna geldik. Bir sonraki yazımızda expressionlar ve girift sorgular üzerinde yoğunlaşacağız.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[e-Reputation management goes beyond Search Engine Marketing]]></title>
<link>http://onlinereputationmanagement.wordpress.com/?p=80</link>
<pubDate>Mon, 22 Sep 2008 16:42:10 +0000</pubDate>
<dc:creator>b2win</dc:creator>
<guid>http://onlinereputationmanagement.pt-br.wordpress.com/2008/09/22/e-reputation-management-goes-beyond-search-engine-marketing/</guid>
<description><![CDATA[One of the most popular questions I got from prospects is &#8220;How do you - as ORM professional - ]]></description>
<content:encoded><![CDATA[<p>One of the most popular questions I got from prospects is "How do you - as ORM professional - compete with Search Engine Marketing (SEM) agencies offering Online Reputation Management?"</p>
<p>Before answering that question, I'd like to add that most of ORM specialists come from eMarketing or PR worlds. As you know I'm a PR. :-)</p>
<p>As PR my answer is: "When I'm doing ORM services, I'm not PR anymore. I don't want to limit our actions portfolio to SEO-friendly press release, online press room, PR campaign,... When I'm offering ORM services, I'm ready to give you advice on how to react to online rumor/attacks with ads, marketing, PR, SEM, legal,... tools. Of course I won't be able to take all the actions on my own. BUT that's not my job as consultant!"</p>
<p>"When you are looking at most of the SEM e-Reputation Management services you rapidly understand that their only focus is ranking/positioning in search engines. They just miss the global idea of Online Reputation Management such as communication opportunities, brand protection, buzz analysis, etc."</p>
<p>All right! SEM is a great tool to manage your online reputation. BUT ORM goes beyond SEM!!!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Bonde Desgovernado]]></title>
<link>http://janeladoquarto.wordpress.com/?p=457</link>
<pubDate>Sun, 21 Sep 2008 20:14:30 +0000</pubDate>
<dc:creator>Nildo</dc:creator>
<guid>http://janeladoquarto.pt-br.wordpress.com/2008/09/21/bonde-desgovernado/</guid>
<description><![CDATA[
Bondinho vira na Feira do Açaí 


O bondinho de Belém virou por volta de 10h deste domingo (21),]]></description>
<content:encoded><![CDATA[<p><img class="aligncenter" title="bonde" src="http://www.jornaldaorla.com.br/imagens/agente-bonde2511.jpg" alt="" width="300" height="322" /></p>
<p style="text-align:center;"><a href="http://www.orm.com.br/plantao/noticia/default.asp?id_noticia=370733" target="_blank"><strong><span class="PL_tit">Bondinho vira na Feira do Açaí </span></strong></a></p>
<p style="text-align:center;">
<div id="tx">
<p>O bondinho de Belém virou por volta de 10h deste domingo (21), enquanto passava pela <strong>Feira do Açaí</strong>, no Centro Comercial de da capital paraense.</p>
<p>Segundo informações iniciais do Ciop (Centro Integrado de Operações), <a href="http://www.orm.com.br/plantao/noticia/default.asp?id_noticia=370737" target="_blank">uma criança teria sofrido ferimentos leves. </a></p>
<p>Uma equipe do Corpo de Bombeiros e da Polícia Militar já foi enviada ao local. Ainda não se sabe as causas do acidente.</p>
<p>Bondinho - O bondinho foi inaugurado no dia 12 de outubro de 2007. Ele sai da Estação Gumercindo Rodrigues, em frente à Praça Dom Pedro II.</p>
<p>via <a href="http://www.orm.com.br/plantao/noticia/default.asp?id_noticia=370733" target="_blank">portal orm</a></p>
<p><span style="text-decoration:line-through;">-----------------------------------------------------------</span></p>
<p><strong>Não sei não, mas acho que botaram álcool no açai do maquinista...</strong></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Online Reputation Monitoring Is Just Good Business!]]></title>
<link>http://gmtacticians.wordpress.com/?p=43</link>
<pubDate>Mon, 15 Sep 2008 14:53:03 +0000</pubDate>
<dc:creator>Nick de Klerk</dc:creator>
<guid>http://gmtacticians.pt-br.wordpress.com/2008/09/15/online-reputation-monitoring-is-just-good-business/</guid>
<description><![CDATA[ORM, Online Repuation Management or Monitoring, whatever you want to call it  makes no difference to]]></description>
<content:encoded><![CDATA[<p>ORM, Online Repuation Management or Monitoring, whatever you want to call it  makes no difference to the fact that everyone who is looking at effectively  managing their PR needs to take great stock in this.</p>
<p>ORM is quite simply, the practice of tracking a group or set of pre-defined  keywords about your company, your competitors or just about anything you want,  across the entire internet from websites, to newsgroups and across the entire  blogosphere... But good ORM is not just tracking everything, a good ORM strategy  also needs some type of analysis and yes, some kind of strategy when dealing  with unruly statements that you may happen to find.</p>
<p>Not too long ago, the world of ORM was started by the advent of <a title="Google Alerts" href="http://www.google.co.za/alerts?hl=en" target="_blank">Google Alerts</a>, relevant  phrases would be setup and carefully monitored... which I suppose is fine, but  then it does not really help if you do nothing about a bad piece of press and if  no-one <strong>actually</strong> monitors this online PR channel then its just  another glorified web-type report that ends up in the "file" pile...</p>
<p>Thankfully, due to the natural evolution of the online marketing environment  though, a number of well-established marketing companies have thrown a bit more  "know-how" behind the aggregation of collecting alerts, and created some great  tools for tracking and managing your reputation online. There are a number of  tools available, notably Andy Beal's <a title="Trakur" href="http://www.trackur.com/" target="_blank">Trackur</a> and local offerings, <a title="Brandseye" href="http://www.brandseye.com/" target="_blank">Brandseye</a> from Quirk and <a title="SaidWOT" href="http://www.saidwot.com/" target="_blank">SaidWot</a> from LongTail. They all have a  similar offering and allow the added advantage of giving you more than just  tracking, which is the strategy and action of dealing with unruly PR on various  channels. This all comes with a small price (obviously) and is really well worth  the cost too, especially when it comes to the interpretation and strategy behind  the Reputation Management tool. As an online marketer myself, I would defintely  advocate the usage of one of these professional offerings - you just can't take  a chance when it comes to your online reputation.</p>
<p>However, if budget is an issue, or if you would prefer to test the world of  Online Reputation Management without spending any money, then there are other  ways to manage your own reputation online.</p>
<p>As mentioned there are Google Alerts, which send daily, weekly, or "as it  happens" news through - related to keywords and is farily comprehensive,  covering everything from mainstream news sites, to entries across the  blogosphere. These alerts arrive in your mailbox in the form of an email so the  information is readily available.</p>
<p>Now, if Google Alerts are not enough, then you can also setup a simple Online  Reputation Monitoring tool by using your Wordpress blog. It's actually a  Wordpress Widget plug-in and gives you an opportunity to monitor pretty much any  source of content that is provided in RSS feeds called <strong><a title="WP-O-Matic" href="http://wordpress.org/extend/plugins/wp-o-matic/installation/" target="_blank">WP-O-Matic</a></strong>.  This plug-in automatically creates posts from RSS/Atom feeds that you provide it  and organises them into campaigns for you to use and easily interpret too. The  plugin has an easy to manage user interface, which features imaging caching,  word rewriting to name a few. It also allows you to import your own OPML files,  so essentially you can create a tracking campaign across thousands of feeds  quite instantly. When it comes to adding the actual feed content, WP-O-matic has  both Unix cron and Wordpress cron jobs to make the fetching process simple, or  alternatively you can just hit the "fetch" button and manually import the latest  posts from the feeds you have specified and collected. It is a very well thought  out and well researched plugin, and one you really need to see in action to  believe.</p>
<p>So there you have it, ORM in a nutshell, as well as some handy free tools and  some very professional options to choose from too.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Dryophiops rubescens, Bako nationalpark, Borneo]]></title>
<link>http://byalvan.wordpress.com/?p=125</link>
<pubDate>Fri, 12 Sep 2008 18:35:56 +0000</pubDate>
<dc:creator>byalvan</dc:creator>
<guid>http://byalvan.pt-br.wordpress.com/2008/09/12/125/</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<p><a href="http://byalvan.files.wordpress.com/2008/09/red-dryophiops-rubescens-4.jpg"><img class="aligncenter size-full wp-image-124" title="Dryophiops rubescens" src="http://byalvan.wordpress.com/files/2008/09/red-dryophiops-rubescens-4.jpg" alt="" width="497" height="576" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Dendrelaphis formosus, Bako nationalpark, Borneo]]></title>
<link>http://byalvan.wordpress.com/?p=122</link>
<pubDate>Thu, 11 Sep 2008 19:25:05 +0000</pubDate>
<dc:creator>byalvan</dc:creator>
<guid>http://byalvan.pt-br.wordpress.com/2008/09/11/dendrelaphis-formosus-pa-borneo/</guid>
<description><![CDATA[
]]></description>
<content:encoded><![CDATA[<p><a href="http://byalvan.files.wordpress.com/2008/09/red-dendrelaphis-formosus-narbild-2.jpg"><img class="aligncenter size-full wp-image-121" title="Dendrelaphis formosus" src="http://byalvan.wordpress.com/files/2008/09/red-dendrelaphis-formosus-narbild-2.jpg" alt="" width="496" height="345" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Hibernate una herramienta de Mapping (I)]]></title>
<link>http://contenidodigital.wordpress.com/?p=9</link>
<pubDate>Thu, 11 Sep 2008 15:14:36 +0000</pubDate>
<dc:creator>kawieli</dc:creator>
<guid>http://contenidodigital.pt-br.wordpress.com/2008/09/11/hibernate-una-herramienta-de-mapping-i/</guid>
<description><![CDATA[
Introducción
Hoy os introduciré una nueva forma guardar y acceder a nuestros datos a los correspo]]></description>
<content:encoded><![CDATA[<p><a href="http://www.hibernate.org"><img class="alignright size-full wp-image-10" title="hibernate_icon" src="http://contenidodigital.wordpress.com/files/2008/09/hibernate_icon.gif" alt="" width="120" height="120" /></a></p>
<p><strong>Introducción</strong></p>
<p>Hoy os introduciré una nueva forma guardar y acceder a nuestros datos a los correspondientes medios de almacenamiento.  Existen multitud de técnicas (DataSet, DataTables, SQL). Estas herramientas sirven para hacernos la vida más facil a la hora de acceder a registros al igual que almacenarlos, de todas las herramientas usadas hoy voy a explicaros brevemente una de ellas y poner un ejemplo de una de las más conocidas (Hibernate).  Día a día os iré introduciendo un poco más en lo que respecta esta maravillosa tecnología que puede ser una  tecnología puente a otro tipo de acceso a datos en un futuro no muy lejano y que será un boom a la hora de desarrollar nuevas aplicaciones.</p>
<p><strong>ORM</strong></p>
<p>Entrando en Hibernate, Hibernate es un ORM  y ¿Qué es un Object Relational Mapping?.</p>
<p>ORM es una especie de traductor que busca solucionar el problema  claramente existente de la diferencia entre los dos modelos usados hoy en día para organizar y manipular datos que son:</p>
<p>-El usado en la memoria nuestro ordenador que sería la orientación a objetos</p>
<p>-Y el usado en nuestras bases de datos que sería el modelo relacional</p>
<p><strong>¿Y porqué si queremos usar objetos en nuestras aplicaciones no nos basamos en bases de datos orientas a objetos? </strong></p>
<p>Aunque existen dichos tipos de datos actualmente la accesibilidad de estas bases de datos es sumamente ineficiente comparadas con las relacionales por eso si queremos simplificar nuestras aplicaciones usar una herramienta ORM puede ser una verdadera ventaja tanto para facilidad de programación como para rendimiento.</p>
<p><strong>¿Cómo logro que se enlacen mis datos a objetos?</strong></p>
<p>El enlace se ha de indicar en un fichero mapeado en algunos casos o vía código en otros siempre dependiendo del ORM que usemos, pero la máquina para poder asociar que ese objeto es esa tabla ha de saber de alguna manera qué tabla mirar. A la asociación la llamaremos mapeo o <em>mapping</em>.</p>
<p><strong>¿Entonces qué es Hibernate y de qué proviene?</strong></p>
<p><strong> Hibernate </strong>es una herramienta del tipo ORM que en un principio se creó para la plataforma JAVA aunque también está para .Net conocida como NHibernate.  La forma en la que mapearemos (enlazaremos tablas con objetos) es mediante archivos declarativos XML. Tenemos que destacar que Hibernate como NHibernate son software libre, distribuido bajo términos de la licencia GNU LGPL así que nos facilitará muchísimo el aprendizaje y el probarla.</p>
<p>Por poneros un ejemplo aquí teneis un archivo de mapeo de una clase llamada Tarifa que constaría de un Id y un nombre.</p>
<blockquote><p>&#60;?xml version="1.0" encoding="utf-8" ?&#62;<br />
&#60;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GestelecomAplicacion" namespace="GestelecomAplicacion"&#62;</p>
<p>&#60;class name="Tarifa" table="T_Tarifas"&#62;</p>
<p>&#60;id name="idTarifa" column ="idTarifa" type="string" unsaved-value="0"&#62;<br />
&#60;generator class="assigned"/&#62;<br />
&#60;/id&#62;</p>
<p>&#60;property name="descripcion" column ="descripcion" type ="string" not-null="false"/&#62;</p>
<p>&#60;/class&#62;<br />
&#60;/hibernate-mapping&#62;</p></blockquote>
<p>En posteriores días os detallaré las ventajas y desventajas que presenta usar este tipo de programación así como experiencias propias.</p>
<p>Un saludo y ya sabéis si teneis alguna duda o sugerencia aquí estaremos</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Online Reputation Monitoring Is Just Good Business!]]></title>
<link>http://pixel8studios.wordpress.com/?p=68</link>
<pubDate>Thu, 11 Sep 2008 09:40:11 +0000</pubDate>
<dc:creator>Nick de Klerk</dc:creator>
<guid>http://pixel8studios.pt-br.wordpress.com/2008/09/11/online-reputation-monitoring-is-just-good-business/</guid>
<description><![CDATA[ORM, Online Repuation Management or Monitoring, whatever you want to call it makes no difference to ]]></description>
<content:encoded><![CDATA[<p>ORM, Online Repuation Management or Monitoring, whatever you want to call it makes no difference to the fact that everyone who is looking at effectively managing their PR needs to take great stock in this.</p>
<p>ORM is quite simply, the practice of tracking a group or set of pre-defined keywords about your company, your competitors or just about anything you want, across the entire internet from websites, to newsgroups and across the entire blogosphere... But good ORM is not just tracking everything, a good ORM strategy also needs some type of analysis and yes, some kind of strategy when dealing with unruly statements that you may happen to find.</p>
<p>Not too long ago, the world of ORM was started by the advent of <a title="Google Alerts" href="http://www.google.co.za/alerts?hl=en" target="_blank">Google Alerts</a>, relevant phrases would be setup and carefully monitored... which I suppose is fine, but then it does not really help if you do nothing about a bad piece of press and if no-one <strong>actually</strong> monitors this online PR channel then its just another glorified web-type report that ends up in the "file" pile...</p>
<p>Thankfully, due to the natural evolution of the online marketing environment though, a number of well-established marketing companies have thrown a bit more "know-how" behind the aggregation of collecting alerts, and created some great tools for tracking and managing your reputation online. There are a number of tools available, notably Andy Beal's <a title="Trakur" href="http://www.trackur.com/" target="_blank">Trackur</a> and local offerings, <a title="Brandseye" href="http://www.brandseye.com/" target="_blank">Brandseye</a> from Quirk and <a title="SaidWOT" href="http://www.saidwot.com/" target="_blank">SaidWot</a> from LongTail. They all have a similar offering and allow the added advantage of giving you more than just tracking, which is the strategy and action of dealing with unruly PR on various channels. This all comes with a small price (obviously) and is really well worth the cost too, especially when it comes to the interpretation and strategy behind the Reputation Management tool. As an online marketer myself, I would defintely advocate the usage of one of these professional offerings - you just can't take a chance when it comes to your online reputation.</p>
<p>However, if budget is an issue, or if you would prefer to test the world of Online Reputation Management without spending any money, then there are other ways to manage your own reputation online.</p>
<p>As mentioned there are Google Alerts, which send daily, weekly, or "as it happens" news through - related to keywords and is farily comprehensive, covering everything from mainstream news sites, to entries across the blogosphere. These alerts arrive in your mailbox in the form of an email so the information is readily available.</p>
<p>Now, if Google Alerts are not enough, then you can also setup a simple Online Reputation Monitoring tool by using your Wordpress blog. It's actually a Wordpress Widget plug-in and gives you an opportunity to monitor pretty much any source of content that is provided in RSS feeds called <strong><a title="WP-O-Matic" href="http://wordpress.org/extend/plugins/wp-o-matic/installation/" target="_blank">WP-O-Matic</a></strong>. This plug-in automatically creates posts from RSS/Atom feeds that you provide it and organises them into campaigns for you to use and easily interpret too. The plugin has an easy to manage user interface, which features imaging caching, word rewriting to name a few. It also allows you to import your own OPML files, so essentially you can create a tracking campaign across thousands of feeds quite instantly. When it comes to adding the actual feed content, WP-O-matic has both Unix cron and Wordpress cron jobs to make the fetching process simple, or alternatively you can just hit the "fetch" button and manually import the latest posts from the feeds you have specified and collected. It is a very well thought out and well researched plugin, and one you really need to see in action to believe.</p>
<p>So there you have it, ORM in a nutshell, as well as some handy free tools and some very professional options to choose from too.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Nhibernate-1]]></title>
<link>http://yahyakoc.wordpress.com/?p=3</link>
<pubDate>Wed, 10 Sep 2008 10:52:37 +0000</pubDate>
<dc:creator>Yahya KOÇ</dc:creator>
<guid>http://yahyakoc.pt-br.wordpress.com/2008/09/10/nhibernate-1/</guid>
<description><![CDATA[Nhibernate-1
Merhaba…Tahminimce bir kaç bölümden oluşacak yazı dizimizde Nhibernate teknoloji]]></description>
<content:encoded><![CDATA[<p><STRONG>Nhibernate-1</STRONG></p>
<p>Merhaba…Tahminimce bir kaç bölümden oluşacak yazı dizimizde Nhibernate teknolojilerini uygulamalı olarak incelemeye çalışacağız.Fırsat bulabilirsek ActiveRecord’a da değineceğiz. Basitçe bir web uygulaması yapıp Nhibernate’in çalışma mantığını irdeleyeceğiz.Basit uygulama deyince aklınıza sağda solda rastladığımız tercüme makalelerde geçen console uygulamaları gelmesin. Nesneler arasındaki ilişkilerin nasıl düzenlendiğini,performans karşılaştırmaları,sık rastlanan hataların ne anlama geldikleri en önemlisi web uygulaması içinde session yönetimine değineceğiz.<br />
<!--more--><br />
Nhibernate bildiğiniz gibi -en azından benim gözümde- çoktan tarih olmuş relational database management systemlerin yerini alan object relational mapping araçlarından biridir.Javada kullanın Hibernate’in .net için yazılmış şeklidir.Sınıfların bir mapping dosyası ile veritabanında yer alan tabloların alanlarıyla ilişkilendirilmesi mantığına dayanır.Nhibernate’i <A href="http://sourceforge.net/project/showfiles.php?group_id=73818" target="_blank">buradan</A> edinebilirsiniz.Ben Nhibernate 1.2.1.400 versiyonunu kullanıyorum.<br />
<STRONG>Neden Nhibernate?</STRONG><br />
Çevrenizde “Eski köye yeni adet”,”Ben zaten bu işleri kendi veri sınıfımla yapıyorum,”datatable doldur boşalt! en güzeli..” şeklinde gelecek muhtemel tepkilere verilecek bazı cevaplarımız olmalı.Örneğin bir arkadaşınız “ben bu veriyi datatable ile alırım, içinde dönerek verileri sınıfa yazarım böylece nhibernate’in yapmış olduğu işi yaparım sınııfları da kullanarak OOP yapmış olurum” derse o arkadaşınız muhtemelen ORM’nin sadece O’sunu anlamış aradaki R(relational)’ye hiç dikkat etmemiş.İlişkiler gerçek dünyada olduğu gibi yazılımın da en önemli parçalarından biri…Eğer siz bir ORM aracı kullanmadan OOP mantığını sürdürmek istiyorsanız sınıfları elle doldurmanızın yanısıra aradaki bütün ilişkileri de elle oluşturmanız gerekir.<br />
Uygulamamıza geçmeden önce net olarak anlamamız gereken bazı kavramlar var.Nhibernate ile uygulama geliştirirken bu kavramlarla sık sık karşılaşacağız.</P></p>
<ul>
<li>
ISession:Uygulamanız ile veritabanızı arasında ilişki kuran,içinde ADO.Net bağlantısı bulunduran veritabanı işlemlerini, sayesinde gerçekleştirdiğimiz yapı.
</li>
<li>
ISessionFactory: Verilen konfigürasyon dosyasını okuyup size Nhibernate session’ları(ISession) oluşturan yapı.
</li>
<li>
ITransaction: Session içinde atomik kod blokları(transaction) oluşturmamıza yarayan yapı.
</li>
<li>
Persistent Object: Veritabanında karşılığı bulunan ISession içerisinde yaşayan nesnelerimize verilen ad.Örneğin veritabanından çektiğimiz bir ogrenci nesnesi persistent objecttir.Nesnenin o an id alanı doludur.
</li>
<li>
Transient Object: Veritabanında karşılığı bulunmayan ISession ile ilişkisi olmayan muhtemelen uygulama tarafından henüz oluşturulan nesnelerimize verilen ad.Nesnenin henüz id değeri atanmamıştır.
</li>
<li>
Detached Object: Persistent olan nesnenin bağlı olduğu Session’ın kapanması sonucu oluşan durumdur.Nesnenin id alanı doludur ve muhtemelen veritabanında bir kayıda karşılık gelmektedir.
</li>
</ul>
<p>Burda dikkat etmemiz gereken diğer bir nokta ASP.net Session ile Nhibernate Session kavramlarını karıştırmamamız gerektiğidir.Birbirinden farklı olan bu kavramları ileride beraber kullanacağız.<br />
<STRONG>Uygulama</STRONG><br />
Ufak ufak uygulamamıza geçip yukarıda bahsetteğimiz konuları kod üzerinde görelim.Uygulamamızı MVP(Model View Presenter) mantığıyla geliştireceğiz.<br />
Bir sanal okul uygulaması geliştirceğiz.Aşağıdaki diagramda da veritabanı tablolarımızın biribirleriyle ilişkilerini görebilirsiniz.İlişkileri kısaca özetlersek;<br />
<UL><br />
<LI>Bir okul içinde birden fazla sınıf olabilir.Bir sınıfın bir okulu vardır.</LI><br />
<LI>Bir sınıfın birden fazla öğrencisi olabilir.Bir öğrencinin bir sınıfı vardır.</LI><br />
<LI>Bir öğrencinin birden fazla dersi olabileceği gibi bir dersin birden fazla öğrencisi olabilir.Burda dikkat ederseniz many-to-many ilişki kurmak yerine çapraz tablo kullandık.(n-1 1-n = n-n)</LI></UL></p>
<p><img src="http://yahyakoc.wordpress.com/files/2008/09/sanalokuldiagram2.jpg" alt="" width="704" height="300" class="alignnone size-full wp-image-259" /></a><br />
Uygulamamızın Model-View-Presenter yaklaşımı ile geliştireceğiz.Solution içerisinde yer alan projelerimiz şöyle:<br />
<TABLE></p>
<tr>
<td valign="top">
<img src="http://yahyakoc.wordpress.com/files/2008/09/sanalokulsolution2.jpg" alt="" title="sanalokulsolution2" width="272" height="510" class="alignnone size-full wp-image-261" />
      </td>
<td valign="top">
<strong>SanalOkul</strong>:                 Web uygulamamız<br />
<strong>SanalOkul.DAO</strong>:          Nhibernate ile veritabanı erişim yapacağımız proje.Nhibernate'i kullanabilmemiz için aşağıdaki dll'lerin projeye referans olarak eklenmesi gerekir.<br />
--&#62;Iesi.Collections.dll<br />
--&#62;Castle.DynamicProxy.dll<br />
--&#62;log4net.dll<br />
--&#62;NHibernate.dll<br />
<strong>SanalOkul.Domain</strong>:    Modellerimizin bulunduğu proje<br />
<strong>SanalOkul.Presenter</strong>:Presenter yapısının bulunduğu proje</p>
<p>Nhibernate'in web uygulamasında çalışabilmesi için hbm.xml uzantılı mapping dosyalarımızın "Build Action" değerini "embedded resource"  yapmamız gerekmektedir.Aksi takdirde Nhibernate ilişkilendirmenizi yapamaz."Unknown entity class" hatası alırsınız.<br />
        <img src="http://yahyakoc.wordpress.com/files/2008/09/sanalokullembeddedresource.jpg" alt="" title="sanalokullembeddedresource" width="272" height="230" class="alignnone size-full wp-image-262" /></p>
</td>
</tr>
</table>
<p>Şimdi nhibernate konfigurasyon ayarlarımızı set edelim.<br />
Bunun için iki farklı yöntem mevcut.Direk kod içerisinden bu ayarlar set edilebileceği gibi bir xml dosyası üzerinden -ki tavsiye edilen yöntem budur- set edilebiliyor.<br />
[sourcecode language="csharp"]<br />
using System.Collections.Generic;<br />
 using NHibernate;<br />
 using NHibernate.Cfg;<br />
 using SanalOkul.Domain;<br />
 namespace SanalOkul.DAO<br />
 {<br />
     public class OkulDAO:IOkulDao<br />
     {<br />
         private static ISessionFactory _sessionFactory;<br />
         public OkulDAO()<br />
         {<br />
             Configuration config = new Configuration();<br />
             config.SetPro