Google Login in Windows Phone 8.1 - windows-runtime

I'm trying to use Google Apis for login in Windows Phone 8.1.
I have this method:
public async Task<bool> AuthenticateAsync()
{
var Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Shared/Jsons/client_secrets.json"),
new[] { PlusService.Scope.PlusLogin},
"user",
CancellationToken.None);
System.Diagnostics.Debug.WriteLine($"Credential: {Credential}");
var loginSuccess = await NetworkManager.LoginWithGoogle(Credential.Token.AccessToken);
return loginSuccess;
}
Everything after GoogleWebAuthorizationBroker.AuthorizeAsync() is not executed.
Also if i try to debug i put breakpoint on that instruction and when i go further i see the app going out of that method, without execute all the other instructions.
I have no exception and so i don't know why.
Some hint?

Related

How to get Google API access code using Code in windows phone 8.1 App?

I am new in Windows phone application development.
I have created my app in Google developer Console.
From my windows phone application I am using "webview" to render the Google login page and with successfull login I got a code like: 4/akd.........
Can anyone tell me how to access the code using "code" first time ?
I have try by following way :
public void GetProfileDetail(string code)
{
StringBuilder authLink = new StringBuilder();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
authLink.AppendFormat("code={0}", code);
authLink.AppendFormat("&client_id={0}", clientId);
authLink.AppendFormat("&client_secret={0}", clientSecret);
authLink.AppendFormat("&redirect_uri={0}", redirect_url);
authLink.Append("&grant_type=authorization_code");
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(authLink.ToString());
Stream os = null;
try // send the post
{
//webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStreamAsync().Result;
os.Write(bytes, 0, bytes.Length); // Send it
}
catch (Exception ex)
{
}
}
but it gives me an error. Let me know what to do next
Thanks in advance.
You are trying to do the OAuth authentication through the webview, but that is not the recommended way to go.
Since wp8.1 there is a WebAuthenticationBroker class that you can use to initiate an OAuth process with a provider ( like Google in your case ).
A good detailed example can be found on MSDN here https://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122

Google and .Net windows console progeam

I need to write a windows console program that will take the results from a SQL query, and dump the results into a excel sheet. We are moving away from Microsoft, and towards Google technology. So I need to create a worksheet, dump the results in that file, and store on drive.
Is the sdk the best way to go on this? Am I going to need the SDK for Drive and for Worksheetes? I also need to have the console run on it's own, no user interaction at all. I have been working with this sample below, and got it to work. I'm not sure if I'm going in the right direction with this. Any advice would be great!
using System;
using System.Threading;
using System.Threading.Tasks;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;
using Google.Apis.Discovery;
using Google.GData.Client;
using Google.GData.Extensions;
namespace GoogleDriveSamples
{
class DriveCommandLineSample
{
static void Main(string[] args)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxxxxxxxxx-bn0vi796pn7tog7utb9pt6pmptl8cpsq.apps.googleusercontent.com",
ClientSecret = "FwuyHxBAj2Z1",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Credit Q",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes("FTP.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
Console.WriteLine("File id: " + file.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
}
}
}
You can do it in google apps script in about 5 lines of code.
Lok at the official samples. Basically use spreadsheetApp and jdbc.

background Agent works fine in local environment but failed after app submission to app store

I have an wp8 app using PeriodicTask background Agent.
The task update the information of multiple live tiles,
using POST Client to get title and image url from my server to update the live tile.
Background agent works just fine in debugging and releasing mode. When the .xap file was deployed into my device using XAPDeployement tool, the background Agent also works perfectly.
However, it won't work after submitted to wp app store, no matter it's beta version or not.
If the app is downloaded from store, the background agent has never worked, and it is blocked by system after a few minutes.
How come it goes wrong since the XAP files are the same?
part of code:
public static Task<string> jsonPostClientTask(Dictionary<string, object> parameters, string url)
{
var results = new TaskCompletionSource<string>();
PostClient proxy = new PostClient(parameters);
try
{
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
string response = e.Result.ToString();
results.TrySetResult(response);
}
else
{
results.TrySetResult("");
results.TrySetException(e.Error);
}
};
proxy.DownloadStringAsync(new Uri(url));
}
catch
{
results.TrySetResult("");
}
return results.Task;
}
ScheduledAgent class:
protected override void OnInvoke(ScheduledTask task)
{
foreach (var tile in tileList)
{
string dataString = jsonPostClientTask(parameters, url);
//update tile in used
FlipTileData tileData = new FlipTileData()
{
BackContent = "string content",
WideBackContent = "string back content",
BackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
WideBackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
};
ShellTile primaryTile = ShellTile.ActiveTiles.First();
if (primaryTile != null)
primaryTile.Update(tileData);
}
}

Reading the content of HTTP Stream before the Content stream is Complete Windows Phone 8

I am trying to get a reference to a response stream before its complete in windows phone 8.
In other .Net platforms you can do
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(myUri);
WebResponse subscribeWebResponse = null;
Stream subscribeStream = null;
subscribeWebResponse = httpRequest.GetResponse();
subscribeStream = subscribeWebResponse.GetResponseStream();
For the purpose of creating Portable class libraries I've used the HttpClientLibrary from nuget.
This Adds ref to extensions assembly Microsoft.Net.Http
this allows me to return the async request at the time the headers have been read instead of waiting for the content transfer to be complete with
var clientResponse = await httpClient.SendAsync(requestmessage, HttpCompletionOption.ResponseHeadersRead);
The problem I'm having is that in windows phone 8 it doesn't work correctly, and still awaits the completion of the content stream to return.
Additionally
await httpWebRequest.BeginGetResponse(callback, request)
has the same behavior as these async methods are actually waiting for the completion of the web's response to continue execution.
So, is there any way to achieve the returning the response/stream at the point that i have received the response headers without Microsoft.Http.Net package?
Even if it has to be a Windows Phone 8 Platform Specific Solution?
Possibly an extension of HttpWebRequest?
From what I can tell, ResponseHeadersRead works on the WP8 emulator as it does on the desktop.
I installed the Win8 SDK. Created a windows phone app. I added this code to the MainPage ctor. This demonstrates a very rudimentary long polling example.
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://oak:1001/longpolling")
};
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, new CancellationToken())
.ContinueWith((t) =>
{
var response = t.Result;
response.Content.ReadAsStreamAsync()
.ContinueWith(s =>
{
var st = s.Result;
while (true)
{
var message= ReadNextMessage(st);
}
});
});
}
private static string ReadNextMessage(Stream stream)
{
int chr = 0;
string output = "";
while (chr != 10)
{
chr = stream.ReadByte();
output += Convert.ToChar(chr);
}
return output;
}
On my host dev machine I have a web api with a controller that looks like this...
public class LongPollingController : ApiController
{
public HttpResponseMessage Get()
{
Thread.Sleep(2000);
var content = new PushStreamContent( (s,c,t) =>
{
int i = 0;
while (true)
{
try
{
var message = String.Format("The current count is {0} " + Environment.NewLine, i++);
var buffer = Encoding.UTF8.GetBytes(message);
s.Write(buffer, 0, buffer.Length);
}
catch (IOException exception)
{
s.Close();
return;
}
Thread.Sleep(1000);
}
});
return new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = Request,
Content = content
};
}
}
So here's the deal. I would say that what you want to do is not possible, due to platform limitations... But SignalR has a WP client and is able to manage it. So it seems to me you have two options:
1) Dig into the SignalR source code to see how they do it (I'm on my phone right now so I can't provide a link).
UPDATE: Here is the link. They do some pretty neat tricks, like setting the Timeout to -1 for long-running clients. I think you should definitely use the techniques here.
OR
2) You can move whatever you're doing over to SignalR, which would gain the benefit of having a robust infrastructure and being cross-platform compatible.
HTH

Message Dialog in Windows Store WITHOUT Async?

So, I'm porting an app over to Windows Store. At the start of the app, I have some code, that asks a question. I DO NOT WANT THE REST OF MY CODE TO FIRE UNTIL I GET A RESPONSE.
I have this:
string message = "Yadda Yadda Yadda";
MessageDialog msgBox = new MessageDialog(message, "Debug Trial");
msgBox.Commands.Add(new UICommand("OK",
(command) => { curSettings.IsTrial = true; }));
msgBox.Commands.Add(new UICommand("Cancel",
(command) => { curSettings.IsTrial = false; }));
await msgBox.ShowAsync();
//... more code that needs the IsTrial value set BEFORE it can run...
When I run the app, the code after the msgBox.ShowAsync() runs, without the correct value being set. It's only after the method finishes that the user sees the Dialog box.
I would like this to work more like a prompt, where the program WAITS for the user to click BEFORE continuing the method. How do I do that?
MessageDialog does not have a non-asynchronous method for "Show." If you want to wait for the response from the dialog before proceeding, you can simply use the await keyword.
Here also is a quickstart guide for asynchronous programming in Windows Store Apps.
I see that your code sample already uses "await". You must also mark the calling function as "async" in order for it to work properly.
Example:
private async void Button1_Click(object sender, RoutedEventArgs e)
{
MessageDialog md = new MessageDialog("This is a MessageDialog", "Title");
bool? result = null;
md.Commands.Add(
new UICommand("OK", new UICommandInvokedHandler((cmd) => result = true)));
md.Commands.Add(
new UICommand("Cancel", new UICommandInvokedHandler((cmd) => result = false)));
await md.ShowAsync();
if (result == true)
{
// do something
}
}