ARTICLE

Create and Consume WCF services in VB.NET

Posted by Mukesh Kumar Articles | WCF with VB.NET February 17, 2011
WCF provides a runtime environment for your services, enabling you to expose CLR types as services and to consume other services as CLR types.
 
Reader Level:

What is WCF?

WCF is a unification technology, which unites .Net Remoting, MSMQ, Web Services and COM+ technologies.

WCF provides a runtime environment for your services, enabling you to expose CLR types as services and to consume other services as CLR types.

Creating WCF Service:

Open Visual Studio 2008/2010. Click on File menu -> New -> Project ->WCF Service Application. Change the name as "WCFService" then click Ok button.

WCF1.gif

Delete auto generated files IService1.cs and Service1.svc and create new (right click on WCFService project and select Add -> New Item -> WCF Service). Rename service as "UserService".

WCF2.gif

Now add an Entity Data Model in your project to communicate with database.

Service Code

Replace interface IUserService with the code given below :

Imports System.ServiceModel

<ServiceContract()>
Public Interface IUserService

    <OperationContract()>
    Sub DoWork()

    <OperationContract()> 
    Function Authenticate(ByVal UserName As String, ByVal A_CryptKey As String) As
String

    <OperationContract()>
    Function GetApprovedUser() As
DataTable
End Interface

Replace UserService class code with the code given below :

Public Class UserService
    Implements
IUserService

    Public Sub DoWork() Implements IUserService.DoWork
    End
Sub

    Public Function Authenticate(ByVal UserName As String, ByVal A_CryptKey As String) As String Implements IUserService.Authenticate
        Using Context = New UserServiceEntities()
            Dim user = Context.Users.Where(Function(c) c.UserName = UserName AndAlso c.A_CryptKey = A_CryptKey).FirstOrDefault()
            If user IsNot Nothing Then
                Return Convert.ToString(user.UserID)
            Else
                Return String.Empty
            End If
        End
Using

    End Function

    Public Function GetApprovedUser() As List(Of User) Implements IUserService.GetApprovedUser
        Using Context = New UserServiceEntities()
            Dim user As New List(Of User)()
            user = Context.Users.Where(Function(c) c.IsApproved = True).ToList()
            Return user
        End Using
    End
Function

End Class

Service configuration


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <
system.web>
    <
compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
      <assemblies>
        <
add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5ccreate-and-consume-wcf-services-in-VB-Net34e089" />
      </assemblies>
    </
compilation>
  </
system.web>
  <
system.serviceModel>
    <
behaviors>
      <
serviceBehaviors>
        <
behavior>
          <!--
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" />
        </behavior>
      </
serviceBehaviors>
    </
behaviors>
    <
serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <
system.webServer>
    <
modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <
connectionStrings>
    <
add name="UserServiceEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=MANDR-PC;Initial Catalog=UserService;User ID=sa;Password=pass;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</
configuration>

Consuming WCF Service:

Now right click on UserService.svc and select "View in Browser". it will show a browser with service url. Copy that url

WCF3.gif

Now right click on WCFClient project select "Add Service Reference" and paste copied url in Address section of "Add Service Reference" dialog box and click on Go button and rename Namespace as "UserService" and click ok button.

WCF4.gif

WCF Client code

Imports Client.UserService

Public Class _Default
    Inherits System.Web.UI.
Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim proxy As New UserServiceClient()

        Dim User As String = proxy.Authenticate("Mukesh", "X%AY#$tZ")

        ' objdt = proxy.GetApprovedUser()

        proxy.Close()
    End Sub
 
End Class

Client side configuration

<system.serviceModel>
    <
bindings>
      <
basicHttpBinding>
        <
binding name="BasicHttpBinding_IUserService" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </
binding>
      </
basicHttpBinding>
    </
bindings>
    <
client>
      <
endpoint address="http://localhost:53820/UserService.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IUserService" contract="UserService.IUserService"
        name="BasicHttpBinding_IUserService" />
    </client>
  </
system.serviceModel>

Login to add your contents and source code to this article
share this article :
post comment
 

The zip files are in C#. Any chance to post them in VB?

Posted by Mark Schumacher Jul 09, 2011
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor