Wednesday, February 29, 2012

[Csharp] Window Context Menu

Today, I read some topic on http://diendan.congdongcviet.com/
I found an enjoyable question on this topic: http://diendan.congdongcviet.com/showthread.php?t=85813
Create an custom menu in Window Context Menu, that I never thought. Get code of creator, I try to make menu.
After some minutes, I successfully create it. Then I have same question, how can get clicked file to my application. Try some ways and search Google. Yes, solution in here:
http://www.jfitz.com/tips/rclick_custom.html
Now, I will show you how to make a menu and do something with file.

For create new menu and remove it, I write a class:

   1:      public static class WindowContextMenu
   2:      {
   3:          public static void RemoveContextMenuItem(string extension, string menuName)
   4:          {
   5:              RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(extension);
   6:   
   7:              if (registryKey != null)
   8:              {
   9:                  string extstring = registryKey.GetValue("").ToString(); //root
  10:   
  11:                  registryKey.Close();
  12:   
  13:                  if (!string.IsNullOrEmpty(extstring))
  14:                  {
  15:                      registryKey = Registry.ClassesRoot.OpenSubKey(extstring, true);
  16:                      if (registryKey != null)
  17:                      {
  18:                          RegistryKey subky = registryKey.OpenSubKey("shell\\" + menuName);
  19:                          if ( subky != null )
  20:                          {
  21:                              subky.Close();
  22:                              registryKey.DeleteSubKeyTree("shell\\" + menuName);
  23:                              registryKey.Close();
  24:                          }
  25:                      }
  26:                  }
  27:              }
  28:          }
  29:   
  30:          public static void AddContextMenuItem(string extension, string menuName, string menuDescription, string menuCommand)
  31:          {
  32:              RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(extension);
  33:   
  34:              if (registryKey != null)
  35:              {
  36:                  string extstring = registryKey.GetValue("").ToString(); //root
  37:   
  38:                  registryKey.Close();
  39:   
  40:                  if (!string.IsNullOrEmpty(extstring))
  41:                  {
  42:                      registryKey = Registry.ClassesRoot.OpenSubKey(extstring, true);
  43:   
  44:                      if (registryKey != null)
  45:                      {
  46:                          string strkey = "shell\\" + menuName + "\\command";
  47:   
  48:                          RegistryKey subky = registryKey.CreateSubKey(strkey);
  49:   
  50:                          if (subky != null)
  51:                          {
  52:                              subky.SetValue("", menuCommand);
  53:                              subky.Close();
  54:                          }
  55:   
  56:                          subky = registryKey.OpenSubKey("shell\\" + menuName, true);
  57:                          if (subky != null)
  58:                          {
  59:                              subky.SetValue("", menuDescription);
  60:                              subky.Close();
  61:                          }
  62:                          registryKey.Close();
  63:                      }
  64:                  }
  65:              }
  66:          }
  67:      }
You can simply understand, it only write and delete key on Registry Editor. So, for use this class here is my sample:
   1:          private void btnRemove_Click(object sender, EventArgs e)
   2:          {
   3:              WindowContextMenu.RemoveContextMenuItem(".xls", "NewMenuOption");
   4:          }
   5:   
   6:          private void btnCreate_Click(object sender, EventArgs e)
   7:          {
   8:              WindowContextMenu.AddContextMenuItem(".xls", "NewMenuOption", "QuangHoang", Application.ExecutablePath + " \"%1\"");
   9:          }
This is code for two buttons Add and Remove.

So, now is the answer of question of topic I mention in top of post.

How your application open file? 
You can use args parameter. When user click on your menu, you can run you application and send file path to. Your application get the path and do what you want. Like this:
   1:          static void Main(string[] args)
   2:          {
   3:              Application.EnableVisualStyles();
   4:              Application.SetCompatibleTextRenderingDefault(false);
   5:   
   6:              if (args != null && args.Length > 0)
   7:              {
   8:                  Application.Run(new FormDemo(args[0]));
   9:              }
  10:              else Application.Run(new FormDemo());
  11:          }
Here, I am overload constructor of Main form.

How can get file's path user click on?
You can see on code I demo in above, you can see menuCommad parameter is Application.ExecutablePath + " \"%1\""
 - First part is path of you application, you can set what you want
 - Second part is "%1", it mean path of file you click on.

Source demo: http://www.mediafire.com/?qdg4ler3gt0guat
I think it so useful for some application.
Enjoy it :)

Saturday, February 25, 2012

[Everyday English] Saturday, day of English

I don't know. What did I do on Saturday? I study English so much but I lazy to code. What right thing to do?
I only want to study one thing per period of time. No other, without something I must do. I am worry about it. How I can change it. How I can quickly think, quickly do. How can I improve my performances, my skills.
So, I will go out a few hours, I need to change up.

Today, I read in this website: english-test.net/forum
And watch video in this: nationalgeographic.com
Day of English, enjoy with me.

You will be found many question and answer about English grammar with international view in here:
http://www.english-test.net/forum/forum4.html
Some explanations are very helpful to me, I like it.

Do you want to watch video to study English and explore the world? Here is good choice: http://video.nationalgeographic.com/video/national-geographic-channel/full-episodes/
But I think it not easy to hear and understand them :)

Good fun!

Thursday, February 23, 2012

[Everyday English] Sleepy day

Today, I start new day at half past six and go to bed at half past one.
Wake up, that I can handle. Get up, that I hate. I get up very slowly, one foot on floor. I always set up phone alarm with many many times. So, you can easily see problem for this day.
Yes, I am not going late. But I feel sleepy during the day. It's not good for work. I haven't enough wise to coding. So, I make many many bugs and cannot smoothly solve it.
Coffee cannot help me, I drink it much. I am listening music and English, it's maybe good for me to go to sleep in.
I think, after work, I will early sleep to night. But now I am right here with tired. Try by my best to write everything I don't understand :))
Don't know how to start, then I start, I don't how  to end.

English, who are you? I will  find you, I will get you. I will not stop, I never give up. Believe me, I am doing it everyday. I am hurry, but I am not hurry. The day will come, and I can use English like I use mother language.

Today, I am continue reading with Power of Seven: http://www.englishclub.com/ref/Power_Of_Seven/
I am not complete it. But I see many many good things from it. Take my thanks.

Tomorrow, I have an pasty with my friend, I have some surprise with a person. He was very lazy to study in my class. What do you guess something I want to talk :) No, it don't like you guess :D He become very bad guy. He always think about money money, play computer game most of time and no plan for future. No one can good without study!
Thanks,

Wednesday, February 22, 2012

[Everyday English] What am I studying?


Today, I read many page on EnglishClub website. This web site is very good and useful for study English.
In this website we can find many articles, documents about all English skill. Some days next, I will spend more time to read it.
Come with me:
http://www.englishclub.com

I am early complete my task on company. Now, it's time for think about plan study to next a few days. Without working on my company, I need to develop 2 projects, one of them is litle project and another is a big project for me. 24 hours per days seem not enough for me, but think about it, sometime I feel lazy. Then I found a post on a blog, it can make me avoid lazy minute. It like a medicine for me It's in here: http://vnhacker.blogspot.com/2012/02/de-hoac-ung.html, try to read it, you can understand.

Review some English tutorials, documents and website I am following. It remind me to focus on study.
1. Effortless Training Course: it's big, recently I don't study it, I need spend time for it.
2. Speaking English like American: so good videos for pronunciation, I am doing it. OK, try to complete it soon.
4. Read website: EnglishClub I will complete in next a few days.
5. Listening website: http://www.eslpod.com/website/index_new.html, I listen litle with it, spend more time.
6. Listening everyday English: It's only on my company, I will try to here it everyday.

Look to the world!

Tuesday, February 21, 2012

[Improve skill] How to read faster


How many wpm (words per minute) do you read? I am not sure about me, but I'm very slow to read.
I am stupid guy but I cannot concentrate when I am reading, I always think and imagine. So, now the solution is find and study a good method for reading faster.
I always start with Google, and here is some links I feel it's good.

http://www.fourhourworkweek.com/blog/2009/07/30/speed-reading-and-accelerated-learning/
http://www.wikihow.com/Read-Fast
http://latimesblogs.latimes.com/jacketcopy/2009/01/how-to-read-462.html

Try to study with me, and share you experience :)

Monday, February 20, 2012

[Csharp] Tranfer data with two objects utility

Developing with an .NET business application, you will familiar with CRUD (it mean Create Read Update Delete).
So, Imagine you have a big object with more than 20 properties. Then you have an old object and a new object, how you can update for it? In normal way, we will set data for each property. So, new we have more than 20 object like this :)
A question, how we can write an function can update property data for T object?
Yes, we can. I found it. This post will you this function and how to use it on your project.
This function in this code snippet:

   1:      public static class Utils
   2:      {
   3:          public static void UpdateProperties<T>(T orginal, ref T dest, params string[] skips) where T : class
   4:          {
   5:              var destType = dest.GetType();
   6:              var destPropertyInfos = destType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
   7:              var orginalType = orginal.GetType();
   8:              var orginalPropertyInfos = orginalType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
   9:              foreach (var destInfo in destPropertyInfos)
  10:              {
  11:                  var propertyName = destInfo.Name;
  12:                  if (skips.Contains(propertyName)) continue;
  13:   
  14:                  var orgInfo = GetValue(propertyName, orginalPropertyInfos);
  15:                  destInfo.SetValue(dest, orgInfo.GetValue(orginal, null), null);
  16:              }
  17:          }
  18:   
  19:          private static PropertyInfo GetValue(string propertyName, IEnumerable<PropertyInfo> propertyInfos)
  20:          {
  21:              return propertyInfos.FirstOrDefault(info => info.Name == propertyName);
  22:          }
  23:      }

This functions will use type of object to get properties information, .NET support we can get and set value for a property. In loop, we will tranfer data from original object to destination object, but some properties you can skips tranfer, when you set names of them on skips parameter.

This is an demo to use it:
   1:          public class MyClass
   2:          {
   3:              public int Id { get; set; }
   4:              //with some properties
   5:          }
   6:   
   7:          static void Main()
   8:          {
   9:              // Original object with some new data
  10:              var fromObject = new MyClass();
  11:              // Destination object will be updated
  12:              var toObject = new MyClass();
  13:   
  14:              // Call update funtion
  15:              Utils.UpdateProperties(fromObject,ref toObject, null);
  16:              // Call update funtion with skip Id
  17:              Utils.UpdateProperties(fromObject, ref toObject, "Id");
  18:   
  19:              Console.ReadKey(true);
  20:          }

I have two objects of MyClass, I want to set data from fromObject to toObject. By call UpdateProperties function I can do it in short code.
It's really useful to me, so you are?
Thank to join it!

Thursday, February 16, 2012

[Csharp] Draw board game using GDI+


Beginning with .NET programming, you can develop some litle games. It will make you interest in study. In this post, I will show you how to use The Graphics Device Interface plus (GDI+) to draw some basic game boards.

1. O an Quan: 
It is an Vietnamese game, it's quite simple to draw. Here is code:

   1:          private void DrawMandarinSquareCapturingBoard(Graphics graphics, int width)
   2:          {
   3:              //Draw Ellipse
   4:              graphics.DrawPie(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X, _startPoint.Y, width * 2, width * 2, 90, 180);
   5:              graphics.DrawPie(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + width * 5, _startPoint.Y, width * 2, width * 2, 270, 180);
   6:   
   7:              //Draw rows
   8:              for (var i = 0; i <= 2; i++)
   9:              {
  10:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + width, _startPoint.Y + i * width, _startPoint.X + 6 * width, _startPoint.Y + i * width);
  11:              }
  12:   
  13:              //Draw columns
  14:              for (var j = 1; j <= 6; j++)
  15:              {
  16:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + j * width, _startPoint.Y, _startPoint.X + j * width, _startPoint.Y + 2 * width);
  17:              }
  18:          }

For the first, we are draw two Pies in two sides.For each, it's a half of cycle. Next we are draw lines for columns and rows.

2. King Chess Board
This is a popular game. Its board is include black and white square. Here is code:
   1:          private void DrawChessBoard(Graphics graphics, int width)
   2:          {
   3:              //Draw bolder
   4:              graphics.DrawRectangle(new Pen(Brushes.DodgerBlue, 4), _startPoint.X, _startPoint.Y, 8 * width, 8 * width);
   5:   
   6:              bool isBlack = false;
   7:              //Draw elements
   8:              for (var i = 0; i < 8; i++)
   9:              {
  10:                  for (var j = 0; j < 8; j++)
  11:                  {
  12:                      graphics.FillRectangle(isBlack ? Brushes.White : Brushes.Black, _startPoint.X + i * width, _startPoint.Y + j * width, width, width);
  13:                      isBlack = !isBlack;
  14:                  }
  15:                  isBlack = !isBlack;
  16:              }
  17:          }

Firstly, we draw a bolder around the board. Then, draw all element in board. Color of element will follow _isBlack variable. It's changing everytime, when we fill rectangle.

3. China Chess Board
This game is popular in Vietnam, I know it come from China. I think this board quite to complex. Here is code:
   1:          private void DrawChinaChessoBoard(Graphics graphics, int width)
   2:          {
   3:              //Draw background
   4:              var linearBrush = new LinearGradientBrush(new Rectangle(_startPoint.X, _startPoint.Y, 8 * width, 9 * width), Color.Turquoise,
   5:                  Color.White, LinearGradientMode.BackwardDiagonal);
   6:              graphics.FillRectangle(linearBrush, _startPoint.X, _startPoint.Y, 8 * width, 9 * width);
   7:   
   8:              //Draw bolder
   9:              graphics.DrawRectangle(new Pen(Brushes.DarkTurquoise, 4), _startPoint.X, _startPoint.Y, 8 * width, 9 * width);
  10:   
  11:              //Draw rows
  12:              for (var i = 0; i <= 9; i++)
  13:              {
  14:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X, _startPoint.Y + i * width, _startPoint.X + 8 * width, _startPoint.Y + i * width);
  15:              }
  16:   
  17:              //Draw columns
  18:              for (var j = 0; j <= 8; j++)
  19:              {
  20:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + j * width, _startPoint.Y, _startPoint.X + j * width, _startPoint.Y + 4 * width);
  21:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + j * width, _startPoint.Y + 5 * width, _startPoint.X + j * width, _startPoint.Y + 9 * width);
  22:              }
  23:   
  24:              //Draw king local
  25:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + 3 * width, _startPoint.Y, _startPoint.X + 5 * width, _startPoint.Y + 2 * width);
  26:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + 5 * width, _startPoint.Y, _startPoint.X + 3 * width, _startPoint.Y + 2 * width);
  27:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + 3 * width, _startPoint.Y + 7 * width, _startPoint.X + 5 * width, _startPoint.Y + 9 * width);
  28:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + 5 * width, _startPoint.Y + 7 * width, _startPoint.X + 3 * width, _startPoint.Y + 9 * width);
  29:   
  30:              //Draw plus
  31:              DrawPlus(graphics, _startPoint.X + width, _startPoint.Y + 2 * width, width);
  32:              DrawPlus(graphics, _startPoint.X + 7 * width, _startPoint.Y + 2 * width, width);
  33:              DrawPlus(graphics, _startPoint.X, _startPoint.Y + 3 * width, width);
  34:              DrawPlus(graphics, _startPoint.X + 2 * width, _startPoint.Y + 3 * width, width);
  35:              DrawPlus(graphics, _startPoint.X + 4 * width, _startPoint.Y + 3 * width, width);
  36:              DrawPlus(graphics, _startPoint.X + 6 * width, _startPoint.Y + 3 * width, width);
  37:              DrawPlus(graphics, _startPoint.X + 8 * width, _startPoint.Y + 3 * width, width);
  38:   
  39:              DrawPlus(graphics, _startPoint.X + width, _startPoint.Y + 7 * width, width);
  40:              DrawPlus(graphics, _startPoint.X + 7 * width, _startPoint.Y + 7 * width, width);
  41:              DrawPlus(graphics, _startPoint.X, _startPoint.Y + 6 * width, width);
  42:              DrawPlus(graphics, _startPoint.X + 2 * width, _startPoint.Y + 6 * width, width);
  43:              DrawPlus(graphics, _startPoint.X + 4 * width, _startPoint.Y + 6 * width, width);
  44:              DrawPlus(graphics, _startPoint.X + 6 * width, _startPoint.Y + 6 * width, width);
  45:              DrawPlus(graphics, _startPoint.X + 8 * width, _startPoint.Y + 6 * width, width);
  46:          }
  47:   
  48:          private static void DrawPlus(Graphics graphics, int x, int y, int width)
  49:          {
  50:              var w = width / 4;
  51:              var h = width / 10;
  52:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), x - h, y - w, x - h, y - h);
  53:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), x - w, y - h, x - h, y - h);
  54:   
  55:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), x + h, y + w, x + h, y + h);
  56:              graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), x + w, y + h, x + h, y + h);
  57:          }

It's about many lines with many point, you see it hard to know where is start and where is end of line. But this code is easy to understand. Read it carefully, you can get experience.

4. Caro Board
Yes, I know you know it. I am interest this game, I think this board not complex to you. Here is code:
   1:          private void DrawCaroBoard(Graphics graphics, int row, int col, int width)
   2:          {
   3:              //Draw background
   4:              var linearBrush = new LinearGradientBrush(new Rectangle(_startPoint.X, _startPoint.Y, col * width, row * width), Color.Turquoise,
   5:                  Color.White, LinearGradientMode.BackwardDiagonal);
   6:              graphics.FillRectangle(linearBrush, _startPoint.X, _startPoint.Y, col * width, row * width);
   7:   
   8:              //Draw rows
   9:              for (var i = 0; i <= row; i++)
  10:              {
  11:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X, _startPoint.Y + i * width, _startPoint.X + col * width, _startPoint.Y + i * width);
  12:              }
  13:   
  14:              //Draw columns
  15:              for (var j = 0; j <= col; j++)
  16:              {
  17:                  graphics.DrawLine(new Pen(Brushes.DarkTurquoise, 2), _startPoint.X + j * width, _startPoint.Y, _startPoint.X + j * width, _startPoint.Y + row * width);
  18:              }
  19:          }

It have many parameters help you easy cho change size of board.

All game board show on screen when you implement them on Form Paint event and call invalidate() function wherever on form.
   1:      private void FormView_Paint(object sender, PaintEventArgs e)
   2:          {
   3:              switch (_choiceDraw)
   4:              {
   5:                  case 2: DrawChessBoard(e.Graphics, 50); break;
   6:                  case 3: DrawChinaChessoBoard(e.Graphics, 48); break;
   7:                  case 4: DrawLudoCirclesBoard(e.Graphics, 400); break;
   8:                  case 5: DrawCaroBoard(e.Graphics, 10, 10, 40); break;
   9:                  default: DrawMandarinSquareCapturingBoard(e.Graphics, 60); break;
  10:              }
  11:          }

It's all simple drawing game board, it hard to make a big or beautiful game. But If you choose right color, right size, you will make it better.
This is source code: http://www.mediafire.com/?ghad2nn1545ndhd
Hope you enjoy it :)

Wednesday, February 15, 2012

[Csharp] Serialize object with XmlSerializer


XML become familiar with application developer. Working with it, I always use XmlSerializer, I can serialize xml string to an object, then I can access to element to change value.
Here is two sample classes, it will serialize string to object and forward:

   1:          public static string ToXmlString<T>(T objectToSerialize)
   2:          {
   3:              var stream = new MemoryStream();
   4:   
   5:              TextWriter writer = new StreamWriter(stream, new UTF8Encoding());
   6:   
   7:              var xmlSerializer = new XmlSerializer(typeof(T));
   8:              xmlSerializer.Serialize(writer, objectToSerialize);
   9:   
  10:              return Encoding.UTF8.GetString(stream.ToArray(), 0, Convert.ToInt32(stream.Length));
  11:          }
  12:   
  13:          public static T FromXmlString<T>(String source)
  14:          {
  15:              var xmlSerializer = new XmlSerializer(typeof(T));
  16:              var sr = new StringReader(source);
  17:              return (T)xmlSerializer.Deserialize(sr);
  18:          }
Put them on a class and try to use it :)

Changing project


A project similar to life... and you are developer.

If you only code, you do not re-factoring code by time, you will create a mess. If you grow up without study and change, you will come to bad guy.

Changing code will be rick, maybe some impact you cannot control, make it false on run-time, careful and make sure what you will change, maybe create a plan is safe and good. So, how can you change  you life, what you change and what impact to...? Maybe it make you afraid and worry. Make a plan is good choice again.

What happen with a big change? Nearly, I always meet it, our project in my company have a big change. So, plan is not enough, we need to study more, logging all step, create some tools. Make everything in control and safe. I have many experience from it. And I am prepare for my big change... you will see me careful change.

Thank for programming, thank for my project.

[Network Programming] Client-Server classes P2 Window Form


Continue from this post: http://zquanghoangz.blogspot.com/2012/02/network-programming-tcplistener-with.html
In this post I will use two classes Client Server in Window Form demo application. But I sure this application have many bugs, because it is an demo. It will give you have some ideas for your exercise. OK, join it.

Application show simply way to chat with client server, you can apply it to all big exercise on your university. I will descirible what I write in project, and how it work with some important node you need remember when custom this code.
Code and video demo in bottom of this post.

1. With Client Server classes you can see in last my post, but I change a litle in Server class. There is a new Event call ClientConnected. It will catch all client connected to server on starting time.
All events in this code:


   1:          #region Events
   2:   
   3:          #region Delegates
   4:   
   5:          public delegate void ReceivedMessageEventHandle(TcpClient client, string message);
   6:          public delegate void ClientConnectedEventHandle(TcpClient client);
   7:   
   8:          #endregion
   9:   
  10:          public event ReceivedMessageEventHandle ReceivedMessage;
  11:          public event ClientConnectedEventHandle ClientConnected;
  12:   
  13:          #endregion


2. Two forms are almost of same functions, we can go to detail:
 - Constructor and events handle
   1:          public FormServer()
   2:          {
   3:              InitializeComponent();
   4:              _isStarted = false;
   5:              _server = new Server();
   6:              _server.ReceivedMessage += server_ReceivedMessage;
   7:              _server.ClientConnected += server_ClientConnected;
   8:   
   9:              _listClientsConnected = new Dictionary<string, TcpClient>();
  10:          }

You can see two events of server will be handle by server_ReceivedMessage, server_ClientConnected. It mean when Server suddenly get message or a client connected to, events will be raise and you can catch it, then write some function you want with data.

Here is code I handle events:
   1:          private void server_ClientConnected(TcpClient client)
   2:          {
   3:              //Add new client to list
   4:              if (!_listClientsConnected.ContainsKey(client.GetHashCode().ToString()))
   5:              {
   6:                  _listClientsConnected.Add(client.GetHashCode().ToString(), client);
   7:   
   8:                  if (InvokeRequired)
   9:                  {
  10:                      lstClients.Invoke(new Action(delegate { lstClients.Items.Add(client.GetHashCode().ToString()); }));
  11:                  }
  12:              }
  13:          }
  14:   
  15:          private void server_ReceivedMessage(TcpClient client, string message)
  16:          {
  17:              if (InvokeRequired)
  18:              {
  19:                  txtReceivedMessages.Invoke(
  20:                      new Action(
  21:                          delegate { txtReceivedMessages.Text += client.GetHashCode() + ": " + message + Environment.NewLine; }));
  22:              }
  23:          }

You can see two classes Client Server, I am using Thread, then if you want to across-thread, you will invoke thread using code above (comment invoke thread you will see exception raised). When a client connected to server, It will store on a dictionary collection with key is a hash code, and show in on screen by all hash code to list box. When server recieved message, It will show it to append to text box. Form client will be same with server.

Send message will quite different bettween client and server. Client is very simple because it will send to only one server, what it connect to. In difference, server have many client connect to, we are have a list client store in _listClientsConnected. So, user need to choose one of them and send. Function will like this:
   1:        private void btnSend_Click(object sender, EventArgs e)
   2:          {
   3:              if (lstClients.Items == null || lstClients.Items.Count < 1 || lstClients.SelectedItem == null) return;
   4:   
   5:              txtReceivedMessages.Text += "Me to" + lstClients.SelectedItem + ": " + txtMessage.Text + Environment.NewLine;
   6:              _server.SendMessage(_listClientsConnected[lstClients.SelectedItem.ToString()], txtMessage.Text);
   7:          }

That will send message to an client you choose.
As I mention, this application use thread. Don't forget, we need close it by this function:
   1:          private void FormServer_FormClosing(object sender, FormClosingEventArgs e)
   2:          {
   3:              Environment.Exit(0);
   4:          }
It will close all working threads.
I hope you can easy to understand this application and custom it like you want to your exercise.
Here is ...
    Source: http://www.mediafire.com/?sgn3y93utpe21rz
    Video: http://www.youtube.com/watch?v=4tBstBvAUUo&feature=youtu.be
Thank for read!

[Everyday English] A day work


Hi great day.
Today I early come to my company, I see a little people came. I turn on my computer and listen some music.
Then I make a plan, what I will do today.
 - Coding, yes of course.
 - Study English. OK, I will watch English Training video after lunch. And listen VOA or BBC during working.
 - Write blog, I am doing...
Nice day to me, to everyone!

Tuesday, February 14, 2012

[Network Programming] Client-Server classes P1 Console App

For a beginner it network programming. I write class for Client and Server. Here is class and demo, I will describe in some posts later.
Demo solution:
Client class

   1:      public class TcpClient
   2:      {
   3:          #region Fields and Properties
   4:   
   5:          private const int Port = 6666;
   6:          private readonly System.Net.Sockets.TcpClient _client;
   7:          private readonly Thread _clientThread;
   8:          private readonly IPEndPoint _ipEndPoint;
   9:   
  10:          public IPAddress IpAddress { get; set; }
  11:   
  12:          #endregion
  13:   
  14:          #region Constructors
  15:   
  16:          public TcpClient()
  17:          {
  18:              _client = new System.Net.Sockets.TcpClient();
  19:   
  20:              // Set default data
  21:              IpAddress = IPAddress.Parse("127.0.0.1");
  22:   
  23:              // Server end point
  24:              if (IpAddress != null) _ipEndPoint = new IPEndPoint(IpAddress, Port);
  25:   
  26:              _clientThread = new Thread(HandleServerCommunication);
  27:          }
  28:   
  29:          #endregion
  30:   
  31:          #region Events
  32:   
  33:          #region Delegates
  34:   
  35:          public delegate void ReceivedMessageEventHandle(System.Net.Sockets.TcpClient client, string message);
  36:   
  37:          #endregion
  38:   
  39:          public event ReceivedMessageEventHandle ReceivedMessage;
  40:   
  41:          #endregion
  42:   
  43:          #region Start/Stop Connect
  44:   
  45:          /// <summary>
  46:          /// Start connect server
  47:          /// </summary>
  48:          public bool StartConnect()
  49:          {
  50:              try
  51:              {
  52:                  if (_client != null)
  53:                  {
  54:                      if (!_client.Connected)
  55:                          _client.Connect(_ipEndPoint);
  56:                      return _client.Connected;
  57:                  }
  58:                  return false;
  59:              }
  60:              catch
  61:              {
  62:                  return false;
  63:              }
  64:          }
  65:   
  66:          /// <summary>
  67:          /// Stop connect server
  68:          /// </summary>
  69:          public void StopConnect()
  70:          {
  71:              if (_clientThread.ThreadState == ThreadState.Running)
  72:                  _clientThread.Abort();
  73:              if (_client.Connected)
  74:                  _client.Close();
  75:          }
  76:   
  77:          #endregion
  78:   
  79:          #region Client
  80:   
  81:          /// <summary>
  82:          /// Send message to server and create thread listen response message
  83:          /// </summary>
  84:          /// <param name="message">string message</param>
  85:          public bool SendMessage(string message)
  86:          {
  87:              if (_client != null && _client.Connected)
  88:              {
  89:                  try
  90:                  {
  91:                      // Send request to Window Service
  92:                      NetworkStream clientStream = _client.GetStream();
  93:   
  94:                      var encoder = new ASCIIEncoding();
  95:                      byte[] buffer = encoder.GetBytes(message);
  96:   
  97:                      clientStream.Write(buffer, 0, buffer.Length);
  98:                      clientStream.Flush();
  99:   
 100:                      _clientThread.Start(_client);
 101:                      return true;
 102:                  }
 103:                  catch
 104:                  {
 105:                      return false;
 106:                  }
 107:              }
 108:              return false;
 109:          }
 110:   
 111:          /// <summary>
 112:          /// Listen response from server and call event ReceivedMessage
 113:          /// </summary>
 114:          /// <param name="client">connected client</param>
 115:          private void HandleServerCommunication(object client)
 116:          {
 117:              var tcpClient = (System.Net.Sockets.TcpClient) client;
 118:              NetworkStream clientStream = tcpClient.GetStream();
 119:   
 120:              var message = new byte[4096];
 121:   
 122:              while (true)
 123:              {
 124:                  int bytesRead;
 125:                  try
 126:                  {
 127:                      //blocks until a client sends a message
 128:                      bytesRead = clientStream.Read(message, 0, 4096);
 129:                  }
 130:                  catch
 131:                  {
 132:                      //a socket error has occured
 133:                      break;
 134:                  }
 135:   
 136:                  if (bytesRead == 0)
 137:                  {
 138:                      //the client has disconnected from the server
 139:                      break;
 140:                  }
 141:   
 142:                  //message has successfully been received
 143:                  var encoder = new ASCIIEncoding();
 144:                  int read = bytesRead;
 145:                  ReceivedMessage(_client, encoder.GetString(message, 0, read));
 146:              }
 147:   
 148:              tcpClient.Close();
 149:          }
 150:   
 151:          #endregion
 152:      }
Client demo

   1:      internal class Client
   2:      {
   3:          private static void Main(string[] args)
   4:          {
   5:              Console.WriteLine("Press any key to start...");
   6:              Console.ReadKey(true);
   7:   
   8:              var client = new TcpClient();
   9:              client.StartConnect();
  10:              client.ReceivedMessage += (c, m) => Console.WriteLine("{0}:{1}", c.Client.AddressFamily, m);
  11:   
  12:              Console.WriteLine("Me: Hello server!");
  13:              client.SendMessage("Hello server!");
  14:   
  15:              Console.WriteLine("Press any key to stop...");
  16:              Console.ReadKey(true);
  17:              Environment.Exit(0);
  18:          }
  19:      }
Server class

   1:      public class TcpServer
   2:      {
   3:          #region Fields and Properties
   4:   
   5:          private readonly Thread _listenThread;
   6:          private readonly TcpListener _tcpListener;
   7:          public IPAddress IpAddress { get; set; }
   8:          private const int Port = 6666;
   9:   
  10:          #endregion
  11:   
  12:          #region Events
  13:   
  14:          #region Delegates
  15:   
  16:          public delegate void ReceivedMessageEventHandle(System.Net.Sockets.TcpClient client, string message);
  17:   
  18:          #endregion
  19:   
  20:          public event ReceivedMessageEventHandle ReceivedMessage;
  21:   
  22:          #endregion
  23:   
  24:          #region Constructors
  25:   
  26:          /// <summary>
  27:          /// Default constructor
  28:          /// </summary>
  29:          public TcpServer()
  30:          {
  31:              IpAddress = IPAddress.Any;
  32:              _tcpListener = new TcpListener(IpAddress, Port);
  33:              _listenThread = new Thread(ListenForClients);
  34:          }
  35:   
  36:          #endregion
  37:   
  38:          #region Start/Stop
  39:   
  40:          /// <summary>
  41:          /// Start listen client
  42:          /// </summary>
  43:          public void StartServer()
  44:          {
  45:              try
  46:              {
  47:                  if (_listenThread.ThreadState != ThreadState.Running)
  48:                      _listenThread.Start();
  49:              }
  50:              catch (Exception ex)
  51:              {
  52:                  //Todo: Write log, or change return fuction is false
  53:              }
  54:          }
  55:   
  56:          /// <summary>
  57:          /// Stop listen client
  58:          /// </summary>
  59:          public void StopServer()
  60:          {
  61:              try
  62:              {
  63:                  if (_listenThread.ThreadState == ThreadState.Running)
  64:                      _listenThread.Abort();
  65:              }
  66:              catch (Exception ex)
  67:              {
  68:                  //Todo: Write log, or change return fuction is false
  69:              }
  70:          }
  71:   
  72:          #endregion
  73:   
  74:          #region Listening
  75:   
  76:          /// <summary>
  77:          /// Listen all accept client and create thread for each client accepted
  78:          /// </summary>
  79:          private void ListenForClients()
  80:          {
  81:              _tcpListener.Start();
  82:              while (true)
  83:              {
  84:                  try
  85:                  {
  86:                      //blocks until a client has connected to the server
  87:                      System.Net.Sockets.TcpClient client = _tcpListener.AcceptTcpClient();
  88:                      if (client.Connected)
  89:                      {
  90:                          //create a thread to handle communication 
  91:                          //with connected client
  92:                          var clientThread = new Thread(HandleClientCommunication);
  93:                          clientThread.Start(client);
  94:                      }
  95:                  }
  96:                  catch (Exception ex)
  97:                  {
  98:                      //Todo: Write log exception
  99:                      break;
 100:                  }
 101:              }
 102:          }
 103:   
 104:          /// <summary>
 105:          /// Receive message from client and call event ReceivedMessage
 106:          /// </summary>
 107:          /// <param name="client"></param>
 108:          private void HandleClientCommunication(object client)
 109:          {
 110:              var tcpClient = (System.Net.Sockets.TcpClient)client;
 111:              NetworkStream clientStream = tcpClient.GetStream();
 112:   
 113:              var message = new byte[4096];
 114:   
 115:              while (true)
 116:              {
 117:                  int bytesRead;
 118:   
 119:                  try
 120:                  {
 121:                      //blocks until a client sends a message
 122:                      bytesRead = clientStream.Read(message, 0, 4096);
 123:                  }
 124:                  catch (Exception ex)
 125:                  {
 126:                      //Todo: Write log exception
 127:                      break;
 128:                  }
 129:   
 130:                  if (bytesRead == 0)
 131:                  {
 132:                      //the client has disconnected from the server
 133:                      break;
 134:                  }
 135:   
 136:                  //message has successfully been received
 137:                  var encoder = new ASCIIEncoding();
 138:                  string receiveMessage = encoder.GetString(message, 0, bytesRead);
 139:   
 140:                  // Event handle
 141:                  if (ReceivedMessage != null)
 142:                      ReceivedMessage(tcpClient, receiveMessage);
 143:              }
 144:   
 145:              tcpClient.Close();
 146:          }
 147:   
 148:          #endregion
 149:   
 150:          #region Send Message
 151:   
 152:          /// <summary>
 153:          /// Send message to client
 154:          /// </summary>
 155:          /// <param name="client"></param>
 156:          /// <param name="message"></param>
 157:          /// <returns></returns>
 158:          public bool SendMessage(System.Net.Sockets.TcpClient client, string message)
 159:          {
 160:              try
 161:              {
 162:                  if (client != null && client.Connected)
 163:                  {
 164:                      NetworkStream clientStream = client.GetStream();
 165:   
 166:                      var encoder = new ASCIIEncoding();
 167:                      byte[] buffer = encoder.GetBytes(message);
 168:   
 169:                      clientStream.Write(buffer, 0, buffer.Length);
 170:                      clientStream.Flush();
 171:                      return true;
 172:                  }
 173:                  return false;
 174:              }
 175:              catch (Exception ex)
 176:              {
 177:                  //Todo: Write log exception
 178:                  return false;
 179:              }
 180:          }
 181:   
 182:          #endregion
 183:      }
Server demo

   1:      internal class Server
   2:      {
   3:          private static void Main(string[] args)
   4:          {
   5:              Console.WriteLine("Press any key to start...");
   6:              Console.ReadKey(true);
   7:   
   8:              var server = new TcpServer();
   9:              server.StartServer();
  10:              server.ReceivedMessage += (c, m) =>
  11:                                            {
  12:                                                Console.WriteLine("Client:{0}", m);
  13:   
  14:                                                Console.WriteLine("Me:Hello client!");
  15:                                                server.SendMessage(c, "Hello client!");
  16:                                            };
  17:   
  18:              Console.WriteLine("Press any key to stop...");
  19:              Console.ReadKey(true);
  20:              Environment.Exit(0);
  21:          }
  22:      }

Source: http://www.mediafire.com/?fc4fftap62g5qew
Video:  http://www.youtube.com/watch?v=DZr9Fnb0WNI&feature=youtu.be
Yes, it run OK. See you late!