Code

Writing Object to XML using XmlSerializer C# Source Code

How to write an object to a file with XML format? There is a class from .NET System.Xml.Serialization.XmlSerializer which can help to completely serialize the objects from program to a XML formatted files.

Suppose that we want to save the data of a person which has attributes:

  1. Name
  2. Age
  3. Height
  4. Weight

And the Person class:

public class Person
{
    public string name;
    public int age;
    public int height;
    public int weight;

    public Person() { }

    public Person(string name, int age, int h, int w)
    {
        this.name   = name;
        this.age    = age;
        this.height = h;
        this.weight = w;
    }
}

Read More →

Rail-Fence Cipher C# Source Code

The rail-fence cipher algorithm has been posted before so this post just show how to implement the algorithm to programming language in C#. First of all always the encryption method:

public static string Encrypt(int rail, string plainText)
{
    List<string> railFence = new List<string>();
    for (int i = 0; i < rail; i++)
    {
        railFence.Add("");
    }

    int number = 0;
    int increment = 1;
    foreach (char c in plainText)
    {
        if (number + increment == rail)
        {
            increment = -1;
        }
        else if (number + increment == -1)
        {
            increment = 1;
        }
        railFence[number] += c;
        number += increment;
    }

    string buffer = "";
    foreach (string s in railFence)
    {
        buffer += s;
    }
    return buffer;
}

Read More →

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();
        }
    }
}

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

Binary Search Tree Java Source Code

Binary Search Tree is a kind of Binary Tree. Let’s start with Tree. Tree is a data structure model which looks like a reversed tree, the root placed on top of the tree and the leaf placed on the bottom of the tree. The model will be looks like pyramid shape. Binary Tree is a tree which every leaves / nodes just have maximum two child leaves, that’s why we call it binary (base 2). Binary Search Tree… this kind of binary tree that have the position of leaves “sorted”. All of elements on the left of a leaf must be smaller than the leaf and all of elements on the right of a leaf must be bigger than the leaf. What about same value? that’s up to you to place it where.

Let’s look this example from wikipedia, “F” is the root of the tree. “B” is a left child of “F”. “G” is a right child of “F”. “B” is a parent of “A”. “B” also a parent of “D”.

Binary Search Tree

Creating Binary Search Tree can’t use the Node which is used for Linked List, Stack, and Queue. Honestly, the Node can be used but the context will be different because the pointer to other Node we will named child. I also give additional pointer, “parent” for pointing the parent of the Node. Let’s see the implementation on Java Programming Language.

public class BinaryTreeNode {

    public BinaryTreeNode parent;
    public BinaryTreeNode leftChild;
    public BinaryTreeNode rightChild;

    private String info;

    public BinaryTreeNode(String info){
        this.parent = null;
        this.leftChild = null;
        this.rightChild = null;
        this.info = info;
    }

    public String getInfo(){
        return this.info;
    }

    public void setInfo(String info){
        this.info = info;
    }

}

Then after we have the Nodes we can construct the Binary Search Tree. Which the most important method is inserting Nodes. If the tree root is null (the tree is new) we just make the node as root. But if the tree is not empty, we must track or find the right place of that node. The concepts is to find an empty place that meet the rules of binary search tree.

  1. If the value of the new node less than current node
    1. If the left child of current node is not empty, move current node to left child
    2. else, the left child of current node is new node
  2. If the value of the new node equal or more than current node
    1. If the right child of current node is not empty, move the current node to right child
    2. else, the right child of current node is new node
public class BinarySearchTree {

    private BinaryTreeNode root;

    public BinarySearchTree(){
        this.root = null;
    }

    public void insertNode(BinaryTreeNode node){
        if (this.root == null){
            this.root = node;
        }
        else{
            trackPosition(node, this.root);
        }
    }

    private void trackPosition(BinaryTreeNode node, BinaryTreeNode start){
        String sInfo = start.getInfo();
        if (sInfo.compareTo(node.getInfo()) > 0){
            if (start.leftChild == null){
                start.leftChild = node;
                node.parent = start;
            }
            else{
                trackPosition(node, start.leftChild);
            }
        }
        else{
            if (start.rightChild == null){
                start.rightChild = node;
                node.parent = start;
            }
            else{
                trackPosition(node, start.rightChild);
            }
        }
    }

}