C#

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 →

Simple HTTP Proxy Server C# Source Code

This time my next step for building the M-NIC Projects, creating a HTTP Proxy Server which is actually just an HTTP Relay :D. The concept just take everything from applications which HTTP Proxy server is set to my application then relaying the request to the destination server then relay again the response from destination server to client application.

The method? Just ordinary Socket Programming in C# (System.Net) Socket.Send(), Socket.Receive(), etc. First let’s take a look to the Server Listener, every server must listen to the incoming client connection. In this application, i’m using TcpListener for that.

using System.Net;
using System.Net.Sockets;

namespace SimpleHttpProxy
{
    class ServerListerner
    {
        private int listenPort;
        private TcpListener listener;

        public ServerListerner(int port)
        {
            this.listenPort = port;
            this.listener = new TcpListener(IPAddress.Any, this.listenPort);
        }

        public void StartServer()
        {
            this.listener.Start();
        }

        public void AcceptConnection()
        {
            Socket newClient = this.listener.AcceptSocket();
            ClientConnection client = new ClientConnection(newClient);
            client.StartHandling();
        }

    }
}

How it works? See the main method implementation below. Just initiate server listener object which is listen to port 9000 (this port number is up to you, but make sure you’re choosing free port number), then start the server to make the server ready to accept incoming connection and do the magic loop (actually just an infinite looping) to accept the incoming connection.

Read More →

Get All Local Network Interface Card (NIC) C# Source Code

Yeah, actually i’m back to blogger activities… This is the part of my next projects, M-NIC Projects. The goal is to get all information of our network interface card (NIC) information such as IP addresses, link speed, name, etc. So after doing some head-to-head within some programming languages, my choices is C# .NET, because i think it’s easiest way to get that. The result is something like below, i retrieve all of my NIC which status is UP

Name            : Wireless Network Connection 2
Type            : Wireless80211
Status          : Up
Speed           : 4294967295
Description     : Microsoft Virtual WiFi Miniport Adapter
InterNetworkV6  : fe80::e1cf:b2ee:f5c7:e23e%31
InterNetwork    : 192.168.2.1
=======================================
Name            : Local Area Connection
Type            : Ethernet
Status          : Up
Speed           : 100000000
Description     : Atheros AR8152 PCI-E Fast Ethernet Controller
InterNetwork    : 192.168.1.3
=======================================
Name            : Loopback Pseudo-Interface 1
Type            : Loopback
Status          : Up
Speed           : 1073741824
Description     : Software Loopback Interface 1
InterNetworkV6  : ::1
InterNetwork    : 127.0.0.1
=======================================

And here is the code: 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();
        }
    }
}