UWP app not launching with one Launcher.LaunchUriAsync override - c#

I have an wpf app that I want to use to open another wpf app.
Call them image viewer (Gallery) and image storage (AppToAppCommunication).
Image storage app shows a list of available images.
Then, on ListBox selection changed I have this code:
private async void lbImages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var options = new LauncherOptions();
options.ContentType = "image/jpg";
var filePath = Environment.CurrentDirectory + "\\Images\\" +
((ListBoxItem)((ListBox)sender).SelectedItem).Content;
var file = await StorageFile.GetFileFromPathAsync(filePath);
var token = SharedStorageAccessManager.AddFile(file);
ValueSet inputData = new ValueSet();
inputData.Add("Token", token);
Uri uri = new Uri("myprotocol:");
//await Launcher.LaunchUriAsync(uri); // #works
//await Launcher.LaunchUriAsync(uri, options, inputData); // #doesn't
}
Now, when I use the line at #works, it works, with no image shown, as expected.
But, when instead I use line at #desn't, it gives me this error:
Now I tried clicking OK on the popup and running a new VS instance an waiting for it to load, but it never does.
I've tried running both applications from the same solution and I can get to a breakpoint in override void OnActivated in image viewer app (Gallery) when using the #works line in image storage app (AppToAppCommunication), but I can't get to that same breakpoint when using the #doesn't line.
I don't know what the problem is and I am not able to debug it.
How could I go about finding a way to debug this properly?

Related

Xamarin Media Plugin Crashes when second photo is taken

I am using the Plugin.Media (jamesmontemagno/MediaPlugin) plugin for Xamarin and I am having an issue with accepting a picture. When I take the second picture (the first picture works fine) and I click to accept the image the whole app crashes with no output as to the error. I have tried trapping the error but cannot find where it is occurring. I have as suggested removing the min SDK from Android manifest, but the crash still happens.
I have tried looking through the output in visual studio but it is always different. I am assuming the code works as it takes the image and gives me data back, to be clear, it only happens when trying to accept the second image.
private string GetTimestamp(DateTime value)
{
string timestamp = value.ToString("yyyyMMddHHmmssfff");
string filename = timestamp + ".jpg";
return filename;
}
public Command CaptureImage => new Command(TakePicture);
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
//Some message
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "FoodSnap",
Name = GetTimestamp(DateTime.Now) //Gets a unique file name,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom,
CustomPhotoSize = 50
});
if (file == null)
return;
FilePath = file.Path;
}
I am completely stumped as to why this is happening. I am also having trouble refreshing my ViewModel when data changes in the page I am using to take the image. I can't help wondering if this has something to do with it.
I solved the problem by testing each line of code. Once I removed PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom I could take as many pictures as I need. I did use the Github information for the plugin.
I would be interested to know what I did wrong to cause the error. I would suggest that I have misunderstood the tutorial on Github.

uwp close browser programmatically

I'm creating a simple news feed, it i want it can open the browser to show the details of the news, but i don't know how to close the browser , here is the code of how I open the browser,anyone can teach me how to off the browser using uwp? '
public async void test()
{
RootObject mynews = await NewsProxy.GetNews();
string website = mynews.articles[i].url;
var uriWeb = new Uri(websites);
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
if (success)
{
//Uri launched
}
else
{
// uri launch failed
}
}
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
Your code is actually telling the OS to Launch the given url and the OS in turn launches the default browser with the given URL. So you are not actually launching the browser.
In order to have full control over the browser behavior you can implement your own WebView and then use the url to navigate your WebView.
webView1.Navigate("http://www.contoso.com");
(MSDN Documentation for WebView)

C# UWP Open web Url with Microsoft Edge

I want open a URL using Microsoft Edge in my UWP. Searching, I found this code:
using System.Diagnostics;
using System.ComponentModel;
private void button_Help_Click(object sender, RoutedEventArgs e)
{
Process.Start("microsoft-edge:http://www.bing.com");
}
But it shows the following error:
The name Process do not exist in the current context
If I press Ctrl+., it only shows generate class options.
Any help is appreciated.
Process.Start is a traditional method used in .NET Framework which can't be used in UWP apps directly. To open web URI with Microsoft Edge in UWP, we can use
Launcher.LaunchUriAsync method. For example:
// The URI to launch
string uriToLaunch = #"http://www.bing.com";
// Create a Uri object from a URI string
var uri = new Uri(uriToLaunch);
// Launch the URI
async void DefaultLaunch()
{
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}
However this will open the URI with the default web browser. To always open it with Microsoft Edge, we can use Launcher.LaunchUriAsync(Uri, LauncherOptions) method with specified LauncherOptions.TargetApplicationPackageFamilyName property. TargetApplicationPackageFamilyName property can specify the target package that should be used to launch a file or URI. For Microsoft Edge, its Package Family Name is "Microsoft.MicrosoftEdge_8wekyb3d8bbwe". Following is an example shows how to use this.
// The URI to launch
string uriToLaunch = #"http://www.bing.com";
var uri = new Uri(uriToLaunch);
async void LaunchWithEdge()
{
// Set the option to specify the target package
var options = new Windows.System.LauncherOptions();
options.TargetApplicationPackageFamilyName = "Microsoft.MicrosoftEdge_8wekyb3d8bbwe";
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
}
You can do it, but Microsoft Edge must be your default browser. See the code bellow
private async void launchURI_Click(object sender, RoutedEventArgs e)
{
// The URI to launch
var uriBing = new Uri(#"http://www.bing.com");
// Launch the URI
var success = await Launcher.LaunchUriAsync(uriBing);
}
I have tried this and it works for me without setting Edge as default browser:
await Launcher.LaunchUriAsync(new Uri("microsoft-edge:https://www.bing.com"));

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);

How to load javascript in windows 8

I am looking for a way to implement Internet explorer - a desktop version in my Winodws 8 app . This is caused by my c# application- i need to run javascript page but its impossible in metro version of IE. Is there any method to do this?
I `ll describe my problem: when i want to load html of DOM page(rendered by javascript) i cant because javascript can run (I use WebView). I tried to open this page using Desktop version and it worked perfectly. Unfortunately Metro IE10 cant show the content and my WebView too.
Thanks for help.
You can sure inject in the c# webview a javascript file:
This is the action for a button:
private async void Lamp_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("ms-appx:///js/injected.js");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
string text = await FileIO.ReadTextAsync(file); //reading content as string
var script = "(function(){" + text + "})()";
}
try
{
var result = wv.InvokeScript("eval", new string[] { script });
}
catch (Exception) { }
wv is you id name for the webview element in the xaml

Categories