I spent the last couple of days working with SketchUp, WCF, and JavaScript. SketchUp is a really cool tool for creating, modifying, and sharing 3D models. I am certainly not a modeling expert but I do have some experience working with 3D models and I have to say I am was impressed with the free version. The pro version is only $500. While this is not a trivial sum of money, it is very affordable compared to some of the packages I have seen.
My job was to create a web service that could be called using JavasSript. I will mention that this was a proof of concept and I specifically did not address security. The following code will work but there is no security of any kind so if the resulting service is exposed to the internet, anybody can call it.
The first thing I did was use the create WCF project wizard. I wasn’t particularly worried about passing complex data types at this point so I defined a simple Service Contract.
- using System.ServiceModel;
- using System.ServiceModel.Web;
- namespace WcfModelService
- {
- [ServiceContract(Namespace = "WcfModelService")]
- public interface IModel
- {
- [OperationContract]
- [WebGet]
- string GetData(int value);
- [OperationContract]
- [WebGet]
- string HelloWorld();
- [OperationContract]
- [WebGet]
- string HelloSomeone(string message);
- }
- }
When you apply the WebGet attribute to a service contract decorated with the OperationContract attribute you are adding some extra metadata to the operation. This metadata doesn’t actually do anything unless a service behavior is looking for it.
Here is the implementation:
- using System.ServiceModel.Activation;
- namespace WcfModelService
- {
- [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
- public class Model : IModel
- {
- #region IModel Members
- public string GetData(int value)
- {
- return string.Format("You entered: {0}", value);
- }
- public string HelloWorld()
- {
- return "Hello World.";
- }
- public string HelloSomeone(string message)
- {
- return "Hello World and " + message + " too.";
- }
- #endregion
- }
- }
As I mentioned, adding the WebGet attribute doesn’t actually have any effect on our ability to call the service via JavaScript unless we have a service behavior that will use the metadata. In our configuration file we add the AjaxBehavior. Notice the enableWebScript element in the behavior. This is logically equivalent to adding the ScriptService attribute to an ASMX service. The final thing we need to do is to expose an endpoint using the webHttpBinding.
- <system.serviceModel>
- <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
- <services>
- <service name="WcfModelService.Model">
- <endpoint address="" binding="webHttpBinding" contract="WcfModelService.IModel" behaviorConfiguration="AjaxBehavior">
- </endpoint>
- </service>
- </services>
- <behaviors>
- <endpointBehaviors>
- <behavior name="AjaxBehavior">
- <enableWebScript/>
- </behavior>
- </endpointBehaviors>
- </behaviors>
- </system.serviceModel>
All we have left to do now is to call the service from JavaScript. We will keep things simple and add a ScriptManager with a ServiceReference to the Model service. Now in JavaScript create the service proxy:
var proxy = new WcfModelService.IModel()
and call an operation:
proxy.HelloSomeone(s2, onSuccess, onFail, null);
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WcfTest.aspx.cs" Inherits="WcfModelService.Test" %>
- <!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>
- <title>Wcf AJAX Service Client Page</title>
- <script type="text/javascript">
- // This function creates an asynchronous call to the service
- function makeCall(operation){
- var n1 = document.getElementById("num1").value;
- var s2 = document.getElementById("string1").value;
- // Instantiate a service proxy
- var proxy = new WcfModelService.IModel();
- // Call correct operation on proxy
- switch(operation){
- case "Data":
- proxy.GetData( parseInt(n1), onSuccess, onFail, null);
- break;
- case "Hello":
- proxy.HelloWorld( onSuccess, onFail, null);
- break;
- case "Someone":
- proxy.HelloSomeone(s2, onSuccess, onFail, null);
- break;
- }
- }
- // This function is called when the result from the service call is received
- function onSuccess(callResult){
- document.getElementById("result").value = callResult;
- }
- // This function is called if the service call fails
- function onFail(){
- document.getElementById("result").value = "Error";
- }
- // ]]>
- </script>
- <style type="text/css">
- #num1
- {
- width: 303px;
- }
- #string1
- {
- width: 317px;
- }
- #result
- {
- width: 333px;
- }
- #btnData
- {
- width: 118px;
- }
- #btnHelloWorld
- {
- width: 99px;
- }
- </style>
- </head>
- <body>
- <h1>
- Wcf AJAX Service Client Page</h1>
- <p>
- A Number:
- <input type="text" id="num1" /></p>
- <p>
- A String:
- <input type="text" id="string1" /></p>
- <input id="btnData" type="button" onclick="return makeCall('Data');"
- value="Get Data" />
- <input id="btnHelloWorld" type="button" onclick="return makeCall('Hello');"
- value="Hello" />
- <input id="btnHelloSomeone" type="button"
- onclick="return makeCall('Someone');" value="Hello Someone" />
- <p>
- Result:
- <input type="text" id="result" /></p>
- <form id="aForm" action="" runat="server">
- <asp:ScriptManager ID="ScriptManager" runat="server" >
- <Services>
- <asp:ServiceReference Path="~/Model.svc" />
- </Services>
- </asp:ScriptManager>
- </form>
- </body>
- </html>
Here is an ASMX version of the same service.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- using System.Web.Script.Services;
- namespace AsmxModelService
- {
- /// <summary>
- /// Summary description for AsmxModelService
- /// </summary>
- [WebService(Namespace = "WcfModelService")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
- [System.Web.Script.Services.ScriptService]
- public class AsmxModelService : System.Web.Services.WebService
- {
- [WebMethod]
- [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
- public string GetData(int value)
- {
- return string.Format("You entered: {0}", value);
- }
- [WebMethod]
- [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
- public string HelloWorld()
- {
- return "Hello World";
- }
- [WebMethod]
- [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
- public string HelloSomeone(string message)
- {
- return "Hello World and " + message + " too.";
- }
- }
- }
If you need to secure the call, we could force the user to login before accessing the aspx page containing the JavaScript service call. An Authentication cookie will now be passed to the application with each request.
By setting aspNetCompatibilityEnabled=true we can access the identity using a call to HttpContext.Current.User.Identity.Name. Each operation should now verify the user is authorized to make the call before executing the operation logic.
Reference:
http://msdn.microsoft.com/en-us/magazine/cc793961.aspx#id0070025