Breeze and Web API (gui and no gui) - breeze

I'm building a new SPA, and I'm having some problems dealing with what appear to be conflicting concerns.
So, on the surface, the SPA is fairly basic CRUD. However, there's a catch: They also want all of the functionality to be available as Web API.
That sounds like a fit, given that Breeze works on top of Web API, but I keep feeling that I'm pounding a square peg into a round hole. Can someone give me a tow?
Example of the issue:
Suppose I have a screen for creating/adding widgets.
There are some validations
There are some business rules (if the widget weighs over 5 lbs, call another web service that sends an email)
So, with Breeze, that's pretty easy. I just hook up my EFContext Provider, and hook the BeforeSaveEntity(ies) events and go to town.
This is great, but they want a CreateWidget web API. It's not going to be acceptable for the client to have to build a Breeze compatible JObject bundle to simulate the save.
The API would seem to want a conventional DTO/Domain Service sort of thing. Something like:
string CreateWidget(widgetDto)
Breeze's client side library is fantastic, and I want to be able to use it for my GUI app. However, I'm having a hard time figuring out how to use Breeze and still separate concerns on my server side so that the domain services are usable from an imperative API, and so that they will support unit testing.
(I know you can override SaveCore, and I've looked at the NoDb example, but the important part just says something like "// your code would go here". Every avenue that I try smells like a huge hack, because really, Breeze wants control of the whole vertical stack on the server, and I just want it to decode the breeze client posts back to my DTOs so that I can map to the same domain services that my API will use, and then I want to traffic errors raised by my services back to the client (which we surface with the really excellent wzValidate angular directive).
I have read a lot of posts of people saying that if you really feel that you need DTOs, then you can use them, but I have come up empty searching for a working example that also incorporates business logic on the server. Can someone point me to a good resource?

Related

Does it make sense to separate Rails API and Rails app?

I have a project that involves both mobile and web clients. The mobile clients will mainly get content and post user updates, while the web client is mainly for creating content. As such, the web client and API share a lot of the same models and validation.
I am trying to decide the best approach in this case:
JSON-only Rails API + separate Rails web client that calls API.
Single Rails app with separation of API and client side (somehow).
The pro for me in terms of option N°1 is the separation of concerns, as I can work on the API while someone else do the web client. The con seems to be lots of duplicated code in terms of validation.
N°2 could make more sense in terms of reducing code duplication but it would get messy if more than one person is working on the same code base and setting up a process to resolve code conflicts is not something I want to do at this point since we're an early stage startup and want to get out something quickly.
Is there anything I'm missing?
The best practice is use ONE rails application for API and Web Interface
To separate those parts, just create a namespace for API like it's described there http://collectiveidea.com/blog/archives/2013/06/13/building-awesome-rails-apis-part-1/
Do it in one.
The con seems to be lots of duplicated code in terms of validation.
No, you would not have duplication the validation happens in the model, which is shared by your API <=> web controllers. Of course, you will have separate implementations for the actual authorization/session handling (if you have those), but these will not likely be duplicate but a bit different for your two access layers.

asp.net mvc consuming asp.net web api end point

Looking at this question:
SO question
The accepted answer by Darin Dimitrov looks appealing (.NET 4.5 version). I am just wondering how this compares performance wise with client side solutions (e.g. using knockout/angular/jquery) to assemble the HTML given some JSON from the web api endpoint. Did someone ever do some perfromance tests on this. What are the pros and cons of the 'client side solution' vs the 'razor server side' solution?
You should have to define performance.
However there is a very big difference between the two options:
if you do it client-side (with ko/ng/jQuery) the server only executes the API controller action and returns the formatted data.
if you do it server side, apart from execution the API action, the server has to execute the MVC controller action, so, undoubtedly, the server does more work.
The only conclusion is that the server has less work to do in the first case. And, usually, the network traffic is reduced (a JSON object is usually lighter than a rendered partial view).
If we're speaking about the user experience, in general client side technologies (jQuery, ko, ng) offer a much better user experience becasue the page is much more responsive: it's easy to show/hide elements, set the focus, make trivial calculations, remote validations... And if we use modern libraries, we can go further on improving the interface resposiveness. For example breeze.js allows to cache data in the client side to avoid making extra ajax calls to the server, giving a much more responsive experience, specially if you anticipate what data can be needed and cached it before hand. You could even persist data in HTML5 storage, so that it's available for other sessions.
Then, from the user viewpoint, I think it's much better the second option. And the server has less work to do, which can make it also more resposive in high-traffic sites.
Even so, I don't know what is "more performant" or even what it is "to be performant".
Whatever it is, using client side technologies is a much better option. But it takes some time to master the associated technologies.

Why does HotTowel include Breeze?

This may sound like a dumb question on the surface, but why does the Hot Towel SPA Template include Breeze at all?
I've been spending the last few days learning Hot Towel and its dependencies, and as far as I can tell, nothing in the template actually uses Breeze. Perhaps that is going to change with some future release?
Sure, Breeze is a good library. But it's bound to CRUD methodology and requires you design your ApiControllers a particular way. (Metadata, SaveChanges, etc.) see here
It also guides you to Entity Framework. While this is more of a soft-dependency, since Breeze also shows a sample without it, it still guides you down a similar pattern of implementation using a modified repository pattern.
If you are using a NoSQL datastore, or CQRS patterns instead of CRUD, then Breeze becomes very difficult to use. There are alternative libraries for data access that work well in this style, such as AmplifyJS.
But the rest of Hot Towel is excellent! I especially like Durandal. So the question begs, if the template isn't actually doing any data access - why include any data access component at all? It would be better to ship it without Breeze, and if the end-user wants to use Breeze, or Amplify, or whatever - then so be it. The rest of Hot Towel would continue to shine as a great SPA implementation.
Matt - Good question. Since I created it I guess I should answer :)
When I built the template I had a focus on providing enough to get folks going with the right tools, and just enough starter code to guide the way. I did not want anyone ripping out code. I'm not a fan of templates that start you down a path and make you remove tons of files and code and change direction. Those are samples.
Samples are good. In fact, samples can be excellent (like the other templates, which I feel are more like samples). Those serve another purpose: to show how you can do things.
Back to the Hot Towel template ...if I include code that uses Breeze, I would be tempted to add a datacontext.js and a model.js on the client. They would contain data access code and code to extend the models on the client. Then I would be tempted to add a controller, some server side models, an ORM and a database. Once there, I'd want to use the data in multiple screens, which leads me to more Knockout and caching with Breeze. Then I might be tempted to add editing, which would lead to change tracking. Soon I have a full blown app. Or more conservatively, I have a sample again. While these approaches would provide more guidance on how to put these together, they would not help you "get started" with a template where you can just start building and adding your own code. If I stop short of some of these features, it's still walking down a road that requires you to change how I did it.
As it stands today, HotTowel is pretty darn close to a template in the truest sense. You create a new project and you are off and adding your own code.
You could argue (and you may be) that Breeze shouldn't be in there since I don't use it in the template. Nor do I use moment.js, BTW. However, I argue that they are both excellent libraries that I would not want to build a CRUD based SPA without them. Breeze is flexible, as you suggest, so you don't have to walk a specific path.
The best way to understand the value of Breeze is to build an app that has its features but without Breeze. Then you can see how much code that takes and how involved it is. For one such example, see my intermediate level SPA course at Pluralsight where I do exactly this: http://jpapa.me/spaps
So you ask "why Breeze?" ... because I strongly recommend it for building a SPA.
Thanks for asking and good luck !
Thanks for asking the question.
John, as author of HT, has offered an answer. I, as a principal of the Breeze project, am inclined to agree with him :)
HotTowel generates a foundation for you to build upon. It is not the building itself.
It is a foundation intended for a specific kind of application, a CRUD application based on a specific set of cooperating JavaScript and ASP.NET technologies. Breeze is a contributor ... but not the only one. Knockout, with its MVVM design and 2-way data binding, is particularly well-suited to the data-entry tasks typical of CRUD apps.
Of course there are other kinds of SPAs. There's an important class of apps that mostly present information and accept little user input. Such apps don't benefit as much from data binding and the people who write them can get pretty hostile about data binding in general and KO in particular.
My point is that HT targets a particular class of application ... one that happens to be immensely successful at least when measured by sustained popularity. It delivers the goods for people who build those apps. It may not be the right starting place for other kinds of apps.
It is true that the easy road to Breeze runs through Web API, EF, and a relational database. Take those away, and you may writing more code on the server (and a little more on the client). That may be the perfect trade-off for you.
The authors of Breeze would like to make that path easier. I don't think BreezeJS makes it harder. I don't understand your statement "Breeze becomes very difficult to use." Have you tried it?
Your client can communicate with any HTTP resource in any manner you chose. It is pretty easy to use existing Web API controllers (albeit easier with Breeze Web API controllers). You can use amplify.js if you prefer (btw, you can tell Breeze to make AJAX calls with amplify). You don't even have to use the Breeze EntityManager to query and save data if you don't want to.
The rest of BreezeJS may still have value for you. There remains plenty of work to do after you've figured out how you'll retrieve and store data and whether you prefer Entity-ChangeSet style or Command/Query style.
You'll have to find answers to these questions:
How will you shape the raw JSON data into bindable objects?
How will you hold on to these objects and share them across multiple screens without making redundant round-trips to the server?
How will you navigate from one object to a related object as you do when binding an Address to a combobox of StatesAndProvinces?
How will you track changes?
How will you validate them?
How will you store some or all of the data in local storage when the app "tombstones"?
Breeze can help with these chores even if you don't want it to query and save for you.
And if you're answer remains "I'll do all of that myself, thank you" ... well, removing Breeze from your HotTowel project is as easy as:
Uninstall-Package breeze.webapi

Struts2 and multiple active wizards / workflows

I'm currently working on a Struts2 application that integrates a wizard / workflow in order to produce the desired results. To make it more clear, there is a business object that is changed on three different pages (mostly with AJAX calls). At the moment I'm using a ModelDriven action (that's extended by all the actions working with the same business object) coupled with the Scope interceptor. While this works okay if the user is handling data for only one business object at a time, if the user opens the wizard for different objects in multiple tabs (and we all do this when we want to finish things faster) everything will get messy, mostly due to the fact that I have only one business object stored in the session.
I have read a few articles about using a Conversation Scope Interceptor (main article) and about using the Scope plug-in (here). However, both approaches seem to have problems:
the Conversation Scope Interceptor doesn't auto-expire the conversations, nor does it integrate properly with Struts2;
the Scope plug-in lacks proper documentation and the last build was made in 2007 (and actually includes some of the ideas written by Mark Menard when he defines his Conversation Scope Interceptor, though it doesn't use the same code).
Spring's WebFlow plug-in seems a bit too complex to be used at the moment. I'm currently looking for something that can be implemented in a few hours time, though I don't mind if you can suggest something that works as needed, even if it requires more time than I'd currently want to spend on this now.
So, seasoned Struts2 developers, what do you suggest? How should I implement this?
Okay this isn't a fully baked idea. But seeing as no else has provided anything, here is what I would start with.
1) See if you can move the whole flow into a single page. I'm a big believer in the less pages is better approach. It doesn't reduce complexity for the application at all, but the user generally finds the interface a lot more intuitive. One of the easiest ways to go about this is by using the json plugin and a lot of ajax calls to your json services.
2) If you must transition between pages (or simply think it is too much client side work to implement #1) then I'd look to the s:token tag. The very first page to kick off a flow will use this tag, which will create a unique value each invocation. You will store a map in your session of model objects. An action will need to be provided with a model by looking it up from the session.
There are a couple challenges with #2. One how do you keep the session from getting too many domain objects? a) Well it might not matter, if the session is set to say six hours you can be rather sure that over night they will get cleared up. b) provided a self management interface which can get/set/list objects in the session. It might be what you thought of at first but it would let a worker do a certain amount and then stop and work on another. If the unit of work has some meaningful name (an invoice number or whatever) it could be quite useful.
A little more sophistication would be to move the model objects out of the session and into the service layer. At which point when inserted you would set an insertion time. You would probably need a manager to hold each type of model object and each manager would have a daemon thread that would periodically scan the map of domain objects and clean out expired ones.
You can figure out more complicated system by kicking a flow off with a token and then using another token on each page. "flowId" and "currentPageId" respectively, then you can graph allowable transitions.
Mind you at this point spring web flow is starting to look pretty good.
There is now a conversation plugin for Struts2 that achieves all these goals with very little work required by the developer: http://code.google.com/p/struts2-conversation/
It has:
-nested conversations
-cleanup of dead conversations
-convention over configuration with annotations and naming conventions
-inherited conversations
-fully integrated with Struts2
-the conversation scope can also be used by Spring IoC container-managed beans
Hope it helps somebody.

Combining Ruby on Rails and Backbone

I was wondering this for quite a while and haven't really found an answer for this yet.
Why would you use Backbone.js exaclty inside a Rails application? Is it to extend functionality, have a more MVC pattern for your JS, build better API's...?
At the moment I can't see a reason why you would want to use it for something, because I don't think I understand the concept of Backbone.js
The big advantage of rails is that you have one platform and one language that you use that will handle the server-code and can generate the client-code (using the views).
Undoubtedly this theoretical advantage quickly starts slipping once you want to improve your user-experience with javascript and jquery. So actually you still have to learn two languages.
But still: all your models, business-rules, ... is handled on the server-side in Ruby. This also means that the server always has to be reachable.
What a javacript/client MVC (like Backbone.js, Sproutcore, ...) can offer you is a more native application feel. A single web-page application, like e.g. Gmail.
Depending on your requirements there are some very valid use-cases for such a platform. E.g. in places or devices with low connectivity it could be very useful (with HTML5) to have a web-application that does not need to be "online" all the time. It could save data and edits to the local storage and sync back to the server/database when the device is back online.
But, there is a big disadvantage when developing client MVC applications in combination with Rails: you will have to do some double development (it is the same when you are using flex/silverlight). Your models will need to be defined both on the server and on the client. I can imagine that some improvements could be made, like on the client MVC you are actually using presenter-classes, which on the server-side could be stored in different models/tables. But still there will be duplication of logic, models, ...
So that's why I think that for most applications, at the moment, it is not wise to switch to some client MVC framework. It will be a lot more work.
But when you do need the look and feel of a real native application, or a one-page-web application, then a javascript client MVC framework is the way to go. And if you do need a client MVC framework, I would propose Sproutcore.
To simply ajaxify your current rails application (reduces load-time of every single page), take a look at pjax-rails.
(better late than never - hope this is useful to someone)
The description on backbonejs's website seems like a lot of words thrown together without much meaning. There is a big hype around it but what's all the fuss about?
The premise behind backbone is that modern day, single page web apps (think gmail) quickly become a very complex interaction between syncing dom elements, UI events and the backend. You could easily find yourself storing data within the dom elements, and then having to somehow extract the data again to update the database. If you don't structure your code very carefully, you'll quickly end up with spaghetti code full of complex bindings, or code without backbone.
Using backbone's models, collections and views gives you a well thought out structure to work within, allowing you to build large apps without being overwhelmed by their complexity. What's more, it ties in beautifully with a restful backend.

Resources