following code demonstrates how we can write a collection to an XML file using C#

we can do it in two ways first lets do it without using serilization.



public static void writetoXML(string fileName)
{
DataSet ds = new DataSet("ds01"); //root node
DataTable t = new DataTable("table01"); //
DataColumn qNo = new DataColumn("questionNo"); //
DataColumn ans = new DataColumn("answer"); //

t.Columns.Add(qNo); //add columns to the table
t.Columns.Add(ans);
ds.Tables.Add(t); //add table to the dataset

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow(); //create a new row of type table
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r); //add the newly populated row to the table
}

//write the added data to the console
Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
ds.WriteXml(fileName);
}

lets rewrite it again using serilization there is a big advantage in this i'll show it right away
when using serialization we write the data using a XMLSerializer object which will be created using the method typeof(). this allows us to write any type of collection to a XML file with little altering of code as possible
lets see how the above method will look like when written using serilization

public static void serializeDatSet(string fileName)
{
//create a new XMLSerializer object of type DataSet
XmlSerializer ser = new XmlSerializer(typeof(DataSet));

DataSet ds = new DataSet("ds01");
DataTable t = new DataTable("table01");
DataColumn qNo = new DataColumn("questionNo");
DataColumn ans = new DataColumn("answer");

t.Columns.Add(qNo);
t.Columns.Add(ans);
ds.Tables.Add(t);

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow();
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r);
}

Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
TextWriter writer=new StreamWriter(fileName);

//write the data set to the writer stream using the serialization object
ser.Serialize(writer,ds);

writer.Close();

}

so lets say you want to write an ArrayList to a XML file
well see the code below

public static void writeToXML(string fileName)
{
ArrayList arr = new ArrayList();
for (int i = 0; i <>
{
arr.Add("answer for question" + i);
}
XmlSerializer ser = new XmlSerializer(typeof(ArrayList));
TextWriter writer = new StreamWriter(fileName);
ser.Serialize(writer, arr);
writer.Close();
}


for this you have to write two applications, one will reside in the server machine and will wait till a client machine request its time. upon a succesful request the server will write its DateTime.Now value to the network stream, where the client can read it out and use it in his application


please consider that these two applications are windows console applications

Code for the Server Program

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                //add a listner to liten on a port on a specified host
                TcpListener listener=new TcpListener(Dns.Resolve("localhost").AddressList[0],14);

                listener.Start();
                Console.WriteLine("Waiting for client to connect");
                Console.WriteLine("Ctrl+C to quit");

                while (true)
                {
                    Socket s = listener.AcceptSocket();     //accept a connection request made by a client                                                                                              on the listning socket
                    DateTime now = DateTime.Now;            //get the servers date time value
                    string dateTime = now.ToShortDateString() + " " + now.ToLongTimeString();
                    byte[] asciiDateTime = Encoding.ASCII.GetBytes(dateTime.ToCharArray()); 

//encode the strring to aASCII byte stream to written in to the socket so it can be decoded from the client easily
                    s.Send(asciiDateTime, asciiDateTime.Length, 0); 

//write to the socket data(asciidatetime) starting from 0th index to a charcter count of(asciidatetime.length)

                    s.Close();       //close the socket connection to the client

                    Console.WriteLine("Sent{0}",dateTime);
                }
            }
            catch (SocketException error)
            {
                if (error.ErrorCode==10048)
                {
                    Console.WriteLine("connection failed to this port, there is another server listning on this port");
                }
            }
        }
    }
}

Code for the Client Program

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient();     //create a client

            Console.WriteLine("specify a server name : ");
            string serverName = Console.ReadLine();
            try
            {
 //gets the DNS information of the specified server
                IPHostEntry ipInfo = Dns.GetHostByName(serverName);    
            }
            catch (SocketException error)
            {
                Console.WriteLine("cannot find server : "+serverName+"\nException :\n"+error.ToString());
                return;
            }

            try
            {
                client.Connect(serverName,14);      //connect to the specified server via port 14
            }
            catch (Exception error2)
            {
                Console.WriteLine("could not connect to server {0}\n"+error2.Message,serverName);
            }

            Stream s;
            try
            {
     //get a network stream to communicate with the server machine
  this will add the client to the servers pending request query and will 
                s = client.GetStream(); initiate the AcceptSocket() method
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("cannot connect to server {0}",serverName);
                return;
            }

            Byte[] read=new byte[32];

  //read the  the byte stream returned from the server
            int bytes = s.Read(read, 0, read.Length);     
 
            string time = Encoding.ASCII.GetString(read);   //decode it to a string

            Console.WriteLine("received"+bytes+"bytes");
            Console.WriteLine("current server date time is : "+time);

            client.Close();
            Console.WriteLine("press enter to exit");
            Console.Read();

        }
    }
}


this code base can be used to construct any simple-client server communication machanism based on your requirements. all you have to do is replace 
DateTime now = DateTime.Now;            //get the servers date time value
        string dateTime = now.ToShortDateString() + " " + now.ToLongTimeString();
part in the server program with ou server task

have fun coding!!!!!!



this is a first of a series about new features in c# 3.0

all the programming languages have some kind of a machanism to store progrmatic data in c# there are two types called reference types and value types when we consider value types almost all the programming languages had implemented them as a part of their framework
Basically their are two types of value types 
static
dynamic

static typing
type of the variables are known in cmpile time this is the common practice in languages like c#, java, c, c++

int a=10;
string name="Dhanushka Sandaruwan Athukorala";

dynamic typing
here the variable comes with some kind of a tag that contains it type. when you assign a value to the variable at the run time this tag value is set to the type of this assigned value

the funny thing is every time an operation is performed the type will be checked to make sure that the operation is safe

for an example this will wok in dynamically typed code but not in static typing

a="Dhanushka Sandaruwan Athukorala";
if(true)
{
a=12;
}
b=a/2;

here as you can see when the devission occur a's type tag is set to int rather than string thats the magic of dynamic typing

now lets see what c# 3.0 offeres
var fullName="Dhanushka Sandaruwan Athukorala";
var age=22;
var arr=new[] {1, 2, 3, 4}
hmm...
what's going on
at first you would say that "var" is just a new value type!!!
No sir!!! its not!!!
its just a new keyword introduced in c# 3.0 to indicate to the compiler that "i'm gona create a new variable, but i dont know about its type. so you just take care of it for me!!"

we all know that c# is a staticstically typed language, but yet it si offering a functionallity similar to a dynamically typed one???
whats the secret??
what happens here is a newly written type inferencing algorithm is used by the compiler(take this to note, which means this happens at compile time not at run time) goes through the code and finds out what's the type of the variables assigned to the "var" variables. which means that this is similar to an explicit declaration of a variable but you dont have to know the type of it.
for an instance if we referfullName.GetType()  and age.GetType() values at run time they will give string and int32 as their variable types

but their are some other issues you should be aware of when you use var 
you must  initialize a variable with a nonnull value when you declare it
this want compile
var a; var b=null;
a=18;
as a conclusion we can say although this will distance c# from being a simple language, it will enhance the developer productivity as well as code readability. 

what is a jagged array

for a start there are two types of arrays in c#
1) rectangular arrays
2) jagged arrays
rectangular arrays are of course rectangular arrays :-) wether single dimensional or multi dimensional all their elements length are equal
e.g

int[] arrSingle=new arrSingle[5];
int[,] arrTwoDimensional=new int[,] {{1,2,3},{1,2,3}}

jagged arrays are just arrays of arrays but when it comes to their shape their element length can vary

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] {1, 2, 3};
jaggedArray[1] = new int[] {1, 2, 3, 4, 5, 6};
jaggedArray[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};

thats all you need to know

"Does C# support multiple inheritance?"

A question i always get from my freinds, specially java guys:-)
the answer is not yet (not in C# 3.0) but there are some ways to get around it
although c# doesnt support mulitple inheritance it does support muliple implementation. which means that in c# you can implement more than 1 interface.
let's try it out
lets say we want a class to have the functionalities of a vehicle, and this class will represent a 4 wheel vehicle lets name this class as myCar
what we have to do now is we have to create two interfaces called IVehicle and I4Wheel

interface Ivehicle
{
void test();
void vehicle();
}

interface I4wheel
{
void test();
void 4wheel();
}

now lets create myCar class and lets inherit from IVehicle and I4Wheel

public class myCar: IVehicle,I4Wheel
{
//some code goes here;
}
 now if you you have noticed it there is a is a method with the same name in both interfaces. so how on earth myCar is going to defferentiate between the two??
simple 
just prefix it with the interface name (which is also known as explicit interface implementation)

public class myCar: IVehicle,I4Wheel
{
void IVehicle.test()
{
//implementation;
}
void I4Wheel.test()
{
//implementation;
}
}

 and "VOLLA" there you go, now c# supports multiple inheritance  :-)

As the name indicate its a puzzle game developed for windows mobile using c# and .net compact framework 2.0
The game contains 15 numbered blocks with a single empty space which acts as a slider space for number swap

Game concept
a number set containing numbers ranging from 1 to  15 is randomly arranged using a random number generator depending on the users difficulty level
What the players have to do is rearrange them within a fixed number of moves and within a selected time frame

What make it stand out from other puzzle games
the game provide some  advance game play features like hints, autoplay... etc
and if  you are a player who choose user interfacer features over advanced algorithms, then thhis game is for you

Hint for the next move and animated autoplay
All the player moves will be taken in to account for both hint and autoplay facilities
Depending on the moves history the most efficient next move will be predicted and is shiwn to the players as a blinking number
The autoplay facility also uses an algorithm which takes the dynamically changing player moves history in to account for predicting the most efficient autoplay move Set
the game also conntains facilities like takeback (lets the users undo any number of  moves), reset initial state (lets the user to restart from the beginning), resume  play (depending on the game exit status the  players can resume from where they left off or start a new game)

if that's not enough  the game also comes with a rich set of sweet animations which will enhance the users game ay experience

Development details (technical defficulties faced and how I get over with them)

When I first received tHe project the main concern was to enhance the game play experience of the user by providing them with  well written algorithms as well as with the best possible user interfaces
Before I started mobile development I had good experience with developing windows applications so I was like, "ok lets get it over with, I’m good at ui designing so what the hell".

The initiatial application consisted of labels where the label.text property is changed in order to swap two numbers. but I decided to add an animation where the two numbers will get swaped with an animation showing the translation. So in order to accomplish this I dedided to add buttons instead of labels. which will enable me to add a good button image as well.
He ! what am I thinking, then I got to know that there's no background image property for buttons in the compact framework. What I did was, Icreated a custom control from scratch combinning a picture box and a label

then i rewrote the useful properties using get, set
eg.
public Color LabelBackColor
        {
            get
            {
                return label1.BackColor;
            }
            set
            {
                label1.BackColor = value;
                this.Refresh();
            }
        }

i also controlled how the controls inner items will behave when its resized
private void pictureButtonController_Resize(object sender, EventArgs e)
        {
            pictureBox1.Width = this.Width;
            pictureBox1.Height = this.Height;// -label1.Height;
            label1.Left = (pictureBox1.Width / 2)-(label1.Width/2);
            label1.Top = (pictureBox1.Height / 2)-(label1.Height/2);
           
        }

and after all these are done, i had my button at my service

The next challenge was to maintain the history of how the buttons got swapped and what is their position in the UI after each swap

What i did was i decided to maintain a button Map with the assistance of some custom written methods
i'll post them so anyone who is doing a similar thing will benefit ffrom it\
:-)

think of the button map in this way
 btn01 btn02 btn03 btn04
 btn05 btn06 btn07 btn08
 btn09 btn10 btn11   btn12
 btn13 btn14 btn15   btn16

btn16 is the empty button when the user click on a button the algorithm will check if it is adjacent to the empty button im a non diagonal direction and swap it with the empty one

following are the helper methods i wrote in order to achive this

        #region find the btnmap position[,] for a given item
        private static int[] findIndex(int item)
        {            
            int[] a = new int[2];
            bool breakStatus = false;
            for (int i = 0; i <>
            {
                for (int j = 0; j <>
                {
                    if (Module11.buttonMap[i, j] == item)
                    {
                        breakStatus = true;
                        a[0] = i;
                        a[1] = j;
                        break;
                    }
                }
                if (breakStatus)
                {
                    break;
                }
            }
            return a;
        } 
        #endregion

        #region set the btnmap to the start state
        private void setFirstState()
        {
            int btnLabel = 1;
            for (int i = 0; i <>
            {
                for (int j = 0; j <>
                {
                    Module11.firstBtnMap[i, j] = Module11.buttonMap[i, j];
                }
            }
        } 
        #endregion

        #region find the place count for the empty button
        private static int findEmptyPosition()
        {
            int place = 1;
            bool breakStatus = false;
            for (int i = 0; i <>
            {
                for (int j = 0; j <>
                {
                    if (Module11.buttonMap[i, j] == 16)
                    {
                        breakStatus = true;
                        break;
                    }
                    place++;
                }
                if (breakStatus)
                {
                    break;
                }
            }
            return place;
        } 
        #endregion

        #region find the place count for a specific button
        private static int findPosition(int item)
        {
            int place = 1;
            bool breakStatus = false;
            for (int i = 0; i <>
            {
                for (int j = 0; j <>
                {
                    if (Module11.buttonMap[i, j] == item)
                    {
                        breakStatus = true;
                        break;
                    }
                    place++;
                }
                if (breakStatus)
                {
                    break;
                }
            }
            return place;
        } 
        #endregion

        #region find the btnmap position[,] for a given place count
        private int[] findPositionOf(int index)
        {
            int[] a = new int[2];
            int count = 1;
            bool breakState = false;
            for (int i = 0; i <>
            {
                for (int j = 0; j <>
                {
                    if (count == index)
                    {
                        a[0] = i;
                        a[1] = j;
                        breakState = true;
                        break;
                    }
                    else
                    {
                        count++;
                    }
                }
                if (breakState)
                {
                    break;
                }
            }
            return a;
        } 
        #endregion

next I'll tell you how i handled the animations

first of all my animations worked on my custom control so i added the following code to the custom controll class

public void Move(Point newLocation)
        {
            if(this.Name.Equals("picCtrl16"))
            {
                this.Location=newLocation;
                goto a;
            }
            BringToFront();

            Point startLoc = this.Location;
            Point newLoc=this.Location;

            int defX = newLocation.X - startLoc.X;
            int defY = newLocation.Y - startLoc.Y;            
                        
            for (int step = 1; step <>
            {
                int factor = step*step;
                Thread.Sleep(10);

                newLoc.X = startLoc.X + (defX * factor) / 100;
                newLoc.Y = startLoc.Y + (defY * factor) / 100;                       
                this.Location = newLoc;              
                Parent.Update();

                if (defX==0)
                {
                    if (newLocation.Y - newLoc.Y <= 1)
                        break;
                }
                if (defY==0)
                {
                    if (newLocation.X - newLoc.X <= 1)
                        break;
                }
                                
            }

            this.Location = newLocation;

        a:
            ;
        }

public void MoveFastest(Point newLocation)
        {
            if (this.Name.Equals("picCtrl16"))
            {
                this.Location = newLocation;
                goto a;
            }
            BringToFront();

            Point startLoc = this.Location;
            Point newLoc = this.Location;

            int defX = newLocation.X - startLoc.X;
            int defY = newLocation.Y - startLoc.Y;           

            this.Location = newLocation;
            Parent.Update();
        a:
            ;
        }

the methods are invoked in the following manner

btn01.MoveFaster(loc02);

what it does is, it'll move the btn01 to location 02 slowly depending on the thread sleep time and the factor of distance getting changed each time its moved

any comments will be appriciated
contact me if u need any help
dhanushka131@yahoo.com
dhanushka8715@gmail.com
bye for now...
:-)

a timer object can be used to acheive this simple task

all yo have to do is 
1)drag an drop a timer from the tool box
2)go to properties of the timer
3)set the intervel to the number of miliseconds you want to raise the tick event
4)select the Tick event and double click it
an event handler will get creteated automatically

add the following code inside it's body

private void timer1_Tick(object sender, EventArgs e)
        {
            int hours = DateTime.Now.Hour;
            int minutes = DateTime.Now.Minute;
            int seconds = DateTime.Now.Second;
            int milSeconds = DateTime.Now.Millisecond;

            string timeString =hours+" : "+minutes + " : " + seconds + " : " + milSeconds;

            label1.Text = timeString;
        }

what happens here is every time the tick event of timer 1 occur the label.text value will get updated with the curent time of the system
you can get those values using the DateTime struct in the System namesapce
 now press F5 and "volla" there goes your own digital clock
you can extend this simple code to tailor your needs very easyly
.NET Z DAT SIMPLE DUDE :-)