HOW CREATE A WCF WebService in VB.NET

0
28

Introduction

This article is intended to show to every developers how we can create a simple WCF Web Service that could be consumed from a Software or Web client. the responses that our WCF have to do, will be :XML response and JSON response. Besides, we gonna work over how consume this WCF WS by URITemplates (If you don’t know what does mean URItemplates…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 this requirements:

  1. You Must have VS 2017 community edition.(download: 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 downloaded POSTMAN)

Using the code

Well let´s start

SETEP #1.- First at All, we need install Visual Studio 2017 ( VS 2015 it’s ok too)

SETP #2.- Remember restart your computer after you install visaul Studio Community.

STEP #3.- now…..let’s coding 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 comunity Edition is in Spanish!! and I have to traslate all the LAbels for you. 🙂

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.

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 appear:

When Visual Studio creates the project, this include some Files to conform all the Solution

you will see a Module1.vb ready to star coding,

Well, sice Microsoft creates de WCF, we need some Namespaces that help us to do the work more Easy about structure. is for that, that we need imports some Namespaces :

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

Wehn you imports the namespaces, you cn 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 te Namespaces that we list above: the Next Image show you how you need mark these options:

When you CHECK and then Accept, you can see, who the green underline dissapear, that means that the NameSpaces has been added Succesfuly!!

Adding The Employee Class

Well the next step is Add our Clase that will help us to Response in XML Format or JSON Format

Right Click over solution Name> Add > Class

Then rename the default class that VS give us. rename it with: employee .

Like the image down:

Then Accepts. and the class Employee is Added to our project 🙂

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

WCF works allways with “Service Contracts” and “Operation Contracts” is for that, that we need imports:
System.runtime.Serialization, to support Too DataContract and DataMember this 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 propertys. well , keep going with this Article.

Here is the DataType of each property:

IdEmployee => Integer

Name => String

LastName => String

<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

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 looks our employee class finished:

As you see, employe 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. im a person that thinks that we need examples before theory. Our brain works more efficient with images.

Ok let’s forward.

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

in our Module.vb please write this:

<ServiceContract>
Public Interface IService

End Interface

Public Class Service
 Implements IService

End Class

Why we only write <SERVICECONTRACT> Over IService?, well the INTERFACE , helpus to define the input and outputs that WCF can resolve or response AND Expose the methods that we define into this section.

The INTERFACE Allow to define how and many methods can be reached by, but here we can not define the logic of the method, is 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 create a Service Class, this class we help us to implements de INTERFACE your section must look like :

Don’t worry if you can not see WHERE WE Implements the IService into Service. wait a momment please.

Ok, first we need to Declare our Method to expose it.

<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 to the INTERFACE, that this method needs to show in the WCF Web service. if we don’t put this tag, the method can not 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 focus in the Public Class Service is in this class where we coding all the logic .

We Gonna create a collection to add some data and then exposed the result like XML format or JSON format.

Remember: you can use a SQL CONNECTION to get some data for this example..but y 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:

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 yo 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:

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’s 3 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 SebService is: Self Hosting

with self-Hosting you only have to do the next:

In the Main Section of the console Code this:

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!!!

***Before you Run your Project keep in mind this***

This Article is intend to run in LOCAL MODE (http://locahost:8000) but if you feels 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 put abc1234.com instead localhost, you can do this, but if in that moment some of your client access to your site, this gonna throw a error like “this site can not be reachable or SITE IS IN MAINTENANCE” to Avoid this, add a subfolder like;

www.abc1234.com/test/

like this:

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:

Now Open POSTMAN SOFTWARE and COPY & PASTE link. Once you have Paste the link here is where WCF works

Adding to your link + method like this: http://localhost:8000/seekEmployee to the POSTMAN box

Then Click inthe SEND Button.

when you click the SEND Button, the POST MAN request the seekEmployee Method Over the WCF and it response in XML like THIS:

If all is Ok so far…. then.. you’re a lucky Man!!

Well this is a Most popular responses in XML Format. With this XML format, we can se the response wraped 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 back into SERVICECONTRACT in our Module1.vb

Is here in the <webGet> where we can configurate 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 parameters configure our Interface WCF, to response in JSON. The next image show this:

When you finished of modify the WebGet,then switch window and focus in POSTMAN again and Click SEND Button Again,, and See what happen 🙂

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

Can I Pass Parameters To My WCF??

Yes!!! you can!!!.

Just do this:

  1. Add a parameter to SeekEmployee Function in INTERFACE Section. iIadded 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:

When you Finish to Add the Var. Then, 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 :

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 do some light changes to our <WebGet>.

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

is for that, that que need add another param in <WebGet> option is: UriTemplate.

Just Add the “SeekEmployee/{DataToMerge}” . Remember this importat thing.

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

and that’s all!!! go Back to POST MAN and Add in Search box: http://localhost:8000/seekEmploye/TESTING

We finished!!!

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 to another USERS that access to 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 help you in anyway…please leave me some stars.

See you

LEAVE A REPLY