Skip to main content

Example - Chat Application

1. Create a WCF Service library project

  • Open Visual Studio > File New Project
  • Select WCF Service Library template under Visual C# > WCF templates
  • Change the name to ChatServiceLibrary and click OK
    • Visual studio will add reference to System.ServiceModel and System.Runtime.Serialization and will add some files with sample code. 
  • Delete IService1.cs and Service1.cs and add a new class called ChatService

1.1 Create the Data Contract 

  • Open ChatService.cs file that you created.
  • Add using System.ServiceModel;
  • Add using System.Runtime.Serialization;
  • Add the following code above ChatService class
   [DataContract]
    public class ChatMsg
    {
        public ChatMsg() { }
        public ChatMsg(string n, string m){ this.User = n; this.Msg = m;}
      
        [DataMember]
        public string User;
        [DataMember]
        public string Msg;
    }

1.2 Create the Service Contract 

  • Add the following code
   [ServiceContract]
    public interface IChatService
    {
        [OperationContract(IsOneWay=true)]
        void Notify(ChatMsg msg);
    }

    [ServiceContract(CallbackContract = typeof(IChatService))]
    public interface IChatAdmin
    {
        [OperationContract(IsOneWay = true)]
        void Register(string name);
        [OperationContract(IsOneWay = true)]
        void Submit(ChatMsg msg);
    }

1.3 Service Implementation

  • Add the following code in the ProductService.cs class
public class ChatService : IChatService
    {
        public void Notify(ChatMsg m)
        {
            Console.WriteLine("{0}: {1}", m.User, m.Msg);
        }
    }

    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class ChatAdminService : IChatAdmin
    {
        Dictionary<string, IChatService> clients = new Dictionary<string, IChatService>();

        public void Register(string user)
        {
            IChatService client = OperationContext.Current.GetCallbackChannel<IChatService>();
            if (client != null)
                clients.Add(user, client);
            Console.WriteLine("{0}has joined.", user);
        }

        public void Submit(ChatMsg m)
        {
            foreach (string key in clients.Keys)
            {
                try
                {
                    if (!m.User.Equals(key))
                        clients[key].Notify(m);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
    }

1.4 Service endpoints 

  • Updated the name of the service in App.config as given below:
    <service name="ChatService.ChatAdminService">
  • Updated the contract in the endpoint of the service in App.config as given below:
<endpoint address="" binding="wsDualHttpBinding" contract                   ="ChatService.IChatAdmin">
     


    1.5 Test Service 

    • Build the Service. 

    2. Create a Service Host

    1. Add a new project to the current solution: Right click Solution on Solution Explorer > Add > Add New Project > Select Console Application template under Visual C# > Windows templates
    2. Change the project name to Host and click OK
    3. In Solution Explorer, under Host project, right click References and select Add Reference... 
    4. In the Reference Manager window, add reference to System.ServiceModel and to ChatServiceLibrary solution
    5. Add using System.ServiceModel;
    6. Add using ProductServiceLibrary;
    7. Add the following code in Program.cs file
    class Program
        {
            static void Main(string[] args)
            {
                ServiceHost host = new ServiceHost(typeof(ChatAdminService));

                try
                {
                    host.Open();
                    Console.ReadKey();
                    host.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    host.Abort();
                    
                }
                Console.ReadKey();
            }
        }

    2.1 Configure Service and Service Endpoints

    1. Right click on App.config > Edit WCF Configuration > under services summary click Create a New Service... 
    2. click browse, go out of the current folder, select ChatServiceLibrary > bin > Debug > ChatServiceLibrary.dll > ChatServiceLibrary.ChatService. Click next.
    3. Keep the default ChatServiceLibrary.IChatAdmin contract and click next. 
    4. Keep the default selection HTTP and click next. 
    5. Select Advanced Web Services interoperability and select Duplex Communication click next 
    6. For address type http://localhost:8733/Design_Time_Addresses/ChatServiceLibrary/ChatService/duplex and click Next and then click Finish
    7. Save and Exit Microsoft Service Configuration Editor
    8. Right click on the Host project and Set as StartUp project.
    9. Right click on ChatServiceLibrary project > properties >  WCF Options > Uncheck Start WCF Service Host when debugging another project in the same solution
    10. Run Service Host

    3. Create Chat Client

    1. Add a new project to the current solution: Right click Solution on Solution Explorer > Add > Add New Project > Select Console Application template under Visual C# > Windows templates
    2. Change the project name to Client and click OK
    3. In Solution Explorer, under Client project, right click References and select Add Service Reference... 
    4. In the Program.cs file, add using System.ServiceModel; and using ChatServiceLibrary;
    5. Add the following code

        class Program
        {
            static void Main(string[] args)
            {
                Console.Write("user name:");
                string user = Console.ReadLine();

                DuplexChannelFactory<IChatAdmin> factory = new DuplexChannelFactory<IChatAdmin>(new ChatService(), "ChatMgr");
                IChatAdmin admin = factory.CreateChannel();
                
                admin.Register(user);

                Console.WriteLine("{0} joined.\n",user);
                string msg = Console.ReadLine();
                while (!msg.Equals("exit"))
                {
                    admin.Submit(new ChatMsg(user, msg));
                    msg = Console.ReadLine();
                }
            }
        }


    3.1 Add endpoint


    1. Right click on App.config > Edit WCF Configuration > under Configuration select Client, under Client section > click Create a New Client...   
    2. select the option Manually
    3. click browse, go out of the current folder, select ChatServiceLibrary > bin > Debug > ChatServiceLibrary.dll > ChatServiceLibrary.IChatAdmin. Click next.
    4. Keep the default ChatServiceLibrary.IChatAdmin contract and click next. 
    5. Keep the default selection HTTP and click next. 
    6. Select Advanced Web Services interoperability and select Duplex Communication click next 
    7. For address type http://localhost:8733/Design_Time_Addresses/ChatServiceLibrary/ChatService/duplex and click Next 
    8. Type ChatMgr as the name and then click Next, click Finish
    9. Save and Exit Microsoft Service Configuration Editor.

    4. Testing the Application  

    1. Set the Host project as the startup project 
    2. Press F5 or Start button 
    3. While the Host application is running, go to solution explorer > right click Client > debug > Start New Instance
    4. Repeat the step 3 two more times. 
    5. Now you should have 4 console windows. One host and three clients. Test the application. 

    Comments

    Popular posts from this blog

    A Comprehensive Evaluation of the Internal Consulting Process: Steps and Considerations

    Introduction Internal consulting has emerged as a critical function within organizations, offering in-house expertise to solve complex business problems and drive change. It closely mirrors external consulting in methodology but is differentiated by the consultant's intimate knowledge of the organization and a vested interest in its long-term success. This article aims to evaluate the key steps involved in the internal consulting process, offering insights into each phase's significance and challenges. Steps in the Internal Consulting Process The internal consulting process can generally be segmented into five distinct stages: Initial Assessment, Data Collection and Analysis, Solution Development, Implementation, and Evaluation. Below is an evaluation of each step: Step 1: Initial Assessment Objective: To understand the problem or opportunity area and define the scope of the project. Significance: A well-defined scope ensures that the consulting project stays focused and manage...

    The Evolving Landscape of Consulting Practice: Changes and Implications

    Introduction Consulting is a field that thrives on its ability to adapt to market demands and emerging trends. As businesses evolve due to technological advancements, shifts in consumer behavior, and fluctuations in global markets, consulting practices must keep pace. This article explores some of the significant changes currently transforming the consulting industry and discusses their implications for both consultants and clients. Technological Disruption Data Analytics and Artificial Intelligence Consulting firms are increasingly integrating data analytics and artificial intelligence into their service offerings. These technologies allow consultants to offer data-driven insights that can significantly enhance strategic decision-making. This evolution means consultants now need skills in data interpretation and analysis, alongside their traditional expertise in business strategy. Virtual Consulting Platforms The advent of digital platforms enables consulting services to be offered re...

    The Imperative of Transition Structure in Implementing Change and A Model for Effective Transition

    Introduction Organizational change is an inevitable phenomenon in the dynamic business landscape of today. While the conception of change is significant, its successful implementation is even more crucial. One key factor that often determines the success of implementing change is the presence of a well-designed transition structure. This article aims to discuss the necessity of having a transition structure in place and proposes a model to effectively guide the transition during organizational change. The Need for a Transition Structure Aligning Stakeholders Any significant change involves a variety of stakeholders, from senior management to front-line employees. A transition structure ensures that all parties are aligned, understand their roles, and are committed to the objectives of the change. Mitigating Risks Change often comes with risks, such as resistance from employees, potential loss in productivity, or lapses in quality. A structured approach can help mitigate these risks by ...