JSON based architecture, how best to synchronise front end and back end - c#

Looking at using JSON for a new .net REST based system and it looks great, but there is one thing thats alluding my understanding. What is the strategy for keeping the JSON on either side of the application in sync?
What I mean by that is if you do a GET for : www.mysite.com/item/12345. Then the .net side of the application goes away to the db, retrieves the Item with id 12345 and resolves it to your object model Item that is then serialised to JSON and returned.
If you do a POST to : www.mysite.com/item and pass -
{
"Id": "12346",
"ItemName": "New Item",
"ItemCost": 45
}
Then the .net side of the application picks it up, deserialises it to an Item object and then hands it off to be added to the db.
How do you get both sides, your JS object model and your .net object model serialisation to sync up? Does this just need to be maintained by hand or is there a clever way of providing a template for the JSON based on the serialisation of the .net model?
I'm kinda just looking for best practices and whats the done thing and don't see how the client side knows what JSON to pass to the server side.

Personally I've found it easier to 'drive' these changes for the .NET environment. Not wishing to teach you how to suck eggs but Javascript is a very loosely bound language means changes / functionality / properties can be added on the hoof whereas in .NET it is far easier to test and stablise your POCOs in a more rigid manner.
One method I have recently toyed with is generating empty POCOs from my service when creating objects, manipulating as appropriate before then pushing them back to the service for persistence, etc. It still doesn't resolve that wild-west like feeling of working in Javascript, but at least the DataContracts can match up on a superficial level.

Related

Creating contracts between React front-end and C# back-end?

I consider myself to be pretty well-versed in C#, but with React / Typescript I'm a relative beginner. One thing which I liked about pure C# projects is that my front-end and back-end can both be based off of the same object model, which means when I make an API call to the back-end, I can be sure that the object I'm passing from the front-end corresponds to the object I'm expecting to receive on the back-end.
Does something like this exist with React / Typescript? The project I'm working with, as-written, has an ApiModel.ts file (which is ostensibly auto-generated) that contains the models for the objects I'm passing - but to me, this feels like a weakly-typed setup. Other than a friendly warning message at the top of the file, there is nothing preventing me from modifying the ApiModel.ts file to add properties that are not present on the receiving end (which, presumably, would either cause an error or be handled internally).
Basically - tl;dr, is there any way for me to validate, at compile time, that the API model on the React side properly matches the API model on the C# side?

Do I have to really create multiple models?

MS stack developer historically.
I have committed to retooling to the following stack
angular -> ms web.api2 -> C# business objects -> sql server
Being old, I develop the database from requirements and use Codesmith to generate the business logic layer. (yes, I have heard of entity framework. even tried it once).
As I embrace Angular and web API 2
I find that Angular wants me to write a model on the front end. This seems to be just a data structure, I cant even add helper methods to it
So I also often write a class with helper methods that takes an instance of the model. Kind of ugly,but it does marry structure and logic.
I find that Web API2 wants me to write a model. This again seems to be just a data structure. I am exploring the dynamic data type, but really this doesn't buy me much. Instead of writing a class, I'm writing a mapping function.
The question is this:
Is there any way around having 3+ copies of each class spread across the stack?
Codesmith is a very capable code generator... it can gen multiple files... but...
If its just a couple data members, and 3 places, I can copy paste edit and get it done.
Just seems to me that now committing to keeping a data structure in synch in 3 different environments is setting oneself up for a lot of work.
I have spent the last 15 years trying to shove as much code as I can into a framework of inheritable classes so I can keep things DRY.
Am I missing something? Are there any patterns that can be suggested?
[I know this isn't a question tailored for SO, but it is where all the smart people shop. Downvote me if you feel honor bound to do so.]
Not entirely familiar with how CodeSmith generates it's classes, but if they are just plain-old-CLR-objects that serialize nicely, you can have WebApi return them directly to your Angular application. There are purists that will frown upon this, but depending on the application, there may be a justification.
Then, in the world of Angular, you have a few options, again, depending on your requirements/justification, and your application - again, purists will definitely frown upon some of the options.
create classes that match what's coming down from the server (more correct method)
Treat everything as "any", lose type safety, and just access properties as you need them i.e. don't create the model. (obviously less correct method)
find a code generation tool that will explore API end points to determine what they return, and generate your typescript classes for you.
Personally, using Entity Framework, I (manually) create my POCO's for database interraction, have a "view"/DTO class that WebAPI would then send back to the client, and a definition of the object in Typescript, but I am a control freak, and don't like generated code.

project design, am I understanding this correctly

I'm a software developer but always worked on "small" projects/solutions.
Now I'm trying to create an application from scratch on my own, just to stay in touch with new developments and learn new stuff. I'm trying to use everything I've never used before.
So basically that means I'm developing a c# application, using EF core 2.1 and SQL Server.
I've read a lot of articles online and I learned A LOT already. But I'm still confused because everyday I find a new article using a different approach.
I would like the opinion of some other developers on what I've got so far.
First of all I'm used to WinForms so for now I'll use that as my UI. Just because I can get fast results with it. Afterwards I'll try using ASP.NET Core.
I also want to be able to use an other UI and still be able to use the rest of my solution.
I have several projects in my solution:
1. Data: EF Context, DbSets, Migrations
2. Models: EF models, used in EF Context (nothing more then POCO's)
3. DTO: Objects exposed to the UI (again, classes and properties, nothing more)
4. Mapper: "DTO to Model" and "Model to DTO"
5. Services: static classes and static methods/functions using all the above, containing the logic. for example GetCustomer uses the EF context class to read the database, gets the model, maps it to a DTO and returns it.
6. UI: binds to the DTO objects and uses the services for every user "action".
That's it, in a nutshell. But am I on the right track?
I've read a lot about IoC but I'm not there yet, but as far as I understand that has "nothing" to do with the above.
I do have 1 specific question: In WinForms there is validation using the IDataErrorInfo interface and for binding I need the INotifyPropertyChanged logic. Where does this belong? I would say in my DTOs but some say a DTO "can't have" any logic.
I'm sorry for the long "question" but I'll appreciate any input to make sure I understand all of this correctly.
A DTO is usually not intended for presentation. It is intended to send raw data, so they're usually dumb objects and are basically just a bunch of property setters and getters.
A View Model is intended to be sent to a View and a View Model also sends back data to a controller. The ViewModel sometimes takes responsibility for presentation logic.

ASP.NET REST API Collections

I'm trying to build REST API based on existing database model. I have already one built but I want to make it simpler and clear before I start coding client app. I've decided to use ASP.NET Core as back-end technology and WPF front end (also there will be Angular/Ionic frontend). The database model is very simple, it contains around 30 tables (different documents with related resources and collections).
So far API use flat URL - this way sometimes I have to post/put child object with its parent. Should I go with nested URL (API/Document/{id}/Item) to make sending object simpler or even use the only id which makes this object flat?
The second problem I have when I need data from child object for data needed to data grid source - should I add new method/controller to get ViewModel with all properties needed for data grid or should I get parent object collection first and then get child objects and construct view in client app?
Ultimately, this choice depends on many parameters and also on your team preferences. You didn't give enough details to give a absolute advice, but even though you did give them, there might not be any absolute answer anyway.
When in doubt, for both of your problems, I would recommend to go for the flat, simple, complete data transfer objects. (EDIT : of course won't be flat if you have linked collections, but still it would be simple and complete)
This has the advantage of reducing the number of connections / calls to the API, which have some overhead for all the network infrastructure, and for the client too.
Second, I think this simplifies development (but I admit this is debatable)
And also, about the second problem, it helps separate the concerns between your API and your client app. Building a ViewModel is often necessary (you maybe don't want to expose some informations, for security or performance reasons), but don't make it too complicated just for the client app; you want your API to be easily used by a new client / new version later.
To show you why it's usually worse to do many individual calls :
Imagine if you want to retrieve 40 documents.
If each document has Item1 and Item2, that would be 80 more calls if you have to retrieve Documents/1/Item1, Documents/1/Item2, etc.. !
Also, for your front-end development, you have to manage the callbacks (first call the document, once it's done get item1 and item2) which seems more complicated than getting the whole lot in one go (since ultimately you need to wait for everything to be there).
Worse, maybe some of the object has changed, and his children too, in between the call. You might end with Version A of your parent object, but with version B of it's children items !
Of course, there are some situations that could make the decomposed children items calls interesting.
If you often have to get only the item part of a document, without needing to reload the whole, that would be a good argument for that.
Or if the overall document is large, and you want to be able to display parts of the loaded documents before the complete loading is finished.
A last drawback I can see, when you have linked collection of related objects, is that you can have many repetition of linked objects. In this case it could make sense to do something more tricky if you need to avoid too many repetition, and have a few separate calls for main object, relations, and load related objects only once even if some are used multiple times can be beneficial.

Asp.net Web API objects definitions

I am working on the asp.net web api where i have to return back objects in json. With respect to making a better approach and easy for (android/ios)mobile developer to consume these Web APIs and parse json objects, what is best approach for making these objects definitions remain shared amongst webapi project and mobile project, so that if we have to change any property then it can easily be reflected on both projects in a better way. It would be great if someone explains it in detail.
There is no such sync method as you are asking.
On your WebAPI server side you'll define the objects and then return them in your API methods. JSON serialization will be automatically handled by the framework, using your serialization engine of choice (i.e. JSON.NET). Remember that with WebAPI you don't decide the output format server side, you just return a response containing the object(s) and then the framework reads the HTTP HEADERS of the request to determine whether the client asked for JSON or XML and then returns what was asked.
The best thing you can do is define a clear API with nice conventions and keep it documented, and if you change anything have the documentation reflect the changes. Avoid making breaking changes, and if you really must, deprecate a property or an object for at least a couple of versions before removing it.
That's the way all public API work anyway.

Categories