Table of Contents
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:
No time for Jayrock right now? Got del.icio.us? Bookmark it and come back later…
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.
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.
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.
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:
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:
The Visual Studio solutions target .NET Framework 4.0 only. To compile for other versions, use the NAnt as described in the previous section.
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.
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!
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.
Jayrock | |
Browse Archives at groups.google.com |
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
.Demo.ashx
in the www
Web Site project
and then choose View in Browser from the file's context menu.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:
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:
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.
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.
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.
If you don't see your questions or concerns addressed below, then try over at the Jayrock discussion group.
Jayrock.Json
assembly.Style and design by Atif Aziz.