Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1577

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T09:26:07+00:00 2024-11-25T09:26:07+00:00

How to build the Client-Server Architecture using Self Hosted WCF Service and WPF Client?

  • 62k

What is a self-hosted WCF service?

Self-hosting is the simplest way to host your services and a Self-hosted is that it hosts the service in an application that could be a Console Application or Window Forms, etc.

Image description

Ways to host the WCF service.

  1. Hosting in Internet Information Services (IIS).
  2. Hosting in Console or Desktop Application (Self-hosting).

WCF service has two types of zones.

  1. Services
  2. Clients
  3. ### Services

Some steps to create live services.

  1. Define a service contract
  2. Implement a service contract
  3. Host and run a service contract

Clients

There are three steps to communicate between WCF Client and service.

  • Create a WCF Clien
  • Configure a WCF Client.
  • Use a WCF Client.

Now, let’s see the steps to create a project.

Step: 1
Open visual studio, and create new project. After project creation, open solution explorer and right-click on the project name and click Add -> New Item -> and select WCF Service Library, this will be creating two files here CompanyClass and ICompanyClass are those two files.

Step: 2
Now, we can add a Service contract and Data contract. Service contract for Operation contract and Data contract for data members.

Here is a Company class model.

using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Runtime.Serialization; usingSystem.Text; usingSystem.Threading.Tasks; namespaceWCFExample {   [DataContract] publicclassCompanyClass   {     [DataMember] publicstring CompanyName { get; set; }     [DataMember] publicstring Address { get; set; }     [DataMember] publicintCompanyYear{ get; set; } publicCompanyClass()     {     }   } }  
Enter fullscreen mode Exit fullscreen mode

Now, add the Service contract and Operation contract.

using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.ServiceModel; usingSystem.Text; usingSystem.Threading.Tasks; namespaceWCFExample {   [ServiceContract] publicinterfaceICompanyService   {     [OperationContract] IList<companyclass>companyClasses();     [OperationContract] voidUpdate(CompanyClass cc);   } } </companyclass>  
Enter fullscreen mode Exit fullscreen mode

Read More: What Are The Different Ways Of Binding In Wpf?

Step: 3
Now, we have to implement a service in our class.

using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceWCFExample { publicclassAddServices :ICompanyService   { static List<companyclass>companyClasses = new List<companyclass>()       {     newCompanyClass() {CompanyName="Ifour", Address="Thaltej", CompanyYear=30},     newCompanyClass() {CompanyName="TCS", Address="AgoraMall", CompanyYear=20},     newCompanyClass() {CompanyName="Tencent", Address="S.G.Highway", CompanyYear=10},     newCompanyClass() {CompanyName="TensorFlow", Address="Sola", CompanyYear=15},     newCompanyClass() {CompanyName="Stridly", Address="Shivranjani", CompanyYear=14},       }; publicvoidUpdate(CompanyClass cc) {     var data = companyClasses.FirstOrDefault(s =>s.CompanyName == cc.CompanyName);     if (data!=null)     {       data.Address = cc.Address;       data.CompanyYear = cc.CompanyYear;     } } publicIList<companyclass>Classes()   {       returncompanyClasses;   } } } </companyclass></companyclass></companyclass>  
Enter fullscreen mode Exit fullscreen mode

usingSystem.ServiceModel; usingSystem.ServiceModel.Description; publicstaticvoid Main(string[] args)   { using (ServiceHost host = newServiceHost(typeof(AddServices)))       {     ServiceMetadataBehaviorserviceMetadata  =newServiceMetadataBehavior { HttpGetEnabled = true };     host.Description.Behaviors.Add(serviceMetadata);     host.AddServiceEndpoint(typeof(AddServices), newNetTcpBinding { Security = { Mode = SecurityMode.None } }, nameof(AddServices));     host.Open();     Console.WriteLine("Services are hosted successfully.");     Console.WriteLine("Press any key to stop the services.");     Console.ReadKey();       }   }  
Enter fullscreen mode Exit fullscreen mode

Step: 4
All Services are ready to host. Now, run your project and check your services are hosted successfully and you can get one service URL.

Now, we can create a WPF project for creating a client and consuming their services.

Step: 5
Create a new project for WPF Windows Application and use services using the MVVM pattern.

First of all, we have to create a proxy channel for the WCF Company service. Using this proxy object, we can get the service data that we want.

Let’s see how to create a proxy and get the data from the server.

using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.ServiceModel; usingSystem.Text; usingSystem.Threading.Tasks; namespaceWCFExample { publicclassProxyService<t>whereT :class {   private T _GetT;   public T GetT(string path)   {     return _GetT ?? (_GetT = ServiceInstance(path));   }   privatestatic T ServiceInstance(string path)   {     varbindpath = newNetTcpBinding();     bindpath.Security.Mode = SecurityMode.None;     EndpointAddressendpointAddress = newEndpointAddress(path);     returnChannelFactory<t>.CreateChannel(bindpath, endpointAddress);   } } } </t></t>  
Enter fullscreen mode Exit fullscreen mode

Step: 6
After setting the proxy channel, create a folder and give it the name view model for the Company models and binding it with the Xaml.

using System; usingSystem.Collections.Generic; usingSystem.Collections.ObjectModel; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Input; namespaceWCFExample.ViewModel { publicclassCompanyViewModel {   privatereadonlyICompanyServicecompanyService;   publicCompanyViewModel()   {     ListData = newObservableCollection<companiesviewmodel>();     varProxyservices = newProxyService<icompanyservice>();     companyService = Proxyservices.GetT("net.tcp://localhost:9950/CompanyService");     var companies = companyService.companyClasses();     foreach (var company in companies)     {       ListData.Add(newCompaniesViewModel(company, this));     }   }   publicObservableCollection<companiesviewmodel>ListData{ get; set; }   publicvoidUpdateProperty(CompaniesViewModelcompaniesViewModel)   {     companyService.Update(companiesViewModel.Model);   } } publicclassCommands :ICommand {   private Action<object> action;   privateFunc<object, bool="">func;   publiceventEventHandlerCanExecuteChanged   {     add     {       CommandManager.RequerySuggested += value;     }     remove     {       CommandManager.RequerySuggested -= value;     }   }   publicCommands(Action<object> action, Func<object, bool="">func = null)   {     this.action = action;     this.func = func;   }    publicboolCanExecute(objectparam)   {     returnthis.func == null || this.func(param);   }   publicvoidExecute(object param)   {     this.action(param);   } } } </object,></object></object,></object></companiesviewmodel></icompanyservice></companiesviewmodel>  
Enter fullscreen mode Exit fullscreen mode

Wants to Talk with Our Highly Skilled WPF Developer? Contact Now.

Step: 7
Now, add one more view model for representing every detail of the Company. In this view model we implicit INotifyPropertyChanged for an instant update.

usingJetBrains.Annotations; using System; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Linq; usingSystem.Runtime.CompilerServices; usingSystem.Text; usingSystem.Threading.Tasks; namespaceWCFExample.ViewModel { publicclassCompaniesViewModel :INotifyPropertyChanged   {   public Commands EventHandler{ get; privateset; }   privatereadonlyCompanyViewModel _base;   privatestring address;   privateint year;   publicCompanyClass Model;   publicstring Address       {     get{ return address; }     set           {       if(address != value)       {         address = value;         Model.Address = value;         _base.UpdateProperty(this);         OnPropertyChanged(nameof(Address));               }           }       }   publicint Year   {     get{ return year; }     set     {       if(year != value)       {         year = value;         Model.CompanyYear = value;         _base.UpdateProperty(this);         OnPropertyChanged(nameof(Year1));         OnPropertyChanged(nameof(Year2));         OnPropertyChanged(nameof(Year3));         OnPropertyChanged(nameof(Year4));         OnPropertyChanged(nameof(Year5));           }         }       }       publicbool Year1 =>Model.CompanyYear>= 30;       publicbool Year2 =>Model.CompanyYear>= 20;       publicbool Year3 =>Model.CompanyYear>= 10;       publicbool Year4 =>Model.CompanyYear>= 15;       publicbool Year5 =>Model.CompanyYear>= 14;   publicCompaniesViewModel(CompanyClass company, CompanyViewModel companies)       {           Model = company;     EventHandler = new Commands(OnClickYear);           _base = companies;           address = company.Address;           year = company.CompanyYear;       }   privatevoidOnClickYear(objectobj)       {     this.Year = int.Parse(obj.ToString());       }     publiceventPropertyChangedEventHandlerPropertyChanged;       [NotifyPropertyChangedInvocator]     protectedvirtualvoidOnPropertyChanged([CallerMemberName] stringpropertyName = null)       {     PropertyChanged?.Invoke(this, newPropertyChangedEventArgs(propertyName));       }   } }  
Enter fullscreen mode Exit fullscreen mode

Conclusion

Self-hosting in WCF is easy to use you can make your service running using a few lines of code, you can control your service through the Open () and Close () methods of ServiceHost. Window Communication Foundation is a reliable, secure, and scalable messaging platform for the .NET framework, and have some other features like Security, Data Contract, Service Oriented, Transaction, etc.

serverwcfwebdevwpf
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.