Google OAuth2.0 - Windows phone 7 - wpf

Experts,
I'm new to OAuth,
I'm writing an small App in windows Phone 7, I'm using OAuth2 for google contacts, I need to get the initial URL API (1) to get the Token
1) https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/m8/feeds/&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&hl=en-US&from_login=1&as=NEW_AS&pli=1
I got the success code, and when I'm trying to use this
https://www.google.com/m8/feeds/contacts/default/full?access_token=TOKEN_CODE
but I'm getting 401 error back,
Can you please advice, what mistake i'm going.
I've taken Twitter OAuth example as base, and doing modifications.
CODE
var uri = new Uri(url);
var request = BuildOAuthWebRequest(url, null);
MakeGetRequest(callback, request);
private static HttpWebRequest BuildOAuthWebRequest( string url, string realm)
{
var header = new StringBuilder();
var request = (HttpWebRequest)WebRequest.Create(url);
return request;
}
private static void MakeGetRequest(EventHandler<OAuthEventArgs> callback, HttpWebRequest request)
{
var asyncState = request.BeginGetResponse(new AsyncCallback((asyncRes) =>
{
HttpWebResponse response = null;
try
{
//request has returned
response = (HttpWebResponse)request.EndGetResponse(asyncRes);
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
var token = sr.ReadToEnd();
callback(null, new OAuthEventArgs() { Response = token });
}
}
}
catch (WebException we)
{
string t = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();
callback(null, new OAuthEventArgs() { Error = we, ErrorMessage = t, IsError = true });
}
catch (Exception e)
{
callback(null, new OAuthEventArgs() { Error = e, ErrorMessage = e.Message, IsError = true });
}
finally
{
if (response != null)
response.Close();
}
}), null);
}

Related

get broken excel file from Spring server

really don't now what to do.
i have on my server xls file and i wont to download it from my client.
i actually do it but the file getting in some weird langue and absolutely broken.
client : angular
server: spring 4
Code
Client
function getXCEL() {
self.onXCELProcess = true;
AdminService.getXL(MotherService.getAppMember())
.then(
function (response) {
var file = new Blob([response], {type: 'application/excel'});
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
if (isChrome){
var url = window.URL || window.webkitURL;
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',url.createObjectURL(file));
downloadLink.attr('target','_self');
downloadLink.attr('download', 'yourReports.xls');
downloadLink[0].click();
}
else if(isEdge || isIE){
window.navigator.msSaveOrOpenBlob(file,'yourReports.xls');
}
else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
self.onXCELProcess = false;
},
function (error) {
console.error("error : "+error+" , error : "+JSON.stringify(error));
self.onXCELProcess = false;
}
)
}
function getXL(admin) {
return MotherService.callToServer({method: 'POST', url: URL + "orderxl", appMember: admin});
}
callToServer() method do request, with json body. and return the deferred.promise
for use of then.
server
#RequestMapping(value = "/"+Request.ADMIN_PATH+"/"+Request.ORDER_XL, method = RequestMethod.POST)
public void getFile(#RequestBody OrderXLRequest request, HttpServletResponse response) {
try {
File file = orderXLService.execute(request).getFile(); //get the file. already saved and ready to send
try{
InputStream inputStream = new FileInputStream(file);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", "excelfilename.xlsx");
response.setHeader(headerKey, headerValue);
try {
FileCopyUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}catch(Exception e){
System.out.println("Exception in file download :"+e);
}
}catch (Exception e) {
e.printStackTrace();
}
}
thank you very much for any help or suggestion

upload file from phonegap camera to .Net web api

Server side
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
Client side code, After I get the imageURI from camera send it to below
function send(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
}
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://localhost/api/api/upload"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
I get error code 1 on the fail function. is their anything wrong with server side code? can I send ImageURI the above web api i wrote?
the code seemed to be working fine. The server user which was set on IIS did not have the proper permissions to do the write hence it was returning error. thanks

get user by access google oauth2 token

I need login user in server side by access token and get their user infomrmations. it is possible ?
Im looks in com.google.appengine.api but Im not find it.
I get acces token in client side using google oauth2 and after send to server.
thanks.
I found the solution with calling url to google api.
public UserInfo login(String token) {
String json = getJsonDataFromUrl("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token);
UserInfo userInfo = new UserInfo();
Gson gson = new Gson();
try{
userInfo = gson.fromJson(json, UserInfo.class);
userInfo.logined = true;
HttpSession session = getRequest().getSession();
session.setAttribute("userKey", userInfo.encodedKey);
}catch (Exception ex){
log.log(Level.WARNING, ex.getMessage());
throw ex;
}
return userInfo;
}
private String getJsonDataFromUrl(String aurl){
String json = "";
try {
URL url = new URL(aurl);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
json+=line;
}
reader.close();
} catch (MalformedURLException e) {
log.log(Level.SEVERE, e.getMessage());
return null;
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
return null;
}
return json;
}

How do I update the UI from a HttpWebRequest?

In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?
EDIT: code below:
MainPage:
private void button1_Click(object sender, RoutedEventArgs e)
{
Member m = new Member(name, id);
}
Member class:
public Member(String Member, String API)
{
APIKey = API;
MemberName = Member;
this.super = super;
DoSend(method, string, "", null);
}
public void DoSend(string method, string url, string body, string mimetype)
{
if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;
request.Method = method;
request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
if (body != "")
{
byte[] bodyData = Encoding.UTF8.GetBytes(body);
request.ContentType = mimetype;
//Stuff Should Happen Here
}
else
doStuff(request);
}
public void doStuff(HttpWebRequest httpReq)
{
httpReq.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
ResponseBlock.Text = response; //Invalid cross-thread reference
}
}, httpReq);
}
MainPage:
customClass.DownloadPage((result) =>
{
textBlock.Text = result;
},
(exception) =>
{
MessageBox.Show(exception.Message);
});
CustomClass:
public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
WebClient webClient = new WebClient();
webClient.DonwloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
callback(e.Result);
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
exception(e.Error);
});
}
};
webClient.DonwloadStringAsync();
}

POST Requests on WP7

I've been dying for about 6 hours trying to figure out how to make a regular POST request in WP7 , I tried the answers of similar questions posted here and on many other places, I also tried many different APIs POST request, they all lead to one certain problem,
The remote server returned an error: NotFound.
it seems like everytime there's something missing.
So, if you please someone show us how to properly get a POST request right in this WP7
I use this to post to facebook without any problem:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetResponse((e) =>
{
try
{
WebResponse response = request.EndGetResponse(e);
// Do Stuff
}
catch (WebException ex)
{
// Handle
}
catch (Exception ex)
{
// Handle
}
}, null);
I assume you would have tried this already so it may be something to do with the post data (which isn't in the above example as facebook uses the query string). Can you give us any more info?
EDIT: This is an (untested) example for writing post data:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetRequestStream((e) =>
{
using (Stream stream = request.EndGetRequestStream(e))
{
// Write data to the request stream
}
request.BeginGetResponse((callback) =>
{
try
{
WebResponse response = request.EndGetResponse(callback);
// Do Stuff
}
catch (WebException ex)
{
// Handle
}
catch (Exception ex)
{
// Handle
}
}, null);
}, null);
I use the following class for making POST requests with WP7:
public class PostMultiPartFormData
{
private Dictionary<string, object> Parameters;
private Encoding ENCODING = Encoding.UTF8;
private string BOUNDARY = "-----------------------------wp7postrequest";
public event EventHandler PostComplete;
public void Post(string postbackURL,
Dictionary<string, object> parameters)
{
Parameters = parameters;
Uri url = null;
url = new Uri(postbackURL);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + BOUNDARY;
request.BeginGetRequestStream(new AsyncCallback(SendStatusUpdate), request);
}
private void SendStatusUpdate(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
Stream stream = request.EndGetRequestStream(ar);
byte[] byteArray = GetMultipartFormData(Parameters, BOUNDARY);
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
stream.Dispose();
request.BeginGetResponse(new AsyncCallback(StatusUpdateCompleted), request);
}
private byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
foreach (var param in postParameters)
{
if (param.Value is byte[])
{
byte[] fileData = param.Value as byte[];
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}.jpg\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, param.Key, param.Key);
formDataStream.Write(ENCODING.GetBytes(header), 0, header.Length);
formDataStream.Write(fileData, 0, fileData.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value);
byte[] b = ENCODING.GetBytes(postData);
foreach (var item in b)
{
formDataStream.WriteByte(item);
}
}
}
string footer = "\r\n--" + boundary + "--\r\n";
byte[] footerbytes = ENCODING.GetBytes(footer);
formDataStream.Write(footerbytes, 0, footerbytes.Length);
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Flush();
formDataStream.Close();
return formData;
}
private void StatusUpdateCompleted(IAsyncResult ar)
{
if (PostComplete != null)
{
PostComplete(ar, null);
}
}
}
Example:
PostMultiPartFormData postRequest = new PostMultiPartFormData();
postRequest.PostComplete += new EventHandler( (sender, e) =>
{
IAsyncResult ar = ((IAsyncResult)sender);
using (WebResponse resp = ((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string responseString = sr.ReadToEnd();
this.Dispatcher.BeginInvoke(() =>
{
textBlock.Text = responseString;
});
}
}
});
postRequest.Post("http://localhost:50624/SSLProxy.ashx",
new Dictionary<string, object>() { { "param1", "value1" } });
This should work...
If it doesn't let me know! :-)
For easier access to advanced http features check out these http classes:
http://mytoolkit.codeplex.com/wikipage?title=Http
It encapsulates GET, POST, FILES (using path or Stream objects) and GZIP (not directly supported by WP7) requests.
To add post data just call BeginGetRequestStream method (also, BeginGetResponse move to GetRequestStreamCallback)
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
string postData = "post data";
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
I recommend you to use the postclient. It is pretty simple. You just need to add reference to dll file into your project, and then write something like:
public void authorize(string login, string password)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("command", "login");
parameters.Add("username", login);
parameters.Add("password", password);
PostClient proxy = new PostClient(parameters);
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
MessageBox.Show(e.Result);
}
};
proxy.DownloadStringAsync(new Uri("http://address.com/service", UriKind.Absolute));
}

Resources