Wednesday, July 25, 2012

WCF Service using ASP.Net 4.0 to create a WSDL

WCF or Windows Communication Foundation is a set of API’s that are used to build service-orientated applications.  WCF supports SOAP (primarily), JSON, XML, and RSS.

WSDL or Web Services Definition Language (v1.0) and Web Services Description Language (v2.0 – 2007) is a web service that uses XML formatting to provide functionality.  WSDL 1.0 is a combination of NASSL (Network Application Service Specification Language) developed by IBM and SDL (Service Description Language) created by Microsoft.  WSDL 2.0 is W3C compliant and renamed from Definition Language to Description Language on June 2007.  WSDLs are cross-platform compliant Web Services that utilize a combination of SOAP and XML Schema.

Now that we know what they are, let’s get started building one -
Let’s start at the Create Project level.  Open VS2010 (You should be at the Start Page).
From there, you will want to Left-Click File | New Project.  Under the template bar on the left, select Visual Basic | WCF.  In the main window pane, select WCF Service Application.
Name your service accordingly and give it a suitable location -
image

As always, ensure you are utilizing the .Net Framework 4.0

You will have some default functionality provided by Microsoft -

' NOTE: You can use the "Rename" command on the context menu 
'
to change the class name "Service1" in code, svc and config file together.
Public Class Service1
Implements IService1

Public Sub New()
End Sub

Public Function
GetData(ByVal value As Integer) As String _
Implements IService1.GetData
Return String.Format("You entered: {0}", value)
End Function

Public Function
GetDataUsingDataContract(ByVal composite As _
CompositeType) As CompositeType Implements IService1.GetDataUsingDataContract
If composite Is Nothing Then
Throw New
ArgumentNullException("composite")
End If
If
composite.BoolValue Then
composite.StringValue &= "Suffix"
End If
Return
composite
End Function

End Class


Note, like Microsoft has suggested, we can rename our service to something a little more appropriate.  So why don’t we do so?  We’ll rename it to Products.svc as we are going to serve up Products from the Northwind Database.  Right click the name Service1.svc in the Solution Explorer and click Rename.  Now we need to go into Products.svc and rename our class to Products -



Public Class Products
Implements IService1


Notice that we are Implementing the Interface IService1.  This is all well and good, but lets go ahead and delete the Interface and start anew.  Right click the IService1.vb Interface in the Solution Explorer and click Delete.  Now we need to add an Interface to replace it.  Right click your solution name in the Solution Explorer and click Add | Class.  We will call this IProducts.vb as it is an Interface for the Products Class.  Our new class should look like -



Public Class IProducts

End Class


However, we are not looking to add another class.  We want an Interface.  So we need to change the code to -



<ServiceContract()>
Public Interface IProducts
<OperationContract()>
Function GetProducts() As Product
End Interface


The <ServiceContract()> tells the compiler and Web Service that THIS is the contract (Interface) that has been created for the Service.  Notice that for our function we have GetProducts() As Product. So naturally, our next step is to create the Product object (class).  Lets again Click our solution name in the Solution Explorer | Add | Class and name it Product.vb.




<DataContract()>
Public Class Product
<DataMember()>
Public Property ProductID As Integer
<DataMember()>
Public Property ProductName As String
<DataMember()>
Public Property UnitPrice As Double
<DataMember()>
Public Property UnitsInStock As Integer

Public Sub New
(ByVal productid As Integer, _
ByVal productname As String, _
ByVal unitprice As Double, _
ByVal unitsinstock As Integer)
Me.ProductID = productid
Me.ProductName = productname
Me.UnitPrice = unitprice
Me.UnitsInStock = unitsinstock
End Sub
End Class


The <DataContract()> again tells the compiler and service that this is the contract for the DataBinder.  DataMember allows us to bind each property to the Service.  Now we have completed the Product object.  Now we have to go back to the Service and Implement our object and interface.

First we need to have it Implement our IProducts Interface -




Public Class Products
Implements IProducts


End Class


You should see a blue squiggly line under IProducts.  Why? Because an interface is a contract on how you will implement a class.  In the interface we defined a GetProducts() Method that we also have to implement.  If you hold your mouse over the blue squiggly, it should notify you of this.

So our first order of business is to add database functionality.  In your web.config, we need to add the ConnectionString -




<?xml version="1.0"?>
<
configuration>
<
connectionStrings>
<
add name="dataconnect" connectionString="Server=ServerName;
Database=Northwind;Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
</
connectionStrings>
<
system.web>


Of course you will want to change “ServerName” to the name of your server.  Next we need to go back to the Products.svc.vb and add our declarations -



Imports System.Data.SqlClient
Imports System.Web.Configuration.WebConfigurationManager

Public Class Products
Implements IProducts


Now we need to write our function that will get the data -



Public Function GetProducts() As List(Of Product) _
Implements IProducts.GetProducts
Dim cn As SqlConnection = New _
SqlConnection(ConnectionStrings("dataconnect").ToString())
Dim cmd As New SqlCommand("dbo.GetProducts", cn)
cmd.CommandType = CommandType.StoredProcedure
cn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim products As List(Of Product) = ConvertReader(reader)
cn.Close()
Return products
End Function




Of course this is a simple ADO.Net function to utilize a stored procedure to get the recordset.  As listed above, you can see the Imported Namespaces that we had to reference.  The method calls the stored procedure listed below which I wrote into the NorthWind database -



USE [Northwind]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE
[dbo].[GetProducts]
AS
BEGIN
SET NOCOUNT ON;

SELECT * From dbo.Products
END




If you look at the method, we are dimensioning products to be the result of a call to another method called ConvertReader.  Obviously, we need to include this method -




Public Function ConvertReader(ByVal reader As SqlDataReader) _
As List(Of Product)
Dim products As List(Of Product) = New List(Of Product)
If reader.HasRows() Then
While
reader.Read()
products.Add(New Product(CInt(reader.Item("ProductID")), _
reader.Item("ProductName").ToString(), _
CDbl(reader.Item("UnitPrice")), _
CInt(reader.Item("UnitsInStock"))))
End While
End If
Return
products
End Function




This completes the coding for the service.  If we run the site and use a browser in debug mode, by going to the URL with service name -

Example:


http://localhost:52458/Products.svc



We get an explanation of how to implement the Service -

image



This is as far you can get in the browser because in order to get a return in SOAP, you need a form post.  However, you can add endpoints or convert the SOAP to XML (outside the scope of this article) to display the service in a browser.

Instead, you can use the WCF Test Client.  If you are actively in the Products.svc.vb page and Start the application in debug mode, it automatically starts.


image



To test the service, left click our GetProducts() Method in the treeview on the left -

image



Since we have no parameters to define, simply click the Invoke button in the middle of the window -

image



You should see a representation of the service response that is formatted.  You can also view it in XML by clicking the XML lower tab at the bottom of the window.



 



We have successfully created a WCF Data Service that creates a WSDL utilizing SOAP.



Happy .Netting…

2 comments:

  1. Well, I’d like to say that the information above is pretty useful for me when developing in ASP.NET Development Company right now I am working with a Mobile App Development Company for an important project. So this is pretty helpful for me.

    ReplyDelete
  2. Nice to know that I'm helping someone. Let me know if there is something specific you would like to see. I just write them as I use them at work.

    ReplyDelete