27 September 2013

Chat using WCF

Hi Friends,

Let see how can we create Chat app using WCF.  This is the basic app we can modify a lot in this sample project.  Its just a sample. You can download the sample from here.

1.  First create the WCF Services Library project in Visual Studio and give a name (FirstWCF).


2. Delete the pre-created files IServices1.cs and Services.cs
3. Add a class into project and named it (Message) and paste the following code. I will use it as a message object to communicate and transfer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace FirstWCF
{
  [DataContract]
  public class Message
  {
     [DataMember]
     public string toUser;
     [DataMember]
     public string fromUser;
     [DataMember]
      public string msg;
  }
}
4. Add another class into project and named it (ISendMsg) and make it interface by paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceContract]
  public interface ISendMsg
  {
     [OperationContract]
     string SendMsg(Message msg);
     [OperationContract]
     List getAllMsg(string toUser);
     [OperationContract]
     List getSentItem(string fromUser);
     [OperationContract]
     string DeleteMsgFrom(string fromUser, string toUser);
  }
}
5. Add another class into project and named it(MsgCollection), it implement the interface defined in previous step.  I implement the method define in interface. Paste the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace FirstWCF
{
  [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
  class MsgCollection:ISendMsg
  {
  List<Message> AllMsgs = new List<Message>();
  public string SendMsg(Message msg)
  {
      try
      {
        AllMsgs.Add(msg);
        return "Message Send Successfully..!!";
      }
      catch (Exception e)
      {
        return "Message Failed..!!";
      }
    }

    public List<Message>  getAllMsg(string toUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if(msg.toUser.Equals(toUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public List<Message> getSentItem(string fromUser)
    {
      List<Message> filterMsgs = new List<Message>();
      foreach (Message msg in AllMsgs)
      {
        if (msg.fromUser.Equals(fromUser))
        {
          filterMsgs.Add(msg);
        }
      }
      return filterMsgs;
    }

    public String DeleteMsgFrom(string fromUser, string toUser)
    {
      try
      {
        AllMsgs.RemoveAll(e => (e.fromUser.Equals(fromUser) && e.toUser.Equals(toUser)));
        return "Message deleted successfully..!!!";
      }
      catch (Exception e)
      {
        return "Deleting message failed..!!!";
      }
    }    
  }
}
6.  Now you can run it, but it will open a client provided by Microsoft to test the WCF apps. But I would say to design you own client and use that to test this chatting application.
7. Right click the project solution file in project explorer in Visual Studio and Add -> Project->Console Application give name (ClientForFirstWCF) to project and click OK.
8. Now you need to add the reference of WCF you created, for that you must know the metadata exchange URL. You can get it from the App.config file under the FirstWCF project you created.
..
..
<host>
  <baseAddresses>
    <add baseAddress="http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/" />
  </baseAddresses>
</host>
..
..
get this baseAddress and add "mex" at all this would be your metadata exchange URL
http://localhost:8732/Design_Time_Addresses/FirstWCF/Service1/mex
9. Now we need to add reference of this WCF to the client project we created in Step 7.
   Right click ClientForFirstWCF project and say 'Add Service Reference' and provide the URL of metadata exchange we found in previous step. Select the Service found on that URL and click Ok.
10. Open Program.cs file of client project and overwrite with following content.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClientForFirstWCF.MsgCollectionServices;

namespace ClientForFirstWCF
{
  class Program
  {
    static string loginName = "";
    static SendMsgClient client = new SendMsgClient("WSHttpBinding_ISendMsg");
    static void Main(string[] args)
    {
      try
      {
        client.Open();      
        int choice=0;
        bool flag = true;
        do
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("");
          Console.Write("Enter Your name : ");
          loginName = Console.ReadLine();
        } while (loginName.Length == 0);
      
        while (flag)
        {
          Console.Clear();
          Console.WriteLine("--------- WCF messaging --------");
          Console.WriteLine("Hello " + loginName);
          Console.WriteLine("");
          Console.WriteLine("Enter You Choice..");
          Console.WriteLine("1. Compose");
          Console.WriteLine("2. Inbox");
          Console.WriteLine("3. Sent Item");
          Console.WriteLine("4. Delete Messages");
          Console.WriteLine("5. Exit");
          Console.Write("Your Choice : ");
          try
          {
            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
              case 1:
                SendMsg();
                break;
              case 2:
                ReadMsg();
                break;
              case 3:
                SentItem();
                break;
              case 4:
                DeleteMsg();
                break;
              default:
                flag = false;
                break;
            }
          }
          catch (Exception e)
          {
          }          
        }

        client.Close();
      }
      catch (Exception e)
      {
        Console.WriteLine("Sorry.!!WCF is down. Please set it up and running.");
        Console.ReadKey();
      }      
    }

    static void SendMsg()
    {
      Message msg = new Message();
      msg.fromUser = loginName;
      msg.toUser="";
      msg.msg = "";
      do
      {
        Console.Clear();
        Console.Write("To : ");
        msg.toUser = Console.ReadLine();
      } while (msg.toUser.Length == 0);
      
      do
      {
        Console.Write("Content : ");
        msg.msg = Console.ReadLine();
      } while (msg.msg.Length == 0);

      //sending message 
      Console.WriteLine(client.SendMsg(msg));
      Console.ReadLine();
    }


    static void ReadMsg()
    {
      Console.Clear();
      Message []all = client.getAllMsg(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("From :"+msg.fromUser);
        Console.WriteLine("Content :"+msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void SentItem()
    {
      Console.Clear();
      Message[] all = client.getSentItem(loginName);
      foreach (Message msg in all)
      {
        Console.WriteLine("To :" + msg.toUser);
        Console.WriteLine("Content :" + msg.msg);
        Console.WriteLine();
      }
      Console.ReadLine();
    }

    static void DeleteMsg()
    {
      string fromUser="";
      do
      {
        Console.Clear();
        Console.WriteLine("Delete the message came from User");
        Console.Write("Enter the User Name : ");
        fromUser = Console.ReadLine();
      } while (fromUser.Length == 0);
      
      Console.WriteLine(client.DeleteMsgFrom(fromUser, loginName));
      Console.ReadLine();
    }
  }
}
11. Now if you try to run the WCF project it will again open the default Microsoft client, so you have to assign your own client. Select your WCF project -> right click -> Properties -> Debug and change the command line argument
/client:"../../../ClientForFirstWCF/bin/debug/ClientForFirstWCF.exe"

12. Congratulation you have created the chat app using WCF. Its basic chat you can still modify it.

You can download the sample from here.
Output - 
When I start two client (deepak and gaurav)to communicate to each other (send/receive message)

When first client(deepak) send the message to second client(gaurav)


When second client(gaurav) check his Inbox

Happy Coding.. :)


No comments:

Post a Comment