Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / WCF

Create a WCF Service using wsHttpBinding and use in a Windows Forms application

4.82/5 (7 votes)
10 Dec 2012CPOL1 min read 67K   2K  
Create a WCF service using wsHttpBinding and use in a Windows Forms application.

Introduction

In this article, I would like to create a WCF service application with wshttpbinding and use it in a Windows Forms application.

Creating a WCF Service Application

  1. Open Visual Studio, choose File => New => Project
  2. .

    Image 1

  3. Choose WCF Service Application and enter the name:
  4. Image 2

  5. Add a new class to the project for the custom validator:
  6. Image 3

  7. Choose class, enter the name, and click the Add button.
  8. Image 4

  9. Here is the sample code for the custom validator:
  10. C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ServiceModel;
    using System.IdentityModel.Selectors;
    
    namespace TestService
    {
        public class CustomValidator : UserNamePasswordValidator
        {
            public override void Validate(string userName, string password)
            {
                if (userName == null || password == null)
                {
                    throw new ArgumentNullException();
                }
    
                if (!(userName == "a" && password == "a"))
                {
                    throw new FaultException("Password or name is wrong");
                }
            }
        }
    }
  11. Change the web config in system service model as below:
  12. aspx
    <system.serviceModel>
        <behaviors>
          <serviceBehaviors >
            <behavior name="ServiceBehaviors"  >
              <!-- To avoid disclosing metadata information, 
              set the value below to false and remove the metadata endpoint above before deployment -->
              <serviceMetadata httpGetEnabled="True"/>
              <!-- To receive exception details in faults for debugging purposes, 
              set the value below to true.  Set to false before deployment 
              to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="False" />
              <serviceCredentials>
                <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName"
                                 storeLocation="LocalMachine" storeName="My" />
                <userNameAuthentication userNamePasswordValidationMode="Custom"
                 customUserNamePasswordValidatorType="TestService.CustomValidator, TestService" />
              </serviceCredentials>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <bindings>
          <wsHttpBinding>
            <binding>
              <security mode="Message">
                <message clientCredentialType="UserName"/>
              </security>
            </binding>
          </wsHttpBinding>
        </bindings>
        <services>
          <service name="TestService.Service1" behaviorConfiguration="ServiceBehaviors" >
            <endpoint contract="TestService.IService1" binding="wsHttpBinding" />
            <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
            <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
          </service>
        </services>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
  13. When trying to run the service, it will show an error like below, so we need to configure the project:
  14. Image 5

    Right click, add the project, and choose Use IIS Express...

    Image 6

    Choose Yes

    Image 7

    Choose OK.

    Image 8

    Choose the project and at the properties window, set SSL Enabled to true.

    Image 9

    The service will be ready to use.

    Image 10

Use the service in a Windows Forms application

  1. Right click, add the solution, and choose Add New Project.
  2. Image 11

  3. Choose Windows Forms Application, enter the name, and click the OK button.
  4. Image 12

  5. Right click, add the project, and choose Add Service Reference.
  6. Image 13

  7. Enter the service address and click the OK button.
  8. Image 14

  9. Add controls to the form as in the below picture.
  10. Image 15

  11. Here is the sample code of the form. Add an event for button click:
  12. C#
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using WindowsFormsApplication1.ServiceReference1;
    using System.ServiceModel.Security;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    Service1Client c = new Service1Client();
                    c.ClientCredentials.UserName.UserName = textBox1.Text;
                    c.ClientCredentials.UserName.Password = textBox2.Text;
                    c.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = 
                                        X509CertificateValidationMode.None;
                    MessageBox.Show(c.GetData((int)numericUpDown1.Value));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.InnerException.Message);
                }
            }
        }
    }
  13. Change the solution properties to run two projects at the same time.
  14. Image 16

    Image 17

  15. Try to submit the data with a random username and password.
  16. Image 18

    Image 19

  17. Here is the sample if the username and the password is correct.
  18. Image 20

    Image 21

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)