Open

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

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

}

Inheritance Vs Object Composition Java Source Code

Let’s start with what is Inheritance and what is Object Composition.

Inheritance is giving the characteristic of an object to the new object which inherited from the first object, as example is a man inherit eyes, hands, head, etc from human. In other way, we can say that inheritance is expanding or extending the parent object by the child object. Inheritance usually said “IS A“, man is a human. We see the implementation later…

Object Composition is inserting the whole object to the new object which created to contain the first object, as example is a computer contain of processor, RAM, Motherboard, etc. In other way, we can say that object composition is creating a new object from other objects. Object Composition usually said “HAVE A“, computer have a processor.

Then which is better, Inheritance or Object Composition? Both of them have some characteristic that give advantage to us. With inheritance, we can inserting the derived objects to their base object where Object composition cannot do that (this can be solve by Object class). But Object Composition can construct a new object from many objects where inheritance just allow one object to be inherited (this can be solve by interface).

Okay let’s see the implementation example. First we must define the base class…

public class RoboCore {

    private int coreID;

    public void setCoreID(int ID){
        this.coreID = ID;
    }

    public int getCoreID(){
        return this.coreID;
    }

    public void sayCoreID(){
        System.out.println(this.coreID);
    }

}

Then here is the code of inherit the base class

public class InheritedCoreRobo extends RoboCore{

    private String roboName;

    public InheritedCoreRobo(String Name, int CoreID){
        this.setCoreID(CoreID);
        this.roboName = Name;
    }

    @Override
    public void sayCoreID(){
        System.out.println("Core ID ["+getCoreID()+
                "] Inherited to "+this.roboName);
    }

    public void sayRoboName(){
        System.out.println("My Name is "+this.roboName);
    }

}

And here is the code for composing from base class

public class ComposedCoreRobo {

    private String roboName;
    RoboCore core;

    public ComposedCoreRobo(String Name, int ID){
        this.roboName = Name;
        this.core = new RoboCore();
        this.core.setCoreID(ID);
    }

    public void sayCoreID(){
        System.out.println("Core ID ["+this.core.getCoreID()+
                "] Composed to "+this.roboName);
    }

    public void sayRoboName(){
        System.out.println("My Name is "+this.roboName);
    }

}

I’ll also give you an example main source code for testing the code above.

    public static void main(String[] args) {

        InheritedCoreRobo ICRobo = new InheritedCoreRobo("ICRobo", 101);
        ComposedCoreRobo CCRobo = new ComposedCoreRobo("CCRobo", 777);

        System.out.println("Inheritance Robot");
        ICRobo.sayRoboName();
        ICRobo.sayCoreID();

        System.out.println("nObject Composition Robot");
        CCRobo.sayRoboName();
        CCRobo.sayCoreID();

    }

The output result is….

Inheritance Robot
My Name is ICRobo
Core ID [101] Inherited to ICRobo
Object Composition Robot
My Name is CCRobo
Core ID [777] Composed to CCRobo

The example above is show that inheritance can construct the object without creating any base object first. So we can imagine the inheritance is the RoboCore is extended by other stuffs to build a InheriteCoreRobo, but on Object Composition, we can imagine the ComposedCoreRobo which has slot for RoboCore is inserted with RoboCore object.

Back to above, inheritance “is a”, InheritedCoreRobo is RoboCore because the original version of InheritedCoreRobo just a RoboCore but with some modification and adding some stuff, it become InheritedCoreRobo. object composition “has a” because the ComposedCoreRobo is a stand-alone object which has a place for inserting RoboCore so we can say ComposedCoreRobo have a RoboCore.

Unbounded Knapsack Java Source Code

Hi there, now in this time i’ll try to explain about solving Unbounded Knapsack Problem (UKP) with Dynamic Programming (DP) Method. What is Knapsack Problem? The basic problem is how to choose combination of items from a set of items given to get the maximum value with the knapsack weight or volume restriction. For example, we want to go camping in the mountain, we must bring some stuff like clothes, foods, and drugs. But we just have the limited bag (knapsack) capacity so we must choose the combination of those items which can give us the most benefit.

What’s the different with bounded knapsack? We also call the bounded knapsack with 0-1 knapsack or binary knapsack. Unbounded knapsack is 0-1 knapsack too, but in the UKP we can take more than one items from the same kind. Example, we bring 2 clothes, 5 foods, and 3 drugs. Not in 0-1 knapsack problem, we just can bring 1 items of the same kind.

How the Dynamic Programming Works? The DP method work with the idea “the optimum value of if this item a put on this knapsack is the optimum value of knapsack weight without this item plus value of this item” little confusing? yes i think so. in other word we can say if i reach this weight with this item, then the maximum value is the previous items was added in knapsack plus the new items value. Example : If we want to reach knapsack weight 5 with adding items with weight 2 then the optimum value is : “the optimum value of knapsack with weight 3 plus the value of item with weight 2”.

f(s) = Value(i) + f(s – Weight(i))

So, we can arrange the dynamic table increasingly from most lightweight knapsack optimum value. from weight=0 which must be 0 (zero) valued because nothing can get in on that knapsack capacity, until knapsack weight=maximumweight. With this method we never calculate again the optimum value of previous knapsack before which needed to calculate the present optimum value.

Okay the implementation, first we need some variables and arrays to store the information

    private static int   maxWeight = 0; //maximum weight of knapsack
    private static int[] w;             //weight of each item
    private static int[] v;             //value of each item
    private static int[] a;             //maximum value each knapsack
    private static int[] l;             //last item added each knapsack

And of course getting the user input

    private static boolean getData(){
        System.out.print("Input Maximum Knapsack Weight : ");
            maxWeight = new Scanner(System.in).nextInt();

        System.out.print("Input the weight of each item (separate by space) : ");
            String[] temp = new Scanner(System.in).nextLine().split(" ");
            w = new int[temp.length];
            for (int i=0;i<temp.length;i++) w[i] = Integer.valueOf(temp[i]);

        System.out.print("Input the value of each item (separate by space) : ");
            temp = new Scanner(System.in).nextLine().split(" ");
            v = new int[temp.length];
            for (int i=0;i<temp.length;i++) v[i] = Integer.valueOf(temp[i]);

        if (w.length != v.length){
            System.err.println("Number of weight and value data not match!");
            return false;
        }
        return true;
    }

Then we can get in to the method, the unbounded knapsack

    private static void fillUnboundedKnapsack()
    {
        int   n = w.length;         //number of items

        /**
         * Initializing table
         * table a with default value =  0
         * table l with default value = -1
         */
        a = new int[maxWeight+1];
        l = new int[maxWeight+1];

        setAllArrayValueTo(a,  0);
        setAllArrayValueTo(l, -1);

        /**
         * Unbounded Knapsack Step
         */
        for (int i=1;i<a.length;i++)
        {
            for (int j=0;j<n;j++)
            {
                if (w[j] <= i &&
                        (v[j] + a[i - w[j]]) > a[i])
                {
                    a[i] = v[j] + a[i - w[j]];
                    l[i] = j;
                }
            }
        }
    }

How can we know the items combination from only the sequence code above? Check this out…

    private static int[] trackCombination()
    {
        int[] combination = new int[w.length];

        int postTracker = l.length-1;
        int itemTracker = l[postTracker];

        /**
         * Tracking back the combination
         */
        while (itemTracker != -1 && postTracker > 0)
        {
            combination[itemTracker]++;
            postTracker = postTracker - w[itemTracker];
            itemTracker = l[postTracker];
        }

        return combination;
    }

And finally the main method which cover it all….

    public static void main(String[] args)
    {
        if (!getData()) return;             //getting data from user
        fillUnboundedKnapsack();            //run the algorithm
        int[] optimal = trackCombination(); //seek for items combination

        /* Just an Output Step */
        System.out.println("Maximum Value : " + a[a.length-1]);
        System.out.print("Combination : ");
        for (int i=0;i<optimal.length;i++){
            System.out.print(optimal[i] + " ");
        }
        System.out.println();
    }

Almost forgot… maybe you ask about the setAllArrayValueTo() method, it just a complementary method to set all array values to the second parameter. The code just like..

    private static void setAllArrayValueTo(int[] array, int value){
        for (int i=0;i<array.length;i++) array[i] = value;
    }

Greatest Common Divisor (GCD) C++ Source Code

GCD or Greatest Common Divisor, is the number which can divide two or more numbers to zero (without remainder). or from wikipedia like this :

In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcf), the greatest common denominator[1], or highest common factor (hcf), of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder.

At this post, we will discuss three ways to solve the GCD (Greatest Common Divisor) problems. The first, we are going to search each integer number between the lower number to 1, if the number can devide two numbers, that’s the GCD. The second and third way, we use euclidean algorithm which using modulus operation :: GCD(a,b) = GCD(b, a mod b)

Okay, that’s just the preface… let’s get to C++ Source code. First, the header


#include <iostream>

using std::cout;
using std::cin;
using std::endl;

Then we define the function prototype


void swapInteger(int* a, int* b);
int gcdSearch(int a, int b);
int gcdEuclidIterative(int a, int b);
int gcdEuclidRecursive(int a, int b);

The function for swapping two integers is


void swapInteger(int* a, int* b){
     int swap = *a;
     *a = *b;
     *b = swap;
}

Now, the function of searching GCD


int gcdSearch(int a, int b){
    int low = 0;
    if (a < b) low = a;
    else low = b;

    for (int i=low;i>0;i--){
        if (a % i == 0 && b % i == 0)
        return i;
    }
}

Then, finding GCD using Iterative Euclidean Algorithm


int gcdEuclidIterative(int a, int b){
    if (a < b) swapInteger(&a, &b);
    int remainder = a % b;

    while (remainder != 0){
          a = b;
          b = remainder;
          remainder = a % b;
    }
    return b;
}

And the last, using Recursive Euclidean


int gcdEuclidRecursive(int a, int b){
    if (a < b) swapInteger(&a, &b);
    int remainder = a % b;

    if (remainder == 0) return b;
    else return gcdEuclidRecursive(b,remainder);
}