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

    CUMIPMT and CUMPRINC function

    CUMIPMT Cumulative interest payment function allows you to calculate the interest paid for a loan or from an investment from period A to period B. When getting a loan, CUMIPMT function can be used to calculate the total amount of interest paid in the first five months or from period 12 to period 20. A period can be a month, a week or two week. Loan Amount : 350,000.00 APR: 4.5% Down payment: 0.00 Years: 25 Payment per year: 12 From the above data, we can calculate the following: No of Period: 25 × 12 = 300 Periodic Rate: 4.5/12 = 0.375% Here is how you will substitute these values into the function. = CUMIPMT (periodic rate, No of period, vehicle price, start period, end period,  ) = CUMIPMT (0.375, 300, 350000, 1, 5, 0) In an excel worksheet, we use cell address instead of actual values as shown below: Here is the formula view of the worksheet: CUMPRINC Another related function is CUMPRINC. CUMPRINC function is used to calculate cumul

    Excel PMT Function

    PMT function is very useful for calculating monthly payment required to payback a loan or mortgage at a fixed rate. This function require a minimum of three inputs, periodic rate, number of periods, present value or the loan amount. Here is a simple example. Home Loan: 350,000.00 Interest rate: 4.5% Number of years to repay the loan: 25 Note: To calculate monthly payment, we need to find the monthly rate and number of months as shown above. Then it is simply a matter of substituting the values into the payment function, as shown in the formula view below.

    BCG's Brand Advocacy Index

    The Boston Consulting Group's (BCG) Brand Advocacy Index (BAI) is a metric developed to help companies measure the degree of customer advocacy for their brands. BAI focuses on the likelihood of customers to recommend a brand to others, which is a powerful indicator of brand strength and customer loyalty. Unlike other customer satisfaction or loyalty metrics, BAI emphasizes the importance of customer referrals and word-of-mouth marketing. BAI is calculated based on a survey where customers are asked about their willingness to recommend a brand to their friends, family, or colleagues. The responses are then used to compute a score, which ranges from -100 to 100. A higher BAI score indicates that a brand has more advocates who are likely to recommend the brand to others, while a lower score suggests that the brand has fewer advocates or even a higher number of detractors. BCG's research has shown that companies with higher BAI scores tend to experience higher growth rates and bett