Sample projection

Hello, I try to create sample projection, which should return last value from TestEvent -

I try add projection with following code:

fromStream(‘test’).whenAny(function(state, event) { return event.body; });

but it ends with “Error: Handler must return string data”

I don’t know how to post string data, because Event.Data is byte[]. Is it possible to post string data from c#?


PS: I also note, that when I create new projection from webgui, it don’t use given name, but use some guid.

Hi Petr,

the error message is about the state returned from the state handler function. And the error message is partially incorrect as it reveals some internals and is not applicable to the user defined function.

The JavaScript projection function must return a state as a JavaScript object. The simplest can be return {}. The sample code should work unless you post non-JSON (or null/empty) data to your “test” stream.

You can try returning

return { body: event.body };

to wrap any body into a JS object and to see whether event.body is null.

Meantime, we are going to add an option to run projections with multiple internal checks, so such errors can be reported with detailed error messages. This mode will be slower, however.


Thank you Yuriy

it don’t work, but it helps me :slight_smile:

I changed your projection to:

//projection usefull for debug

fromStream(‘test’).whenAny(function(state, event) {

return { body: event }


it returns

{“body”:{“bodyRaw”:“Some data”,“eventType”:“WebApplication.TestEvent”,“streamId”:“test”,“sequenceNumber”:“7”,“metadataRaw”:"",“jsonError”:{}}}

It looks like it uses bodyRaw instead of body so this works fine

//my sample projection

fromStream(‘test’).whenAny(function(state, event) {

return event.bodyRaw


I also try basic counting projection

//sample count projection

fromStream(‘test’).whenAny(function(state, event) {

if (state.count == null) return {count : 1};

return {count : state.count + 1};


Thanks for help

If a project receives an event without JSON-formatted flag, it does not attempt to deserialize its body. The bodyRaw property is available for both: JSON and non-JSON formatted events.

You can also use log(‘text’)anywhere in your projection code for debugging. It just outputs the text to the server console (for now).

Thanks for explanation,

I would like to ask about correct way to add json formatted event from C#?


It looks like new version of Event Class had IsJson property :slight_smile: