Expose WCF Service to JavaScript in ASP.NET 3.5 VB


Server Intellect


Expose WCF Service to JavaScript in ASP.NET 3.5 VB

This tutorial will show you how to create and implement an AJAX-enabled WCF Service into an ASP.NET Web page. WCF (or Windows Communication Foundation) is a union of technologies developed by Microsoft to make it easier and quicker for developers to build distributed applications.

We are going to create a single web page that will allow the input of two numbers from the user, then we will access a WCF Service to make a calculation and return the value back to the Web Page. We will do this using AJAX so that we will get a near-instant response.

To start, create a new Web Application in Visual Studio 2008, and then in Solution Explorer, right-click the Project, choose Add New Item.. AJAX-enabled WCF Service. Name it Service1.svc - you will see that it is added to the Solution Explorer, along with a Service1.vb in the App_Code folder. The .vb file should open upon creation, and look something like this:

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=
AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub

' Add more operations here and mark them with <OperationContract()>
End Class

This is where we will add our logic to perform the calculation We will add a method to add two numbers together, like so:

' Add more operations here and mark them with <OperationContract()>
<OperationContract()> _
Public Function Add(ByVal theNum1 As Double, ByVal theNum2 As Double) As Double
Return theNum1 + theNum2
End Function

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

Notice we specify a static method, and the OperationContract attribute defines it as an operation of this Service.
Now if we move to our ASPX page, we will want to add a ScriptManager to the page to manage all of our AJAX calls behind the scenes. But in order for our Service method to be accessible at page level, we will need to add a Service reference to our WCF Service. We do so like this:

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>

Now let's go ahead and create our form. We will use HTML form elements, as we are going to use JavaScript to call our Service method.

<input type="text" id="num1" size="3" /> + <input type="text" id="num2" size="3" /><br />
<input type="button" id="jsSubmit" value="Submit" onclick="AddNumbers()" />

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!

Nothing much different to a regular ASP.NET Web Application here. Notice we include the handler for the button. Here we are calling a JavaScript function, which we can now add to the page. Add the following to the bottom of the page:

<script language="javascript" type="text/javascript">
function AddNumbers() {
Service1.Add(document.getElementById('num1').value, document.getElementById('num2').value, onSuccess);
}

function onSuccess(string) {
alert('Answer = ' + string);
}
</script>

Here, we are directly referencing the public method we created within the WCF Service. We have access to this via JavaScript because we are using the ScriptManager to expose the Service to page level. We get the response from the method and display it in a JavaScript alert window. We have no need to write any code-behind logic, as all of the functionality is being handled by the Service. We can expand this Web Application by creating more methods (Operation Contracts) in the Service, and then referencing them in the same way via JavaScript.
Our entire Service code looks like this:

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=
AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub

' Add more operations here and mark them with <OperationContract()>
<OperationContract()> _
Public Function Add(ByVal theNum1 As Double, ByVal theNum2 As Double) As Double
Return theNum1 + theNum2
End Function
End Class

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

Our ASPX page will look something like this:

<html>
..
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>

<input type="text" id="num1" size="3" /> + <input type="text" id="num2" size="3" /><br />
<input type="button" id="jsSubmit" value="Submit" onclick="AddNumbers()" />
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function AddNumbers() {
Service1.Add(document.getElementById('num1').value, document.getElementById('num2').value, onSuccess);
}

function onSuccess(string) {
alert('Answer = ' + string);
}
</script>

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
buknoy said:

i want to learn from the basic of this ajax things pls help me

Posted May 3, 2009 9:41 PM
kumar said:

I found this website very much informative for ne developer like me. thanks www.planetsourcecode.in

Posted May 29, 2009 10:59 AM
Gambling online resources said:

Your sample is great.. but I am having a problem with the ProvidePolicyFile method. The first time I run the console app, and try to consume the WCF service from Silverlight, it works. The second time I get a cross domain access error .. and when I debug the console app, it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Jun 23, 2009 5:50 AM
babydoll lingerie said:

If you have been following along you may have noticed that we only have one WSDL. The WSDL contains all of our endpoints. Even though we have three endpoints, we still only have one WSDL. In testing with some third party clients my experience has been that clients only generate proxies for the endpoints they understand. Add a service reference to the service to the windows application.

Posted Oct 30, 2009 12:52 AM
womens lingerie said:

Earlier today we shipped a public beta of our upcoming .NET 3.5 SP1 and VS 2008 SP1 releases. These servicing updates provide a roll-up of bug fixes and performance improvements for issues reported since we released the products last November. They also contain a number of feature additions and enhancements that make building .NET applications better

Posted Oct 30, 2009 5:37 AM
Bulk Sms said:

I just read the article that a friend posted, well i gotta say it definitely makes you wonder thats for sure, but if its true which would be awesome, that is just a cool thing to know, another reason to want to get into motorcycle riding haha. But hey would it then (if this is true) help with memory like short term or long term, just curious. Any info can be good info.

Posted Oct 30, 2009 1:43 PM
Christmas Presents for Women said:

ASP.NET 3,5 building on top of its popular predecessor, ASP.NET 2.0. When you save backward compatibility with sites built using this version of Microsoft. NET Framework 3.5 in general and ASP.NET 3.5 in particular, to add many new opportunities to combine compelling.

Posted Oct 30, 2009 1:58 PM
plumber mascot said:

This is really a cool post. I really like this design very much. I absolutely love this dress! the shape, design everything shouts pretty! I would like to visit your blog often. Thanks a bunch for sharing such a great and innovative post with us.

Posted Nov 18, 2009 12:09 AM
brabantia products said:

I debug the console app, it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right.

Posted Nov 25, 2009 2:27 AM
jugar al poker gratis said:

the products last November. They also contain a number of feature additions and enhancements that make building .NET applications better

Posted Nov 25, 2009 11:03 AM
jugar poker online said:

the OperationContract attribute defines it as an operation of this Service.I absolutely love this dress! the shape, design everything shouts pretty! I would like to visit your blog often. Thanks a bunch for sharing such a great and innovative post with us.

Posted Nov 26, 2009 10:37 AM
Hendersonville kitchen remodeling said:

I'm getting around it by opening the file for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Nov 26, 2009 11:37 AM
poker online said:

I think your suggestion would be helpful for me. I will let you know if its work for me too.

Posted Nov 27, 2009 4:28 AM
aprender poker said:

that is just a cool thing to know, another reason to want to get into motorcycle riding haha. But hey would it then (if this is true) help with memory like short term or long term, just curious. Any info can be good info.

Posted Dec 4, 2009 12:49 AM
chat software said:

I want to express my admiration of your writing skill and ability to make reader to read the while thing to the end. I would like to read more of your blogs and to share my thoughts with you. I will be your frequent visitor, that’s for sure.

Posted Dec 17, 2009 7:50 AM
treatment for hiv said:

built using this version of Microsoft. NET Framework 3.5 in general and ASP.NET 3.5 in particular, to add many new opportunities to combine compelling.

Posted Jan 18, 2010 11:21 PM
Valentines Presents said:

the file for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Jan 20, 2010 4:39 AM
aprender a jugar poker said:

for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Jan 22, 2010 9:02 AM
Madame Alexander Doll said:

we will want to add a ScriptManager to the page to manage all of our AJAX calls behind the scenes. But in order for our Service method to be accessible at page level, we will need to add a Service reference to our WCF Service. We do so like

Posted Jan 23, 2010 5:10 AM
Second Hand Cars said:

I debug the console app, it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Feb 5, 2010 10:54 AM
frwcs royal trader review said:

Financial centers around the world function as anchors of trading between a wide range of different types of buyers and sellers around the clock with the exception of weekends.

Posted Feb 17, 2010 5:45 AM
Temporary Tattoos said:

These servicing updates provide a roll-up of bug fixes and performance improvements for issues reported since we released the products last November. They also contain a number of feature additions and enhancements that make building .

Posted Feb 19, 2010 8:47 PM
Stainless Steel Cookware Sets said:

I debug the console app, it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right.

Posted Feb 23, 2010 4:54 AM
Play Tents said:

some third party clients my experience has been that clients only generate proxies for the endpoints they understand. Add a service reference to the service to the windows application.

Posted Mar 4, 2010 11:32 AM
DUI Attorney Houston said:

Its always said Give service take service.

Posted Mar 5, 2010 3:52 AM
ankhi said:

we will want to add a ScriptManager to the page to manage all of our AJAX calls behind the scenes. But in order for our Service method to be accessible at page level, we will need to add a Service reference to our WCF Service.<a href="http://www.myerectorsets.com/">Erector Set Sets</a>

Posted Mar 6, 2010 12:07 PM
Erector Set Sets said:

it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right.

Posted Mar 6, 2010 12:07 PM
blog commenting service said:

it reports an error that it can't open the "ClientAccessPolicy.XML" file because it is already open. I'm getting around it by opening the file for shared-read access but that doesn't quite seem right.

Posted Mar 7, 2010 10:29 PM
forex trading website online said:

by opening the file for shared-read access but that doesn't quite seem right... any attempt to close the filestream before the method returns causes it to fail. Any ideas?

Posted Mar 7, 2010 10:40 PM
Leadership Development said:

Great tutorial. I liked it.

Posted Mar 8, 2010 11:52 PM

Leave a Comment