Copy video files to Local folder is not working - c#

I want to upload files to LocalFolder of UWP. It works well for images.But for some large mp4 files it goes to already exist exception and shows error
"System.Runtime.InteropServices.COMException:Error HRESULT E_FAIL has been returned from a call to a COM component."
private async void BtnTestUpload_ClickAsync(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".mp4");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
try
{
await file.CopyAsync(ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.FailIfExists);
var dialog = new MessageDialog("Upload Successfull");
await dialog.ShowAsync();
}
catch (Exception ex)
{
var dialog = new MessageDialog("fail" + ex.ToString());
await dialog.ShowAsync();
}
}
}

Related

Xamarin computer vision

I am trying to create a Xamarin application using Azure computer vision API, I got the API key and endpoint URL whenever i click a picture and set in image view and then describe image function not working and i am not getting output captions, my code is below:
private async void Button_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
try
{
if(!CrossMedia.Current.IsTakePhotoSupported&&!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("INFO", "CAMERA NOT AVAILABEL", "OK");
}
else
{
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory="Images",
Name="test.jpg"
});
if (file==null)
{
await DisplayAlert("ERROR", "FILE NOT FOUND", "OK");
return;
}
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
var visionapi = new ComputerVisionClient(new ApiKeyServiceClientCredentials(""));
visionapi.Endpoint = "";
var desc = await visionapi.DescribeImageInStreamAsync(file.GetStream());
foreach (var tag in desc.Captions)
{
cap.Text = cap.Text + "\n" + tag;
}
}
}
catch(Exception )
{
await DisplayAlert("", "ERROR", "OK");
}
}
DescribeImageInStreamAsync functon is not working it is moving into catch block after few minutes with the below error:
Microsoft.Azure.CognitiveServices.Vision.ComputerVisionErrororException: Operation returned an invalid status code 'Not Found'
Exception

The process cannot access the file because it is being used by another process

I am running a program where a file gets uploaded to a folder in IIS,and then is processed to extract some values from it. I use a WCF service to perform the process, and BackgroundUploader to upload the file to IIS. However, after the upload process is complete, I get the error "The process cannot access the file x because it is being used by another process." Based on similar questions asked here, I gathered that the file concerned needs to be in a using statement. I tried to modify my code to the following, but it didn't work, and I am not sure if it is even right.
namespace App17
{
public sealed partial class MainPage : Page, IDisposable
{
private CancellationTokenSource cts;
public void Dispose()
{
if (cts != null)
{
cts.Dispose();
cts = null;
}
GC.SuppressFinalize(this);
}
public MainPage()
{
this.InitializeComponent();
cts = new CancellationTokenSource();
}
public async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
GlobalClass.filecontent = file.Name;
GlobalClass.filepath = file.Path;
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
await HandleUploadAsync(upload, true);
stream.Dispose();
}
}
catch (Exception ex)
{
string message = ex.ToString();
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
}
private void CancelAll(object sender, RoutedEventArgs e)
{
Log("Canceling all active uploads");
cts.Cancel();
cts.Dispose();
cts = new CancellationTokenSource();
}
private async Task HandleUploadAsync(UploadOperation upload, bool start)
{
try
{
Progress<UploadOperation> progressCallback = new Progress<UploadOperation>(UploadProgress);
if (start)
{
await upload.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The upload was already running when the application started, re-attach the progress handler.
await upload.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = upload.GetResponseInformation();
Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
cts.Dispose();
}
catch (TaskCanceledException)
{
Log("Upload cancelled.");
}
catch (Exception ex)
{
string message = ex.ToString();
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
}
private void Log(string message)
{
outputField.Text += message + "\r\n";
}
private async void LogStatus(string message)
{
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
private void UploadProgress(UploadOperation upload)
{
BackgroundUploadProgress currentProgress = upload.Progress;
MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid,
currentProgress.Status));
double percentSent = 100;
if (currentProgress.TotalBytesToSend > 0)
{
percentSent = currentProgress.BytesSent * 100 / currentProgress.TotalBytesToSend;
}
MarshalLog(String.Format(CultureInfo.CurrentCulture,
" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", currentProgress.BytesSent,
currentProgress.TotalBytesToSend, percentSent, currentProgress.BytesReceived, currentProgress.TotalBytesToReceive));
if (currentProgress.HasRestarted)
{
MarshalLog(" - Upload restarted");
}
if (currentProgress.HasResponseChanged)
{
MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);
}
}
private void MarshalLog(string value)
{
var ignore = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Log(value);
});
}
}
}
After this is done, the file name is sent to a WCF service which will access and process the uploaded file to extract certain values. It is at this point I receive the error. I would truly appreciate some help.
public async void Extract_Button_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.Service1Client MyService = new ServiceReference1.Service1Client();
string filename = GlobalClass.filecontent;
string filepath = #"C:\Users\R\Documents\Visual Studio 2015\Projects\WCF\WCF\Uploads\"+ filename;
bool x = await MyService.ReadECGAsync(filename, filepath);
}
EDIT: Code before I added the using block
try
{
Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
GlobalClass.filecontent = file.Name;
GlobalClass.filepath = file.Path;
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
await HandleUploadAsync(upload, true);
}
When you work with stream writers you actually create a process, which you can close it from task manager. And after stream.Dispose() put stream.Close().
This should solve your problem.
You should also close the stream that writes the file to disk (look at your implementation of CreateUpload).
i got such error in DotNet Core 2 using this code:
await file.CopyToAsync(new FileStream(fullFileName, FileMode.Create));
counter++;
and this is how I managed to get rid of message (The process cannot access the file x because it is being used by another process):
using (FileStream DestinationStream = new FileStream(fullFileName, FileMode.Create))
{
await file.CopyToAsync(DestinationStream);
counter++;
}

BackgroundDownloader.CreateDownload method not working in windows phone 8.1

I'm trying to download a file with this code:
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Uri source;
Uri.TryCreate(txbUri.Text.Trim(),UriKind.Absolute, out source);
StorageFile destfile = await x.CreateFileAsync(Path.GetFileName(source.LocalPath), CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = await Task.Run(() => { return downloader.CreateDownload(source, destfile); });
await HandleDownloadAsync(download, true);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
but there is a exception on the line:
downloader.CreateDownload(source, destfile);
the exception is:
class not registered
I Compiled Microsoft sample with the exact codes and it worked fine. But I don't know why my App Doesn't.
Just in case "x" is a StorageFolder object that picked by user.

FileSavePicker for Audio file is not working in Windows Phone 8.1 Universal Apps

I tried this below code, the audio file is saving but it shows 0 bytes, I tried a lot if any one know about this please help me...
WP8.1 Universal Apps
Code in Mainpage.cs:
private async void pick_Click(object sender, RoutedEventArgs e)
{
string path = #"Assets\Audio\DeviPrasad.mp3";
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync(path);
var st =await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var size = st.Size;
FileSavePicker savePicker = new FileSavePicker();
//savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.SuggestedSaveFile = file;
savePicker.FileTypeChoices.Add("MP3", new List<string>() { ".mp3" });
savePicker.ContinuationData.Add("SourceSound", path);
savePicker.SuggestedFileName = "DeviPrasad";
savePicker.PickSaveFileAndContinue();
}
internal async void ContinueFileOpenPicker(FileSavePickerContinuationEventArgs e)
{
var file = e.File;
var ff= file.Properties;
if(file!=null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteTextAsync(file, file.Name);
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
}
Code In App.xaml.cs:
protected async override void OnActivated(IActivatedEventArgs args)
{
var root = Window.Current.Content as Frame;
var mainPage = root.Content as MainPage;
if (mainPage != null && args is FileSavePickerContinuationEventArgs)
{
mainPage.ContinueFileOpenPicker(args as FileSavePickerContinuationEventArgs);
}
}
The FileSavePicker will not help you to write or copy the content of the file to the destination.
Actually, I think you just simply copy the following code from somewhere but don't exactly know what it is doing.
await FileIO.WriteTextAsync(file, file.Name);
This is to write things to the file, and seems it is from a sample which handles txt file. For your case, we need to do the following things:
Add the source file path to ContinuationData in pick_Click event. Change the code to:
savePicker.ContinuationData.Add("SourceSound", file.Path);
Read the source file path and destination file in ContinueFileOpenPicker to write the content as below:
var file = e.File;
string soundPath = (string)e.ContinuationData["SourceSound"];
//var ff = file.Properties;
if (file != null)
{
CachedFileManager.DeferUpdates(file);
StorageFile srcFile = await StorageFile.GetFileFromPathAsync(soundPath);
await srcFile.CopyAndReplaceAsync(file);
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}

Screenshot Feature on Windows Store App

I am making an app for the windows store, and one section, 'Create' allows the user to drag images onto a background to create their own little scene (the app is aimed at kids). I'm adding a screenshot button so the user can save their work once they are done, and I have all the coding done, error free, but once I run it and press the screenshot button the app fails. Any advice or help is appreciated.
I get this message originating from the button once it fails:
An exception of type 'System.UnauthorizedAccessException'
occurred in mscorlib.dll but was not handled in user code
async void btnScreenshot_Click(object sender, RoutedEventArgs e)
{
var bitmap = await SaveScreenshotAsync(controlsGrid);
}
async Task<RenderTargetBitmap> SaveScreenshotAsync(FrameworkElement uielement)
{
var file = await PickSaveImageAsync();
return await SaveToFileAsync(uielement, file);
}
async Task<StorageFile> PickSaveImageAsync()
{
var filePicker = new FileSavePicker();
filePicker.FileTypeChoices.Add("Bitmap", new List<string>() { ".bmp" });
filePicker.FileTypeChoices.Add("JPEG format", new List<string>() { ".jpg" });
filePicker.FileTypeChoices.Add("Compuserve format", new List<string>() { ".gif" });
filePicker.FileTypeChoices.Add("Portable Network Graphics", new List<string>() { ".png" });
filePicker.FileTypeChoices.Add("Tagged Image File Format", new List<string>() { ".tif" });
filePicker.DefaultFileExtension = ".jpg";
filePicker.SuggestedFileName = "screenshot";
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.SettingsIdentifier = "picture picker";
filePicker.CommitButtonText = "Save picture";
return await filePicker.PickSaveFileAsync();
}
async Task<RenderTargetBitmap> SaveToFileAsync(FrameworkElement uielement, StorageFile file)
{
if (file != null)
{
CachedFileManager.DeferUpdates(file);
Guid encoderId = GetBitmapEncoder(file.FileType);
try
{
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
return await CaptureToStreamAsync(uielement, stream, encoderId);
}
}
catch (Exception ex)
{
DisplayMessage(ex.Message);
}
var status = await CachedFileManager.CompleteUpdatesAsync(file);
}
return null;
}
Guid GetBitmapEncoder(string fileType)
{
Guid encoderId = BitmapEncoder.JpegEncoderId;
switch (fileType)
{
case ".bmp":
encoderId = BitmapEncoder.BmpEncoderId;
break;
case ".gif":
encoderId = BitmapEncoder.GifEncoderId;
break;
case ".png":
encoderId = BitmapEncoder.PngEncoderId;
break;
case ".tif":
encoderId = BitmapEncoder.TiffEncoderId;
break;
}
return encoderId;
}
async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
{
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
var pixels = await renderTargetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
logicalDpi,
logicalDpi,
pixels.ToArray());
await encoder.FlushAsync();
return renderTargetBitmap;
}
catch (Exception ex)
{
DisplayMessage(ex.Message);
}
return null;
}
async void DisplayMessage(string error)
{
var dialog = new MessageDialog(error);
await dialog.ShowAsync();
}

Categories