How to trigger HTTP requests based on OpenAPI .json files? - c#

I'm looking for a way to interpret an OpenAPI .json definition. This is my workflow:
The user provides the .json file during runtime.
I would like to show all existing endpoints, their HTTP methods, parameters and expected bodies like e.g. Postman or Swagger are doing it.
The user can choose one endpoint and an HTTP method, then provide all needed parameters and send a request. As soon as I retrieve the response I will show it as plain text to the user.
The user can choose an endpoint and HTTP method and I will serialize the information needed to do step 3. later again without reading the whole .json file again.
I googled and tested a few libraries but did not find one or multiple which do exactly what I'm looking for.
I think OpenAPI.NET might do the reading job necessary for step 2.
Regarding the part that's able to trigger the HTTP request I only found fully-fledged "Client Creators" which take an OpenAPI .json and create C# code which can then be compiled to get a full client library. Many of these "Client Creators" are also build up on other tech stacks (e.g. Java) and make it difficult to use from a .Net application.
I had a deeper look into NSwag which is written in C# and can be installed as a NuGet but again this one creates C# code that needs to be compiled and it also seems it creates way more then I need (deserialization and handling of Non-OK status codes etc.)
I would just need a way to create something like a System.Net.Http.HttpRequestMessage or RestSharp.RestRequest. I could have a look into what it needs to create them by my own but I fear to reinvent the wheel and miss some more specific parts of the OpenAPI specification.
Do you know any libraries that would help me achieving my workflow but especially step 3 and step 4 of it?

Related

.NET Core WEB API Modelbinding: how to make use of JSON Schema validation

I have a JSON Schema and want to make use of it iny my PUT/POST/PATCH API endpoints.
Basically I want to make use of JSON Schema validation and handle invalid JSON in the Http request pipeline.
I did not findy anything on the internet on that matter so I start thinking that I might missunderstood something essential here.
I assumed I could register Json Schema with options as middleware in startup but well, how can this be done ?
You'll want to check out OpenAPI -- it provides the specification that builds on top of JSON Schema to enable request and response validation, document generation, code generation, and lots more.
Also see https://github.com/OAI/OpenAPI-Specification/blob/main/IMPLEMENTATIONS.md for a list of implementations (although there are many more out there that aren't listed, too).
In a previous version of the site, I used this middleware for https://json-everything.net, which is my showcase site for my JSON library suite. It's powered by JsonSchema.Net, which itself is part of the suite.
It's likely not the best way to do it, but it works well. I'm still playing with it before I put it into a library, but you're welcome to copy it for your uses.

get raw xml response from amazon mws api

I am developing a software solution using Amaon mws api in c#, using the classes from their c# library. I would like to get the xml response info in raw form, not thru their classes which are a little clumsy for my needs. Is there anyway to get out the full xml info from the response object? Please reply
They've made it easy by serializing everything into objects for you. You can go through their Sample cs file (MarketplaceWebServiceProductsSample.cs for the Products API) and dig out the method you want to call and put it into your own app, and then make the call, get back the serialized objects and then you can do what you want with them, no need to look at raw XML.
However, if you want to, just add the code that is in the runtime-src folder of the client library to your project, set a breakpoint and step into the code. You'll find it in there eventually and then copy out the parts you need.
I've written about a dozen client applications that use the various MWS client libraries and I find them easy to work with. If you don't like their classes, just write a method that converts theirs to yours.
Im not very sure about C# library.But you can get raw xml response over http connection. You can refer this:
http://docs.developer.amazonservices.com/en_IN/feeds/Feeds_GetFeedSubmissionResult.html
All the best :)

Designing code for accessing a WebService that accepts xml requests

I'd like to create C# code that accesses a WebService that has only 1 method:
public string HandleRequest(string xml).
The request itself is sent in xml, where the xml content specifies which type of action to perform and required/optional parameters as well.
The response from the service is also returned in xml and may be different per each request type that is sent.
I'd like to design a solution that will facilitate interacting with this service, and that will allow me to:
Dynamically generate an xml from given parameters (action type, other optional args, etc). Currently the xml is loaded from a file that was already created
Parse the response in an easy way (creating a strongly typed object from it?)
What's a good solution for doing this? I find it hard to come up with one, as the request/response xml is dynamic and may change from call to call.
Some additional info:
The service is Java based and is hosted under Tomcat (Axis 1.2)
There's no wsdl document for the service (even if there was, i wouldn't be able to automatically generate some strongly typed request/response classes, as the service itself receives and outputs only XML and not some complex type).
That sounds like an XML-RPC implementation could be what you are after. From Wikipedia;
XML-RPC works by sending a HTTP request to a server implementing the
protocol. The client in that case is typically software wanting to
call a single method of a remote system. Multiple input parameters can
be passed to the remote method, one return value is returned. The
parameter types allow nesting of parameters into maps and lists, thus
larger structures can be transported. Therefore XML-RPC can be used to
transport objects or structures both as input and as output
parameters.
Wikipedia also lists some Java Implementations of this protocol.
While, I've not used this specifically, I've worked with a service designed around a bastardised version of JSON-RPC. As it didn't follow the spec truely, we couldn't utilise any pre-existing implementations.
Personally, I didn't see the benefit of using such a protocol as we still needed to have clear definitions of the operations exposed by the service along with their associated constraints such as mandatory parameters etc. In addition to that, we had to handle the serialisation/deserialisation of JSON (XML in your case) to the associated object model. This was largely due to the vendor we were interacting with and their lack of conformance to the spec. If yours is conformant, then you may find that the existing implementations provided might give you a neat way of handling this.
Note the critisims regarding bloat of XML-RPC on Wikipedia too. It might pay to look into JSON-RPC as an alternative. There are certainly a few implementations listed that you can check out.
Edit: I didn't read your question properly. Sorry. I thought you were looking at providing a service. I'd still look at the links around XML-RPC/JSON-RPC as it may give you an idea as to how to knock up a test client. As far as .NET goes, I looked at the Jayrock codebase to get an idea of how the JSON-RPC protocol was implemented and if we could have used that in our scenario. You can get a rough idea as to how they handle the requests and responses. From memory, they may even have a test harness or sample code showing how to call the service. That could give you some ideas.

How can I retrieve SoapEnvelope information just from the URL of web services in C#?

Basically I am trying to make a generic client which will retrieve the Methods Names, Parameters that it takes and Parameter that it returns from the any kind of web service. I thought of parsing the WSDL xml for that, but in that the required information is scattered over different elements. then I saw the SOAP Envelopes which contains the exact information I need. so I thought of downloading the web service page and doing the series of string operations so that I get extract the data I need from particular tag. but I guess there might be any C# functions which can give me this data containing the Request and Response headers information.
Can anybody please guide me.
Thanks in advance.
The only valid approach is through WSDL because it is the only real description of the service. Those "help pages" are just a feature of ASMX. WCF for example doesn't have this help page showing examples of SOAP messages. Also examples of SOAP messages don't really cover the whole content of the message - it doesn't correctly show which elements are mandatory and which are not. It doesn't correctly show advanced features like XSD choices etc. If you want to write generic client you must parse WSDL. It is really BIG task. Also be aware that WSDL can reference other WSDLs and XSDs.
To make things much more easier you should check available classes in .NET framework to deal with service descriptions. For example System.ServiceModel.Description.MetadataExchangeClient and other classes from that namespace.

Accept Data With A Webservice C# .NET 3.5

I was curious as to how I would accomplish the following with webservices:
Authenticate a user.
Accept a CSV or XML file.
Process the file and put it into an SQL database.
Someone mentioned in a previous post that I should use a webservice. I can't seem to find any resources that explain how to begin something like this. All the simple examples seem to just show how you can serve XML given a query.
I want to know how to accept stuff and also, how this would differ from an upload control on an authenticated webpage. I don't think I really understand webservices and their benefits.
How would the user sending the XML file interface with my webservice?
If you want to do large file uploads, then a web service may cause some issues, because some web service platforms (including .NET) have default settings limiting the size of the data.
The advantage of a web service is that it does all the mapping of the request to/from XML, so you can return a .NET type, and don't need to muck around with processing request parameters.
However, you may have to put more effort into maintaining state, etc.
For logins, what you can do is have a login function that returns some kind of identifier which can be used to verify the user as valid for that session - one way of doing this being to have columns in your user table for lastActive and sessionGUID, and when they log in you generate a new sessionGUID and return that, and on that and any other valid request they make you update the lastActive, and if there is a request too long after the lastActive time, then you refuse the request... there's any number of similar ways of doing that, but hopefully you get the general idea - you don't want to require the login details each time, but you can generate a temporary identifier and use that.
For accepting an XML file, you'd want to use something like XDocument or XMLReader to read the data that you receive. Assuming you're not talking about the parsing of the XML format that the web service itself uses, you're most likely to be receiving a string and then pushing that into an XDocument and then using the standard XDocument functions to process the data. If the document would be large, then XMLReader should be more efficient.
For reading a CSV file, there are some (free and non-free) CSV readers which help avoid some of the issues you can have, giving you a nice API for processing a string or strings of CSV data. If you know that the source data doesn't have non-structural commas, though, you can just take the string and split it by commas, and then strip any quotes around the values. That tends to get flaky quite fast if there might be addresses or other data that could have commas in, though.
The XML should be able to be passed via the web service just fine - it should be encoded and decoded, so it's then compliant strings being passed out.
As for storing it in a database, there's any number of ways to do that - you can use ADO.NET to store things in a database without further libraries, you can create a database structure in Visual Studio or SQL Server Management Studio and then use SQLMetal or Linq to SQL to generate classes for saving the data, you can use a 3rd party database mapping tool (such as Castle ActiveRecord), or whatever. It depends what you know and how much you're willing to learn. That's really separate to the web service. When you define a web service in .NET you effectively define standard functions with attributes marking them as web services, so the database side is standard .NET database stuff that's not necessarily any different to what you'd do for an ASP.NET website, or even a desktop program.
A web service is not really appropriate for sending an arbitrary file. It can be done, but if that's your only reason for creating the web service, you might as well just stick to HTTP.
If the file has a specific format or specific contents then you might want to create a web service for that. The purpose of an ASMX or WCF web service is to provide discoverability and strong typing to the data (among other things, but I'm sticking to the basics for the moment). From the perspective of the client, instead of trying to create some ugly XML or CSV blob and chuck it over HTTP, you use an actual service proxy with POCO classes:
MyService service = new MyService();
MyData data = new MyData() { ID = 3, Name = "Test", Date = DateTime.Now };
service.Save(data);
Visual Studio (and equivalent tools in Java and some other platforms) will take care of generating the proxy for you, so really all you have to do is write the above code.
But if you're just trying to send any data, this won't get you anywhere, because you can't generate a proxy for raw XML. Well, you can, but it would just be an XmlDocument and that accomplishes nothing in terms of usability, type safety or discoverability.
Don't get confused by the "XML" in "XML Web Service". It's not a tool for sending around vanilla XML. Rather, XML refers to the format of the message, as it is transmitted over the wire, as opposed to a POST string (id=3&name=Test&date=2010-01-24) or a binary RPC call as used in .NET Remoting.
In terms of authentication, if you do decide to use WCF, you just have to use the right binding. A WCF proxy is normally configured by default to use wsHttpBinding, which uses integrated Windows authentication to secure the messages. Again, assuming you use Visual Studio, this is all done pretty much automatically for you unless you decide to change the defaults.

Categories