Uri activation to "ms-appdata:///local/" - c#

Running this code below gives me this unexpected result:
private async void OpenItemAppBarBtn_Click(object sender, RoutedEventArgs e)
{
MediaViewModel media = MyListView.SelectedItem as MediaViewModel;
if (media.VidOrPic)
{
var uriString = "ms-appdata:///local/" + media.Name + ".mp4";
Uri muUri = new Uri(uriString);
Launcher.LaunchUriAsync(new Uri(uriString, UriKind.RelativeOrAbsolute));
}
else
{
var uriString = "ms-appdata:///local/" + media.Name + ".jpeg";
Uri muUri = new Uri(uriString);
Launcher.LaunchUriAsync(new Uri(uriString, UriKind.RelativeOrAbsolute));
}
}
UriString Content:

to run the file use Launcher.LaunchFileAsync, not Launcher.LaunchUriAsync
var uriString = "ms-appdata:///local/" + media.Name + ".mp4";
Uri muUri = new Uri(uriString);
var file = await StorageFile.GetFileFromApplicationUriAsync(muUri);
await Launcher.LaunchFileAsync(file);

The Launcher.LaunchUriAsync method always shows the application picker, if no default application is associated with the Uri you provide.
However, there's an overload:
Launcher.LaunchUriAsync(Uri, LauncherOptions)
The launcher options allow you to set a property called DisplayApplicationPicker. If the default app is defined and you set this value to true, using the overload, the application will start directly, without displaying the application picker.

Related

Android Share method does not share text and image, only the image - Android

I have a method to be able to share images through SMS, WhatsApp, Email, Fb, etc., to which when calling it a URL is passed.
The method downloads the image from the shared URL and the image is ready to send (Xamarin.Essentials.Share is used).
The problem is that I pass a text along with the image (need to give some context) as part of the method property, but the text does not show it to me at the time of sharing, only the image alone, and it does not serve me well since it would send it without any context or information.
Any other ideas on how to pass the image and a text on Android?
Maybe some kind of automatic copy and then paste some text to the keyboard clipboard?
Image and Text Method:
public async Task DownloadImageAndShareIt(string URL)
{
try
{
string localPath = "";
var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) =>
{
byte[] bytes = new byte[e.Result.Length];
bytes = e.Result; // get the downloaded data
string documentsPath = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DirectoryPictures).AbsolutePath;
var partedURL = URL.Split('/');
string localFilename = partedURL[partedURL.Length - 1];
localFilename = "MyAPP" + localFilename;
localPath = System.IO.Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, bytes); // writes to local storage
MediaScannerConnection.ScanFile(Application.Context, new string[] { localPath }, null, null);
};
var url = new Uri(URL);
webClient.DownloadDataAsync(url);
var partedURL = URL.Split('/');
string localFilename = partedURL[partedURL.Length - 1];
localFilename = "MyAPP" + localFilename;
string documentsPath = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DirectoryPictures).AbsolutePath;
localPath = System.IO.Path.Combine(documentsPath, localFilename);
//Done.
}
catch (Exception Ex)
{
string LineErrorNumber = "Error line: " + Ex.StackTrace.Substring(Ex.StackTrace.Length - 7, 7) + "\r\n" + "Error: " + Ex.Message;
}
finally
{
await Share.RequestAsync(new ShareFileRequest
{
Title = **"Delicate info from MyAPP"**,
File = new ShareFile(localPath)
});
}
}
It should be noted that if I use another Share method that is only for text, there if I share it without problems.
Text only Method:
private async Task ShareText(string Tipo, string Titulo, string ContenidoaCompartir)
{
try
{
await Share.RequestAsync(new ShareTextRequest
{
Uri = "Delicate info from MyAPP",
Title = Titulo,
Subject = (Tipo + " de " + Titulo).ToString(),
Text = "MyApp - " + Tipo + " de " + Titulo + ":" + System.Environment.NewLine + ContenidoaCompartir + System.Environment.NewLine
});
}
catch (Exception Ex)
{
string LineErrorNumber = "Error line: " + Ex.StackTrace.Substring(Ex.StackTrace.Length - 7, 7) + "\r\n" + "Error: " + Ex.Message; Crashes.TrackError(Ex);
}
}
You can check the question below which shows how to share text and image through whatsapp Share image and text through Whatsapp or Facebook

Saving bitmap to gallery in Android

I thought that should be simple, yet I can't figure it out.
I keep getting the error: System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/Pictures/Screenshots/name.jpg".
The code:
string root = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).Path;
File myDir = new File(root + "/Screenshots");
myDir.Mkdirs();
string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date());
string fname = CommunicationHandler.GetNickname() + "|" + timeStamp + ".jpg";
File file = new File(myDir, fname);
if (file.Exists())
file.Delete();
try
{
using (System.IO.Stream outStream = System.IO.File.Create(file.Path))
{
finalBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream);
outStream.Flush();
outStream.Close();
}
}
catch (Exception e)
{
Toast.MakeText(Activity, e.ToString(), ToastLength.Long).Show();
}
Also, I can't access manually to /storage/emulated/0..
Why can't I manage to save the bitmap to my phone gallery? What's the problem in the code above?
If you want to create a new directory, you can use System.IO.Directory.CreateDirectory(root); to create it.
//create a directory called MyCamera
string root = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim).ToString() + "/MyCamera/";
//create the Directory
System.IO.Directory.CreateDirectory(root);
As taken from here:
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
Also, note that you could just add an image to the gallery via a simple line:
MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), IMAGE ,"nameofimage" , "description");

Windows Universal - Display images from Assets

I'm trying to scroll through images in my app, but I'm having trouble figuring out how to populate my list. The images are named using numbers from 1.jpg upwards. If anyone could help it would be great.
async private void Exec()
{
// Get the file location.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string myImageFolder = (appFolder.Path + "\\Assets\\Images");
int imageNumber = 1;
List<Uri> fileList = new List<Uri>();
foreach (var fileItem in fileList)
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(myImageFolder + "/" + imageFileName);
fileList.Add(uri);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
imageNumber++;
}
}
UPDATE
I have tried to create a workaround and do this without the foreach statement but its crashing when testing if the next file exists: :(
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
Uri uri1 = new Uri(path + "\\" + testFile);
if (await appFolder.TryGetItemAsync(uri1.ToString()) != null)
{
test = 99999;
}
}
while (test != 99999);
}
Your list does not contain any items. Your foreach will never run, as there will be no entries in your list.
You need to go through all paths in myImageFolder-root and add those uris to the list, then you can just use them in a foreach to create images and set their source, for every uri in the list.
Also imageNumber is un-needed then as you will have the URIs.
Prep the list of URIs first, by traversing the folder. Then modify the existing foreach to use those to build image objects.
Also, refrain from adding to a collection WHILE iterating it...
I have this working, and not a single foreach was required :D Thanks #Richard Eriksson
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
if (await appFolder.TryGetItemAsync(testFile) != null)
{
test = 99999;
}
else
{
test = 1;
}
}
while (test == 99999);
}

How to add GPS data to metadata on windows phone 8.1 RT

I am making a camera app in C# for Windows Phone 8.1 RT and want to add GPS location to the metadata of the just taken picture.
Reading location data from the GPS is not a problem.
Reading metadata from an (in this case) image.jpg is not a problem.
Writing/editing data however is, because some fields are readonly.
Take picture, then saving:
public async void take_picture()
{
ImageEncodingProperties format = ImageEncodingProperties.CreateJpeg();
format.Width = resolutionwidth;
format.Height = resolutionheight;
var imageStream = new InMemoryRandomAccessStream();
await captureManager.CapturePhotoToStreamAsync(format, imageStream);
//some more code
StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync("nameofpicture.jpg", CreationCollisionOption.GenerateUniqueName);
var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
await RandomAccessStream.CopyAsync(imageStream, fileStream);
}
Read the metadata. (These properties are now empty, but properties can be read from another picture.)
private async void metaread_button_click(object sender, RoutedEventArgs e)
{
StorageFile file1 = await KnownFolders.PicturesLibrary.GetFileAsync("nameofpicture.jpg");
var fileprops = await file1.Properties.GetImagePropertiesAsync();
textblock1.Text = "manufacturer: " + fileprops.CameraManufacturer; //writable property
textblock2.Text = "model: " + fileprops.CameraModel; //writable property
textblock3.Text = "title: " + fileprops.Title; //writable property
textblock4.Text = "latitude: " + fileprops.Latitude; //readonly property
textblock5.Text = "longtitude: " + fileprops.Longitude; //readonly property
textblock6.Text = "orientation: " + fileprops.Orientation; //readonly property
}
Modify writable metadata:
private async void metawrite_button_click(object sender, RoutedEventArgs e)
{
StorageFile file2 = await KnownFolders.PicturesLibrary.GetFileAsync("nameofpicture.jpg");
var fileprops = await file2.Properties.GetImagePropertiesAsync();
fileprops.Title = "picture by me";
await fileprops.SavePropertiesAsync();
}
Question: how can the readonly properties be set?
The "ImageEncodingProperties" set properties of the image, but not the file.
Finally found the answer to this one. See RD8388's answer. Just need to convert the lat/long to Degree/Minute/Second format. You do not need to comment out the longitude denominator as he suggested. Just make sure that your the seconds (of numerator property) divided by the denominator falls within the expected range.
http://answers.flyppdevportal.com/categories/metro/csharpvb.aspx?ID=aaf0b373-b0e0-4d91-84d8-69e768a374d8

ShellTile.Create with FlipTileData throws InvalidOperationException?

I am trying to create a tile using FlipTileData in Windows Phone 8. I use this code:
const string mainPage = "/MainPage.xaml";
...
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
This throws an InvalidOperationException at the ShellTile.Create method. There are no other tiles with the same Navigation URI. What am I doing wrong here?
This code works fine using the StandardTileData class, excluding the SmallBackgroundImage and WideBackgroundImage properties.
If it matters, the full code is:
const string mainPage = "/MainPage.xaml";
...
private void createbutton_Click(object sender, RoutedEventArgs e)
{
string tileId = new Random().Next().ToString();
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(tileGrid, null);
string isourl = "/Shared/ShellContent/" + tileId + ".jpg";
IsolatedStorageFileStream isfs = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(isourl);
wbmp.SaveJpeg(isfs, 173, 173, 0, 100);
isfs.Close();
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
}
If using the new tile templates you need to use the overload of ShellTile.Create() that includes a third parameter.
This should do the trick:
ShellTile.Create(mp, tileData, true);
Are you calling this code inside the Closing handler?
In Windows Phone 8, creating a Tile by using the Create(Uri, ShellTileData) method inside the Closing handler will throw an InvalidOperationException.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206947(v=vs.105).aspx
edit: i guess not, since you said it worked with StandardTileData...

Categories

Resources