Download and launch default app in windows phone 8 in C# - c#

I am using Live api to download SkyDrive files.
My code has a download click event which triggers the OnDownloadedCompleted function.
OnDownloadedCompleted function copies the file to "filename".
and calls the DefaultLaunch(), which takes in the "filename" and tries to launch it by the default program in windows phone 8.
When i execute this code (The file downloaded is a OneNote file) OneNote opens and says that the file can't be open.
Can anyone please help me validate this code?
Thanks a lot!
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
if (App.Current.LiveSession == null)
{
infoTextBlock.Text = "You must sign in first.";
}
else
{
LiveConnectClient client = new LiveConnectClient(App.Current.LiveSession);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadAsync("file_id");
}
}
The code for OnDownloadCompleted is
void OnDownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)
{
if (e.Result != null)
{
var filestream = File.Create(#"filename");
e.Result.Seek(0, SeekOrigin.Begin);
e.Result.CopyTo(filestream);
filestream.Close();
DefaultLaunch();
e.Result.Close();
}
else
{
infoTextBlock.Text = "Error downloading image: " + e.Error.ToString();
}
}
The code for Default launch function is
async void DefaultLaunch()
{
try
{
string imageFile = #"File.one";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{}
else
{}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.ToString());
}
}

try this tutorial.. http://msdn.microsoft.com/en-us/live/ff519582.aspx.. it is given there how to use live sdk in windows 8 platform

Related

How to transfer the file from Windows Form Application to Xamarin Forms using USB cable C#.net

I am now developing Android Application and the Windows Form.
In the previous, the users need to plug in with USB, copy the file and paste into android folder but it would be troublesome and takes time to do.
How can I transfer the file directly from the PC to android Folder (Internal Storage/ downloads) ?
I tried with FolderBrowserDialog to browse and copy into android but "OK" button is disabled when I point the location. enter image description here
Should I write it in Windows Form backend or Xamarin Forms backend side in order to direct transfer into the Android App?
I cannot use Web API as cannot use the internet connection.
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
txtCopy.Text = dialog.SelectedPath;
}
string copyFileName = Path.Combine(txtCopy.Text, originalFile); //originalFile->FileName (testing.jpg)
File.Copy(txtFile1.Text, copyFileName, true);
Direct file transfer from Windows Form and Xamarin Forms by clicking button
I too had issues with copying to/from Android with Xamarin. Originally directed to use ADB.exe (Android Debug Bridge), but that had too many security holes / issues and was restricted from using that. Could not use generic 3rd party for other reasons and had to write my own Android / Xamarin file transfer library (works great). One thing I found in MY research was what was the naming convention for paths did not always match what you think it might / should. For example, your "Internal shared storage" wasn't really that when I connected.
"DT50\Internal shared storage\Download"
it was just
"Internal Storage\Download".
Did not have a leading \ character and it worked. Writing to other directories, you need to prompt/grant permission on the Xamarin side to look at SOME possible other working folder directories, but that might be something for you at another time.
Based on your code, I made a Windows Form project to complete the copy.
You could refer to the following code:
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dialog.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
textBox2.Text = dialog.SelectedPath;
}
private void button3_Click(object sender, EventArgs e)
{
DirectoryInfo thefolder = new DirectoryInfo(textBox1.Text);
foreach (FileInfo nextfile in thefolder.GetFiles())
{
try
{
string filename = nextfile.Name;
string filefullname = nextfile.FullName;
string mudi = textBox2.Text + "\\" + filename;
if (File.Exists(mudi))
{
//File.Delete(mudi);
}
else
{
File.Copy(filefullname, mudi);
MessageBox.Show("Successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
Now I got it. I have to download MediaDevices framework in NuGet Package Manager to download/ transfer the file from Android device to PC.
I can transfer the file from Android to PC.
But the thing is I cannot transfer/ Upload the file from PC to Android (when using PCToPDA()). When I run the program, the error Director "DT50\Internal shared storage\Download" not found appear even though the directory path is correct.
Any idea why is that happening?
Updated One
The problem has been solved. Instead of writing "DT50\Internal shared storage\Download", I have to remove DT50 and just "\Internal shared storage\Download". Commented the wrong one and Updated the correct the source code below.
string originalFile;
private void BtnBrowse_Click(object sender, EventArgs e)
{
Browse(); //Get the files from Android Folder
}
private void Browse()
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtFile1.Text = openFileDialog1.FileName;
string fileName = Path.GetDirectoryName(openFileDialog1.FileName);
originalFile = Path.GetFileName(openFileDialog1.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Browse-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BtnCopy_Click(object sender, EventArgs e)
{
PDAToPC(); //Android to PC
//PCToPDA(); //PC to Android
}
private void PDAToPC()
{
try
{
string DeviceNameAsSeenInMyComputer = "DT50";
var devices = MediaDevice.GetDevices();
using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
{
device.Connect();
var photoDir = device.GetDirectoryInfo(#"\Internal shared storage\Download");
var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
string destinationFileName = $#"D:\KhineThein\Testing\TransferTesting\photo\{file.Name}";
if (!File.Exists(destinationFileName))
{
using (FileStream fs = new FileStream(destinationFileName, FileMode.Create, System.IO.FileAccess.Write))
{
device.DownloadFile(file.FullName, fs);
}
}
}
device.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "PDAToPC-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PCToPDA()
{
try
{
string DeviceNameAsSeenInMyComputer = "DT50";
string tempFileName = "CaptureImport.txt";
var devices = MediaDevice.GetDevices();
using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
{
device.Connect();
var photoDir = device.GetDirectoryInfo(#"\Internal shared storage\Download");
var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
string originalFileName = $#"D:\KhineThein\Testing\TransferTesting\photo\{tempFileName}";
//string transferToFileName = $#"{DeviceNameAsSeenInMyComputer}\Internal shared storage\Download\{tempFileName}";
string transferToFileName = $#"\Internal shared storage\Download\{tempFileName}";
using (FileStream fs = new FileStream(originalFileName, FileMode.Open, System.IO.FileAccess.Read))
{
//device.DownloadFile(file.FullName, fs); //Path, Stream
device.UploadFile(fs, transferToFileName); //Stream, Path
}
}
device.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "PCToPDA-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Xamarin MediaElement: setDataSource failed on URL

The following works ok:
using Plugin.FilePicker;
using Plugin.FilePicker.Abstractions;
using Xamarin.CommunityToolkit.Core;`
...
private void btnPlaySource_Clicked(object sender, EventArgs e)
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
mediaElement.Source = MediaSource.FromFile(fileData.FilePath);
mediaElement.Play();
}
But these lines throw an exception with a delay of ~7 secs (it's not immediately thrown):
private void btnPlayURL_Clicked(object sender, EventArgs e)
{
//http://docs.google.com/uc?export=open&id=XXXXXXXXXXXXXXXXXX
var fileURL = GetGDriveFileURL();
mediaElement.Source = MediaSource.FromUri(fileURL);
mediaElement.Play();
}
Java.Lang.RuntimeException: 'setDataSource failed: status = 0x80000000'
What could be the reason of the exception? The URL is 100% working, I tested it on a WPF application's MediaElement and it played fine. I also build the application for Android with Android API level 29 SDK.
<Grid><xct:MediaElement x:Name="mediaElement" Grid.Row="0" AutoPlay="False" ShowsPlaybackControls="True"/>
Some of the problems were solved using Xamarin.Essentials.FilePicker. It allows picking audio from Google Drive if it's connected to the Android device. Although, the problem with URL still remains.
//var fileResult = await App.PickAndShow(Xamarin.Essentials.PickOptions.Default);
//if (fileResult == null) return false;
public static async Task<string> PickAndShow(Xamarin.Essentials.PickOptions options)
{
try {
Xamarin.Essentials.FileResult result =
await Xamarin.Essentials.FilePicker.PickAsync(options);
if (result != null) {
// For certain types of files, like ".mp3"
if (result.FileName.EndsWith("mp3", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
{
// for debug purposes
bool exists = File.Exists(result.FullPath);
}
}
return result.FullPath;
} catch (Exception ex) {
// The user canceled or something went wrong
}
return null;
}

How can I open the savefile-dialog out of webview in an UWP

I've taken over an UWP project and have to fix an issue with a download button. On a website, there is a link to a software-package. The EXE can be downloaded using a browser.
In my webview, as far as I understood, I won't be able to download directly to disk, but it should be possible to open the standard-browser to take over that part. I managed to open PDFs in the standard-browser from my webview. That already was tricky for me and my noob skills, but it's working now. I tried the same with EXE-files, but that doesn't seem to work. Here is what I did so far:
private async void WebView1_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
{
if (args.Uri != null && args.Uri.OriginalString.ToLower().Contains(".pdf"))
{
return;
}
else
{ webView1.Navigate(args.Uri); }
args.Handled = true;
}
So this works for PDF, but when I do the same with EXE, it doesn't do anything (visible).
Any ideas on that?
How can I open the savefile-dialog out of webview in an UWP
You could listen NavigationStarting event handler, if the uri contains .exe you could create BackgroundDownloader to download exe file specific folder.
private async void TestWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
if (args.Uri != null && args.Uri.OriginalString.ToLower().Contains(".exe"))
{
try
{
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
"test.exe", CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(args.Uri, destinationFile);
await download.StartAsync();
}
catch (Exception ex)
{
}
}
}
Mahobo solution
string Link = args.Uri.Segments.Last();
try
{
var messagedialog = new MessageDialog("Saving File " + Link + " to your Download folder.");
await messagedialog.ShowAsync();
StorageFile destinationFile = await DownloadsFolder.CreateFileAsync(Link, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(args.Uri, destinationFile);
await download.StartAsync();
}
catch (Exception e)
{
}

Async file download in VB not working

I have the following:
wc.DownloadDataCompleted += Wc_DownloadDataCompleted;
FileStream f = File.OpenWrite(insLoc + "\\update.zip");
wc.DownloadDataAsync(new Uri("http://example.com/file.zip"), installLoc + "\\file.zip");
(and in a separate function)
private void Wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error == null) {
MessageBox.Show("Download success");
}
else { MessageBox.Show("Download failed"); }
f.Flush();
f.Dispose();
}
When I check the file it is supposed to be downloading to, it exists, but there is nothing in it (ie, it is 0 bytes). I have flushed the FileStream after the download has finished, so what is happening? I have a progress bar as well, and it slowly increases to 100% so I know it's downloading the ZIP file, and the "Download Success" messagebox is shown.
Thanks in advance!
You should use the callback function to save the resulting file (represented as a byte array passed as second argument):
wc.DownloadDataCompleted += Wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri("http://example.com/file.zip"));
and then:
private void Wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error == null)
{
string resultFile = Path.Combine(insLoc, "update.zip");
System.IO.File.WriteAllBytes(resultFile, e.Result);
MessageBox.Show("Download success");
}
else
{
MessageBox.Show("Download failed");
}
}
Now you can quickly see that using this method the entire file is loaded in memory as a byte array before flushing it to the file system. This is hugely inefficient especially if you are downloading large files. For this reason it is recommended to use the DownloadFileAsync method instead.
wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
string resultFile = Path.Combine(insLoc, "update.zip");
var uri = new Uri("http://example.com/file.zip");
wc.DownloadFileAsync(uri, resultFile);
and the corresponding callback:
private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("Download success");
}
else
{
MessageBox.Show("Download failed");
}
}
I would use DownloadFileTaskAsync method of WebClient which I find very simple to use..
await wc.DownloadFileTaskAsync(new Uri("http://example.com/file.zip"), installLoc + "\\file.zip");
That is all. If you want to see the download progress, you can attach to DownloadProgressChanged event.

Cannot save song from isolated storage, SaveSong method throws InvalidOperationException error

I'm building a FTP application for Windows Phone 8, and want to save the downloaded songs from the isolated storage to the media library. I check if the file exists in isostore, and it returns true, but when I'm using the SaveSong method it always throws an exception. Here is the code sample:
private async void contextMenuItem1_Click(object sender, RoutedEventArgs e)
{
string fileName = (sender as MenuItem).DataContext.ToString();
MediaLibrary library = null;
......
else if (fileName.EndsWith(".mp3") || fileName.EndsWith(".wav") || fileName.EndsWith(".aac"))
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(fileName))
{
library = new MediaLibrary();
StorageFile localFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
if (localFile != null)
{
//MessageBox.Show("StorageFile is: " + localFile.Name);
try
{
library.SaveSong(new Uri(localFile.Name, UriKind.RelativeOrAbsolute), null, SaveSongOperation.CopyToLibrary);
//MediaLibraryExtensions.SaveSong(media, new Uri(fileName, UriKind.RelativeOrAbsolute), null, SaveSongOperation.CopyToLibrary);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Exception caught: " + ex.Message);
}
}
}
else
MessageBox.Show("File does not exist in isostore");
}
}
I wolud be very grateful if anybody could help me, thx.
If your file name or file path is null then this exception comes.Also please verify ID_CAP_MEDIALIB_AUDIO capability added or not.
FYI

Categories

Resources