Monday, December 26, 2011

Bytes vs String Over Network


Bytes vs String Over Network

Message in bytes format is always good to transfer data over network compare to string.
Communication of message in bytes format required convertion of every data while sending and receving at both end of connection.
In scenario of Stock Market or Very fast data transfer over network, It is recommened not to use bytes format to send and receive data over network because it consume more time for conversion of data compare to volume of data, Hence in this case string format is recommeneded for data comunication

Asynchronous TCP Client Easy Example


 private TcpClient tcpClient = null;

         public void ConnectToServer()
         {
                try
               {
                tcpClient = new TcpClient(AddressFamily.InterNetwork);

                IPAddress[] remoteHost = Dns.GetHostAddresses("hostaddress");
              
                //Start the async connect operation          

                tcpClient.BeginConnect(remoteHost, portno, new
                              AsyncCallback(ConnectCallback), tcpClient);

                }
                catch (Exception ex)
                {
Logger.WriteLog(LogLevel.Error,"ex.Message);
                 }
         }
      

        private void ConnectCallback(IAsyncResult result)
        {                      
            try
            {
              //We are connected successfully.

               NetworkStream networkStream = tcpClient.GetStream();

               byte[] buffer = new byte[tcpClient.ReceiveBufferSize];

              //Now we are connected start asyn read operation.

               networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
             }
             Catch(Exception ex)
             {
Logger.WriteLog(LogLevel.Error,"ex.Message);
              }
          }
      

          
          /// Callback for Read operation
         private void ReadCallback(IAsyncResult result)
         {    
  
            NetworkStream networkStream;

            try
            {

                networkStream = tcpClient.GetStream();  
        
            }

            catch
            {
Logger.WriteLog(LogLevel.Warning,"ex.Message);
             return;

            }        

            byte[] buffer = result.AsyncState as byte[];

            string data = ASCIIEncoding.ASCII.GetString(buffer, 0, buffer.Length );

            //Do something with the data object here.

            //Then start reading from the network again.

            networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);

        }
    
  

Thursday, June 16, 2011

Working with Microsoft MessageQueuing (MSMQ)



1) Create Class

 public class RequestMessage
 {
     public string UserId { get; set; }
     public string RequestType { get; set; }
 }


2. Creating Client 1 class

This class creates queue if it doesn’t exist and sends message to it.

class MSMQSender
 {
     public void SendMessage(string userId, string requestType)
     {
         private string queuePath = @".\Private$\test";
         MessageQueue mq;

         // open or create message queue
         if (MessageQueue.Exists(queuePath))
             mq = new MessageQueue(queuePath);
         else
             mq = MessageQueue.Create(queuePath);

        Message message = new Message();
        message.Recoverable = true;

        RequestMessage rm = new RequestMessage();
        rm.UserId = userId;
        rm.RequestType = requestType;

        message.Body = rm;

        mq.Send(rm);

     }
 }

3. Creating Server class

Class creates or open queue receives messages and processes them by worker object. Worker can only process single message. It returns control to server object when processing is done.

class Server
 {
      public Server()
      {
           MessageQueue mq;

           // open or create message queue
           // …

           // set type of message
           ((XmlMessageFormatter)mq.Formatter).TargetTypes = new Type[] { typeof(RequestMessage) };

           while(true)
           {
               Message message = mq.Receive();
               RequestMessage rm = (RequestMessage)message.Body;

               Worker worker = new Worker(rm.UserId, rm.RequestType);
               worker.DoJob();
           }
      }
 }

4. Creating Client 2 class

Class reads all messages in the queue, checks its content and adds it to the list . It is a simple queue monitor.

class MSMQReceiver
 {
     public List ReadFromQueue(string userId)
     {
         // open or create message queue
         // …

         // set type of message

         Cursor cursor = mq.CreateCursor();

         Message m = mq.Peek(new TimeSpan(1), cursor,
                            PeekAction.Current);

         RequestMessage rm = (RequestMessage)m.Body;

         rm.UserId == userId)
             list.Add(rm.RequestType);

         while ((m = mq.Peek(new TimeSpan(1), cursor,
                 PeekAction.Next)) != null)
         {
             rm = (RequestMessage)m.Body;

             if (rm.UserId == userId)
                 list.Add(rm.RequestType);
         }

         return list;
    }
 }

Tuesday, March 22, 2011

Background Worker


Why use the BackgroundWorker?

You can use it to shift some heavy calculations, for example database access or file searching, to another thread and make the user interface more responsive. If both UI and the heavy calculations are ran within the same thread the UI appears to hang, making the average pc user think the program has crashed. So let's do it the decent way and use BackgroundWorker! 

How to use the BackgroundWorker?

The BackgroundWorker may sound quite intimidating, but actually it's very easy and intuitive to do use once you've done the first time. So let's get going and make a simple application showing you the usage of the BackgroundWorker. In case you want to look up the BackgroundWorker class on MSDN, it's in the System.ComponentModel namespace.

The first thing you need to do is to add the BackgroundWorker to the application and the easiest way to do so is to drag it from the toolbox onto your form. It's under the components tab. You'll see the BackgroundWorker showing up as BackgroundWorker1 in the gray box under your form.
Attached Image

The BackgroundWorker is event-driven, so what you need to do to get the basics working is this:
-Invoke the BackgroundWorker's DoWork class from your application.
-Give DoWork some work to do by adding the code in the BackgroundWorker1.DoWork method.
-After the code in the DoWork method is done, the event RunWorkerCompleted is invoked.
-Through the RunWorkerCompleted method, we'll retrieve our return values from the 2nd thread

Ok, lets get coding! Double click on the DoWork event and add:


Find below the simple and easy code how to use background worker



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;


namespace Backgroundworker

{
public partial class MainPage : UserControl
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();

public MainPage()

{

InitializeComponent();


backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);

backgroundWorker.WorkerReportsProgress = true;

backgroundWorker.WorkerSupportsCancellation = true;

backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);


backgroundWorker.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);


}


void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

if (e.Error != null)

{
txtPercentComplete.Text = e.Error.Message;
}

else if (e.Cancelled)
{
txtPercentComplete.Text = "Task Cancelled";
}

else

{
txtPercentComplete.Text = "Task Completed";
}

}


void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
txtPercentComplete.Text = e.ProgressPercentage.ToString() + " %";
}


void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
const int SECOND = 1000;

BackgroundWorker backgroundWorker = (BackgroundWorker)sender;


for (int i = 0; i < 20; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}

backgroundWorker.ReportProgress((i + 1) * 5);

System.Threading.Thread.Sleep(SECOND / 4);

}

}



private void btnStartTask_Click(object sender, RoutedEventArgs e)

{
backgroundWorker.RunWorkerAsync();
}


private void btnCancelTask_Click(object sender, RoutedEventArgs e)
{
backgroundWorker.CancelAsync();
}

}
}

Saturday, March 19, 2011

Display Log in Logviewer

1) Create the FileSystemWatcher and set its properties.



FileSystemWatcher_Log_1.Path = Directory.GetParent("C:\\temp").FullName;

FileSystemWatcher_Log_1.Filter = "MyLogFile.log";

NotifyFilters notifyFileters = new NotifyFilters();

notifyFileters = notifyFileters
NotifyFilters.LastWrite;

// You can choose other notification filters


FileSystemWatcher_Log_1.NotifyFilter = notifyFileters;

FileSystemWatcher_Log_1.EnableRaisingEvents = true;




2) Set the event handler.



this.FileSystemWatcher_Log_1.Changed += new

System.IO.FileSystemEventHandler(this.FileSystemWatcher_Changed);



3) Update GUI when event occours



// create stream writer only once so that whenever new log is appended in the log file,

// only that text will be shown in the list view (or which ever the gui component you are using).

if (null == sr_Log_1)

{

sr_Log_1 = new StreamReader(new FileStream(SelectedFileName_Log1_textbox.Text,

FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true);

}

string line;

while (sr_Log_1.EndOfStream != true)

{

line = sr_Log_1.ReadLine();

if (line.Trim().Length == 0)

{

continue;

}

Log_1_listBox.Items.Add(line);

Log_1_listBox.TopIndex = Log_1_listBox.Items.Count - 26 + 1;



}






WIndows Communication Foundation


Now learn windows communication foundation in few easy steps.





Please find the power point presentation  and example of windows communication foundation