I Made Krisna's Times My Way to Write the Times

15Jun/102

phpMyAdmin + PHP 5.3.x Blank Page Login

phpMyAdmin with PHP 5.3.x blank page login issue was the problem that bothering me for few times. Starts from when i want to update my PHP version from 5.2.12 to 5.3.1 then i got that error. I think that's the bugs from PHP 5.3.1 so i'm cancelling my upgrade to PHP 5.3.1

A few times passed, PHP releasing the new version, PHP 5.3.2 that i think php developers must have encounter that bugs because phpmyadmin is also main application that use php. But i got same problem there. After search on google and many experts blogs and references, i found some solutions to solve this problems.

31May/100

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();
        }
    }
}
31May/100

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

31May/100

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

27May/101

Number of Word on each row MySQL Query

Hi, now i'm gonna share my problems and my solve for that problems. It's welcome if you know about other solution of this problems and want to share it, just comment this post below.

The problem is how to count a word on each record. The example, there is an article table which i want to know how many word 'MySQL' on each row of that table. We cannot use COUNT() function because that function is counting the number of row which contain 'MySQL' if we use the query like :

SELECT COUNT(*) FROM article WHERE article_body LIKE '%MySQL%'

Okay, here is the article table :

article_id article_body
1 WordPress is the most popular Content Management System for blog engine. It just need webserver with PHP and MySQL and then just run it and the script for MySQL database will executed automatically
2 MySQL is one of database management system. MySQL community is free version of MySQL. This version of MySQL, already enough for developing application

We know that word 'MySQL' shown 2 times on article 1 and shown 4 times on article 2. If we use the COUNT() query above, we just get result : 2. So, how we can get that true result? On this solution, i use a simple mathematical formula to solve the problems.

WORD_COUNT = {LENGTH(WHOLE_ARTICLE) - LENGTH(WHOLE_ARTICLE WITHOUT WORD)} / LENGTH(WORD)

From the formula above, we can write it on SQL Query like :

SELECT
   article_body,
   @all := length(article_body) as whole_length,
   @word := length('MySQL') as word_length,
   @rep := length(replace(article_body,'MySQL','')) as wihout_word,
   @count := (@all - @rep)/@word as word_count
FROM article

Just see this type of query and feel confuse? I'll try to explain about it.

  1. @all, @word, etc is a variable that can be assigned by := operator
  2. length() is a function that count the number of character || length(field or text)
  3. replace() is a function that return replaced text || replace(field or text, text to find, replacement text)

And here is the result :

article_body whole_length word_length wihout_word word_count
WordPress is the most popular Content Management S... 197 5 187 2
MySQL is one of database management system. MySQL ... 150 5 130 4