Table of Contents

What is Jayrock?

Web services, the light and simple way!

Jayrock is a modest and an open source (LGPL) implementation of JSON and JSON-RPC for the Microsoft .NET Framework, including ASP.NET. What can you do with Jayrock? In a few words, Jayrock allows clients, typically JavaScript in web pages, to be able to call into server-side methods using JSON as the wire format and JSON-RPC as the procedure invocation protocol. The methods can be called synchronously or asynchronously.

Compatibility & compliance:

Microsoft Windows Linux Microsoft .NET Framework Mono Python Microsoft Internet Explorer FireFox Opera Open Source (OSI) Certified

No time for Jayrock right now? Got del.icio.us? Bookmark it and come back later…

Where is the Source, Luke?

You can obtain the latest source of code of Jayrock from the Mercurial repository hosted at Google Code. Needless to say, you will need a Mercurial client for your platform to access the repository. If you don't have a Mercurial client handy and just wish to browse the source code, you can do so online.

The respository is located at http://jayrock.googlecode.com/hg/. The command-line for the Mercurial client would therefore be:

hg clone http://jayrock.googlecode.com/hg/ jayrock

The third argument, jayrock, is the directory name where the local working copy will be downloaded so this can be another name if you like.

If you want a snapshot of the latest files without bothering to go through the source repository then you can simply download them from the Files section of the project.

Jayrock was originally maintained in a Subversion repository that is still available in case you want to consult its earlier history using Subversion clients.

Search the Source

Google: Browse

Bear in mind that search engine(s) maintain a periodically crawled and cached copy of the source code so results may be inaccurate sometimes due to differences from the original.

Compiling

Note: For quicker setup instructions, see the section Setting Up Jayrock.

Once you have checked out a working copy of the source from the respository, you can compile Jayrock in one of two ways. You can either open the included Microsoft Visual Studio solution files and use the IDE to compile the projects or you can use the included NAnt build script to compile from the command-line.

Compiling with NAnt

You do not need NAnt installed on your machine to compile Jayrock. The right version of all required tools (NAnt, NUnit, NCover and NCoverExplorer) is already included under the tools directory. If you are on the Windows platform, you can simply run the build.cmd batch script to invoke NAnt and have it build all the targets. To invoke NAnt explicitly, otherwise, use the following command (assuming you are in the root of the working directory):

tools\NAnt\NAnt -f:nant.build

A full build compiles the debug and release assemblies (inlcuding unit testing) for Jayrock and Jayrock.Json for whichever of the following platforms are available on the build machine:

Compiling with Microsoft Visual Studio

Jayrock comes with Microsoft Visual Studio 2010 project and solution files that compile assemblies for Microsoft .NET Framework 4.0. There is little to know except open the desired solution in Visual Studio and build away! The two solutions that you will find under src and tests are:

Jayrock
The complete solution that includes and builds the JSON-RPC, JSON and some experimental sandbox (playground) bits.
Jayrock.Tests
Solution that contains a test-view of the project, with references and sources for unit tests.

The Visual Studio solutions target .NET Framework 4.0 only. To compile for other versions, use the NAnt as described in the previous section.

Contributing to the Project

Jayrock is provided as open source and free software (as per Open Source Definition and under LGPL) for two principal reasons. First, an open source community provides a way for individuals and companies to collaborate on projects that none could achieve on their own. Second, the open source model has the technical advantage of turning users into potential co-developers. With source code readily available, users can help debug quickly and promote rapid code enhancements. In short, you are encouraged and invited to contribute!

Please contact Atif Aziz (principal developer and project leader) if you are interested in contributing.

You don't have to necessarily contribute in the form of code submissions only. Contributions are appreciated and needed in any of the following forms:

For more information, see Jayrock on Google Code.

How Else?

The above things require time and energy and if you can donate it then there is nothing better for Jayrock. Honestly! On the other hand, there is only this to consider. Has Jayrock helped you in a project at your daytime job? Well, a lot of companies happily profit from open source projects in terms of time and money (especially if time is money), so talk to your manager or development lead about making a small donation. If you or your company wish to be listed as a donor, then send along any or all of the following information to be directly listed here: your name, company you work for and a link to your and/or company's home page (would also be nice to know the country). Thanks!

Community & Discussions

Jayrock is an open source project and so naturally relies on to build, leverage and enjoy peer support from a community of users with a shared interest in the project. Assessing if Jayrock is right the right solution for you? Having trouble using some aspect of it? Want to simply provide feedback or ideas for further development? Then Jayrock Google Group is the place to go.

Google Groups Jayrock
Browse Archives at groups.google.com

Setting Up Jayrock

  1. Open the Microsoft Visual Studio 2008 solution file called Jayrock Web under src and build the entire solution to compile all contained projects. There is also a NAnt build script but this builds all other projects except the web project. If you compile from the command-line, the only additional step required at the moment is to manually copy the resulting Jayrock.dll and Jayrock.Json.dll assemblies from one of the bin sub-directories (depending on the target platform and desired configuration) to the bin directory under www.
  2. Select the Demo.ashx in the www Web Site project and then choose View in Browser from the file's context menu.

ASP.NET Quick Start

IMPORTANT! This quick start tutorial and its code illustrations are based on $Rev: 790 $ of Jayrock. If you are using an older build then some of this tutorial may not make sense or work. In that case, use the tutorial supplied with the version you have instead if you cannot upgrade right away.

To use Jayrock in your ASP.NET project, add a reference to the Jayrock.dll and Jayrock.Json.dll assemblies add a copy of json.js (distributed with Jayrock and found in www subdirectory) to the root of your web. A JSON-RPC service is best exposed using Jayrock by creating an ASP.NET HTTP handler. In this quick start, we will create a JSON-RPC service called HelloWorld. Begin by creating a file called helloworld.ashx in the root your ASP.NET application. Add the following code to the file:

<%@ WebHandler Class="JayrockWeb.HelloWorld" %>

namespace JayrockWeb
{
    using System;
    using System.Web;
    using Jayrock.Json;
    using Jayrock.JsonRpc;
    using Jayrock.JsonRpc.Web;

    public class HelloWorld : JsonRpcHandler
    {
        [ JsonRpcMethod("greetings") ]
        public string Greetings()
        {
            return "Welcome to Jayrock!";
        }
    }
}

There are a few interesting things to note about this code. First of all, HelloWorld inherits from the Jayrock.JsonRpc.Web.JsonRpcHandler class. This is all that is needed to make your service callable using the standard JSON-RPC protocol. Second, the Greetings method is decorated with the JsonRpcMethod attribute. This is required to tell Jayrock that your method should be callable over JSON-RPC. By default, public methods of your class are not exposed automatically. Next, the first parameter to the JsonRpcMethod attribute is the client-side name of the method, which in this case happens to be greetings. This is optional, and if omitted, will default to the actual method name as it appears in the source (that is, Greetings with the capital letter G). Since JavaScript programs usually adopt the camel case naming convention, providing an alternate and client-side version of your method's internal name via the JsonRpcMethod attribute is always a good idea. You are now almost ready to test your service. The last item needed is the addition of a few sections in the web.config of your ASP.NET application:

Note: As of version 0.9.8316, the configuration shown here is the assumed default and not required in web.config anymore. For the purpose of this tutorial, you may skip adding the following sections to your web.config.

<configSections>
    ...
    <sectionGroup name="jayrock">
        <sectionGroup name="jsonrpc">
            <section 
                name="features" 
                type="Jayrock.JsonRpc.Web.JsonRpcFeaturesSectionHandler, Jayrock" />        
        </sectionGroup>
    </sectionGroup>
    ...
</configSections>
...
<jayrock>
    <jsonrpc>
        <features>
            <add name="rpc" 
                 type="Jayrock.JsonRpc.Web.JsonRpcExecutive, Jayrock" />
            <add name="getrpc" 
                 type="Jayrock.JsonRpc.Web.JsonRpcGetProtocol, Jayrock" />
            <add name="proxy" 
                 type="Jayrock.JsonRpc.Web.JsonRpcProxyGenerator, Jayrock" />
            <add name="pyproxy" 
                 type="Jayrock.JsonRpc.Web.JsonRpcPythonProxyGenerator, Jayrock" />
            <add name="help" 
                 type="Jayrock.JsonRpc.Web.JsonRpcHelp, Jayrock" />
            <add name="test" 
                 type="Jayrock.JsonRpc.Web.JsonRpcTester, Jayrock" />
        </features>
    </jsonrpc>
</jayrock>
...

The above configuration lines enable various features on top of your service. These features are accessed by using the feature's name in the query string to your handler's URL, as in ?feature (very similar to how you request the WSDL document for an ASP.NET Web Service). First and foremost, there is the rpc feature. It is responsible for actually making the JSON-RPC invocation on your service upon receiving a request over HTTP POST. Without this feature, your service is JSON-RPC ready but won't be callable by anyone. The getrpc feature is similar except it makes the services methods callable over HTTP GET.

The proxy feature dynamically generates JavaScript code for the client-side proxy. This code will contain a class that you can instantiate and use to call the server methods either synchronously and asynchronously. In an HTML page, you can import the proxy by using your handler's URL as the script source and using ?proxy as the query string:

<script 
    type="text/javascript" 
    src="http://localhost/foobar/helloworld.ashx?proxy">
</script>

The help feature provides a simple help page in HTML that provides a summary of your service and methods it exposes. Finally, the test feature provides a simple way to test the methods of your service from right within the browser. This is exactly what we are going to work with next. Open up a browser window and point it to the URL of your ASP.NET handler. For example, if your ASP.NET application is called foobar and is running on your local machine, then type http://localhost/foobar/helloworld.ashx. You should now see a page appear that lists the methods exposed by your service:

HelloWorld Help

Notice that there are two methods, namely greetings and system.listMethods. The system.listMethods is always there and inheirted by all services that inherit from the JsonRpcHandler class. It provides introspection similar to some XML-RPC implementations. As this point, you are looking at the help page generated by the help feature. Notice, though, you did not have to specify the ?help query string. That's because JsonRpcHandler defaults to the help feature when it sees a plain HTTP GET request for your service. You should also be able to see a link to the test page from where you can invoke and test each individual method. Click on this link now, which should yield a page similar to the one shown here:

HelloWorld Test

To see if everything is working correctly, select the greetings method from the drop-down list and click the button labeled Test. If all goes well, you should see the string "Welcome to Jayrock!" returned in the response box of the page.

Great. So far we have the service running and tested. Now it is time to try and call the service from JavaScript within a web page. In the same directory as where you placed helloworld.ashx, create a plain text file called hello.html and put the following HTML source in there:

<!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" lang="en" xml:lang="en">
<head>
    <title>Hello Jayrock</title>
    <script type="text/javascript" src="json.js"></script>
    <script type="text/javascript" src="helloworld.ashx?proxy"></script>
    <script type="text/javascript">
/* <![CDATA[ */

window.onload = function() 
{
    var s = new HelloWorld();

    alert("sync:" + s.greetings());

    s.greetings(function(response) { 
      alert("async:" + response.result) 
    });
}

/* ]]> */
    </script>
</head>
<body>
    <p>This page tests the HelloWorld service with Jayrock.</p>
</body>

This page references two scripts. The first one is json.js, (distributed with Jayrock) which contains code for converting JavaScript values into JSON text and vice versa. This is required by the second script reference, which points to the JavaScript proxy that will be dynamically generated by Jayrock from the server so that we can call the service. The third script is embedded in the page and causes the greetings method to be called on the HelloWorld service twice. In its first form, greetings is called synchronously whereas in its second form, it is called asynchronously. How is that? If the proxy sees that the last parameter supplied is a JavaScript function then it treats it as a callback. The call is made to the service and control returned immediately. When the response becomes available, the proxy invokes the callback function and sends it the JSON-RPC response object as the first and only parameter. The result property of this object can then be consulted to obtain the return value from the server-side RPC method. On failure, the response object instead contains an error property.

Back in the browser, type the URL http://localhost/jayrock/hello.html in the address bar. As soon as the page loads, you should see two message boxes show up one after the other and which display the string "Welcome to Jayrock!" returned from our JSON-RPC service method greetings. The first message box will be from the synchronous execution whereas the second from the asynchronous one.

Calling Services from Windows Script Host (WSH)

One of the interesting things about the JavaScript proxy (the one dynamically served by Jayrock for your service) is that it can also be used from outside a web page and therefore the whole web browser environment. More specifically, you can use the proxy without any modifications from within a WSH script. This enables a number of key scenarios like:

Let's take the same HelloWorld service developed in the previous section and try to call it from a WSH script. Put the following markup into a Windows Script Host Script file called hello.wsf.

<job>
    <script language="JScript" src="http://localhost/jayrock/json.js" />
    <script language="JScript" src="http://localhost/jayrock/helloworld.ashx?proxy" />
    <script language="JScript">
var s = new HelloWorld();
WScript.Echo(s.greetings());
    </script>
</job>

Open a Window Command Prompt, change to the directory where you saved hello.wsf and simply type hello to execute it. If that does not work, you may have to type the full command-line, as in cscript hello.wsf or wscript hello.wsf. When the script runs, it should display the greeting message from the service.

Just as in the case of the web page, the WSH script references the JSON and service proxy script files as external sources to be imported at run-time. In fact, since the scripts will be fetched from the web server, the WSH script will pick up changes automatically by downloading the latest copy. Notice also that the references to the external scripts use absolute URLs since the WSH script will in reality live at an independent location from the web server.

That's it! We're done. Hope you enjoyed this quick tour.

Samples & Demos

You can find a number of JSON-RPC methods demonstrating various features in the supplied demo service. See http://localhost/jayrock/demo.ashx on your machine for a working copy of the demo.

Documents

An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET
An MSDN article that takes a cursory look at JSON, its origins and then its application from within JavaScript and C#. Reading and writing JSON text from C# is demonstrated using classes from Jayrock. See the Working with JSON in the .NET Framework section of the article for more.
Jayrock Project Presentation
This presentation contains illustrations that briefly cover the architecture of Jayrock's JSON and JSON-RPC implementations. Beware, however, that some bits may be obsolete now since the presentation is based on a very early build.

Got Questions?

If you don't see your questions or concerns addressed below, then try over at the Jayrock discussion group.

What is Jayrock?
Jayrock is a modest and an open source implementation of JSON and JSON-RPC for the Microsoft .NET Framework, including ASP.NET. What's so modest about it? Well, modest as in plain and basic and no work of genius.
What can I do with Jayrock?
Two things come to mind:
  1. You can use just the Jayrock's JSON infrastructure for manipulating JSON data and text without all the JSON-RPC fuss. Just use the stand-alone Jayrock.Json assembly.
  2. In addition to the above, you can use Jayrock to expose light-weight services with procedures from within your ASP.NET application. You can then invoke the procedures on those services over HTTP using JSON-RPC as the protocol. A typical use case would be some JavaScript code embedded inside a web page calling back into your services on the web server.
So wait, is Jayrock yet another Ajax framework?
That depends on what fits your bill for or definition and expectation of an Ajax framework. While you can certainly use Jayrock to write rich and interactive web page enabled by the Ajax style of development, you'll be a more enlightened soul to believe that it has a wider applicability. You can build light-weight services in ASP.NET and then deploy them on your web server, but beyond that, any client with HTTP capability, be that scripts or console applications, can benefit from Jayrock by remotely invoking procedures of your services. If you have a JSON-RPC client library for your language, environment or platform then all the better. If not, Jayrock comes with one for JavaScript to get you started off the ground in Microsoft Internet Explorer, FireFox and even WSH (Windows Script Host). Given a service, Jayrock can dynamically provide a JavaScript proxy that implements the JSON-RPC protocol to call back into your service (synchronously and asynchronously). Jayrock, however, does not provide any client-side whiz-bang widgets or controls that you may have come to generally expect from other and more ambitious Ajax frameworks. For that, you are recommended to shop around elsewhere, like Dojo toolkit, Microsoft ASP.NET AJAX, Yahoo! UI Library or many others.
Which versions of the Microsoft .NET Framework are supported?
Jayrock is compiled and delivered for Microsoft .NET Framework 1.x, 2.0 and 4.0. Just toss the corresponding assemblies at your application and you are good to go.
What is JSON?
JSON stands for JavaScript Object Notation. It is a simple, human-readable, text-based and portable data format that is ideal for representing and exchanging application data. It has only 5 data types (Boolean, Number, String, Object and Array) that are commonly used across a wide number of applications and programming languages. For more information, see RFC 4627.
What is JSON-RPC?
JSON-RPC is a light-weight remote procedure call protocol that relies on JSON for the wire format. All it does is provide a simple way to express a call frame as a JSON Object and the result or an error resulting from the invocation as another JSON Object. For details, see the JSON-RPC specification

Style and design by Atif Aziz.

Valid XHTML 1.0 (Transitional)