I use Visual studio with Xamarin, c#.
I've done a REST service with Slim, PHP and MySql. It works fine (chrome ARC is awesome).
I want to be able to use POST, GET, PUT and DELETE from an application. Searching the web I found tons of things, but I didn't find anything for C# (always java, I'm sure I have to learn it very well!), or if it's for C# it is not suitable for mobile app (like using System.Net.Http).
(my rest uses application/x-www-form-urlencoded as Content-Type of the Header, I don't know if it change something).
I have no clue, any suggestion is apreciated.
(Sorry if it could looks like a repost, but really, I didn't find any way searching for 3 hours)
Are you trying to find something that will allow you to use your REST service in an App?
Check this blog post on network services for Xamarin. It talks about using Refit which is a really nice library here is its github.
What's Refit?
Refit (along with http://json2csharp.com) allow you to really quickly create client libraries for Web APIs, by defining their contract in an Interface, and letting Refit do the grunt work of implementing the API for you. Here's an example:
public interface IGitHubService
{
[Get("/users/{user}/repos")]
Task<List<Repo>> ListRepos(string user);
}
It also supports application/x-www-form-urlencoded as you can see here
Form posts
For APIs that take form posts (i.e. serialized as application/x-www-form-urlencoded), initialize the Body attribute with BodySerializationMethod.UrlEncoded.
The parameter can be an IDictionary:
public interface IMeasurementProtocolApi
{
[Post("/collect")]
Task Collect([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
}
var data = new Dictionary<string, object> {
{"v", 1},
{"tid", "UA-1234-5"},
{"cid", new Guid("d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c")},
{"t", "event"},
};
// Serialized as: v=1&tid=UA-1234-5&cid=d1e9ea6b-2e8b-4699-93e0-0bcbd26c206c&t=event
await api.Collect(data);
Related
Hi does anyone know how to use the streaming API for C#? Therefore, whenever there is a new tweet in my account, it will be reflected in my program.
So far the only reliable wrapper I've found for this in .Net land is TweetInvi. Try to ignore that the web site looks like it was designed by a hyperactive 10-year old (thanks MS 'metro' team), the actual library is very well designed and rock solid.
Assuming of course you have the relevant access tokens (if not see http://dev.twitter.com), an example of how easy it is to have up and running:
TwitterCredentials.SetCredentials(userToken,userTokenPrivate,apiKey,apiKeyPrivate);
_userStream = Stream.CreateUserStream();
_userStream.TweetCreatedByFriend += (sender,args) => Console.WriteLine(args.Tweet.Text);
_userStream.Start();
This will write the body of tweets to your console output, and it updates even faster than leaving the actual Twitter web site open. There are other events exposed for when a tweet is favourited, retweeted, when you have a new follower etc.
I can vouch for this library as being reliable - I am using it for my CovertTweeter project and have had absolutely no issues with it. In fact accessing the streaming API through TweetInvi has been even easier than the many brick walls I was left hitting when using REST wrappers like Linq2Twitter and TweetSharp.
Have a look at this post:
Streaming with New .NET HttpClient and HttpCompletionOption.ResponseHeadersRead
You don't have the complete implementation there but you will get the idea.
Here is a sample which "Reads data from the Twitter Streaming API and adds it to MSMQ. A second process (included) reads from the queue, parses the json message, and updates a data store."
https://github.com/swhitley/TwitterStreamClient
You can change the above problem to generate an event when it updates the data store. In your program you can subscribe this event to do whatever you want.
If you are looking for OAuth based sample then please use "AuthPack" which Provides .NET oAuth for Twitter, Facebook, LinkedIn, and Google:
https://github.com/swhitley/AuthPack/tree/master/AuthPack
I have found a good sample code that uses streaming API, here Twitterizer.
This is how I have currently managed to consume a particular Microsoft web service. Notice that it is located on an HTTPS server and that it requires a username, a password, and a .cer file to be installed in the operating system's "root certificate authorities".
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Message.NegotiateServiceCredential = true;
binding.Security.Message.AlgorithmSuite
= System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
binding.Security.Message.EstablishSecurityContext = true;
EndpointAddress endpoint = new EndpointAddress("https://address.of.service");
//"GreatClient" was created for me automatically by running
//"svcutil.exe https://address.of.service?wsdl"
GreatClient client = new GreatClient(binding, endpoint);
//Username and password for the authentication. Notice that I have also installed
//the required .cer certificate into the system's "root certificate authorities".
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
//Now I can start using the client as I wish.
My question is this: How can I obtain all the information necessary so that I can consume the web service with a direct POST to https://address.of.service, and how do I actually perform the POST with C#? I only want to use POST, where I can supply raw XML data using POST directly to https://address.of.service and get back the result as raw XML data. The question is, what is that raw XML data and how exactly should I send it using POST?
(The purpose of this question: The reason I ask is that I wish to consume this service using something other than C# and .NET (such as Ruby, or Cocoa on Mac OS X). I have no way of knowing how on earth to do that, since I don't have any easy-to-use "svcutil.exe" on other platforms to generate the required code for me. This is why I figured that just being able to consume the service using regular POST would allow me to more easily to consume the service on other platforms.)
What you are attempting to do sounds painful to do now and painful to maintain going forwards if anything changes in the server. It's really re-inventing the wheel.
If you haven't considered it already, I would:
(a) Research whether you can use the metadata you have for the service and use a proxy generator native to your target plaform. There aren't many platforms that don't have at least some tooling that might get you part of the way if not all of it. Perhaps repost a question targetting Ruby folk asking what frameworks exist to consume an HTTPS service given it's WSDL?
(b) Failing that, if your scenario allows it I would consider using a proxy written in C# that acts as a facade for the service which translates it into something easier to consume (for example, you might use something like ASP.NET MVC WebAPI which is flexible and can easily serve up standards compliant responses over which you can maintain total control).
I suspect one of these may prove easier and more valuable than the road you are on at the moment.
I had to go through something similar when porting .NET WCF code to other platforms. The easiest approach I found was to enable message logging on the WCF client. This can be configured to save both envelope and body and once everything is working on the .NET side of the house, you can use the message log to have "known-good" XML request/response to port to other platforms.
I found this approach to be more elegant since I didn't have to add an additional behavior to log messages, and it can be easily enabled/disabled/tweaked in the config. The Service Trace Viewer Tool that ships with Visual Studio is also handy for reviewing the log files.
I think when you say that the service should be consumed from other platforms, which do not have proxy class generation logic, you can go with REST services. This will allow you to create input as simple string concatenation instead of complex XML. Though its applicability depends on the situation.
Check this discussion : http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6907d765-7d4c-48e8-9e29-3ac5b4b9c405/
As far as the certificate is concerned, refer http://msdn.microsoft.com/en-us/library/ms733791.aspx on how to configure it.
I know this is not a very precise answer, but you will be the best person to evaluate above procedure, hence posted. Hope it helps.
What I'll do:
1- Create a small c# app that can post on this webservice (using svcutil). And modify it to show the XML send/received. To view the xml there are several ways: logging, wireshark etc. To add it directly to the small app there is another question here that give a good answer.
2- Once you know what you have to send, you can do it in c# like this:
// implement GetXmlString() to return the XML to post
string xml = GetXmlString();
// create the url
string url = new UriBuilder("http","address.of.service",80).ToString();
// create a client object
using(System.Net.WebClient client = new System.Net.WebClient()) {
// performs an HTTP POST
client.UploadString(url, xml);
}
I'm not a .NET programmer but I've had to interoperate with a few .NET services and have lots of SOAP/WSDL experience. Sounds like you've captured the XML for your service. The other problem you'll face is authentication. OOTB, .NET web services use NTLM for authentication. Open-source language support for NTLMv2 can be hit and miss (although a quick google search pulled up a few possibilities for ruby), and using NTLM auth over HTTP may be something that you have to wire together yourself. To answer a question above: where are the auth creds? If the service is using NTLM over the wire, authentication is happening at some layer below HTTP. If the service is using NTLM to authenticate HTTP, your NTLM creds are in the HTTP Authorization header. You should be able to tell with wireshark where they are. You'll also probably need a SOAPAction header; this can also be sniffed with wireshark. For the C# client, I'm sure there are docs explaining how to add headers to your request.
I am required to consume a SOAP web service with a Java program I am writing. I have a basic test .NET service on my server in a .asmx file. There are a bunch of complicated examples that I found on Google but can someone provide a short explination for me? It would be greatly appreciated. Thanks!
Here is my .asmx file.
<%# WebService Language="C#" Class="Example1" %>
using System.Web.Services;
[WebService(Namespace="urn:Example1")]
public class Example1 {
[ WebMethod ]
public string sayHello(string name) {
return "Hello " + name;
}
}
Maybe there is a different way I should be doing this? Thanks again.
You can use a tool that comes with the JDK called wsimport to parse your WSDL file and generate Java classes.
wsimport http://path/to/your?wsdl -d /desired/output/folder
You can then use the generated classes like so:
Example1Endpoint example1 = new Example1Service().getExample1Port();
System.out.println(example1.sayHello("tkcsam"));
Is your .Net service a "page" that you post a string to as a parm? I've had to talk to a few of those in the past (I wouldn't really call them "web services", but anyway....).
If that is the case, find out what you need to post. Use your Java to build the giant String that you need to feed to the page and then send it to the page as a parm and wait for the response String coming back. You'll have to parse that string then.
This is terribly inelegant, but it used to be how Microsoft did things. Not sure if it is true in your case. Otherwise if you do have a WSDL to work with then I'd probably use either Jack's answer or follow the comment by djhaskin987 as there are some frameworks listed there that will dynamically generate web service clients based on published web services (that have their WSDL published with them).
JAXWS is the standard technology for interacting with SOAP webservices in java. the default implementation in the oracle jdk is the metro stack, which has an extensive user guide.
What I basically need is a small console application that listens on port 80 and is capable of putting JSON objects around.
Receiving value types, objects and List<T> (or array) from a JSON client and converting them to .NET classes
Sending value types, objects and List<T> to the client
Outputting some information to the console
Performance is not a problem as I expect about 20 - 30 request per hour.
I don't want the IIS or Cassini Web server as a requirement on the client side. Only my console application and dependencies.
I already tried servicestack.net which looks very promising and has an example for a console host. Howevery I din't manage to get JSON out of the console host (only XML).
Any ideas how to use servicestack.net or alternatives are welcome.
By the way: The client will be an Android phone and since my current approach IIS + WDSL + kSOAP 2 (on the phone) causes more trouble than it solves, I really want to try a lightweight standalone JSON solution.
Maybe I'm incorrect, but I suppose you could use WCF hosted in a console application.
The Kayak project does pretty much exactly what you want to do. It's very lightweight and very powerful. Check out some of the examples (taken directly from the project page):
public class PostAPI
{
[Path("/widgets")]
public Widget[] GetWidgets()
{
return Widget.GetAll();
}
[Verb("POST")]
[Path("/widgets")]
public void CreateWidget([RequestBody] Widget w)
{
w.Created = DateTime.UtcNow;
w.Create();
}
}
public class Widget
{
public string Author;
public string Text;
public string Created;
// (Methods would be here...)
}
It can automagically serialize and deserialize between JSON objects and CLR objects and accept routes as well as both POSTs and GETs. Finally, it includes a built-in server that you can easily throw into a console application.
You could use a HttpListener to hande HTTP requests in your application. You would have to handle the JSON serialization yourself, but that may not be a problem?
Depending on which framework version you are using you could use either the built-in JSON serialization support or you could use the Json.NET library to do this. In either case it should be easy to detect the requests and to return a JSON response.
As of August 15, Amazon made it compulsory to sign all requests made to their Product Advertising API. I thought I had got everything working just fine but when the 15th finally came around, my web application stopped working and pretty much ever since I have been trying to find out how to sign the SOAP requests.
Amazon has an outdated sample code for signing requests that doesn't appear to work here
Basically, I need to know how to add a signature to the my requests using the most current C# SOAP API and .NET 3.5.
I hope I have given enough details, if I haven't please feel free to ask me to elaborate.
Thank You
The_Lorax
UPDATE:
I am using MVC and need to know how to add the Signature to the the ItemLookup or AWSECommerceService object. Is there an attribute that contains the signature value? How does it get attached to the request?
On this page, they say that I must include the Signature and TimeStamp parameters but the intellisense does now show any such attributes.
Check out http://flyingpies.wordpress.com/2009/08/01/17/. It has a walkthrough and a sample visual studio solution using C#, SOAP, WCF on .NET 3.5.
This library automatic sign the requests (Install-Package Nager.AmazonProductAdvertising)
https://www.nuget.org/packages/Nager.AmazonProductAdvertising/
Example:
var authentication = new AmazonAuthentication("accesskey", "secretkey");
var client = new AmazonProductAdvertisingClient(authentication, AmazonEndpoint.US);
var result = await client.SearchItemsAsync("canon eos");