Google Access on WP7 - c#

I am having problems building an app that can access google accounts. I have the following code that gets the sign in page for google accounts and then the access permissions page is also displayed!. Once i click on "Allow Access" the app is redirected to error page. here are few screenshots so that whoever is trying to help can understand better.. and below is the code that am using
private void browseGoogle_Loaded(object sender, RoutedEventArgs e)
{
string address = "https://accounts.google.com/o/oauth2/auth" +
"?client_id=" + "*******.apps.googleusercontent.com" +
"&scope=" + "https://www.googleapis.com/auth/plus.me" +
"&response_type=code" +
"&redirect_uri=" + "https://www.****.com/oauth2callback";
browseGoogle.Navigate(new Uri(address, UriKind.Absolute));
}
https://accounts.google.com/o/oauth2/approval?as=634f855389bf10ff&hl=en_GB&xsrfsign=APsBz4gAAAAAUHZvwB3xTqisyv8hEcWem5X3eKvwAHN9
this is the URI its navigating to after allow access is selected/clicked. What does this mean?
This is all am doing. My BrowserNavigated Method doesn't contain any code as of now. I dunno what to do further.hence seeking help.
Please help me resolve this issue.. All answers and suggestion appreciated.

Just check the GDrive open-source application code here.
The Authorization View and ViewModel show you how you can make OAuth sign-in with Google credentials.
Download the code, read the pre-build instructions on the site, and test it!

private void browseGoogle_Loaded(object sender, RoutedEventArgs e)
{
try
{
StringBuilder autheticateURL = new StringBuilder();
autheticateURL.Append(GmailSettings.AuthorizeUri).Append("?client_id=").Append(GmailSettings.clientID).Append("&scope=").
Append(GmailSettings.ScopeValue).Append("&response_type=code").Append("&redirect_uri=").Append(GmailSettings.CallbackUri);
browseGoogle.Navigate(new Uri(autheticateURL.ToString(), UriKind.Absolute));
}
catch (Exception ex)
{
Logger.log(TAG, "browseGoogle_Loaded()", ex.Message);
}
}
/// <summary>
/// Called when the web browser initiates Navigation to various pages
/// </summary>
/// <param name="sender">Browser</param>
/// <param name="e">Navigating event arguments</param>
private void browseGoogle_Navigating(object sender, NavigatingEventArgs e)
{
try
{
string hostName = e.Uri.Host;
string URL = e.Uri.ToString();
if (hostName.StartsWith("localhost"))
{
NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.Relative));
}
}
catch (Exception ex)
{
Logger.log(TAG, "browseGoogle_Navigating()", ex.Message);
}
}
The XAML goes like this
<phone:WebBrowser x:Name="browseGoogle" Loaded="browseGoogle_Loaded" IsScriptEnabled="true" Navigating="browseGoogle_Navigating" />
My mistakes were two:-
1) as vignesh has mentioned in his comments I was using a wrong Redirect URI.
2)IsScriptEnabled was not at all set in my Web Browser Controls. Once i set it true everything was fine.

Related

How to fix C# google search

So I'm creating a program that can go into google and search for the word that has
been saved into a variable. So my question is how I can do this, without having it go to a URL instead just going to Google and search "whatever" Here's the code.
private void button2_Click(object sender, EventArgs e)
{
if (Script.Text == Script.Text)
{
Console.AppendText("\n[1] Loading Websites of " + Script.Text + "...");
}
WebClient wc = new WebClient();
Process.Start(#"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "Scripts " + Script.Text);
}
This should solve your problem
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start("chrome.exe", url);
}
you can also change browser dynamically by adding a second params
You can also do this:
String stringToSearch = “stackoverflow”;
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + stringToSearch);
This assumes IE is the default browser on your machine. If Chrome or Firefox is the default browser, then code will fail.
This is a useful link:
http://www.seirer.net/blog/2014/6/10/solved-how-to-open-a-url-in-the-default-browser-in-csharp
Maybe you can put it in a try catch block and see if there is an exception. If there is an exception with starting IE, then open chrome.

How to store persistent User Connection Strings with .NET WPF Click-Once

We're developing a Click-Once WPF Windows Application that retrieves all its data from a database. I implemented a Form where a User could enter the corresponding data and using a SqlConnectionStringBuilder we build the Connection String and that works just fine.
We then add the Connection String to the ConfigurationManager using
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
If we use some other ConfigurationUserLevel, the application crashes (I don't know why yet, but I believe the Entity Framework Model tries to load the connection string and doesn't find it, because the file is not stored in the correct User Level?). Now, we store the connection string in a separate file and load it in App.config so we don't have to check it into Version Control:
<connectionStrings configSource="connections.config"/>
We don't deploy this file because it contains our own development connection strings. Rather, we create an empty file for deployment where the user-entered connection string will be stored. This works completely fine.
Our problem is that with a click-once update, the file will be "lost". What is the best way to store persistent per-user connection strings encrypted in a configuration file? Or should we completely switch to Registry? Or create our own encrypted File somewhere outside the %APPDATA%/Local/Apps/2.0/...../ folders and load it manually when initializing the Entity Framework Context?
You can go to MSDN site it might help you
https://msdn.microsoft.com/en-us/library/dd997001.aspx
with the help of below code, you need to modify this code for your requirement, hope this will help.
To create a custom ClickOnce application installer
In your ClickOnce application, add references to System.Deployment and System.Windows.Forms.
Add a new class to your application and specify any name. This walkthrough uses the name MyInstaller.
Add the following Imports or using statements to the top of your new class.
using System.Deployment.Application;
using System.Windows.Forms;
Add the following methods to your class.
These methods call InPlaceHostingManager methods to download the deployment manifest, assert appropriate permissions, ask the user for permission to install, and then download and install the application into the ClickOnce cache. A custom installer can specify that a ClickOnce application is pre-trusted, or can defer the trust decision to the AssertApplicationRequirements method call. This code pre-trusts the application
Note:- Permissions assigned by pre-trusting cannot exceed the permissions of the custom installer code.
InPlaceHostingManager iphm = null;
public void InstallApplication(string deployManifestUriStr)
{
try
{
Uri deploymentUri = new Uri(deployManifestUriStr);
iphm = new InPlaceHostingManager(deploymentUri, false);
}
catch (UriFormatException uriEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + uriEx.Message);
return;
}
catch (PlatformNotSupportedException platformEx)
{
MessageBox.Show("Cannot install the application: " +
"This program requires Windows XP or higher. " +
"Error: " + platformEx.Message);
return;
}
catch (ArgumentException argumentEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + argumentEx.Message);
return;
}
iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted);
iphm.GetManifestAsync();
}
void iphm_GetManifestCompleted(object sender, GetManifestCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download manifest. Error: " + e.Error.Message);
return;
}
// bool isFullTrust = CheckForFullTrust(e.ApplicationManifest);
// Verify this application can be installed.
try
{
// the true parameter allows InPlaceHostingManager
// to grant the permissions requested in the applicaiton manifest.
iphm.AssertApplicationRequirements(true) ;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while verifying the application. " +
"Error: " + ex.Message);
return;
}
// Use the information from GetManifestCompleted() to confirm
// that the user wants to proceed.
string appInfo = "Application Name: " + e.ProductName;
appInfo += "\nVersion: " + e.Version;
appInfo += "\nSupport/Help Requests: " + (e.SupportUri != null ?
e.SupportUri.ToString() : "N/A");
appInfo += "\n\nConfirmed that this application can run with its requested permissions.";
// if (isFullTrust)
// appInfo += "\n\nThis application requires full trust in order to run.";
appInfo += "\n\nProceed with installation?";
DialogResult dr = MessageBox.Show(appInfo, "Confirm Application Install",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr != System.Windows.Forms.DialogResult.OK)
{
return;
}
// Download the deployment manifest.
iphm.DownloadProgressChanged += new EventHandler<DownloadProgressChangedEventArgs>(iphm_DownloadProgressChanged);
iphm.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>(iphm_DownloadApplicationCompleted);
try
{
// Usually this shouldn't throw an exception unless AssertApplicationRequirements() failed,
// or you did not call that method before calling this one.
iphm.DownloadApplicationAsync();
}
catch (Exception downloadEx)
{
MessageBox.Show("Cannot initiate download of application. Error: " +
downloadEx.Message);
return;
}
}
/*
private bool CheckForFullTrust(XmlReader appManifest)
{
if (appManifest == null)
{
throw (new ArgumentNullException("appManifest cannot be null."));
}
XAttribute xaUnrestricted =
XDocument.Load(appManifest)
.Element("{urn:schemas-microsoft-com:asm.v1}assembly")
.Element("{urn:schemas-microsoft-com:asm.v2}trustInfo")
.Element("{urn:schemas-microsoft-com:asm.v2}security")
.Element("{urn:schemas-microsoft-com:asm.v2}applicationRequestMinimum")
.Element("{urn:schemas-microsoft-com:asm.v2}PermissionSet")
.Attribute("Unrestricted"); // Attributes never have a namespace
if (xaUnrestricted != null)
if (xaUnrestricted.Value == "true")
return true;
return false;
}
*/
void iphm_DownloadApplicationCompleted(object sender, DownloadApplicationCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download and install application. Error: " + e.Error.Message);
return;
}
// Inform the user that their application is ready for use.
MessageBox.Show("Application installed! You may now run it from the Start menu.");
}
void iphm_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// you can show percentage of task completed using e.ProgressPercentage
}
To attempt installation from your code, call the InstallApplication method. For example, if you named your class MyInstaller, you might call InstallApplication in the following way.
MyInstaller installer = new MyInstaller();
installer.InstallApplication(#"\\myServer\myShare\myApp.application");
MessageBox.Show("Installer object created.");

How can i save the image from the webBrowser control?

In the top of form1 i did
WebBrowser webbrowser1;
Then in the constructor
webbrowser1 = new WebBrowser(); webbrowser1.Navigate("http://www.ims.gov.il/IMS/tazpiot/RainRadar.htm");
webbrowser1.DocumentCompleted += webbrowser1_DocumentCompleted;
Then in the DocumentCompleted event
void webbrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsoluteUri != webbrowser1.Url.AbsoluteUri)
{
return;
}
IHTMLDocument2 doc = (IHTMLDocument2)webbrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
foreach (IHTMLImgElement img in doc.images)
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
bmp.Save(#"E:\newimages\" + img.nameProp);
}
}
}
I'm getting on the hard disk 20 images saved.
But not the one i needed. The one i need to save from this page in the webBrowser is the image in this link: http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=
The radar it self image. I can make save as...
And i can use like i'm doing today WebClient...
But WebClient is not working all the time. So i'm trying to surf to the site and get the image of the radar from the webBrowser. But without success.
UPDATE
This is my webclient how i'm downloading the radar image today:
private void fileDownloadRadar()
{
if (Client.IsBusy == true)
{
Client.CancelAsync();
}
else
{
try
{
Client.DownloadFileAsync(myUri, Path.Combine(combinedTemp));
}
catch(Exception errors)
{
string errors2 = errors.ToString();
}
}
}
Client is WebClient
Now i'm going to the directory of where it was downloaded combinedTemp and i see that the downloaded file is 0kb empty.
The url in myUri is:
http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=
When i put this link in my chrome and surf to it i see the latest radar image but when i'm looking in my hard disk it's 0kb the downloaded file.
And i will add this is not happening now but some time ago some months ago i had another problem in some cases not all the time but in many times when i downloaded the image i had another error i even have open question about it one year ago : Why i'm getting exception: Too many automatic redirections were attempted on webclient?
So in general it's two problems but now the problem is that the downloaded file is 0kb.
This is the Client completed event:
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
try
{
client_Error_counter = client_Error_counter + 1;
if (client_Error_counter == 5)
{
Logger.Write("Tried to download radar image file " + client_Error_counter + " times without success");
Logger.Write("Error Tried to download radar image file : " + e.Error);
client_Error_counter = 0;
}
else
{
Client.DownloadFileAsync(myUri, Path.Combine(combinedTemp));
Logger.Write("Times tried to download radar image file: " + client_Error_counter);
Logger.Write("Error Tried to download radar image file : " + e.Error);
}
}
catch(Exception errors)
{
string myerr = errors.ToString();
}
}
And i see now i missed it that when it's getting to the DownloadFileCompleted event there is an error:
e.Error show: e.Error = {"Too many automatic redirections were attempted."}
StackTRace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
This is why i tried to use the WebBrowser. I can't find a way to solve this "Too many automatic redirections were attempted" problem.
That's why i see the file 0kb on my hard disk.
Another thing is today few hours ago it did download fine some radar images but now it's making this error again.

How to use LockScreen.SetImageUri to Set Windows Phone 8 Lock Screen Background

I have an image in IsolatedStorage, and I would like to programmatically set it as the device lock screen background. My problem is that I cannot get the correct path required by LockScreen.SetImageUri. From referencing http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206968(v=vs.105).aspx it is evident that `"ms-appdata:///local/" is the required precursor for local images.
var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
I have created a folder in my applications IsolatedStorage called Pictures in which jpg images are saved from the CameraCaptureTask. I have tried several ways to access images within this folder via the above scheme but I always receive an ArgumentException on the next line
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
When debugging, however, I see that uri = "ms-appdata:///Local/Pictures/WP_20130812_001.jpg", how is this not correct?
My implementation is as follows
private void recent_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
capturedPicture = (sender as LongListSelector).SelectedItem as CapturedPicture;
if (capturedPicture != null)
{
//filename is the name of the image in the IsolatedStorage folder named Pictures
fileName = capturedPicture.FileName;
}
}
void setAsLockScreenMenuItem_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(fileName))
{
//PictureRepository.IsolatedStoragePath is a string = "Pictures"
//LockHelper("isostore:/" + PictureRepository.IsolatedStoragePath + "/" + fileName, false); //results in FileNotFoundException
LockHelper(PictureRepository.IsolatedStoragePath + "/" + fileName, false); //results in ArgumentException
}
else
{
MessageBoxResult result = MessageBox.Show("You must select an image to set it as your lock screen.", "Notice", MessageBoxButton.OK);
if (result == MessageBoxResult.OK)
{
return;
}
}
}
private async void LockHelper(string filePathOfTheImage, bool isAppResource)
{
try
{
var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication;
if (!isProvider)
{
// If you're not the provider, this call will prompt the user for permission.
// Calling RequestAccessAsync from a background agent is not allowed.
var op = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
// Only do further work if the access was granted.
isProvider = op == Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted;
}
if (isProvider)
{
// At this stage, the app is the active lock screen background provider.
// The following code example shows the new URI schema.
// ms-appdata points to the root of the local app data folder.
// ms-appx points to the Local app install folder, to reference resources bundled in the XAP package.
var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
// Set the lock screen background image.
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
// Get the URI of the lock screen background image.
var currentImage = Windows.Phone.System.UserProfile.LockScreen.GetImageUri();
System.Diagnostics.Debug.WriteLine("The new lock screen background image is set to {0}", currentImage.ToString());
}
else
{
MessageBox.Show("You said no, so I can't update your background.");
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
How might I modify LockScreen.SetImageUri to the proper expected uri?
For setting lock screen images from the app, you might want to declare your app as lock screen provider. You can do that by modifying the WMAppManifest.xml file by adding the following tag:
<Extensions>
<Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
</Extensions>
Check to see if you have this tag in your manifest file.
I hope this could help you to address your issue.
If your app is already installed, make sure that it is an background image provider. If not then go to settings -> lock screen -> background and select your application from the list.
On the programmatic side:
1. Declare the app’s intent in the application manifest file
Edit WMAppManifest.xml with the XML editor, make sure the following extension is present:
<Extensions> <Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" /> </Extensions>
2. Write code to change the background image
The following is an example of how you can write the code for setting the background.
private async void lockHelper(Uri backgroundImageUri, string backgroundAction)
{
try
{
//If you're not the provider, this call will prompt the user for permission.
//Calling RequestAccessAsync from a background agent is not allowed.
var op = await LockScreenManager.RequestAccessAsync();
//Check the status to make sure we were given permission.
bool isProvider = LockScreenManager.IsProvidedByCurrentApplication; if (isProvider)
{
//Do the update.
Windows.Phone.System.UserProfile.LockScreen.SetImageUri(backgroundImageUri);
System.Diagnostics.Debug.WriteLine("New current image set to {0}", backgroundImageUri.ToString());
}
else { MessageBox.Show("You said no, so I can't update your background."); }
}
catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Regarding Uris, there are many options, but keep on mind:
To use an image that you shipped in your app, use ms-appx:///
Uri imageUri = new Uri("ms-appx:///background1.png", UriKind.RelativeOrAbsolute); LockScreen.SetImageUri(imageUri);
To use an image stored in the Local Folder, use ms-appdata:///local/shared/shellcontent
Must be in or below the /shared/shellcontent subfolder
Uri imageUri = new Uri("ms-appdata:///local/shared/shellcontent/background2.png", UriKind.RelativeOrAbsolute); LockScreen.SetImageUri(imageUri);

SecurityException with Silverlight Web Services

I've been following along with this Silverlight tutorial, using Twitter instead of Digg. Everything is working fine, until I get to the step where I try to get data from the service.
private const string TWITTER_API_URL_FORMAT = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name={0}";
private void Button_Click(object sender, RoutedEventArgs e)
{
string username = searchBox.Text;
string url = String.Format(TWITTER_API_URL_FORMAT, username);
WebClient twitterService = new WebClient();
twitterService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterService_DownloadStringCompleted);
label.Text = "Loading... " + url;
twitterService.DownloadStringAsync(new Uri(url));
}
void twitterService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
label.Text = String.Format("Error: {0}", e.Error);
return;
}
// ...
}
It fails with the following error:
[System.Security.SecurityException] = {System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<E...
I'm not sure why this is happening. The URL is legit. I have a wp7 Silverlight project that uses this same code, and it works fine. What could I be doing wrong?
You're probably running into a cross site scripting (XSS) error. Take a look here: Making a Service Available Across Domain Boundaries

Categories