Integrate a C# client into a node.js + socket.io chat app - c#

As part of learning node.js, I just created a very basic chat server with node.js and socket.io. The server basically adds everyone who visits the chat.html wep page into a real time chat and everything seems to be working!
Now, I'd like to have a C# desktop application take part in the chat (without using a web browser control :)).
What's the best way to go about this?

I created a socket server in nodejs, and connected to it using TcpClient.
using (var client = new TcpClient())
{
client.Connect(serverIp, port));
using (var w = new StreamWriter(client.GetStream()))
w.Write("Here comes the message");
}

Try using the HttpWebRequest class. It is pretty easy to use and doesn't have any dependencies on things like System.Web or any specific web browser. I use it simulating browser requests and analyzing responses in testing applications. It is flexible enough to allow you to set your own per request headers (in case you are working with a restful service, or some other service with expectations of specific headers). Additionally, it will follow redirects for you by default, but this behavior easy to turn off.
Creating a new request is simple:
HttpWebRequest my_request = (HttpWebRequest)WebRequest.Create("http://some.url/and/resource");
To submit the request:
HttpWebResponse my_response = my_request.GetResponse();
Now you can make sure you got the right status code, look at response headers, and you have access to the response body through a stream object. In order to do things like add post data (like HTML form data) to the request, you just write a UTF8 encoded string to the request object's stream.
This library should be pretty easy to include into any WinForms or WPF application. The docs on MSDN are pretty good.
One gotcha though, if the response isn't in the 200-402 range, HttpWebRequest throws an exception that you have to catch. Fortunately you can still access the response object, but it is kind of annoying that you have to handle it as an exception (especially since the exception is on the server side and not in your client code).

Related

C# calling a webservice result in 401

I'm trying to call a simple web service to get long and lat of an address, which works when I try it manually :
https://services.gisgraphy.com/geocoding/?address=paris
But with the code, I get 401 unauthorize.. What am I doing wrong ?
WebRequest request = WebRequest.Create("https://services.gisgraphy.com/geocoding/?address=paris");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";
WebResponse response = request.GetResponse(); // It happens here.
What am I doing wrong?
You haven't read the big blue bar on top of the website belonging to the API you're calling:
Gisgraphy is open sources and only use open data. This server is for demonstration only. Test it, Play with webservices but then Install Gisgraphy locally or subscribe to premium hosted services
So they're probably detecting that you're calling their API from outside their playground, and are denying you to do so.
So, either install it locally, or subscribe to their hosted services. The latter probably gives you an API key that allows you to make API calls.
Of course you can fake your way around this by imitating that your request comes from a browser, for example with User-agent and Accept headers, but surely they'll try and detect this and block your IP address entirely. Just pay up, or host it locally.
Few things on this question :
Check if the URL/web-service is directly accessible via
browser/postman tool.
Secondly , as one of my fellow friend there mentioned this
web-service has some security protocol. May be its not allowing
requests from outside (i.e. other than its domain to come in)
Once you drill down the above two possibility ,you should be in a good shape to move ahead.

Android HTTP to C# Server

Using HTTP I want to send simple string data through android to a C# .NET server. This link suggests using OKHTTP which looks great, but I'm not sure how this would talk to a C# server as I will need a 'connection' where I can send data back to the android phone.
OKHTTP seems to manage drops in connection elegantly according to the website, which is fantastic because I need this kind of persistance, but I'm not sure how I would implement the C# side.
Does anyone know a method of accomplishing this?
It sounds as though you want to do a normal HTTP POST to your server. It's the same thing that would happen when you fill out a form on a web-page and submit the data to a server. If it's a normal kind of webserver it should have full support for receiving a POST and returning a response as well. Are you writing the .NET web service as well?
As for client side technology to use: OkHTTP is a greaty drop-in class for making HTTP requests to a server, but if you plan to do many of them you should also look into wrapping the actual HTTP client into an API that takes care of asynchronous callbacks and things like that. You don't want to be doing HTTP requests on the UI thread and it's boring and error prone to wrap all such calls in AsyncTasks or similar. Take a look at AndroidAsyncHttpClient:
"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."
(As a sidenote AndroidAsyncHttpClient might get support for using OkHTTP instead of the default Apache HttpClient)
POSTing to a server is as simple as this:
RequestParams params = new RequestParams();
params.put("A_KEY_TO_IDENTIFY_YOUR_STRING", "THE_STRING_YOU_WANT_TO_SEND");
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.yourserver.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// handle your response from the server here
System.out.println(response);
}
});

HTML message or login pages intercepting web service requests

I am busy working on a mobile application that retrieves data from a web service.
Ofcourse everything is working perfectly, I get everything I need to and I can consume the services without much effort... on the emulator.
However, when I move over to testing this application on the device, instead of getting back the data that I am expecting I am getting a website returned. How am I supposed to handle this?
Currently I am using this to call my service: (using system.net - I dont know if this is what I should be using on windows phone 7 either)
WebClient proxy = new WebClient();
string strURI = "http://www.google.co.za";
proxy.OpenReadCompleted +=
new OpenReadCompletedEventHandler(proxy_openreadcompleted);
proxy.OpenReadAsync(new Uri(strURI));
Please note: I am not really calling google, it is just an example. So anyways I am expecting my JSON to be returned, instead I am getting a message from the service provider to change mobile options... I can put this into isolated storage and render it with a browser, however I do not know what the source of the message is so when you click on a button, the forms use relative URLs, so instead of it doing what it is intened to do I just see what it is trying to call.
Is there anyway to get the source of the response? I am looking for a source like http://vodafonelive.mobi/ or something like that. If someone can tell me what to do I would greatly appreciate it, my current thinking is that if I can identify the source I can create a webbrowser task so that my application does not need to handle this, however... since I am calling a specific source I don't know how to identify where the response is comming from.
Any help is appreciated.
This is most likely due to differences in the user agent of the emulator and the device. Check what is sent or set this explicitly to ensure that the 2 behave in the same way. To ensure the server doesn't try and redirect to a different location.
Alternatively, it could be a mobile operator proxy being "helpful" and adjusting the request that goes over their network.
Ok so after spending some time on this, I finally found a way that I could get a response uri (where the response was comming from) by using another method to do the call to the service:
So basically this is the call:
WebRequest request = HttpWebRequest.Create(strURI);
var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
So in the function ResponseCallBack function I do something like this:
WebRequest request = (HttpWebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result);
which then allows me to check the response uri (the source of the intercepted message) and have the native browser handle the html that I was not expecting.
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = response.ResponseUri;
Thanks for the help though, hopefully this will help someone with a similar issue.

Both WebClient and HttpWebRequest suddenly failing to pull basic Amazon pages?

We have an in-house application that pulls some data from some of Amazon's pages occassionally (We know they have APIs for certain operations... what we're doing requires some custom info not included in the APIs). We have never had a problem pulling their pages, but suddenly Amazon is returning "(503) Server Unavailable" on pretty much every request, and this has been happening for several days, so we doubt it's a temporary thing. Even something as simple as this:
System.Net.WebClient client = new System.Net.WebClient();
string data = client.DownloadString(new Uri("http://www.amazon.com/Bose-Companion-multimedia-speaker-Graphite/dp/B000HZBR64/"));
The strange thing is that these pages load just fine in a web browser, but any time we try to pull them through code, it is failing.
What could cause these functions to fail? Is it possible that they changed something on their end and that we need to do some custom logic with our calls?
After some further testing, it turns out that this was happening because Amazon needs the Accept parameter of the HttpWebRequest to be specifically set. When setting it to:
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Everything worked fine. This is a recent change, so they must have altered something on their end.
check the user-agent of you request. make the user-agent the same as your browser. And check if you set any proxy for your app? maybe your browser and your app are using different proxies

Very fast and light web call, which technology to use: legacy web service or HttpWebRequest

I need some insecure, fast, light and easy to implement web method. Something like this:
// Client side
// Parametrize client address which is dynamic and we don't know until run-time
myClient.Address = "http://example.com/method.aspx/?input=" + value;
string result = "";
if (myClient.TryCallWebMethod(out result))
// Web method succeed. Use returned value.
else
// Web method failed. No problem, go with plan B.
// Server side
Response.Write("Answer is: " + Request.QueryString[input]);
I know this is reconstructing the wheel, but what I need is as simple as above code. I can implement client with HttpWebRequest but maybe using a legacy Web Service is a better choice.
I have tried WCF but there are more choices which I don't need like sessions, security, etc. Also I did a localhost benchmarking and WCF came to it's knees at 200 concurrent requests, where I need a support of more than 1000 concurrent calls which is a normal load for an aspx page.
This web method is gonna be consumed from a asp.net page. I never used a legacy web service, is it OK for my scenario or like WCF it has a dozen of configurations and certificate installations... ?
After going through the operations provided by WebClient, it looks like it just wraps a HttpWebRequest functionality and provides extra utility operations. Hence I would suggest you to go for HttpWebRequest.
Also on the server side, try to go for a HttpHandler instead of aspx page (handlers are light weight)
If this is a standard ASPX page you could use a WebClient:
using (var client = new WebClient())
{
var url = "http://example.com/method.aspx?input=" + HttpUtility.UrlEncode(value);
string result = client.DownloadString(url);
}

Categories

Resources