By András Jankó on Wednesday, December 7, 2016 — 2 comments

Distributed web applications in F# with WebSharperCore team

This article is part of F# Advent 2016

Introduction

Often some functionality of a web application is split between the server and client layers. For example you want a separate component on the page which needs server interaction and package it to reuse in multiple projects. Sometimes you need to talk to the server to be which is hosting the current application, sometimes another one that hosts a service for multiple web applications.

We will look at the tools that WebSharper provides to achieve all this and some more using only F#.

There is just a fresh release of WebSharper 4 beta out which contains fixes for these features, be sure to grab Zafir beta-5 packages from NuGet or get the Visual Studio installer for project templates here. For a short introduction, read The road to WebSharper 4.

WebSharper remoting

We will go into a couple new features of WebSharper 4 beta later, but start with a long-time basis of WebSharper: RPCs. Just having a Remote annotated method exposes it to be callable from client-side code which is translated to JavaScript:

1
2
3
4
5
6
7
8
9
10
[<Remote>] // runs on the server
let GetData key = async { return DataStore.[key] } 

[<JavaScript>] // runs in the browser
let DataView key =
	async { 
		let! data = GetData key // calls server asynchronously
		return div [ text data ] // creates the view when response has arrived
	} |> Doc.Async // converts to an `Async<Doc>` to `Doc` value that can be embedded
				   // on a page and displays content as soon as it is available

This is transparent and lightweigth way of communicating with the server, no larger state is sent back to the server, only what you explicitly pass and a user session cookie.

Let's take a look at what is happening here behind our backs:

  • The client-side gets constructs an instance of a "RemotingProvider" object. By default it is the AjaxRemotingProvider defined in WebSharper.
  • The Async method of the RemotingProvider is called with with the RPC method handle (auto-generated) and arguments. There are separate functions for calling Rpcs that return an async a Task and unit, but all use a method AsyncBase for common logic. The method handle is something like MyApp:MyApp.Server.GetData:-1287498065, containing the assembly name, full path of method and a hash of the method's signature.
  • The default implementation of AsyncBase sends a XMLHttpRequest to the client with the JSON-serialized form of the arguments.
  • Server handles the request: looks up the method based on the handle, deserializes the arguments to .NET values and executes the method.
  • Server serializes result based on metadata information which tells how they are represented in the JavaScript translation, and sends this back in the response.
  • Client deserializes JSON response into objects and applies prototypes.
  • Async continuation is called, or in case of a server error, the Error value will be propagated as in the async workflow.

So calling a remote is not a safe operation as it can throw an exception, but we can catch it:

1
2
3
4
5
6
7
8
	async {  
		try 
			let! data = GetData key 
			return div [ text data ]  
		with e ->
			Console.Log("GetData error:", e)
			return div [ text "Error" ]
	} |> Doc.Async

But it is a not a nice functional approach to rely on exceptions. There is a way to catch the error around every RPC call automatically.

Customizing the client request

We can inherit from the default AjaxRemotingProvider and override the AsyncBase member which is has the common logic to handle calling RPC methods :

1
2
3
4
5
6
7
8
9
[<JavaScript>]
type SafeRemotingProvider() =
    inherit Remoting.AjaxRemotingProvider()

	override this.AsyncBase(handle, data) =
        async.TryWith(base.AsyncBase(handle, data), 
            fun e -> 
                Console.Log("Remoting exception", handle, e)
                async.Return(box None)

This does not knows about the RPC method is actually returning, so it is just assuming that it is an option so None is a correct value. So we still need to be a bit careful to apply it only to Remote methods which are indeed returning an option.

1
2
3
4
5
6
7
[<Remote; RemotingProvider(typeof<SafeRemotingProvider>)>]
let GetData key =
    async { 
		match DataStore.TryGetValue(key) with 
		| true, c -> return Some c
		| _ -> return NOne
	} 

A good practice would be to have all RPC methods return an option (or Result or similar union) value and use the RemotingProvider attribute on the module defining the server-side functions, or even on assembly level.

Setting the target server

The default AsyncBase looks up the Endpoint property on the same object, which by default reads a module static value WebSharper.Remoting.Endpoint. This gives us a couple possibilities:

  • If we want all remoting to target a server with a known URL, we can just set WebSharper.Remoting.Endpoint in the client side startup.
  • If we want to host some server-side functionality as a separate service used by multiple web applications, we can put the it in a library project and apply a custom RemotingProvider class for the assembly that overrides the Endpoint property. You can use the WebSharper.Web.Remoting.AddAllowedOrigin method on server startup to allow access to the RPCs from other origins (sites which will be using your service).

Decouple server-side implementation

WebSharper allows a fully type-checked communication between your web appication server and client code but if you have it all in one project then there is more coupling between the two layers than desired. It comes in handy to define your RPC methods on abstract classes so that you can implement it in another project. Then you can have your communication protocol defined in a common project referenced by a server-side and client-side project not depending directly on each other.

1
2
3
4
5
namespace Model
[<AbstractClass>]
type ServerDataStore() =
	[<Remote>]
	abstract GetData : string -> Async<option<string>>

Note that now we are putting the Remote attribute on an instance method. There is no restriction on how many Remote methods you can have on a class, and you can mix abstract and non-abstract members of course. In another project we can implement this with a subclass, its methods do not need the Remote attribute as they are not directly exposed but will be called through its virtual slot.

1
2
3
4
5
6
7
8
9
type ServerDataStoreImpl(store: Dictionary<string, string>) = 
	inherit Model.ServerDataStore()
	
	override this.GetData(key) =
		async { 
			match store.TryGetValue(key) with 
			| true, c -> return Some c
			| _ -> return NOne
		}

Then we need to provide the server runtime at startup with an instance of the ServerDataStore class, which will execute its implementations of the abstract remote methods:

1
2
3
    let store = Dictionary()
    store.Add("greeting", "Hello world!")
	AddRpcHandler typeof<Model.ServerDataStore> (ServerDataStoreImpl(store))

There should be only one handler object per type. As now the RPC is an instance method, we need a small helper to call it from the client code:

1
2
3
4
	async {
		let! greet = Remote<Model.ServerDataStore>.GetData("greeting")
		greet |> Option.iter Console.Log
	}

Putting it together

These features are all combinable. So you can write a library that houses both server-side and client-side functionality for a feature, customize what happens on the client when the application calls one of the RPCs, and make the implementation of some or all RPCs overridable. We are using these possibilities actively in our current projects, we hope that WebSharper can bring joy to even more developers in the future.

By Kimserey Lam on Monday, August 29, 2016 — 0 comments

Bring internationalization (i18n) to your WebSharper webapps in FSharpCommunity

Bring internationalization (i18n) to your WebSharper webapps in FSharp When working on webapps which need to be used by international clients, it is important to provide internationalization (i18n). I18n is the process of developing web/desktop/mobile applications which provide an easy way to change language and culture to be localized to different markets. For example, English and French markets
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Tuesday, August 2, 2016 — 0 comments

Create HTML componants for your WebSharper webapp with UI.Next templateCommunity

Create HTML componants for your WebSharper webapp with UI Next template WebSharper.UI.Next comes with a simple template engine which can be used to build doc elements. It is built using a F# typeprovider therefore gives typesafety for templating. If you never used WebSharper or WebSharper.UI.Next before, I published a tutorial few months ago on how WebSharper works and how you can use it to
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Tuesday, July 19, 2016 — 0 comments

How to setup a nice output folder for WebSharper projectsCommunity

How to setup a nice output folder for WebSharper projects There are part of software development which aren’t very exciting. Setting up output directories is one of them. But we have to go through it because having a well defined output structure helps tremendously when time comes to deploy and publish an application. When using the default template from WebSharper, it could be confusing how and
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Tuesday, July 5, 2016 — 0 comments

From idea to product with WebSharper in FSharpCommunity

From idea to product with WebSharper in FSharp From time to time I get asked, Why do you use WebSharper? A legitimate question as from the abundance of libraries, tools and frameworks available, one might think that WebSharper + F# is just another hippie stack. My answer to this question is: What matters isn’t the tools that you use but the products that you build with those tools WebSharper
>> Read the full article on kimsereyblog.blogspot.com
By Frank Joppe on Monday, June 27, 2016 — 0 comments

Three is a crowd – Actor basedCommunity

I was asked to give a presentation at work about Akka.Net. Even though my audience is 100% C# loving, I will give a demonstration with F# code. I was already working on a project to rewrite “Three is a Crowd” to the Actor model in F#, and this presentation was a driver to finish this project. Let’s share my experiences with Akka.Net here.Choices and MotivationThere were two goals of rewriting the game to Akka.Net. First of all, I wanted to try out a few design patterns. Secondly, if you ru [...[...]
>> Read the full article on fjoppe.weebly.com
By Kimserey Lam on Tuesday, June 21, 2016 — 0 comments

Keep your UI framework up to date for your WebSharper SPA with Paket GitHub dependenciesCommunity

Keep your UI framework up to date for your WebSharper SPA with Paket GitHub dependencies Have you ever been guilty of referencing Bootstrap in your web app just to use one feature (like the navbar for example)? Hunting for the most full featured CSS/JS UI framework for hours. Referencing a huge framework just to use one or two features. Bootstrap, Foundation, MUI or Materialize, there are so many
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Tuesday, June 14, 2016 — 0 comments

Three ways to manage your resources for WebSharper SPACommunity

Three ways to manage your resources for WebSharper SPA WebSharper official documentation can be found here http://websharper.com/docs/resources. The doc focus more on how to reference resources for Sitelets so today, I will explain how you can reference your own js and css file and explore the different ways available to make the SPA of your dreams. There are three ways to reference files:
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Tuesday, May 31, 2016 — 0 comments

Transform your WebSharper web app into a Android mobile app with Xamarin.Forms WebViewCommunity

Transform your WebSharper web app into a Android mobile app with Xamarin.Forms WebView With WebSharper, it is easy and quick to build Single Page Applications (SPA) in F#. If you followed my blog, you must have noticed that I regularly post about WebSharper functionalities. Building a SPA using F# is one of the reason why I started to look into WebSharper. It is also the subject of one of the
>> Read the full article on kimsereyblog.blogspot.com
By Kimserey Lam on Monday, May 23, 2016 — 0 comments

Understand the difference between Direct and Inline attributes in WebSharperCommunity

Understand the difference between Direct and Inline attributes in WebSharper In WebSharper, there are two keywords to bind JS code to our F# code - Direct and Inline. The documentation about the attributes can be found here http://websharper.com/docs/translation. I have demonstrated the use of it in previous blog posts: External JS library with WebSharper in F# Sort, drag and drop in UI Next
>> Read the full article on kimsereyblog.blogspot.com