May 2010

You are browsing the site archives by month.

NHibernate for MySQL C# Source Code

Now we’re going to make a database connection using ORM Framework that was discussed before, NHibernate.

What the requirement of using NHibernate for our projects? First, add some reference like i’ve explained on previous post (Using NHibernate ORM for .NET Framework), NHibernate.dll, NHibernate.ByteCode.LinFu.dll, and MySql.Data.dll

Second step, create the app.config file and this step also have been explained on my previous post. And for this project the app.config content is :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.connection_string">server=127.0.0.1;User Id=nhibernate;password=nhibernate;Persist Security Info=True;database=nhibernate</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
      <mapping assembly="SimpleNHibernate"/>
    </session-factory>
  </hibernate-configuration>
</configuration>

Then the most important step, creating a persistant class that representing the database table. Suppose my database just have 1 table, user and the structure like this :

NHibernate MySQL Structure

namespace SimpleNHibernate
{
    class User
    {
        private int userId;
        private string userName;

        public User() { }

        public virtual int UserId
        {
            set { this.userId = value; }
            get { return this.userId; }
        }

        public virtual string UserName
        {
            set { this.userName = value; }
            get { return this.userName; }
        }

    }
}

The important thing to remember is make the property “public virtual” because that NHibernate need

And the second important step, create a mapping xml which tells NHibernate how to make relation between persistent objects with relational database table. Now, create a xml file named user.hbm.xml then change the Build Action propery to “Embedded Resource” and the content like this :

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="SimpleNHibernate" assembly="SimpleNHibernate">
  <class name="User" table="user">
    <id name="UserId">
      <column name="user_id" sql-type="int(32)" not-null="true" />
      <generator class="increment" />
    </id>
    <property name="UserName">
      <column name="user_name" sql-type="varchar(128)" not-null="true" />
    </property>
  </class>
</hibernate-mapping>

For primary key we use <id> and the other column we use <property>. And inside those tag there is <column> tag that’s the mapping for the <id> or <property> attribute from persistant class to the databasae column. And for auto_increment function from MySQL Database use <generator class=”increment” /> on the id.

Okay the persistant class and it’s mapping done now, next step is creating a helper class or connector class to make our job easier. This step is optional if you’re prefer to use NHibernate directly and repeat some code. And here’s my code for creating the helper class.

using NHibernate;
using NHibernate.Cfg;

namespace SimpleNHibernate
{
    class NHibernateConnector
    {
        private ISessionFactory sessionFactory;
        private ITransaction transaction;
        private ISession session;

        public NHibernateConnector()
        {
            this.sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }

        public void OpenConnection()
        {
            this.session = sessionFactory.OpenSession();
            this.transaction = this.session.BeginTransaction();
        }

        public void CloseConnection()
        {
            this.session.Close();
        }

        public void Commit()
        {
            this.transaction.Commit();
        }

        public void Rollback()
        {
            this.transaction.Rollback();
        }

        public IQuery CreateQuery(string hql)
        {
            return this.session.CreateQuery(hql);
        }

        public ISession Session
        {
            get { return this.session; }
        }

        public ITransaction Transaction
        {
            get { return this.transaction; }
        }

    }
}

The preparation step is done.. now look at the example for inserting data to the MySQL DBMS using NHibernate Framework.

namespace SimpleNHibernate
{
    class Program
    {
        static void Main(string[] args)
        {
            NHibernateConnector conn = new NHibernateConnector();
            conn.OpenConnection();

            User imKrisna = new User();
            imKrisna.UserName = "I Made Krisna Widhiastra";

            conn.Session.Save(imKrisna);

            conn.Commit();
            conn.CloseConnection();
        }
    }
}

NHibernate .NET Framework ORM

NHibernateNHibernate is the most common ORM (Object-Relational Mapping) that used on .NET Framework Programming. With NHibernate the relational object such as Database Tables can be represented with Object such as Classes on Object Oriented Programming. So how to start it?

First step, of course you must download the NHibernate library. Where? Just go to http://sourceforge.net/projects/nhibernate/files/ and there is many files but the most important is bin package. Extract the zip compressed package to some folder.

Second step, adding the library or references to Visual Studio Project. Open your Visual Studio 2008 and create new project. Just right click on the References then Add References, Browse the .dll files named NHibernate.dll on Required_Bins. Then Add the LazyLoading references, i’m using LinFu so add the NHibernate.ByteCode.LinFu.dll

Then next step is preparing the database. Let’s see now i’m using MySQL as the DBMS you also can use other DBMS that recommended by NHibernate (look at Dialect that supported by NHibernate at reference package). Suppose there are MySQL Database named “nhibernate” with username and password = “nhibernate”

Then let’s create the app.config for connection between NHibernate Framework and MySQL DBMS. To create app.config just right click on your project then “Add New Item” and choose Application Configuration File.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.connection_string">server=127.0.0.1;User Id=nhibernate;password=nhibernate;Persist Security Info=True;database=nhibernate</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
      <mapping assembly="SimpleNHibernate"/>
    </session-factory>
  </hibernate-configuration>
</configuration>

For helping you creating the App.config file, you can set the xml schema. Click on editor window where App.config file opened and look at properties window and set the Schemas, browse to “nhibernate-configuration.xsd” at Required_Bins folder from NHibernate bin package.

Some explanation :

  1. Dialect is what DBMS that you’re using, look at the references for the list of Dialects
  2. Connection String can be got from ADO.NET Connection string, it’s same
  3. Proxy Factory is the LazyLoading library that you choose
  4. mapping is for map the relational table to object class on .NET usually use the Project Name

MySQL Query with C# ADO.NET

This post is using MySQL .NET Connector for connecting .NET Framework with MySQL Database Management System, so if you’re looking for OBDC connection that’s not here but you still can learn this because this much easier than ODBC Connection. Please look at my previous post for preparing your Visual Studio to be able connect with MySQL [How to Connect MySQL Database with C# ADO.NET]

Directly to the code, leave the default library using and add two additional lines below the defaults.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Common;
using MySql.Data.MySqlClient;

Now the main part, creating ADO.NET connection for MySQL Database. I’ve found two ways that’s very similar but the result for programme portability is very different. First way is using Database Factories and the second way is using directly MySQL Connection object from the reference which was added before (MySql.Data.dll)

Here is the example code using Database Factories

        static void connectUsingFactory()
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = "server=10.151.34.31;User Id=adonet;password=adonet;Persist Security Info=True;database=adonet";
            connection.Open();

            DbCommand command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM item";

            DbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader["itmid"]+"t"+reader[1]+"t"+reader[2]+"t"+reader["price"]);
            }
            reader.Close();
            connection.Close();
        }

And the second way, using MySQL Connection object

        static void connectUsingReference()
        {
            DbConnection connection = 
                new MySqlConnection("server=10.151.34.31;User Id=adonet;password=adonet;Persist Security Info=True;database=adonet");
            connection.Open();

            DbCommand command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM item";

            DbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader["itmid"] + "t" + reader[1] + "t" + reader[2] + "t" + reader["price"]);
            }
            reader.Close();
            connection.Close();
        }

And the last is the main method for testing the codes above…

        static void Main(string[] args)
        {
            connectUsingFactory();
            Console.WriteLine();
            connectUsingReference();
            Console.ReadKey();
        }

The first way, using Database Factories is easier if we didn’t know the Database Connection Class or if we’re using the connector that the default ADO.NET Driver already support it because we just insert the namespace for parameter. But the first way didn’t work if you’re using MySQL Database .NET Connector when the computer that you’re use didn’t installed by the connector or only using non-installer connector. So we must use second way to make the project portable.

Download the complete Project example here : MySQLNET Connection VS2008 Project

Pidgin for Facebook Chat

Good news… for you who are looking the way to chat on facebook but don’t want to open web browser or facebook site. And if you’re using ebuddy or digsby maybe they already have that services.

What if i’m using pidgin? There’s no need to worry…. Just follow this step

  1. Make sure you’re not running pidgin, if it’s running just close it.
  2. Download the facebook chat plugin for pidgin here
  3. I recommend to download .exe if you’re using windows
  4. Install the downloaded file
  5. Run your pidgin again….
  6. Add your facebook account like other account on pidgin

Removing ‘index.php’ from CodeIgniter URL

CodeIgniter is the one of most famous PHP Framework now. But if we’re using CodeIgniter, by default the URL will be shown as http://localhost/index.php/welcome. Some people doesn’t like this way to accessing a website, the index.php suffix in the URL.

Here is some step that can make us accessing the website using http://localhost/welcome. But we’re also still accessing the url ith index.php suffix. Before, i will list my system so if we’re using different system it may cause different solution.

  1. Apache 2.2.14
  2. PHP 5.2.12

STEP one : create .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#‘system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css folders, and the robots.txt file
#Submitted by Michael Radlmaier (mradlmaier)
RewriteCond $1 !^(index.php|images|robots.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don’t have mod_rewrite installed, all 404’s
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>

STEP two : edit CodeIgniter Configuration

$config['index_page'] = "index.php";

TO

$config['index_page'] = "";

That’s all. Go and try that….

Source and References

  1. http://arifn.web.id/blog/2009/02/06/codeigniter-removing-indexphp.html