How To Build Client-Server Architecture Using Self Hosted WCF Service And WPF Client

In this blog, I am going to illustrate a Client-Server architecture to have a server-side as a self-hosted service using WCF,  consumed by WPF client.
 
Let's take an XBox game example here, where the requirement is to develop a service to provide a list of games (name, description, and rating) and allow the user to rate each game from the UI. We will break this into two parts. The first part is to create a server-side service to provide a list of Games and the second part is to consume the same service at the UI side developed using WPF platform. I will not be using any database here on the server-side to get data from the database (only static data is used). If you want to use entity framework to create the table etc., you can refer to this article which explains how to create SQL database and work around it.
 
Let's start with Visual Studio to create three .NET projects:
  • Game class i.e. DataContract and Datamemeber (.net class library project).
  • Game Service i.e. ServiceContract and OperationContract (.net class library project, refer to the first project). 
  • and the third one is a console application to host game service (console application using .net framework). 
With this design, we are trying to break into multiple layers, i.e., Database, service layer and hosting service. Let's start one by one in detail with a code snippet.
 
Server-side model objects could be your persistent object. Here, you can add your DB layer to load an object from the database and mark as datacontra.
 
Here is the game class server model object. 
  1. [DataContract]  
  2.     public class XboxGame  
  3.     {  
  4.         [DataMember]  
  5.         public string Title { getset; }  
  6.   
  7.         [DataMember]  
  8.         public string Description { getset; }  
  9.   
  10.         [DataMember]  
  11.         public int Rating { getset; }  
  12.   
  13.         public XboxGame()  
  14.         {  
  15.         }  
  16.     }  
Second step is to define Service and operation contract.
  1. [ServiceContract]  
  2.     public interface IGameService  
  3.     {  
  4.         [OperationContract]  
  5.         IList<XboxGame> GetGames();  
  6.   
  7.         [OperationContract]  
  8.         void Update(XboxGame g);  
  9.     }  
Implementation of Service,
  1. public class GameService : IGameService  
  2.     {  
  3.         // DB layer can be added to get the data.  
  4.         static List<XboxGame> games = new List<XboxGame>()  
  5.         {  
  6.             new XboxGame() { Title = "Games of thrones", Description = "Games of.......", Rating = 5 },  
  7.             new XboxGame() { Title = "Step Up for kinnect", Description = "Integer.......", Rating = 1 },  
  8.             new XboxGame() { Title = "Dead island", Description = "Viamurs.......", Rating = 3 }  
  9.         };  
  10.   
  11.   
  12.         public void Update(XboxGame g)  
  13.         {  
  14.             var game = games.FirstOrDefault(s => s.Title == g.Title);  
  15.             if (game != null)  
  16.             {  
  17.                 game.Description = g.Description;  
  18.                 game.Rating = g.Rating;  
  19.             }  
  20.         }  
  21.   
  22.         public IList<XboxGame> GetGames()  
  23.         {  
  24.             return games;  
  25.         }  
  26.     }  
And the final step to is host the service using TCP binding and define the base address in config file and contract. You can find many articles on the ABCs of WCF and here is one of them from c# corner. Here is the implementation of the self hosting service.
  1. static void Main(string[] args)  
  2.        {  
  3.            using (ServiceHost host = new ServiceHost(typeof(GameService)))  
  4.            {  
  5.                // adding behaviour from code instead of defining in config file.  
  6.                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior { HttpGetEnabled = true };  
  7.                host.Description.Behaviors.Add(behavior);  
  8.   
  9.                // adding end point from code.  
  10.                host.AddServiceEndpoint(typeof(IGameService), new NetTcpBinding { Security = { Mode = SecurityMode.None } }, nameof(GameService));  
  11.   
  12.                host.Open();  
  13.                Console.WriteLine("GameService hosted");  
  14.                Console.WriteLine("Press any key to stop service");  
  15.                Console.ReadKey();  
  16.            }  
  17.        }  
Build and run the host.exe to launch the service. Once the service is hosted successfully you should check the url of this service, default service url should be using 9950 port and this is the url for this example: "net.tcp://localhost:9950/GameService". Now, we can start the second part of this article; i.e., creating client and consuming the above service. Let's create a new VS project for WPF Windows Application to consume the service using MVVM pattern.
 
The first step isa to create a proxy channel for wcf game service. Once proxy object is created you can make as many calls via that service to get the data as you wish. Currently I am setting security as none in all places, I will take full security as another article to explain how security can be implemented in these types of applications using Public/Private keys.
 
Here is code to create proxy of Service to get the data from the server. 
  1. public class ServiceFactory<T> where T : class  
  2.     {  
  3.         private T _service;  
  4.   
  5.         public T GetService(string address)  
  6.         {  
  7.             return _service ?? (_service = GetServiceInstance(address));  
  8.         }  
  9.   
  10.         private static T GetServiceInstance(string address)  
  11.         {  
  12.             var binding = new NetTcpBinding();  
  13.             binding.Security.Mode = SecurityMode.None;  
  14.             EndpointAddress endpoint = new EndpointAddress(address);  
  15.   
  16.             return ChannelFactory<T>.CreateChannel(binding, endpoint);  
  17.         }  
  18.     }  
The second step is to create view Model for Game Model object and Bind this view model with xmal.
 
Here, we need to two view models, one for collection; i.e., Full view, and another view model is to represent each game in every row.
  1. public class GamesViewModel  
  2.    {  
  3.        private readonly IGameService service;  
  4.   
  5.        public GamesViewModel()  
  6.        {  
  7.            GameList = new ObservableCollection<GameViewModel>();  
  8.            var serviceFactory = new ServiceFactory<IGameService>();  
  9.            service = serviceFactory.GetService("net.tcp://localhost:9950/GameService");  
  10.            var games = service.GetGames();  
  11.            foreach (var game in games)  
  12.            {  
  13.                GameList.Add(new GameViewModel(game, this));  
  14.            }  
  15.        }  
  16.   
  17.        public ObservableCollection<GameViewModel> GameList { getset; }  
  18.   
  19.        public void UpdateProperty(GameViewModel gameViewModel)  
  20.        {  
  21.            service.Update(gameViewModel.Model);  
  22.        }  
  23.    }  
  24.   
  25.    public class RelayCommand : ICommand  
  26.    {  
  27.        private Action<object> execute;  
  28.        private Func<objectbool> canExecute;  
  29.   
  30.        public event EventHandler CanExecuteChanged  
  31.        {  
  32.            add { CommandManager.RequerySuggested += value; }  
  33.            remove { CommandManager.RequerySuggested -= value; }  
  34.        }  
  35.   
  36.        public RelayCommand(Action<object> execute, Func<objectbool> canExecute = null)  
  37.        {  
  38.            this.execute = execute;  
  39.            this.canExecute = canExecute;  
  40.        }  
  41.   
  42.        public bool CanExecute(object parameter)  
  43.        {  
  44.            return this.canExecute == null || this.canExecute(parameter);  
  45.        }  
  46.   
  47.        public void Execute(object parameter)  
  48.        {  
  49.            this.execute(parameter);  
  50.        }  
  51.    }  
  1. public class GameViewModel : INotifyPropertyChanged  
  2.     {  
  3.         public RelayCommand ClickEventHandler { getprivate set; }  
  4.   
  5.         private readonly GamesViewModel _parent;  
  6.         private string description;  
  7.         private int rating;  
  8.   
  9.         public XboxGame Model;  
  10.   
  11.         public string Description  
  12.         {  
  13.             get { return description; }  
  14.             set  
  15.             {  
  16.                 if (description != value)  
  17.                 {  
  18.                     description = value;  
  19.                     Model.Description = value;  
  20.                     _parent.UpdateProperty(this);  
  21.                     OnPropertyChanged(nameof(Description));  
  22.                 }  
  23.             }  
  24.         }  
  25.   
  26.         public int Rating  
  27.         {  
  28.             get { return rating; }  
  29.             set  
  30.             {  
  31.                 if (rating != value)  
  32.                 {  
  33.                     rating = value;  
  34.                     Model.Rating = value;  
  35.                     _parent.UpdateProperty(this);  
  36.                     OnPropertyChanged(nameof(Rating1));  
  37.                     OnPropertyChanged(nameof(Rating2));  
  38.                     OnPropertyChanged(nameof(Rating3));  
  39.                     OnPropertyChanged(nameof(Rating4));  
  40.                     OnPropertyChanged(nameof(Rating5));  
  41.                 }  
  42.             }  
  43.         }  
  44.   
  45.         public bool Rating1 => Model.Rating >= 1;  
  46.   
  47.         public bool Rating2 => Model.Rating >= 2;  
  48.   
  49.         public bool Rating3 => Model.Rating >= 3;  
  50.   
  51.         public bool Rating4 => Model.Rating >= 4;  
  52.   
  53.   
  54.         public bool Rating5 => Model.Rating >= 5;  
  55.   
  56.         public GameViewModel(XboxGame model, GamesViewModel parent)  
  57.         {  
  58.             Model = model;  
  59.             ClickEventHandler = new RelayCommand(OnRatingClick);  
  60.             _parent = parent;  
  61.             description = model.Description;  
  62.             rating = model.Rating;  
  63.         }  
  64.   
  65.         private void OnRatingClick(object obj)  
  66.         {  
  67.             this.Rating = int.Parse(obj.ToString());  
  68.         }  
  69.   
  70.         public event PropertyChangedEventHandler PropertyChanged;  
  71.   
  72.         [NotifyPropertyChangedInvocator]  
  73.         protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)  
  74.         {  
  75.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  76.         }  
  77.     }  
I hope you liked this blog. Let me know about any questions you might have in the comments section. Thanks!