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();
}
Related
I have a function that works great when opening JPG and PNG files, but locks my computer up when opening a CR2 file. The CRS files are coming from my Canon EOS Rebel T6 Camera and they are big, see:
but I feel like it should not lock my computer up and it should not move this slow.
here is my code :
public async Task OpenFile()
{
OriginalImage = null;
await SetProcessBarInformation(0, "Openning Image file");
OpenFileDialog _openFileDialog = new OpenFileDialog();
if (_openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
await SetProcessBarInformation(20, "Openning Image file");
FileName = System.IO.Path.GetFileName(_openFileDialog.FileName);
BitmapImage tempOriginalImage = await GetPicture(_openFileDialog.FileName);
Height = (int)tempOriginalImage.Height;
Width = (int)tempOriginalImage.Width;
await SetProcessBarInformation(80, "Openning Image file");
await Task.Run(() =>
{
OriginalImage = tempOriginalImage;
});
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}
protected async Task<BitmapImage> GetPicture(string tempImage)
{
BitmapImage timage = null;
await Task.Run(() =>
{
timage = new BitmapImage(new Uri(tempImage));
timage.Freeze();
});
return timage;
}
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
I want to upload a video into server from my app, now I can upload small size video's, but in the case of larger size the video uploading is not done.How can I do this.
I found a reason that the 2 minutes video has the size 300 mb, so how can I reduce the size of the video with out losing the quality
Please somebody help me..
Here is my code for video taking
private async void TakeVideo_Clicked(object sender, EventArgs e)
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakeVideoSupported)
{
await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}
var _file = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
{
Name = "gtsvideo.mp4",
Directory = "GTSVideos",
});
if (_file == null)
{
return;
}
else
{
_path = _file.Path;
using (var _streamReader = new StreamReader(_file.GetStream()))
{
var _array = default(byte[]);
using (MemoryStream _memoryStream = new MemoryStream())
{
_streamReader.BaseStream.CopyTo(_memoryStream);
_array = _memoryStream.ToArray();
if (await DisplayAlert(App._confirmation, "It may take few Minutes..,Do you want to save the video?", "Yes", "Cancel"))
{
FileUploadAsync(_array, false);
activity_Indicator.IsVisible = true;
activity_Indicator.IsRunning = true;
}
else
{
return;
}
}
}
}
}
public async void FileUploadAsync(byte[] fileUpload, bool IsImage)
{
APIResponse _response = await App.DataManager.UpdateFilesAsync(_task.ID, fileUpload, IsImage);
if (IsImage == false)
{
await System.Threading.Tasks.Task.Delay(5000);
}
if (_response != null)
{
activity_Indicator.IsRunning = false;
if (IsImage)
{
DependencyService.Get<IAlertPlayer>().AlertMessege("Image upload successfully");
}
else
{
DependencyService.Get<IAlertPlayer>().AlertMessege("Video upload successfully");
}
}
else
{
DisplayAlertMessage();
}
}
UploadVideo
public async Task<APIResponse> UpdateFilesAsync(int id, byte[] file, bool IsImage)
{
Url _url = new Url(BaseURL).AppendPathSegment("tasks/UploadFiles");
_url.QueryParams["ID"] = id;
return await Service.POSTFILE<APIResponse>(_url, file, IsImage);
}
public async Task<T> POSTFILE<T>(Url url, byte[] uploadFile, bool IsImage)
{
try
{
using (MultipartFormDataContent _content = new MultipartFormDataContent())
{
ByteArrayContent _filecontent = new ByteArrayContent(uploadFile);
if (IsImage)
{
_filecontent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid().ToString() + ".png"
};
}
else
{
_filecontent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid().ToString() + ".mp4"
};
}
_content.Add(_filecontent);
using (HttpResponseMessage _response = await Client.PostAsync(url, _content))
{
string _result = await _response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(_result);
}
}
}
catch (Exception ex)
{
}
return default(T);
}
Simple answer: Unless you implement some fancy lossless compression code yourself, you don't. You get what the operating system of your phone gives you.
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++;
}
after downloading a JPG file from OneDrive successfully under Windows 8.1, I am not able to open it and use the stream as image source immediately. Instead, my app must run in a waiting loop to retry the opening until the exception "Error HRESULT E_FAIL has been returned from a call to a COM component" does not occur anymore. Or the app must inform the user to retry the action. After about one second or so, the file can be opened and the stream can be used as image source. This problem occurs if the JPG file was initially not available offline and my app downloads it. I want to know if anybody has a better solution for that problem. Here is some of my code:
private async void LoadFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpe");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".gif");
Stream stream = null;
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
var basicProperties = await file.GetBasicPropertiesAsync();
var props = await basicProperties.RetrievePropertiesAsync(
new string[] { "System.OfflineAvailability", "System.StorageProviderFileRemoteUri" });
if (props.ContainsKey("System.OfflineAvailability"))
{
var offline = (uint)props["System.OfflineAvailability"];
if (offline == 0)
{
if (file.Provider.DisplayName == "OneDrive")
{
if (props.ContainsKey("System.StorageProviderFileRemoteUri"))
{
var uri = (string)props["System.StorageProviderFileRemoteUri"];
var res = await GameStorage.DownloadOneDriveFile(file, uri, _downloadProgressBar);
if (res is string)
{
await App.InformUserAsync(res.ToString(), _title.Text);
return;
}
stream = (Stream)res;
}
}
else
{
await App.InformUserAsync(String.Format(
App.GetString("MakeFileOfflinePrompt", "GameManagement"),
file.Path), _title.Text);
return;
}
}
}
if (stream == null)
{
stream = await file.OpenStreamForReadAsync();
}
await _photoClipper.SetDisplayImageStreamAsync(stream);
_clipPhotoButton.IsEnabled = true;
}
}
internal static async Task<object> DownloadOneDriveFile(StorageFile file, string url,
ProgressBar progressBar = null)
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 1;
}
if (__liveClient == null)
{
var msg = await ConnectLive();
if (!String.IsNullOrEmpty(msg))
{
return msg;
}
}
var uri = new Uri(WebUtility.UrlDecode(url));
var pathElements = uri.LocalPath.Split(new char[] { '/' },
StringSplitOptions.RemoveEmptyEntries);
var parentId = "folder." + pathElements[0];
IDictionary<string, object> props = null;
for (var i = 1; i < pathElements.Length; i++)
{
props = await FindOneDrivePathElement(parentId, pathElements[i]);
if (props == null)
{
return String.Format(App.GetString("OneDrivePathElementNotFound",
"GameManagement"), pathElements[i], uri);
}
parentId = props["id"].ToString();
if (progressBar != null) progressBar.Value += 1;
}
try
{
var operation = await __liveClient.CreateBackgroundDownloadAsync(parentId +
"/content", file);
LiveDownloadOperationResult result = null;
if (progressBar != null)
{
progressBar.Value = 10;
var progressHandler = new Progress<LiveOperationProgress>(
(progress) => { progressBar.Value = progress.ProgressPercentage; });
var cts = new CancellationTokenSource();
result = await operation.StartAsync(cts.Token, progressHandler);
}
else
{
result = await operation.StartAsync();
}
var trialsCount = 0;
string openErr = null;
Stream stream = null;
while (trialsCount < 5)
{
try
{
stream = await result.File.OpenStreamForReadAsync();
break;
}
catch (Exception ex)
{
openErr = ex.Message;
}
trialsCount += 1;
await App.SuspendAsync(1000);
}
if (stream != null)
{
return stream;
}
return String.Format(App.GetString("OneDriveCannotOpenDownloadedFile",
"GameManagement"), file.Path, openErr);
}
catch (Exception ex)
{
return String.Format(App.GetString("OneDriveCannotDownloadFile",
"GameManagement"), file.Path, ex.Message);
}
finally
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Collapsed;
}
}
}
private static async Task<IDictionary<string, object>> FindOneDrivePathElement(
string parentId, string childName)
{
var res = await __liveClient.GetAsync(parentId + "/files");
if (res.Result.ContainsKey("data"))
{
var items = (IList<object>)res.Result["data"];
foreach (var item in items)
{
var props = (IDictionary<string, object>)item;
if (props.ContainsKey("name"))
{
var name = props["name"].ToString();
if (name == childName)
{
if (props.ContainsKey("id"))
{
return props;
}
}
}
}
}
return null;
}
I have tried again to open a "available online-only" file and as by a miracle the exception "Error HRESULT E_FAIL" did not occur any more. For what ever reason, I don't know. But, I really do not need to handle that scenario by myself. Thanks.