Skip to main content

JavaScript Client for CoreService

This blog post shows a way to connect to CoreService directly from a JavaScript client. The CoreService is a WCF web-service, which by default uses SOAP to communicate with its clients. However, it is quite simple to convert it into a REST service that accepts plain POST requests with parameters sent in the request body.

To keep things simple, I secured the REST endpoint with Basic auth, and thus made use of the Basic Authenticator handler over an HTTPS connection.

The Server

The WCF framework allows us to easily expose any web-service as a REST service. For this, I had to modify the file [SDLWebHome]\webservices\Web.config, and add an endpoint behavior under node <system.serviceModel> / <behaviors>. The new behavior enables endpoint to be accessible as REST service:

  <endpointBehaviors>
    <behavior name="MyJS">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>

Next, because we want to use HTTPS, we define a web HTTP binding with security mode Transport, under node <system.serviceModel> / <bindings>:

  <webHttpBinding>
    <binding name="MyHttps">
      <security mode="Transport"/>
    </binding>
  </webHttpBinding>

Next, under our CoreService service definition, we add a new endpoint based on the new MyJS behavior and using the MyHttps binding. Add the following node under <system.serviceModel> / <services>:

  <service behaviorConfiguration="Tridion.ContentManager.ServiceHost.IISHost.CoreServiceBehavior"
    name="Tridion.ContentManager.ServiceHost.IISHost.CoreService201603">

    <endpoint binding="webHttpBinding" bindingConfiguration="MyHttps" behaviorConfiguration="MyJS"
      bindingNamespace="http://www.sdltridion.com/ContentManager/CoreService/201603"
      contract="Tridion.ContentManager.CoreService.ICoreService201603" address="rest" />

This configuration enables a new endpoint rest under the service CoreService201603.svc that accepts HTTPS POST requests to interact with the CoreService. Namely, the endpoint is https://web85.playground/webservices/CoreService201603.svc/rest

Even more so, the endpoint automatically generates JavaScript proxy classes based on the contract interface defined (i.e. Tridion.ContentManager.CoreService.ICoreService201603). These proxies can be used directly from the server, by loading the following script URL directly in the client web page: https://web85.playground/webservices/CoreService201603.svc/rest/js



We need to configure one last thing – we must allow cross site scripting. The client JavaScript that will consume our CoreService REST endpoint will most likely make calls to the REST endpoint from a different machine than our Content Manager. This means, we need to configure the remote IPs and the headers that are accepted to make REST calls. For example, a simple way to configure this is to add Access-Control response headers in file [SDLWebHome]\webservices\Web.config, under node <system.webServer>:

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Methods" value="POST,OPTIONS" />
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Authorization, Content-Type, X-Requested-With" />
    </customHeaders>
  </httpProtocol>

The Client

The JS proxies generated by the REST endpoint are readily usable, if we use the MicrosoftAjax framework. This is the easiest and quickest way to get the client application going. However, there is one big drawback – the MicrosoftAjax framework doesn’t accept any kind of security configuration when making the AJAX calls to the service (or at least I couldn’t figure it out). Our service requires Basic auth, and it seems there is no way to specify that in the MicrosoftAjax framework. Of course, one can always modify the JS source of the framework, but that would be a hack :)

In Microsoft Visual Studio (I used 2015), create a new project of type Visual C# / Web / ASP.NET Web Application. This creates all the skeleton code that is needed, including the MicrosoftAjax JS classes.

The following sample page makes a call to CoreService using the automatically generated proxy classes and MicrosoftAjax framework. Note that this code does not work OOTB in our case, because we are not sending a Basic auth request header:

<html>
<head>
    <script src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/WebForms/MSAjax/MicrosoftAjax.js"></script>
    <script src="https://web85.playground/webservices/CoreService201603.svc/rest/js"></script>
</head>
<body>
    <script>
        var service = new www.sdltridion.com.ContentManager.CoreService._201603.ICoreService();
        service.GetApiVersion(function (result) {
            alert(result);
        });
    </script>
</body>
</html>

The parameter method to GetApiVersion is a callback function that is called if the GetApiVersion invocation is a success. The response from the service is inside variable result.

Conclusion

This is a quick and elegant way of exposing a WCF service as a RESTful API without having to rewrite any server code.

The client however is not very configurable, because we can’t set an authentication method, unless we change the actual framework.

In a follow-up post, I will show a purely JQuery client that doesn’t depend or use MicrosoftAjax framework, it is much more configurable, and overall smaller in size, but we must write our skeleton proxy classes ourselves.



Comments

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as...

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...