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

How to Create a WCF WebService in VB.NET

5.00/5 (11 votes)
16 May 2017CPOL9 min read 54.3K   1.4K  
WCF WebService IN VB.NET Response JSON
In this article, you will learn how to create a simple WCF Web Service that could be consumed by a Software or Web client.

Introduction

This article is intended to show every developer how we can create a simple WCF Web Service that could be consumed by a Software or Web client. The responses that our WCF has to do will be :XML response and JSON response. Besides, we are going to work over how to consume this WCF WS by URITemplates (If you don't know what does URItemplates mean, don't worry, I'll explain it in this article.)

So, let´s work!

Background

Well, before we start with this article, we need to know these requirements:

  1. You must have VS 2017 community edition. (Download link: https://www.visualstudio.com/es/)
  2. POSTMAN (To test our WCF OPTIONAL)
  3. Google Chrome (IMPORTANT: This is to test our WCF if we don't download POSTMAN.)

Using the Code

Well, let´s start.

Step #1 - First at all, we need to install Visual Studio 2017 (VS 2015 is ok too):

Image 1

Step #2 - Remember to restart your computer after you install Visual Studio Community.

Step #3 - Now... let's code our WCF Web Service.

Coding Our WCF Web Service

Open your Visual Studio 2017 community and File>New>Project, then from the Left-column, select:

VISUAL BASIC>Classic Windows Desktop>Console App (like the image shown down):

NOTE: Remember that my VS 2017 community Edition is in Spanish!! and I have to translate all the Labels for you. :)

Image 2

Then, you should change the Project Name to WCF_WS_Employee like the next Image shown Down.¬
You must change your path of Project for a best Organization of your projects.

Image 3

Well, after you change the PROJECT NAME and PATH PROJECT, let's click on OK OR ACCEPT to create the project and here is how this appears:

Image 4

When Visual Studio creates the project, this includes some files to conform to the entire solution.

You will see a Module1.vb ready to star coding.

Well, since Microsoft creates the WCF, we need some namespaces that help us to do the work more easily about structure. It is for that, that we need imports for some namespaces:

VB.NET
system.runtime.serialization
System.ServiceModel.Description
System.ServiceModel
System.ServiceModel.Activation

Image 5

When you import the namespaces, you can see a green underline, well, the next step is to Add references to our project like this: Right click in Project name > ADD > REFERENCES.

Then MARK the namespaces that we list above: the next image shows you how you need to mark these options:

Image 6

When you CHECK and then Accept, you can see the green underline disappears, that means the NameSpaces have been added succesfully!!

Image 7

Adding the Employee Class

Well, the next step is Add our Class that will help us to respond in XML format or JSON format.
Right click over solution Name> Add > Class

Image 8

Then rename the default class that VS gave us. Rename it as employee.

Like the image below:

Image 9

Then Accept and the class Employee is added to our project. :)

Image 10

Well, here is where we have to do some work. First, we need some properties. We are going to call these properties: IdEmployee , Name and LastName.

WCF works always with "Service Contracts" and "Operation Contracts" is for that, that we need imports:
System.runtime.Serialization, to support too DataContract and DataMember, these functions provide functionality for the classes to be exposed into WCF response. Don´t worry about that. I will explain later the meaning of these properties. Well, keep going with this article.

Here is the DataType of each property:

  • IdEmployee => Integer
  • Name => String
  • LastName => String
VB.NET
<DataMember>
  Public Property IdEmployee() As Integer
      Get
          Return m_IdEmployee
      End Get
      Set(ByVal value As Integer)
          m_IdEmployee = value
      End Set
  End Property

We also need a constructor class to use when we add parameters into a collection. with the next parameters: IdEmployee, Name, LastName.

VB.NET
Public Sub New(ByVal IdEmplyee As Integer, ByVal Name As String, ByVal LastName As String)
        Me.m_IdEmployee = IdEmplyee
        Me.m_Name = Name
        Me.m_LastName = LastName
    End Sub

Here is how our employee class looks when it is finished:

Image 11

As you see, employee class only has system.runtime.serialization because the employee class needs to be reachable by WCF. (DataMember, DataContract)

Remember that all the terms will be explained at the end. I am a person that thinks that we need examples before theory. Our brain works more efficiently with images.

Ok, let's move forward.

After we created our Employee class, we need to go back to our module1.vb, to coding the INTERFACE SERVICE.

In our Module.vb, please write this:

VB.NET
<ServiceContract>
Public Interface IService

End Interface

Public Class Service
   Implements IService

End Class

Why we only write <SERVICECONTRACT> over IService? Well, the INTERFACE helps us to define the input and outputs that WCF can resolve or respond AND expose the methods that we define into this section.

The INTERFACE allows to define how many methods can be reached by, but here we cannot define the logic of the method. For that, we need implements the INTERFACE in a class that can contain the logic and code of the method exposed. It´s why we need to create a Service Class, this class will help us to implement the INTERFACE your section must look like:

Image 12

Don't worry if you cannot see WHERE WE Implement the IService into Service. Wait a moment please.

Ok, first we need to declare our method to expose it.

VB.NET
<ServiceContract>
Public Interface IService

<OperationContract()>
<webGet()>
function SeekEmployee() AS List(Of employee)

End Interface

As you see, we write <OperationContract()> And <WebGet>, OPERATION CONTRACT is used to tell the INTERFACE, that this method needs to show in the WCF Web service. If we don't put this tag, the method cannot be reachable for anyone.

Well, the next section is define the Body or Logic of our method called: SeekEmployee. To define the Body of the method, we need to focus in the Public Class Service is in this class where we code all the logic .

We are going to create a collection to add some data and then expose the result like XML format or JSON format.

Remember: You can use a SQL CONNECTION to get some data for this example... but you recommended keep like this article, then you finish this article, is when you can modify to get data dynamically.

Well, to do this, please copy & paste the next code into Class service or Remove Class service:

VB.NET
Public Class Service
    Implements IService

    Public Function SeekEmployee(ByVal DataToMerge As String) _
           As List(Of employee) Implements IService.SeekEmployee
        Dim EmployeeCollection As New List(Of employee)()

        EmployeeCollection.Add(New employee(1, DataToMerge & "Matt", "Daimon"))
        EmployeeCollection.Add(New employee(2, "Arnold", "Mendez"))
        EmployeeCollection.Add(New employee(3, "Silvester", "Stallone"))
        EmployeeCollection.Add(New employee(4, "Scarlet", "johanson"))
        EmployeeCollection.Add(New employee(5, "Jean Claude", "VanDame"))
        EmployeeCollection.Add(New employee(6, "Terminator", "Baby"))
        EmployeeCollection.Add(New employee(7, "John", "HILL"))
        EmployeeCollection.Add(New employee(8, "Steven", "Hall"))
        EmployeeCollection.Add(New employee(9, "Renee", "Ruso"))
        Return EmployeeCollection
    End Function
End Class

As you see, we use the Implements IService to tell the interface that we need that our methods defined and Service Class, must be exposed!!

Here is who looks like:

Image 13

Well, so far, we did:

  1. Imports NameSpaces and References to the project
  2. We added the employee.vb (employee class) (DataContract And DataMember)
  3. We define: Method (OperationContract) and body of method (Class service)

Well, we almost finished our own WCF WebService in VB.NET and using FW 4.1 or later.

The next step is hosting our WebService: there are three ways for HOST our WebService.

  • IIS
  • Windows Services
  • Self Hosting

Each way has good Practices and Bad Practices, but the easy way to host a WCF WebService is: Self Hosting.

With self-hosting, you only have to do the next:

In the Main Section of the console, code this:

VB.NET
Module Module1
    Sub Main()

        Dim SetupWCF As WebServiceHost = New WebServiceHost(GetType(Service), 
                                         New Uri("http://localhost:8000/"))
        SetupWCF.Open()
        Console.WriteLine("Press <ENTER> to stop the WCF Self-Hosted")
        Console.ReadLine()
    End Sub

End Module

That's it!!!

Image 14

***Before you run your project, keep this in mind.***

This article is intended to run in LOCAL MODE (http://locahost:8000), but if you feel like "Luckiest man in the world", you can test it in PRODUCTION BUTTTTT be careful with this:

For example, if your site is http://www.abc1234.com and you want to put abc1234.com instead of localhost, you can do this, but if in that moment, some of your clients access your site, this is going to throw an error like "this site cannot be reachable or SITE IS IN MAINTENANCE". To avoid this, add a subfolder like:

www.abc1234.com/test/

Like this:

VB.NET
Module Module1
    Sub Main()

        Dim SetupWCF As WebServiceHost = New WebServiceHost(GetType(Service), 
                                         New Uri("http://www.abc1234.com/test/"))
        SetupWCF.Open()
        Console.WriteLine("Press <ENTER> to stop the WCF Self-Hosted")
        Console.ReadLine()
    End Sub

End Module

Well, once we explained this, that's time to test:

Run your project and a console will appear:

Image 15

Now open POSTMAN SOFTWARE and COPY & PASTE link. Once you have pasted the link, here is where WCF works.

Adding to your link + method like this: http://localhost:8000/seekEmployee to the POSTMAN box.
Then, click in the SEND button.

Image 16

When you click the SEND button, the POSTMAN requests the seekEmployee method over the WCF and its response in XML is like THIS:

Image 17

If all is Ok so far.... then... you're a lucky man!!

Well, this is a most popular response in XML Format. With this XML format, we can see the response wrapped in employee tags, this means that all the data is returned OK.

How Return JSON With this WCF Webservice?

Well to do this, we need to go back into SERVICECONTRACT in our Module1.vb.
It is here in the <webGet> where we can configure the type of response that we need for our application.

Just add the next Lines in WebGet:
<WebGet(ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare)>

This parameter configures our Interface WCF, to response in JSON. The next image shows this:

Image 18

When you finished off, modify the WebGet, then switch window and focus on POSTMAN again and Click SEND Button Again, and see what happens. :)

Image 19

YEP!! We have a JSON response, ready to add to several Clients like INTERNET BROWSERS, MOBILES, DESKTOP SOFTWARE, ETC.

Can I Pass Parameters to My WCF??

Yes!!! you can!!!.

Just do this:

  1. Add a parameter to SeekEmployee Function in INTERFACE Section. I added a parameter named DataToMerge.
  2. In Function seekEmployee (Inside of Public class service), add a parameter like INTERFACE Parameter.
  3. Merge the Var in your data.

This is how it looks like:

Image 20

When you finish adding the Var, go back to POSTMAN and then change the link.

http://localhost:8000/seekEmployee?DataToMerge=TESTING instead http://localhost:8000/seekEmployee

The Click SENDING BUTTON and now the value of DataToMerge will appear merge in NAME property of the first Index LIKE:

Image 21

As you see, when the method doesn't needs parameters, this can be called like a SubDomine or SubFolder.

But when this needs parameters, this is adapted for.

Adding UriTemplate to our WCF WebService

Well, to add this functionality and permit to developers, call your WCF WebService like:

http://localhost:8000/seekEmployee/TESTING

We need to make some light changes to our <WebGet>.

The URITemplates are used to determine what requests are sent to which service Operations.

It is for that reason queue needs add another param in <WebGet> option is: UriTemplate.

Just add the "SeekEmployee/{DataToMerge}". Remember this important thing.

ALWAYS the URI Template has the Function name/var name like the example:

Image 22

And that's all!!! Go back to POSTMAN and add in Search box: http://localhost:8000/seekEmploye/TESTING

Image 23

We are done!!!

Remember that this article is just to know the structure and how it conforms in WCF XML response and JSON Response.

Points of Interest

Remember that, the Self hosted WCF WebService is fast, but, if you don't configure correctly, this can affect other USERS that access your website.

Also, you can test this WCF Web Service in Google Chrome. :)

If you have any questions, please feel free to ask me, ok?

Best regards!!!

IF my article helped you in any way... please leave me some stars.

History

  • 4th May, 2017: Initial version

License

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