I would like to build a simple REST web service (using Ruby on Rails). However, I would like to be able to call this service from a Windows mobile app. Is that possible? or do I have to use SOAP?
I don't have much experience with Windows Mobile apps so it would be nice if you can provide pseudo code or link to tutorial for the possible case.
Thanks,
Tam
Yes you can. I've done it lots using the Win32 wininet API.
You can also do it in C# using the System.Net HttpWebRequest API.
dim sendUrl : sendUrl = baseUrl & url
dim objXML : Set objXML = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objXML.open "GET", sendUrl, false
objXML.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXML.send(sendxml)
HttpPost = objXml.responseText
Set objXML = nothing
On desctop Microsoft offers an com interface which can be used to implement REST APIs.
Maybe this also exists on Windows Mobile.
Here's an example of using a HttpWebRequest to call the twitter search api,hth:
Uri uri = new Uri("http://search.twitter.com/search.json?q=twitter");
String result = String.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
Related
I need to return result in jsonp format while I'm using asp.net MVC Core.
In asp.net MVC we can use MVC.jsonp dll an it's work fine but what is the alternative in MVC Core because I can't find any.
public JsonpResult FunctionalitesTblList()
{
var settings = new JsonSerializerSettings();
return Jsonp(Rows, settings);
}
There was no built in ability to handle JSONP with MVC, so you were always using a third-party addition. Apparently, that library is incompatible with .NET Core. Therefore, your option is to find a similar library that is compatible or choose some other approach.
#CuongLe is correct that CORS is a better approach overall, so you should definitely investigate that. However, if you insist on JSONP, it's so simple to implement manually, you don't really need a library.
Simply, all JSONP is a is JSON passed into a "callback" function, specified by the client. In other words, if the callack was specified as "mycallback", the response should just look like:
mycallback({ "foo": "bar" });
As a result, your code simply becomes:
string json = null;
using (var ms = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(Foo));
serializer.WriteObject(ms, foo);
json = Encoding.UTF8.GetString(ms.ToArray());
}
var jsonp = String.Format("{0}({1});", callback, json);
Response.ContentType = "application/javascript";
return Content(jsonp);
We are trying to integrate a "sign in with twitter" function in our application and for this purpose we are using javascript (hello.js).
Unfortunately, twitter is using oauth 1.0 so we can't have only a javascript solution but we need to implement a server-to-server communication to sign the request. The hello.js author provided an auth-server implementation for demo purposes based on node.js.
In our application for the backend part we are using java and I was wondering if a java solution exists for this purpose. Could I use for instance signpost or similar to do the job of auth-server ?
[UPDATE]
I tried to set the proxy used by hello.js to a mine servlet (so, instead of herokuap now I'm using a localhost servlet with oauth in the buildpath).
This servlet is doing the following:
OAuthConsumer consumer = new DefaultOAuthConsumer(
"xxxx",
"yyyyyyyyyyy");
OAuthProvider provider = new DefaultOAuthProvider(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
System.out.println("Fetching request token from Twitter...");
// we do not support callbacks, thus pass OOB
String authUrl = provider.retrieveRequestToken(consumer, "http://localhost:8080/oauth1/twitter/response_server");
URL url = new URL(authUrl);
HttpURLConnection req = (HttpURLConnection) url.openConnection();
req.setRequestMethod("GET");
req.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(req.getInputStream()));
StringBuilder d = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null){
d.append(line + '\n');
}
System.out.println(d);
PrintWriter out = response.getWriter();
out.println(d);
and it prints the twitter login page in the hello.js popup. In this way I got some encoding error but it is quite working.
Anyway the callback url is mapped to another servlet where I should simply "sign" the request but I think I am missing something because sometimes I got the error
"The server understand the request but it is still refusing it"
but if I close all browser window it works.
However the response servlet is similar to this one
OAuthConsumer consumer = new AbstractOAuthConsumer(
"xxxxx",
"yyyyyyyyyyy"){
#Override
protected HttpRequest wrap(Object arg0) {
return (HttpRequest)arg0;
}
};
consumer.sign(request);
But this code does not work because I don't know how to sign a tomcat request. In oauth homepage is explained how to sign jetty and apache common http request but not the tomcat one. However, is it correct my approach ?
Please checkout the spec of node-oauth-shim which is used my //auth-server and which HelloJS delivers.
Can i make asp application or mvc application that can download data from other server (site) using ftp. I have 2 web sites and i want to download a file from one site to another using ftp.
Yes.
Example copied from How to Download Files with FTP. The example is for a console app, but I think you can figure quite easily how to adapt it to your site's structure.
One thing you might consider is just hosting the file on the site (like normal HTTP) and then download it via WebClient instead of FTP.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}
I am building an extension for open source ASP.NET CMS Umbraco where I want to fetch the analytic's from the user's account once they have authorised via oAuth.
The example MVC 4 snippet over on the Google API .NET wikiw page for oAuth seems to only work with a controller and not a WebAPI controller as far as I can tell, is this right?
AuthorizationCodeMvcApp(this, new AppFlowMetaData()).AuthorizeAsync(cancellationToken);
The first parameter in the example expects it to be a regular MVC Controller
https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.Auth.Mvc4/OAuth2/Mvc/AuthorizationCodeMvcApp.cs
So my question is really, how do I work with oAuth with a WebAPI in mind, as I want to return stats back from the API as JSON from the WebAPI so I can use a client side library such as AngularJS to bind the JSON returned to the HTML view?
I would love for any ideas, feedback or suggestions on how I could solve this please.
Thanks,
Warren :)
I have looked into your problem and the i have tested the service account solution. It's tricky to setup but when it runs it works.
This is the code I used in a webapi controller :
String serviceAccountEmail = "805395301940-cu3nhkuqi4ipa3453o276bar5u2e70lq#developer.gserviceaccount.com";
var cert = HttpContext.Current.Server.MapPath("/key.p12");
var certificate = new X509Certificate2(cert, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
//var ga = service.Data.Ga.Get("ga:31335471", "2013-01-01", "2013-01-31", "ga:visits");
// Not Working Currently in Beta
//var ga = service.Data.Realtime.Get("ga:31335471", "ga:activeVisitors");
var ga = service.Management.Profiles.List("~all", "~all");
return ga.Execute();
Ok, so here is the scenario:
I have an activeX that uploads files using HttpWebRequest class. My problem is that I have to specify the network credentials in order to get the activeX to work properly behind a proxy server.
Here is the code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_url);
req.Proxy = new WebProxy("http://myProxyServer:8080");
req.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
How can i get this information from iExplorer with no (or minimal) user interface?
Thank You :)
I managed to do it ;)
private static WebProxy QueryIEProxySettings(string strFileURL)
{
HttpWebRequest WebReqt = (HttpWebRequest)HttpWebRequest.Create(strFileURL);
WebProxy WP = new WebProxy(WebReqt.Proxy.GetProxy(new Uri(strFileURL)));
WP.Credentials = CredentialCache.DefaultCredentials;
return WP;
}