<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>wcode.net &#187; Programming</title>
	<atom:link href="http://wcode.net/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://wcode.net</link>
	<description>Article and Personal Blog</description>
	<lastBuildDate>Tue, 24 Nov 2009 10:51:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Create Array Parameters in C#</title>
		<link>http://wcode.net/2009/11/create-array-parameters-in-c/</link>
		<comments>http://wcode.net/2009/11/create-array-parameters-in-c/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 15:20:58 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[KNN]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[Nearest Neighbor]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[Parameters]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=75</guid>
		<description><![CDATA[Today i have request from &#8216;bad friend&#8217; code name &#8216;mashudi&#8217; to create Nearest Neighbor Class, Artificial Intelegent system that can compute distance from one to other node.
From this project I will share how to create a constructor or maybe you need for method that use array parameters.
Design of implementation in KNN node class will be [...]]]></description>
			<content:encoded><![CDATA[<p>Today i have request from &#8216;bad friend&#8217; code name &#8216;mashudi&#8217; to create Nearest Neighbor Class, Artificial Intelegent system that can compute distance from one to other node.</p>
<p>From this project I will share how to create a constructor or maybe you need for method that use array parameters.</p>
<p>Design of implementation in KNN node class will be like this :</p>
<pre class="brush:csharp">
KNNNode node1 = new KNNNode("Rose", 2.5, 4, 4.2);
KNNNode node2 = new KNNNode("Height", 2.5, 4, 4.2, 4.5, 6.3);
</pre>
<p>So you can add more parameters to that class.</p>
<p><span id="more-75"></span></p>
<p>Here my code in KNNNode class :</p>
<pre class="brush:csharp">

using System.Collections.Generic;

namespace Algorithm.KNN
{
    public class KNNNode
    {
        List<float> val;
        string label;

        public string Label
        {
            get { return label; }
            set { label = value; }
        }

        // 'params float[] val' it will create array parameters
        public KNNNode(string label, params float[] val)
        {
            //set label
            this.label = label;
            //Set actual size of val
            this.val = new List<float>(val.Length); 

            //iterate from first to last argument
            //and fill to list
            foreach (float v in val)
            {
                this.val.Add(v);
            }
        }

        public int Count
        {
            get {
                return val.Count;
            }
        }

        //prevent default constructor inisialization
        private KNNNode()
        { }

        //Direct access to list value
        public float this[int index]
        {
            get { return val[index]; }
            set { val[index] = value; }
        }
    }
}
</pre>
<p>Hope it&#8217;s help<br />
Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/11/create-array-parameters-in-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>C# with MySQL Database</title>
		<link>http://wcode.net/2009/10/csharp-with-mysql-database/</link>
		<comments>http://wcode.net/2009/10/csharp-with-mysql-database/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 16:23:44 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=71</guid>
		<description><![CDATA[If you want direct connection from C# to MySQL you can use MySQL.Data library from this resource. I&#8217;ve write down my own DataAccess class to make my work in other class easier.
Settings is setting class in .NET you can click on project->properties->settings to generate this class. You can find this file in Debug folder that [...]]]></description>
			<content:encoded><![CDATA[<p>If you want direct connection from C# to MySQL you can use MySQL.Data library from <a href="http://dev.mysql.com/downloads/connector/net/1.0.html">this</a> resource. I&#8217;ve write down my own DataAccess class to make my work in other class easier.</p>
<p><em>Settings</em> is setting class in .NET you can click on project->properties->settings to generate this class. You can find this file in Debug folder that have .config extension.</p>
<p><span id="more-71"></span></p>
<p>Here is my Data Access class manage command from C# to MySQL database.</p>
<pre class="brush:csharp">
    public class DataAccess
    {
        static internal string GetConnectionString()
        {
            return String.Format("server={0};user id={1};Password={2};database={3}",
                Settings.Default.DbServer, Settings.Default.DbUserId, Settings.Default.DbPassword,
                Settings.Default.DbName);
        }

        static DataAccess()
        { }

        public static DataTable ExecuteSelectCommand(MySqlCommand command)
        {
            DataTable table = null;
            try
            {
                command.Connection.Open();
                MySqlDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
                reader.Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Data.ToString());
            }
            finally
            {
                command.Connection.Close();
            }
            return table;
        }

        public static MySqlCommand CreateCommand()
        {
            string dataProviderName = Settings.Default.DbProvoderName;
            string connectionString = GetConnectionString();
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connectionString;
            MySqlCommand comm = conn.CreateCommand();
            return comm;
        }

        public static int ExecuteNonQuery(MySqlCommand command)
        {
            int affectedRows = -1;
            try
            {
                command.Connection.Open();
                affectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                command.Connection.Close();
            }
            return affectedRows;
        }
    }
</pre>
<p>Now here&#8217;s the sample to call that DataAccess class</p>
<pre class="brush:csharp">
    public class Golongan
    {
        private int idGolongan;
        private string namaGolongan;

        public int IdGolongan
        {
            get { return idGolongan; }
            set { idGolongan = value; }
        }

        public string NamaGolongan
        {
            get { return namaGolongan; }
            set { namaGolongan = value; }
        }

        public Golongan()
        { }

        public Golongan(int idGolongan, string namaGolongan)
        {
            this.idGolongan = idGolongan;
            this.namaGolongan = namaGolongan;
        }

        public static DataTable SelectAllGolongan()
        {
            MySqlCommand command = DataAccess.CreateCommand();
            command.CommandText = "select * from golongan";
            DataTable table = DataAccess.ExecuteSelectCommand(command);
            return table;
        }

        public int InsertGolongan()
        {
            MySqlCommand commmand = DataAccess.CreateCommand();
            commmand.CommandText = "insert into golongan (golongan) " +
                                    "values(    '" + this.namaGolongan + "')";

            return DataAccess.ExecuteNonQuery(commmand);
        }

        public int UpdateGolongan()
        {
            MySqlCommand commmand = DataAccess.CreateCommand();
            commmand.CommandText =
                String.Format("update golongan set golongan = '{0}' where idgolongan = {1}",
                this.namaGolongan, this.idGolongan);

            return DataAccess.ExecuteNonQuery(commmand);
        }

        public int DeleteGolongan()
        {
            MySqlCommand commmand = DataAccess.CreateCommand();
            commmand.CommandText =
                String.Format("delete from golongan where idgolongan = {0}",
                this.idGolongan);

            return DataAccess.ExecuteNonQuery(commmand);
        }
}
</pre>
<p>Hope it&#8217;s help<br />
Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/10/csharp-with-mysql-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mutex for one instance application</title>
		<link>http://wcode.net/2009/10/mutex-for-one-instance-application/</link>
		<comments>http://wcode.net/2009/10/mutex-for-one-instance-application/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 15:34:49 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=69</guid>
		<description><![CDATA[If you want to create application that must be running only once (can&#8217;t duplicate). Mutex class in System.Threading namespace can help you to done this problem.
Here the sample of my code to control&#8217;s my program only run once, i need this cause i working on serial communication. But, you can use this for other purpose.


 [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to create application that must be running only once (can&#8217;t duplicate). Mutex class in System.Threading namespace can help you to done this problem.</p>
<p>Here the sample of my code to control&#8217;s my program only run once, i need this cause i working on serial communication. But, you can use this for other purpose.<br />
<span id="more-69"></span></p>
<pre class="brush:csharp">
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        ///
        public static string name = "SMSGrabApplication";
        public static Mutex mutex;

        [STAThread]
        static void Main()
        {
            if (!isMutexActive(name))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FormUtama());
            }
            else
            {
                Application.Exit();
            }

        }

        public static bool isMutexActive(string mutexName)
        {
            try
            {
                mutex = Mutex.OpenExisting(mutexName);
                return true;
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                mutex = new Mutex(true, mutexName);
                return false;
            }
            catch (UnauthorizedAccessException)
            {
                return true;
            }
        }
    }
</pre>
<p>You need to release this Mutex before you close your application.</p>
<p>here my simple code :</p>
<pre class="brush:csharp">
   Program.mutex.ReleaseMutex();
</pre>
<p>Hope it&#8217;s help<br />
Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/10/mutex-for-one-instance-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exposing Inner Control Event in WPF UserControl</title>
		<link>http://wcode.net/2009/08/exposing-inner-control-in-wpf-usercontrol/</link>
		<comments>http://wcode.net/2009/08/exposing-inner-control-in-wpf-usercontrol/#comments</comments>
		<pubDate>Sun, 16 Aug 2009 17:26:02 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=63</guid>
		<description><![CDATA[When you have controls inside your custom UserControl you can&#8217;t call directly to any controls inside user control in WPF. There&#8217;s a way to expose them.. First you can add RoutedEvents to a custom control you can declare a public static RoutedEvent in your class and use EventManager.RegisterRoutedEvent() method to register these events.  EventManager.RegisterRoutedEvent() [...]]]></description>
			<content:encoded><![CDATA[<p>When you have controls inside your custom UserControl you can&#8217;t call directly to any controls inside user control in WPF. There&#8217;s a way to expose them.. First you can add RoutedEvents to a custom control you can declare a public static RoutedEvent in your class and use EventManager.RegisterRoutedEvent() method to register these events.  EventManager.RegisterRoutedEvent() has some parameters: the event name, routing strategy, type of RoutedEventHandler and type of the custom control.</p>
<p><span id="more-63"></span><br />
Now, create user custom UserControl that contains a button. Here the XAML code :</p>
<pre class="brush:xml">
<UserControl x:Class="AddCustomEventUserControl.CustomUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="60" Width="200">
    <Grid>
        <Button x:Name="button1" Height="23"  Width="75" Click="button1_Click">Button</Button>
    </Grid>
</UserControl>
</pre>
<p>Than add this code inside .cs file</p>
<pre class="brush:csharp">
public partial class CustomUserControl : UserControl
{
    public static readonly RoutedEvent ButtonClickEvent = EventManager.RegisterRoutedEvent(
        "ButtonClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CustomUserControl));

    public event RoutedEventHandler ButtonClick
    {
        add { AddHandler(ButtonClickEvent, value); }
        remove { RemoveHandler(ButtonClickEvent, value); }
    }

    public CustomUserControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RaiseEvent(new RoutedEventArgs(ButtonClickEvent));
    }
}
</pre>
<p>Here the code where you add that user control, dont forget to add reference :<br />
xmlns:local=&#8221;clr-namespace:&#8230;. bla2&#8230; </p>
<p>So here my Window1 xaml code :</p>
<pre class="brush:xml">
<Window x:Class="AddCustomEventUserControl.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:local="clr-namespace:AddCustomEventUserControl"
        >
    <Grid>
        <local:CustomUserControl ButtonClick="CustomUserControl_ButtonClick"></local:CustomUserControl>
    </Grid>
</Window>
</pre>
<p>From that listing now your window can recognize property of ButtonClick event. Now here is code in my Window1.xaml. So when button inside user control clicked Message box will appear&#8230;</p>
<pre class="brush:csharp">
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void CustomUserControl_ButtonClick(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Inner Button Clicked!!");
    }
}
</pre>
<p>by : Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/08/exposing-inner-control-in-wpf-usercontrol/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Acessing WinAPI from C#</title>
		<link>http://wcode.net/2009/08/acessing-winapi-from-c/</link>
		<comments>http://wcode.net/2009/08/acessing-winapi-from-c/#comments</comments>
		<pubDate>Sun, 16 Aug 2009 04:11:54 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://wcode.net/2009/08/acessing-winapi-from-c/</guid>
		<description><![CDATA[The Windows API, informally WinAPI, is Microsoft&#8217;s core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. It was formerly called the Win32 API; however, the name Windows API more accurately reflects its roots in 16-bit Windows and its support on 64-bit Windows.
When declaring APIs in C#, use the following syntax:

using [...]]]></description>
			<content:encoded><![CDATA[<p>The Windows API, informally WinAPI, is Microsoft&#8217;s core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. It was formerly called the Win32 API; however, the name Windows API more accurately reflects its roots in 16-bit Windows and its support on 64-bit Windows.</p>
<p>When declaring APIs in C#, use the following syntax:</p>
<pre class="brush:csharp">
using System.Runtime.InteropServices;

...

[DllImport( dll_filename )]
[public|private] static extern ret_type function( [type para, ...] );
</pre>
<p><span id="more-61"></span><br />
Here sample to play sound that I get from www.csharpfriends.com</p>
<pre class="brush:csharp">
using System;
using System.Runtime.InteropServices;

namespace APITest
{
    class clsAPI
    {
        [DllImport("winmm.dll")]
        public static extern long PlaySound(string lpszName, long hModule, long dwFlags);

        [STAThread]
        static void Main(string[] args)
        {
            long retval;
            string fname = "e:\\sounds\\hit.wav";
            retval = PlaySound( fname, 0, 1 );
        }
    }
}
</pre>
<p>Now, how we can know what&#8217;s function inside dll?? check <a href="http://www.pinfoke.net">pinfoke</a>.</p>
<p>by : Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/08/acessing-winapi-from-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unsafe in C# and Image Processing</title>
		<link>http://wcode.net/2009/08/unsafe-in-c-and-image-processing/</link>
		<comments>http://wcode.net/2009/08/unsafe-in-c-and-image-processing/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 13:48:44 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=53</guid>
		<description><![CDATA[From my last projects, I write many custom class to manipulating image. Today I will share basic code to write C# code when you focusing on Image Processing. 
When I use Bitmap function GetPixel and SetPixel, oh.. .NET is bad for Image Processing.. and that&#8217;s not 100% right. We still have pointers on C# like [...]]]></description>
			<content:encoded><![CDATA[<p>From my last projects, I write many custom class to manipulating image. Today I will share basic code to write C# code when you focusing on Image Processing. </p>
<p>When I use Bitmap function GetPixel and SetPixel, oh.. .NET is bad for Image Processing.. and that&#8217;s not 100% right. We still have pointers on C# like on C++. To use it just go to Project->Properties->Build than check &#8220;Allow unsafe code&#8221;. </p>
<p>Now, go ahead and try to understand how to use unsafe code in C# and implement it on Image Processing.<br />
<span id="more-53"></span><br />
First thing is get image from file :</p>
<pre class="brush:csharp">
Bitmap bmp = (Bitmap)Image.FromFile("image.jpg");
</pre>
<p>Than lock that bitmap,  The public functions in the class that locks and unlocks the specified area of the image into the memory. The paramenters of the LockBits function are, a Rectangle object specifying the area to be Locked, then 2 integers specifying the access level for the object and the other showing the format of the image. This is done through two enumirations like ImageLockMode, and PixelFormat. They are narrated after this class. The LockBits returns the object of the BitmapData class and UnLockBits takes the object of the BitmapData class.</p>
<pre class="brush:csharp">
//Lock bitmap
BitmapData imageData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
 ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
</pre>
<p>The pixel format defines the number of bits of memory associated with one pixel of data. In other words the format defines the order of the color components within a single pixel of data. Normaly, PixelFormat.Format24bppRgb is used. PixelFormat.Format24bppRgb specifies that the format is 24 bits per pixel; 8 bits each are used for the red, green, and blue components. In the 24 bit format image, the image consists of pixels consisting of 3 bytes, one for each red, green, and blue. The first byte in the image contains the blue color, the second byte contains the green color, and the third byte contains the red color of the pixel, and they form the color<br />
of the specified pixel.</p>
<pre class="brush:csharp">
 //Pixel size from right most line to next down first line
int offset = imageData.Stride - imageData.Width * 3;
</pre>
<p>Now here the unsafe block code</p>
<pre class="brush:csharp">
unsafe
{
    //Go to first pixel
    byte* p = (byte*)imageData.Scan0.ToPointer();

    //For each line
    for (int y = 0; y < bmp.Height; y++)
    {
         //For Each Pixel (bmp.Width * 3) because jpg has R, G, and B value
         for (int x = 0; x < bmp.Width * 3; x++)
         {
                //Make invert from original image
                *p = (byte)(255 - *p);
                //Go to next pointer
                p++;
          }
          //move pointer right most line to next down first line
          //skip the unused space
          p += offset;
     }
}
</pre>
<p>After that call UnlockBits </p>
<pre class="brush:csharp">
//Call UnlockBits function
bmp.UnlockBits(imageData);
</pre>
<p>Here my full code :</p>
<pre class="brush:csharp">
private void btnLoad_Click(object sender, EventArgs e)
{
     OpenFileDialog openFileDialogImage = new OpenFileDialog();
     openFileDialogImage.Filter = "JPEG Image|*.jpg;";

      if (openFileDialogImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
      {
           //original image
           Bitmap original = (Bitmap)Image.FromFile(openFileDialogImage.FileName);
           pictureBox1.Image = original;

           //Image to manipulate
           Bitmap bmp = (Bitmap)Image.FromFile(openFileDialogImage.FileName);

           //Lock bitmap
           BitmapData imageData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

           //Pixel size from right most line to next down first line
           int offset = imageData.Stride - imageData.Width * 3;

           unsafe
           {
                //Go to first pixel
                byte* p = (byte*)imageData.Scan0.ToPointer();

                //For Each Line
                for (int y = 0; y < bmp.Height; y++)
                {
                    //For Each Pixel (bmp.Width * 3) because jpg has R, G, and B value
                    for (int x = 0; x < bmp.Width * 3; x++)
                    {
                        //Make invert from original image
                        *p = (byte)(255 - *p);
                        p++;
                    }
                    p += offset;
                }
          }

          //Unlock data
          bmp.UnlockBits(imageData);

          //Set it to picture box
          pictureBox2.Image = bmp;
    }
}
</pre>
<p>Here result of both image : </p>
<p><img src="http://farm3.static.flickr.com/2481/3823335650_3dd22eff87_m.jpg" alt="Unsafe in C# and Image Processing" /></p>
<p>By : Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/08/unsafe-in-c-and-image-processing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Serialize Collection of Object in C#</title>
		<link>http://wcode.net/2009/08/serialize-collection-of-object-in-c/</link>
		<comments>http://wcode.net/2009/08/serialize-collection-of-object-in-c/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 13:32:15 +0000</pubDate>
		<dc:creator>Willy</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://wcode.net/?p=5</guid>
		<description><![CDATA[Today i&#8217;ve create a simple project&#8230; finally I find way to serialize collection of object in C#. 
As luck would have it, most of the types found within the System.Collections and System.Collections.Generic namespaces have already been marked as [Serializable]. Therefore, if you wish to persist a set of objects, simply add the set to the [...]]]></description>
			<content:encoded><![CDATA[<p>Today i&#8217;ve create a simple project&#8230; finally I find way to serialize collection of object in C#. </p>
<p>As luck would have it, most of the types found within the System.Collections and System.Collections.Generic namespaces have already been marked as [Serializable]. Therefore, if you wish to persist a set of objects, simply add the set to the container (such as an ArrayList or a List<T>) and serialize the object to your stream of choice. Other choice is make a class that inherits from collection&#8230; </p>
<p>first we can create a simple SoundData class like this :</p>
<pre class="brush:csharp">[Serializable]
public class SoundData
{
   private int soundId;
   private string soundName;

   public int SoundId
   {
        get { return soundId; }
        set { soundId = value; }
    }

   public string SoundName
   {
        get { return soundName; }
        set { soundName = value; }
   }

   //You will get error if you miss this constructor ^_^
   public SoundData()
   { }

   public SoundData(int soundId, string soundName)
   {
       this.soundId = soundId;
       this.soundName = soundName;
   }
}
</pre>
<p><span id="more-5"></span><br />
Then we make new collection class that use SoundData class as item :</p>
<pre class="brush:csharp">[Serializable]
public class ListSoundData : Collection
{
    private SoundData sound;

    public SoundData Sound
    {
        get { return sound; }
        set { sound = value; }
    }

    public ListSoundData()
    { }

    public ListSoundData(SoundData sound)
    {
        this.sound = sound;
    }
}</pre>
<p>Now you can add this code to Serialize and Deserialize code :</p>
<pre class="brush:csharp">[Serializable,
XmlRoot(Namespace = "http://wcode.net")]
public class SoundMainData
{
    private int lastId;
    private ListSoundData listOfSound = new ListSoundData();

    public int LastId
    {
        get { return lastId; }
        set { lastId = value; }
    }

    public ListSoundData ListOfSound
    {
        get { return listOfSound; }
        set { listOfSound = value;}
    }

    public int Add(string soundName)
    {
        lastId++;
        SoundData sData = new SoundData(lastId, soundName);
        this.ListOfSound.Add(sData);
        return lastId;
    }

    public void Save()
    {
        Stream stream = File.Create("result.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(SoundMainData),
        new Type[] { typeof(ListSoundData), typeof(SoundData) });
        serializer.Serialize(stream, this);
        stream.Close();
    }

    public void Load()
    {
        this.ListOfSound.Clear();
        Stream stream = new FileStream("result.xml",
        FileMode.Open, FileAccess.Read, FileShare.Read);
        XmlSerializer serializer = new XmlSerializer(typeof(SoundMainData));

        SoundMainData data = (SoundMainData)serializer.Deserialize(stream);

        foreach (SoundData sound in data.ListOfSound)
        {
               this.ListOfSound.Add(sound);
         }
         this.LastId = data.LastId;
     }
}</pre>
<p>If you add SoundData in ListSoundData than Serialize it with this code:</p>
<pre class="brush:csharp">
SoundMainData data = new SoundMainData();
data.Add("willy");
data.Add("achmat");
data.Save();
</pre>
<p>Than you will have an result.xml file that contains this code :</p>
<pre class="brush:xml">
<?xml version="1.0"?>
<SoundMainData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://wcode.net">
  <LastId>2</LastId>
  <ListOfSound>
    <SoundData>
      <SoundId>1</SoundId>
      <SoundName>willy</SoundName>
    </SoundData>
    <SoundData>
      <SoundId>2</SoundId>
      <SoundName>achmat</SoundName>
    </SoundData>
  </ListOfSound>
</SoundMainData>
</pre>
<p>by : Willy Achmat Fauzi</p>
]]></content:encoded>
			<wfw:commentRss>http://wcode.net/2009/08/serialize-collection-of-object-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
