We help IT Professionals succeed at work.
Get Started

Consuming WCF service with JavaScript in .NET 4.0 application

leskelly
leskelly asked
on
835 Views
Last Modified: 2015-03-09
I have a small application developed in Visual Studio 2010 that I'm using to test Consuming a WCF service with JavaScript.  The service takes a single string parameter and returns that parameter prefixed with "Hello " The service is in a WCF Service Library.  The service is hosted in a WCF Service web site.  I access the service from a ASP.NET web application.  I know the  service  is functional as it returns the expected value when I call it from a VB procedure.  When I try to call it from JavaScript I get an error message that says, "JavaScript runtime error: 'HelloServiceReference' is undefined".  My code is below.  The error occurs on the third line, "var HelloClient2 = new HelloServiceReference.HelloClient;" of Hello.js. I have a Service Reference to the service named "HelloServiceReference". I'm assuming I'm missing an attribute of some sort that allows for JavaScript access.  Any assistance would be greatly appreciated.

TestLibrary(WCF Service Library)


IHello.vb
<ServiceContract()>
Public Interface IHello
	<OperationContract()>
	<System.ServiceModel.Web.WebInvoke()> _
	Function SayHello(ByVal value As String) As String
End Interface

Open in new window


Hello.vb
Public Class Hello
	Implements IHello

	Public Function SayHello(ByVal value As String) As String Implements IHello.SayHello
		Return String.Format("Hello {0}", value)
	End Function

End Class

Open in new window


App.config
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="TestLibrary.Hello">
        <endpoint address="" binding="wsHttpBinding" contract="TestLibrary.IHello">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/TestLibrary/Service1/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <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>
  </system.serviceModel>

</configuration>

Open in new window



HelloHost(WCF Service)


Hello.svc
<%@ ServiceHost Language="VB" Debug="true" Service="TestLibrary.Hello" %>

Open in new window


Web.config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0"/>
    <pages>
      <namespaces>
        <add namespace="System.Runtime.Serialization"/>
        <add namespace="System.ServiceModel"/>
        <add namespace="System.ServiceModel.Web"/>
      </namespaces>
    </pages>
  </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="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

Open in new window



Hello Client(ASP.NET web application)


TestHello.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestHello.aspx.vb" Inherits="Hello_Client.TestHello" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <script src="<%=ResolveUrl("~/Scripts/Hello.js")%>" type="text/javascript"></script>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        <Services>
            <asp:ServiceReference Path="http://localhost/HelloHost/Hello.svc"/>
        </Services>
    </asp:ScriptManager>       
        <div>
            <label id="lblName">Name:</label>
            <input id="txtName" name="tName" type="text" /><br />
            <input id="btnHello" type="button" value="Hello" onclick="fnHello(document.getElementById('txtName').value)" />
            <asp:Button ID="btnASPHello" runat="server" Text="ASP Hello" />
        </div>
    </form>
</body>
</html>

Open in new window


Hello.js
function fnHello(Name)
{
    var HelloClient2 = new HelloServiceReference.HelloClient;
    alert(HelloClient2.SayHello(Name, fnHelloCallBack));
}

Open in new window


TestHello.vb
Public Class TestHello
    Inherits System.Web.UI.Page

	Protected Sub btnASPHello_Click(sender As Object, e As EventArgs) Handles btnASPHello.Click
		Dim TestRun As HelloServiceReference.HelloClient = New HelloServiceReference.HelloClient()
		Dim script As String = "<script type='text/javascript' defer='defer'> alert('" + TestRun.SayHello("Les") + "');</script>"
		ClientScript.RegisterClientScriptBlock(Me.GetType(), "AlertBox", script) 
	End Sub

End Class

Open in new window


Web.config
<?xml version="1.0"?>
<configuration>
	
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
	
  <system.serviceModel>
		<services>
			<service name="TestLibrary.Hello">
				<endpoint address=""
									binding="wsHttpBinding"
									contract="TestLibrary.IHello">
					<identity>
						<dns value="localhost"/>
					</identity>
				</endpoint>
				<endpoint address="mex"
									binding="mexHttpBinding"
									contract="IMetadataExchange"/>
				<host>
					<baseAddresses>
						<add baseAddress="http://localhost:8732/Design_Time_Addresses/TestLibrary/Service1/"/>
					</baseAddresses>
				</host>
			</service>
		</services>
		<bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IHello" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost/HelloHost/Hello.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IHello" contract="HelloServiceReference.IHello"
        name="BasicHttpBinding_IHello" />
    </client>
  </system.serviceModel>
		
</configuration>

Open in new window

Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 24 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE