Call web APIs in C# using .NET framework 3.5 - c#

I am trying to find the nearest store given a zip code. I came to know that yelp and foursquare provides the required APIs to do this. I am using .NET 3.5 framework. How do you make the http requests and handle the responses.Most of the solns on the web give it for .NET 4.5 onwards which includes the usage of HTTPClient class.

You can use System.Net.WebClient class to make an http request.
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin#admin.com\",\"Password\": \"pass#123\"}")));
There are also other methods which can be used, but that depends on your requirements. You can find more details here
from MSDN.

Related

MYOB .NET SDK - Invoice creation

I'm not sure if anyone will be able to help me or not but I am hoping there is someone familiar with the .NET SDK for MYOB.
The service classes accessible in the SDK provide the core HTTP
operations available for each consumable endpoint. These include the
following operators:
Get/GetRange – HTTP GET Insert – HTTP POST Update – HTTP PUT Delete –
HTTP DELETE
https://developer.myob.com/api/myob-business-api/arlive-sdk/dotnet_sdk/sdk-services/
The InvoiceService is accessed via
MYOB.AccountRight.SDK.Services.Sale.InvoiceService.
I have instantiated an InvoiceService object:
var invService = new InvoiceService(configuration);
However the InvoiceService class does not have an "Insert" function.
The API endpoint documentation suggests a "POST" is possible though: https://developer.myob.com/api/myob-business-api/v2/sale/invoice/invoice_service/
Am I using the wrong class? I unfortunately can't find any SDK documentation.
Try to use MYOB.AccountRight.SDK.Services.Sale.ItemInvoiceService instead of MYOB.AccountRight.SDK.Services.Sale.InvoiceService.

Unity 3D Puts/Deletes http methods

I'm thinking of porting a JavaScript web app to C# Unity3D (Free / Personal Version) for an RPG I'm developing. I have an extensible, separate API built in PHP Laravel 5.1, which my game interacts with through jQuery http calls.
I need to continue making standard restful calls, get, post, put, delete, etc within Unity but have only found UnityEngine.WWW# which makes gets and posts.
This SO Post shares the other available Unity3D http methods, but none which actually get all restful calls in one. I'm asking again because this was posted in 2012 and I haven't found any updates which satisfy this within the updated documentation.
There is Best HTTP Basic and Best HTTP for $45 and $55, but was thinking there would be other free options.
Am I missing something within Unity that allows for standard restful calls?
WebClient and WebRequest are both available in Unity and looks like it will only work with Pro Unity version just like any other API from the System.Net namespace. I don't know if this restriction has changed in Unity 5. They support all those restful calls mentioned in your question.
Unity Added a new API called UnityWebRequest in version 5.2 with mobile platform support in 5.3. It was designed to replace WWW and it supports all the restfull calls listed in your question. Below are example for each one. This is not a full example. You can find full examples in the link I provided above.
//Get
UnityWebRequest get = UnityWebRequest.Get("http://www.myserver.com/foo.txt");
//Post
UnityWebRequest post = UnityWebRequest.Post("http://www.myserver.com/foo.txt","Hello");
//Put
byte[] myData = System.Text.Encoding.UTF8.GetBytes("This is some test data");
UnityWebRequest put = UnityWebRequest.Put("http://www.my-server.com/upload", myData);
//Delete
UnityWebRequest delete = UnityWebRequest.Delete("http://www.myserver.com/foo.txt");
You can see complete example for each one including posting with json here.

Consuming a web service using POST instead of the going the usual WSDL route

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.

HttpClient for C# application

just starting to create an API to my a web application using the ASP.NET MVC4 Web API project template. http://www.asp.net/mvc/mvc4
No problems with the API so far, but I was about to write a small C# app to test the API.
Almost all the sample I can find is using the a class called HttpClient.
Where can I find the HttpClient and how do I install it?
Rather than using the build in HttpClient class of the .NET framework which has a lot of issues when dealing with StatusCodes that are different than the expected ones. I recommend using a library called RestSharp.
It has become .NET Http/Rest client of choice, you can get it here: http://restsharp.org/
It is a very powerful library that is perfectly suited to do what you want.
It's on nuget, search for HttpClient
http://nuget.org/packages/System.Net.Http
Use WebRequest as described here
// Create a new 'Uri' object with the specified string.
Uri myUri =new Uri("http://www.contoso.com");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest= WebRequest.Create(myUri);
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse= myWebRequest.GetResponse();
If its a REST interface use RestSharp but you would need XSD first.
If the class is not available from your code, then you could download it from a NuGet package, like described in the article:
http://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
or you can try to locate it inside the namespace: System.Net.Http
There is also an example for you wich should get you started!

.NET Compact Framework, WCF service, compression and DIGEST authentication

I'm trying to put a number of features together, which is proving increasingly difficult due to the limitations of the .NET Compact Framework.
Specifically, I've got a WCF service and I'm writing a mobile device client for it. The catch? I want to use some sort of data compression (due to a very slow modem connected to said device) and HTTP DIGEST authentication (which is already in place on the site hosting the WCF service).
I've followed this blog entry to get the compression and generated code needed for the WCF service client.
I am, however, struggling with the HTTP DIGEST. I've no idea how to add this functionality.
Previously I didn't use compression and as such I connected to the WCF service using SOAP, using a simple WebService reference, and to add HTTP DIGEST I had to override the GetWebRequest method and add the required headers manually. This time around the generated classes seem to give very little leeway and there isn't much I can override. Also, all security or authentication parameters seem to be designed for SSL, rather than such basic authentication schemes.
To summarize: how can I create a WCF client using compression and HTTP DIGEST authentication using .NET Compact Framework?
EDIT:
Here's the code I've currently got:
System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding();
CompressionMessageEncodingBindingElement compressionBindingElement = new CompressionMessageEncodingBindingElement();
customBinding.Elements.Add(compressionBindingElement);
HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
customBinding.Elements.Add(httpBindingElement);
EndpointAddress endPoint = new EndpointAddress("http://localhost:5100/Service.svc");
ServiceClient client = new ServiceClient(customBinding, endPoint);
I suspect I somehow need to add the HTTP DIGEST functionality to the CustomBinding class, but I don't know how.
I suspect I should also note, that while I am using .NET Compact Framework 3.5, I am creating a Windows CE application. As such, I didn't bother downloading Windows Mobile 6 SDKs. If these SDKs add more functionality which can be used in Window CE applications and are required for the HTTP DIGEST to work, please let me know.
We ended up disabling the DIGEST authentication for devices running .NET CF. It's not as safe, but we figured the data send and retrieved by the devices running .NET CF in our case isn't THAT sensitive, so all we really need to do is validate it.
If the client is running on the .NET Compact Framework 3.5, you can use WCF to invoke the service and use the built-in support for HTTP Digest authentication without requiring SSL.
Here's how to programmatically configure a WCF client to use Digest authentication with the BasicHttpBinding:
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
var endpoint = new EndpointAddress("http://server/myservice");
var client = new MyServiceClient(binding, endpoint);
// We have to set the actual credentials on the client proxy object
// before invoking the service:
client.ClientCredentials.HttpDigest.ClientCredential.UserName = "me";
client.ClientCredentials.HttpDigest.ClientCredential.Password = "password";
try
{
client.MyServiceOperation();
client.Close();
}
catch
{
client.Abort();
}
Related resources:
The WCF subset supported by the .NET Compact Framework 3.5
WCF Guidance for Mobile Developers (see page 66 for HTTP Digest Authentication)
The only way to achieve this is to use HttpWebRequest (manually) and specify ClientCredentials, instead of the generated classes from NetCFSvcUtil which does not support authentication.
The only WS-Security specification it supports on CF with WCF is to effectively use message security with a Mutual Certificate exchange. (Which by the way has a memory leak which a colleage and I found: http://connect.microsoft.com/VisualStudio/feedback/details/727247/native-memory-leak-in-wcf-proxy-client-with-mutual-certificate-security-in-net-compact-framework-3-5-on-windows-ce-6-0)
Of note, the generated CFClientBase also has a memory leak which can be worked around, see: http://geekswithblogs.net/GruffCode/archive/2013/03/31/memory-leak-in-cfclientbaselttgt-service-proxy-for-compact-framework-.net.aspx
For reference: The WCF subset supported by NetCF: http://blogs.msdn.com/b/andrewarnottms/archive/2007/08/21/the-wcf-subset-supported-by-netcf.aspx

Categories

Resources