views:

130

answers:

4

I have a library with some objects that I use both from C# and JavaScript. There are several objects, let's call one of them Foo, with the same basic implementation in C# and JavaScript. When I want to transmit an object of this type from the server to the browser, I simply call Foo.ToJson() to serialize this object to JSON and then revive the object on the browser side with a safe eval() operation.

This is all well and good, but the library is becoming complex and the need to keep the JavaScript and C# code bases synchronized is increasingly difficult and error-prone. I'm interested in ideas for simplifying this architecture or making it easy to maintain. Thoughts?

+3  A: 

You could look at using script#: http://projects.nikhilk.net/ScriptSharp

Since your classes are all coded in C#, you could reuse the same .cs file for both the server and client projects. that way, when you make changes, it's automatically compiled into the javascript :-)

Joel Martinez
Script# looks really nice. It would be nice to generate my JavaScript code from the C#.
PeterAllenWebb
+1  A: 

have you considered making your "shared code" into a web service, this way any of your applications can access it, and you can make everything distributed to help with performance.

Just one solution.

http://en.wikipedia.org/wiki/Web_services

Robert Greiner
So under your strategy I would not maintain a copy of the object client side, but rather make web service requests to update and query the state of a server-side object, yes?
PeterAllenWebb
correct, this way you reduce the amount of client code and can share you common utilities across all of your applications. Another benefit is that you can access your web service using virtually any programming language.
Robert Greiner
+1  A: 
  1. Make the parts of your app that overlap as data-driven as possible. At a certain size, it's easier to have a state-machine interpreter running on both sides that can parse the same data.
  2. Write the code once. There are a couple C# to JavaScript compilers you can look into. Script# and jsc.
Nosredna
+1  A: 

Use DTOs. Data Transfer Objects.

This way if your JScript or C# objects change, your DTOs don't necessarily have to change unless that property is immediately required at the client. And even then, you have a clear separation of what is intended to be Serialized and what is not.

Dave Ward at Encosia speaks a lot about this.

Jonathan
That's a terrific article.
Nosredna