Tuesday, 27 August 2013


Difference between Dictionary and Hashtable




Simply, Dictionary<TKey,TValue> is a generic type, allowing:
  • static typing (and compile-time verification)
  • use without boxing
If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)
A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) useConcurrentDictionary<TKey, TValue>.

Wednesday, 21 August 2013

What Is the Difference between Synchronous and Asynchronous?

Answer
The difference between Asynchronous and Synchronous is that Synchronous is the more efficient method of PC communication. However Asynchronous is the most
common method of communication used for email applications, internet access and networking. Synchronous is usually used for transmission of large data bocks.

---------------------
Asynchronous communication works much like the postal system: An application creates a message (that's a piece of data such as the text String "Order 1000 barrels
crude oil", or an XML expression), and labels the message with a destination address (that's typically the logical name of a "mail box", and not an IP address).
The message is passed to the messaging middleware system.
Now the sender application proceeds happily, without needing to wait for the message to be delivered.
Synchronous communication works much like a phone call. The Receiver (callee) must be available, otherwise the conversation cannot occur.
There are many pros and cons about both models, and many details (message priorities, message persistency, forwarding and routing, etc.).
------------------------------

Advantages and disadvantages

AdvantagesDisadvantages
Asynchronous transmission
  • Simple, doesn't require synchronization of both communication sides
  • Cheap, because Asynchronous transmission require less hardware
  • Set-up is faster than other transmissions, so well suited for applications where messages are generated at irregular intervals, for example data entry from the keyboard and the speed depends on different applications.
  • Large relative overhead, a high proportion of the transmitted bits are uniquely for control purposes and thus carry no useful information
Synchronous transmission
  • Lower overhead and thus, greater throughput
  • Slightly more complex
  • Hardware is more expensive

Friday, 16 August 2013

Create your Custome Control

Gradient button


Gradient button c#

add this class in your form.cs

Download Code

public class rakeshButton : System.Windows.Forms.Button
    {
        // declare two color for linear gradient
        private Color cLeft;
        private Color cRight;

        // property of begin color in linear gradient
        public Color BeginColor
        {
            get
            {
                return cLeft;
            }
            set
            {
                cLeft = value;
            }
        }
        // property of end color in linear gradient
        public Color EndColor
        {
            get
            {
                return cRight;
            }
            set
            {
                cRight = value;
            }
        }

        public rakeshButton()
        {
            // Default get system color
            cLeft = SystemColors.ActiveCaption;
            cRight = SystemColors.Control;
        }

        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            // declare linear gradient brush for fill background of Button
            LinearGradientBrush GBrush = new LinearGradientBrush(
                new Point(0, 0),
                new Point(this.Width, 0), cLeft, cRight);
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            // Fill with gradient
            e.Graphics.FillRectangle(GBrush, rect);

            // draw text on label
            SolidBrush drawBrush = new SolidBrush(this.ForeColor);
            StringFormat sf = new StringFormat();
            // align with center
            sf.Alignment = StringAlignment.Center;
            // set rectangle bound text
            RectangleF rectF = new RectangleF(0, this.Height / 2 - Font.Height / 2, this.Width, this.Height);
            // output string
            e.Graphics.DrawString(this.Text, this.Font, drawBrush, rectF, sf);

        }
    }

and declare it

 public partial class Form1 : Form
    {
        private rakeshButton mybutton;


-----------and call this object with class insistilization


 public Form1()
        {
            InitializeComponent();
               

            this.rkbutton = new rakeshButton();
            this.rkbutton.BeginColor = System.Drawing.SystemColors.ActiveCaption;
            this.rkbutton.EndColor = System.Drawing.SystemColors.Control;
            this.rkbutton.Name = "gLabel1";
            this.rkbutton.Font = new Font("Verdana", 12F, FontStyle.Bold);
            this.rkbutton.Size = new System.Drawing.Size(352, 56);
            this.rkbutton.TabIndex = 0;
            this.rkbutton.Text = "Test gradient Button";
            this.Controls.Add(rkbutton);
        }





Thursday, 15 August 2013

Blending

http://www.codeproject.com/Articles/20018/Gradients-made-easy

Blending

With blending, we can define a custom gradient and therefore take control over how the gradient is rendered. Blending allows us to override the normal blending behavior and set points along the path where we define alternate drop off rates. We still go from a start color to an end color, but as you can see in the figure below, the drop off rates at the various positions allow much greater control over the rendering process.
Screenshot - Blend.png
Figure 6. Blending using LinearGradientBrush (left) and PathGradientBrush (right)
A couple of terms are in order here:
  • Position - A point along the gradient path
  • Factor - Drop off rate at the defined position
In Figure 6 above, I have numbered the positions, and combined with the listing below, you will get a better understanding of how blending works. This code is used to produce the right hand drawing in Figure 6.
private void label1_Paint(object sender, PaintEventArgs e)
{
    GraphicsPath gp = new GraphicsPath();
    gp.AddEllipse(label1.ClientRectangle);    

    PathGradientBrush pgb = new PathGradientBrush(gp);
    pgb.FocusScales = new PointF(0f, 0f);

    Blend blnd = new Blend();
    blnd.Positions = new float[] { 0f, .25f, .5f, .75f, 1f };
    blnd.Factors = new float[] { 1f, 0f, 1f, 0f, 1f };
    pgb.Blend = blnd;
    e.Graphics.FillPath(pgb, gp);

    pgb.Dispose();
    gp.Dispose();
}
Both gradients were drawn using the same values, and from what we've learned so far, the outcome is predictable. The only difference being the PathGradientBrush, the positions radiate outward from the center point, and at the positions noted, you can see the transitions made.
Note: There are three things that are very important here:
  1. The number of positions and factors must be the same.
  2. The first position must be 0 and the last 1.
  3. The number of positions, factors, and colors should not exceed the number of points in the graphics point list. If it does, I turn off color blending, or GDI+ throws an exception. (Working on this.)
If either of these conditions is not met, GDI+ will throw an exception.

SocketHelper class will help you to socket Programming


SocketHelper



using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.CompilerServices;


namespace TestIt.helper
{
    public static class SocketHelper
    {
        public static byte[] GetByteArrayFromStructure(byte[] CompleteStructure, int StartPosition, int length)
        {
            byte[] temp = new byte[length];
            for (int ArrayCount = 0; ArrayCount < length; ArrayCount++)
            {
                temp[ArrayCount] = CompleteStructure[StartPosition + ArrayCount];
            }
            return temp;
        }
        public static char[] GetPreciseArrayForString(string Str, int ArraySize)
        {
            Str = Str.Replace('\0', ' ');
            string temp = new string(' ', ArraySize);
            temp = Str + temp;
            temp = temp.Substring(0, ArraySize);
            temp = temp.Replace(' ', '\0');
            return temp.ToCharArray();
        }

        public static byte[] ConvertCharFrom16to8bit1(char[] CharArray)
        {
            byte[] temp = Encoding.ASCII.GetBytes(CharArray);
            return temp;
        }

        public static byte[] GetBytesFromNumbers1(Int16 Number)
        {
            byte[] temp = BitConverter.GetBytes(Number);
            return temp;
        }

        public static byte[] GetBytesFromNumbers1(Int32 Number)
        {
            byte[] temp = BitConverter.GetBytes(Number);
            return temp;
        }
        public static T[] SubArray<T>(this T[] data, int index, int length)
        {
            T[] result = new T[length];
            Array.Copy(data, index, result, 0, length);
            return result;
        }
        public static string ByteString(this byte[] data)
        {
            string Message = Encoding.UTF8.GetString(data, 0, data.Length);
            return Message.Replace('\0', ' ').Trim();
        }
    }
}

Wednesday, 14 August 2013

Using an Asynchronous Client Socket

Using an Asynchronous Client Socket


An asynchronous client socket does not suspend the application while waiting for network operations to complete. Instead, it uses the standard .NET Framework asynchronous programming model to process the network connection on one thread while the application continues to run on the original thread. Asynchronous sockets are appropriate for applications that make heavy use of the network or that cannot wait for network operations to complete before continuing.
The Socket class follows the .NET Framework naming pattern for asynchronous methods; for example, the synchronous Receive method corresponds to the asynchronousBeginReceive and EndReceive methods.
Asynchronous operations require a callback method to return the result of the operation. If your application does not need to know the result, then no callback method is required. The example code in this section demonstrates using a method to start connecting to a network device and a callback method to complete the connection, a method to start sending data and a callback method to complete the send, and a method to start receiving data and a callback method to end receiving data.
Asynchronous sockets use multiple threads from the system thread pool to process network connections. One thread is responsible for initiating the sending or receiving of data; other threads complete the connection to the network device and send or receive the data. In the following examples, instances of theSystem.Threading.ManualResetEvent class are used to suspend execution of the main thread and signal when execution can continue.
In the following example, to connect an asynchronous socket to a network device, the Connect method initializes a Socket and then calls the BeginConnect method, passing a remote endpoint that represents the network device, the connect callback method, and a state object (the client Socket), which is used to pass state information between asynchronous calls. The example implements the Connect method to connect the specified Socket to the specified endpoint. It assumes a global ManualResetEvent namedconnectDone.
public static void Connect(EndPoint remoteEP, Socket client) {
    client.BeginConnect(remoteEP, 
        new AsyncCallback(ConnectCallback), client );

   connectDone.WaitOne();
}

The connect callback method ConnectCallback implements the AsyncCallback delegate. It connects to the remote device when the remote device is available and then signals the application thread that the connection is complete by setting the ManualResetEvent connectDone. The following code implements the ConnectCallback method.
private static void ConnectCallback(IAsyncResult ar) {
    try {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        Console.WriteLine("Socket connected to {0}",
            client.RemoteEndPoint.ToString());

        // Signal that the connection has been made.
        connectDone.Set();
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}

The example method Send encodes the specified string data in ASCII format and sends it asynchronously to the network device represented by the specified socket. The following example implements the Send method.


private static void Send(Socket client, String data) {
    // Convert the string data to byte data using ASCII encoding.
    byte[] byteData = Encoding.ASCII.GetBytes(data);

    // Begin sending the data to the remote device.
    client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
        new AsyncCallback(SendCallback), client);
}

The send callback method SendCallback implements the AsyncCallback delegate. It sends the data when the network device is ready to receive. The following example shows the implementation of the SendCallback method. It assumes a global ManualResetEvent named sendDone.
private static void SendCallback(IAsyncResult ar) {
    try {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;

        // Complete sending the data to the remote device.
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);

        // Signal that all bytes have been sent.
        sendDone.Set();
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}

Reading data from a client socket requires a state object that passes values between asynchronous calls. The following class is an example state object for receiving data from a client socket. It contains a field for the client socket, a buffer for the received data, and a StringBuilder to hold the incoming data string. Placing these fields in the state object allows their values to be preserved across multiple calls to read data from the client socket.

public class StateObject {
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

The example Receive method sets up the state object and then calls the BeginReceive method to read the data from the client socket asynchronously. The following example implements the Receive method.

private static void Receive(Socket client) {
    try {
        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = client;

        // Begin receiving the data from the remote device.
        client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReceiveCallback), state);
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}

The receive callback method ReceiveCallback implements the AsyncCallback delegate. It receives the data from the network device and builds a message string. It reads one or more bytes of data from the network into the data buffer and then calls the BeginReceive method again until the data sent by the client is complete. Once all the data is read from the client, ReceiveCallback signals the application thread that the data is complete by setting the ManualResetEvent sendDone.
The following example code implements the ReceiveCallback method. It assumes a global string named response that holds the received string and a globalManualResetEvent named receiveDone. The server must shut down the client socket gracefully to end the network session.
private static void ReceiveCallback( IAsyncResult ar ) {
    try {
        // Retrieve the state object and the client socket 
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket client = state.workSocket;
        // Read data from the remote device.
        int bytesRead = client.EndReceive(ar);
        if (bytesRead > 0) {
            // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
                //  Get the rest of the data.
            client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                new AsyncCallback(ReceiveCallback), state);
        } else {
            // All the data has arrived; put it in response.
            if (state.sb.Length > 1) {
                response = state.sb.ToString();
            }
            // Signal that all bytes have been received.
            receiveDone.Set();
        }
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}






Socket Programming Concept

Although you can argue that one can overcome these shortcomings by multithreading meaning that one can spawn a new thread and let that thread do the polling and notifies the main thread of the data. Well this concept will work well. But even if you create a new thread it would require your main thread to share the CPU time with this new thread. Windows operating system (Windows NT /2000 /XP) provide what is called Completion Port IO model for doing overlapped ( asynchronous) IO.
The details of IO Completion port are beyond the scope of the current discussion, but to make it simple you can think of IO Completion Ports as the most efficient mechanism for doing asynchronous IO in Windows that is provided by the Operating system. Completion Port model can be applied to any kind of IO including the file read /write and serial communication.   
The .NET asynchronous socket programming helper class's Socket provides the similar model. 

BeginReceive
  
.NET framework's Socket class provides BeginReceive method to receive data asynchronously i.e., in an non-blocking manner The BeginReceive method has following signature: 
public IAsyncResult BeginReceive( byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state );
The way BeginReceive function works is that you pass the function a buffer , a callback function (delegate)   which will be called whenever data arrives.
The last parameter,  object,   to the BeginReceive can be any class derived from object  ( even null ) .
When the callback function is called it means that the BeginReceive function completed which means that the data has arrived.
The callback function needs to have the following signature: 
void AsyncCallback( IAsyncResult ar);
As you can see the callback returns void and is passed in one parameter , IAsyncResult interface , which contains  the status of the asynchronous receive  operation.
The IAsyncResult interface has several properties. The first parameter - AsyncState - is an object which is same as the last parameter that you passed to BeginReceive(). The second  property is AsyncWaitHandle which we will discuss in a moment. The third property indicates whether the receive was really asynchronous or it finished synchronously. The important thing to follow here is that it not necessary for an asynchronous function to always  finish asynchronously - it can complete immediately if the data is already present. Next parameter is IsComplete   which indicates whether the operation has completed or not.
If you look at the signature of the BeginReceive again you will note that the function also returns IAsyncResult. This is interesting. Just now I said that I will talk about the second peoperty of the IAsyncResult  in a moment. Now is that moment. The second parameter is called AsyncWaitHandle.
The AsyncWaitHandle is of type WaitHandle, a class defined in the System.Threading namespace. WaitHandle class encapsulates a Handle (which is a pointer to int or handle ) and provides a way to wait for that handle to become signaled. The class has several static methods like WaitOne ( which is similar to WaitForSingleObject ) WaitAll ( similar to WaitForMultipleObjects with waitAll true ) , WaitAny etc. Also there are overloads of these functions available with timeouts.
Coming back to our discussion of IAsyncResult interface, the handle in AsyncWaitHandle (WaitHandle) is signalled when the receive operation completes. So if we wait on that handle infinitely we will be able to know when the receive completed. This means if we pass that WaitHandle to  a different thread, the different thread can wait on that handle and can notify us of the fact that the data has arrived and so that we can read the data. So you must be wondering if we use this mechanism why would we use callback function. We won't. Thats right. If  we choose to use this mechanism of the WaitHandle then the callback function parameter to the BeginReceive can be null as shown here:
//m_asynResult is  declared of type IAsyncResult and assumming that m_socClient has made a connection.
m_asynResult = m_socClient.BeginReceive(m_DataBuffer,0,m_DataBuffer.Length,SocketFlags.None,null,null);
if ( m_asynResult.AsyncWaitHandle.WaitOne () )
{
int iRx = 0 ;
iRx = m_socClient.EndReceive (m_asynResult);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
txtDataRx.Text = txtDataRx.Text + szData;
}
Even though this mechanism will work fine using multiple threads, we will for now stick to our callback mechanism where the system notifies us of the completion of asynchronous operation which is Receive in this case .
Lets say we made the call to BeginReceive and after some time the data arrived and our callback function got called.Now question is where's the data? The data is now available in the buffer that you passed as the first parameter while making call to BeginReceive() method . In the following example the data will be available in m_DataBuffer :
BeginReceive(m_DataBuffer,0,m_DataBuffer.Length,SocketFlags.None, pfnCallBack,null);
But before you access the buffer you need to call EndReceive() function on the socket. The EndReceive will return the number of bytes received . Its not legal to access the buffer before calling EndReceive.
To put it all together  look at the following simple code:
byte[] m_DataBuffer = new byte [10];
IAsyncResult m_asynResult;
public AsyncCallback pfnCallBack ;
public Socket m_socClient;
// create the socket...
public void OnConnect()
{
m_socClient = new Socket (AddressFamily.InterNetwork,SocketType.Stream ,ProtocolType.Tcp );
// get the remote IP address...
IPAddress ip = IPAddress.Parse ("10.10.120.122");
int iPortNo = 8221;
//create the end point
IPEndPoint ipEnd = new IPEndPoint (ip.Address,iPortNo);
//connect to the remote host...
m_socClient.Connect ( ipEnd );
//watch for data ( asynchronously )...
WaitForData();
}
public void WaitForData()
{
if ( pfnCallBack == null )
pfnCallBack = new AsyncCallback (OnDataReceived);
// now start to listen for any data...
m_asynResult =
m_socClient.BeginReceive (m_DataBuffer,0,m_DataBuffer.Length,SocketFlags.None, pfnCallBack,null);
}
public void OnDataReceived(IAsyncResult asyn)
{
//end receive...
int iRx = 0 ;
iRx = m_socClient.EndReceive (asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
WaitForData();
}


The OnConnect function makes a connection to the server and then makes a call to WaitForData. WaitForData creates the callback function and makes a call to BeginReceive passing a global buffer and the callback function. When data arrives the OnDataReceive is called and the m_socClient's EndReceive is called which returns the number of bytes received and then the data is copied over to a string and a new call is made to WaitForData which will call BeginReceive again and so on.  This works fine if you have one socket in you application.  

MULTIPLE SOCKETS
Now lets say you have two sockets connecting to either two different servers or same server(which is valid) . One way is to create two different delegates and attach a different delegate to different BeginReceive function. What if you have 3 sockets or for that matter n sockets , this approach of creating multiple delegates does not fit well in such cases. So the solution should be to use only one delegate callback. But then the problem is how do we know what socket completed the operation.
Fortunately there is a better solution. If you look at the BeginReceive function again, the last parameter is  a state is an object. You can pass anything here . And whatever you pass here will be passed back to you later as the part of parameter to the callback function. Actually this object will be passed to you later as a IAsyncResult.AsyncState. So when your callback gets called, you can use this information to identify the socket that completed the operation. Since you can pass any thing to this last parameter, we can pass a class object that contains as much information as we want. For example we can declare a class as follows:
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
and call BeginReceive as follows:
CSocketPacket theSocPkt = new CSocketPacket ();
theSocPkt.thisSocket = m_socClient;
// now start to listen for any data...
m_asynResult = m_socClient.BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length , SocketFlags.None,pfnCallBack,theSocPkt);
and in the callback function we can get the data like this:
public void OnDataReceived(IAsyncResult asyn)
{
  try
  {
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
//end receive...
int iRx = 0 ;
iRx = theSockId.thisSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
txtDataRx.Text = txtDataRx.Text + szData;
WaitForData();
  }
  catch (ObjectDisposedException )
  {
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
  }
  catch(SocketException se)
  {
MessageBox.Show (se.Message );
  }
}
To see the whole application download the code and you can see the code.

There is one thing which you may be wondering about. When you call BeginReceive , you have to pass a buffer and the number of bytes to receive. The question here is how big should the buffer be. Well, the answer is it depends. You can have a very small buffer size say, 10 bytes long and if there are 20 bytes ready to be read, then you would require 2 calls to receive the data. On the other hand if you specify the length as 1024 and you know you are always going to receive data in 10-byte  chunks you are unnecessarily wasting memory. So the length depends upon your application.

Server Side
If you have understood whatever I have described so far, you will easily understand the Server part of the socket application. So far we have been talking about a client making connection to a server and sending and receiving data.
On the Server end, the application has to send and receive data. But in addition to adding and receiving data, server has to allow the clients to make connections by listening at some port. Server does not need to know client I.P. addresses. It really does not care where the client is because its not the server but client who is responsible for making connection. Server's responsibility is to manage client connections.

On the server side there has to be one socket called the Listener socket that listens at a specific port number for client connections. When the client makes a  connection, the server needs to accept the connection and then in order for the server to send and receive data from that connected client it needs to talk to that client through the socket that it got when it accepted the connection . Following code illustrates how server listens to the connections and accepts the connection:
public Socket m_socListener;
public void StartListening()
{
 try
 {
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
//bind to local IP Address...
m_socListener.Bind( ipLocal );
//start listening...
m_socListener.Listen (4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
cmdListen.Enabled = false;
 }
 catch(SocketException se)
 {
MessageBox.Show ( se.Message );
 }
}
If you look at the above code carefully you will see that its similar to  we did in the asynchronous client. First of all the we need to create a listening socket and bind it to a local IP address. Note that we have given Any as the IPAddress . I will explain what it means later. and also we have passed port number as 8221. Next we made a call to Listen function. The 4 is a parameter indicating backlog indicating the maximum length of the queue of pending connections.
Next we made a call to BeginAccept passing it a delegate callback. BeginAccept is a non-blocking method that returns immediately and when a client has made requested a connection, the callback routine is called and you can accept the connection by calling EndAccept. The EndAccept returns a socket object which represents the incoming connection. Here is the code for the callback delegate:
public void OnClientConnect(IAsyncResult asyn)
{
try
{
  m_socWorker = m_socListener.EndAccept (asyn);
WaitForData(m_socWorker);
}
catch(ObjectDisposedException)
{
             System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show ( se.Message );
}
}
Here we accept the connection and call WaitForData which in turn calls BeginReceive for the m_socWorker.

If we want to send data  some data to client we use m_socWorker socket for that purpose like this:
Object objData = txtDataTx.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
m_socWorker.Send (byData);
Here is how our client looks like
Here is how our server looks like
That is all there is to the socket programming. 

Read more at http://www.devarticles.com/c/a/C-Sharp/Socket-Programming-in-C-sharp-Part-II/1/#dMdpCjIYbEVGwxK4.99 
- See more at: http://www.devarticles.com/c/a/C-Sharp/Socket-Programming-in-C-sharp-Part-II/1/#sthash.XoywZviW.dpuf

Saturday, 3 August 2013

option premium

option premium


The amount per share that an option buyer pays to the seller. The option premium is primarily affected by the difference between the stock price and the strike price, the time remaining for the option to be exercised, and the volatility of the underlying stock. Affecting the premium to a lesser degree are factors such as interest rates, market conditions, and the dividend rate of the underlying stock. Because the value of an option decreases as its expiration date approaches and becomes worthless after that date, options are called wasting assets. The total value of an option consists of intrinsic value, which is simply how far in-the-money an option is, andtime value, which is the difference between the price paid and the intrinsic value. Understandably, time value approaches zero as the expiration date nears. also called option price.

Read more: http://www.investorwords.com/3487/option_premium.html#ixzz2ataCa0Po