How to walk a C# object hierarchy and create JSON string? - c#

I am creating a metadata site for our API. It is like swagger implementation. Currently I am facing difficulty with creating a sample JSON representation of our request response objects. These are complex objects that may even contain lists.
Right now I am at the point where via using reflection I am able to find all the request and their corresponding response objects.
Is there a library that can convert a reflection
assembly.GetType("FullyQuallifiedObjectName")
output to a JSON sample string? My research so far has not been fruitful.

Implementing your own inspector class may be too difficult and take much time. You may consider Microsoft's way to build help pages in WebApi. New Mvc4 and Mvc5 projects in VS2013 already contain complete help pages in WebApi templates.
(You do not need to implement custom XmlDocumentationProvider, just create a new WebApi project in VisualStudio 2013 and you will find completed xml doc provider)
If you use WebApi - it's exactly what you need. If not - modify and reuse already implemented xml doc provider.

Related

.net 6.0 Core migration changes JSON from framework. Polymorphism restriction

We're migrating a .net 4.7 framework solution to .net 6.0 (core). The solution interfaces with a React front-end system, and a NodeJS MongoDb back-end, so we have gone with the MVC model and copied our code to new projects.
Our problem is the change in design relating the the JSON controller response. In the live system, the JSON sent to the external system is fully resolved to the polymorphic version, while in the new core system it is resolved to the base class. Here's a snip of the response class:class start showing interface used to send the screen data to display
Postman shows us that when we have the interface swapped with a base class, the JSON response is the base class. Interestingly, swapping it for an interface has the default JSON response (System.Text.Json) use the properties in the interface, while Newtonsoft.Json correctly renders the full/inherited class with JsonConvert.SerializeObject() versus JsonSerializer.Serialize().
We have changed the Program.cs to include "services.AddControllers().AddNewtonsoftJson();" which seems to get past our problem so far, but I'm assuming it should be possible to use the new library instead. Performance isn't an issue, but we are upgrading to stay on a strategic path.
We have looked at explanations like https://www.tutorialdocs.com/article/webapi-data-binding.html and https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-polymorphism but don't know the best way forward. Get rid of polymophism (composition instead of inheritance?) But then our system just exported the interface properties. We've also tried to validate our System.Runtime.Serialization annotations, but without success.
We'd appreciate guidance on a good approach to solve this.

ASP .Net Core Dto's and Controllers to typescript classes & interfaces

My idea consists of two main elements:
Take C# Dto's (Data-tranfer-objects) and convert them into typescript interfaces to ensure client-side models are in sync with server side.
Take ASP .Net core controller endpoints and convert them to typescript classes that uses a http-service or similar. Again, to ensure client-side requests are in sync with the server.
And whenever a change have been made to a controller or dto, the typescript generated items should then refresh to stay in sync while developing.
I have done some research and found the following Stack Overflow threads and other sources:
DTO to TypeScript generator which suggest using the TypeLite library, which seems great, but according to the documentation, this either requires a [TsClass] Attribute or a reference to class on startup. But, since the project structure I'm using is setup so that all dto's is located in a *.Dtos namespace, I'm kinda missing a TypeScript.Definitions().ForNameSpace(). Also, this only solves the first idea/problem.
Swashbuckly.AspNetCore Would allow me to generate swagger documentation from both the controllers and dto's, and then the task would be to someway interpret the swagger documentation and create typescript classes and interfaces from that. The cons is that as far as i can read, this requires me to startup the server, which if possible i would like to avoid since it would make it hard to update on file change.
FYI, this is a new project I'm about to start, so there's no legacy code to update, also, all of the ASP .NET Core endpoints will return IActionResult to enable the return of Ok(), BadRequest() and so on. So to get the return model would in my mind be hard, since there's not an easy way to get the dto it produces, if any.
So, i have thought of the following solutions that solves both problems:
Create a separate package/application that uses the Swashbuckly lib and generates the models and controllers without starting up the whole server.
Create annotations on every endpoint, something along the lines of [Produces(SomeDto)], where after i would create a small console-application that uses reflection to get information and generate typescript from that. This would of cause requires developers to keep this information in sync, so in my mind there's kinda duplicate information.
But, both of these solutions would not auto-update on C# source file save.
Looking forward to any discussions/suggestions.
Considering your first point, I made a C# DTO to typescript interface generator that uses MSBUILD tasks so its completely independent of your workflow. It also just does it from the source which makes it a bit less stable but you don't have to make any template files.
Find it here or just search for MTT on nuget
In case you are still looking.... I think Typewriter http://frhagn.github.io/Typewriter/ is your solution. You can generate templates specifying what and how to transform.
It doesn't meet all of my needs only because I need a tool to dynamically generate a complicated folder structure, but that's coming in their v2 roadmap.
Besides that, it does a lot of heavy lifting and is pretty easy to configure.

Per resource Json Formatting asp.net core

I am building a REST api using ASP.Net core 1.0.0, and I am currently trying to figure out a way to serialize and deserialize Incoming request body and out going responses.
for example, I have the following
[HttpPost]
public async Task<IActionResult> Post([FromBody]ScheduleEvent scheduleEvent)
{
.
.
.
return Ok(scheduleEvent);
}
The thing is, ScheduleEvent is a database model, so not all the properties should be sent or received from/to the client.
The only solutions I could find are either creating DTO classes and converting the DTO objects to and from model objects, or placing jsonattributes over the object. The first seems like an unnecessary workaround, and the second forces you to make your models depend on json.net, besides the fact that it also makes serialization and deserialization exactly the same. Basicly they all seem like bad solutions - mostly since json.net allows using schemas to invalidate incoming/outgoing json, and If someone were to use it he could create such functionality easily by creating input and output schemas per type or per Controller/Action.
However, JsonConverter doesn't seem like the right way to go, and creating my own json output and input formatters seems like a lot of work, for something that might have a better solution.
So basically, the question is, what is the common way of addressing this problem, and do you know any better solution?

NSJSONSerialization in iOS 5 like c# serialize to class

I am porting our C# MVC Repository code to iOS5 for the iPad. I have been working successfully with the calls to the services, pulling Json and serializing to built in NS objects. But this seems like a lot of work to pull the pieces out and then assign them to a class. In C# this is a breeze, just serialize to your class, mapped to the data attributes and you are off with a strong typed view model.
Anyone done something similar in iOS/XCode and I know you can use NSData in interesting ways, I am just not expert enough yet and I am looking for pointers and best practces.
You question is not very clear to me. But as per my interpretation, you want to consume web service data in your application.In that case, see if it helps to you:
Are you able to connect to web service and get serialised data from it? You will receive data in object of type NSData. Then you you can use NSXMLParser class (initialised with NSData received from web service) and it's delegate methods to parse the data.
This blog may help you:
http://iphonebyradix.blogspot.com/2011/04/working-with-webservices.html
If you want to write serialised data, using NSJSONSerialization class then you can use
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
method. You can find details on developer.apple :
https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Try the KeyValueObjectMapping project on github, it has some good support for object mapping(auto) and remapping if the property/class is named different from the context of the json.

Generate Contracts for REST objects

I'm new to REST and this sounds like it should be pretty simple. In a .NET app, I can create a reference to a WCF service and the contracts for all the available types will be generated for me.
Now I'm trying to consume a REST service in a Windows Phone 7 app. While I can make my call and get back the proper response, is there a simple way to create the classes that each object would be deserialized to?
I'm using RestSharp to manage my calls. In some examples I've seen, user's have created their own classes, and generated the xml manually. I would like to avoid this if at all possible.
many thanks!
Assuming your response is XML, you can save the xml into a file, then call xsd.exe on it to generate a schema. Call xsd.exe on the schema and it will generate a c# class file you can seriazlize and deserialize to from the xml. Here's the documeantion on how XSD.exe works:
http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=VS.100).aspx
You have to generate the classes that your response data will map to (or use a dynamic deserialization scheme if you're on .NET 4) since REST does not include a schema definition system the way SOAP does. In RestSharp, there's a T4 helper to make generating the C# classes easier. It gets you about 80% of the way there. If you need any help with it, post to the RestSharp Google Group.

Categories

Resources