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
Related
I'm working with C# xamarin forms android and I'm trying to go back using OnBackButtonPressed. It kind of works but my problem is that the user has to touch 2 times to go back. I will left a photo below to explain my point. But basically the user goes from Home page to Scaner page and when he touch buttom back when he is scanning doesn't come back to home page. He has to touch 2 times and i don't want that. I need that when he touches the buttom back he goes to the home page.
my scanPage.xaml.cs:
protected override bool OnBackButtonPressed()
{
try
{
if (Shell.Current.FlyoutIsPresented == false)
{
Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
else
{
Shell.Current.FlyoutIsPresented = false;
}
}
catch(Exception ex)
{
}
//return base.OnBackButtonPressed();
return true;
}
private async Task Scanner()
{
try
{
var scannerPage = new ZXingScannerPage();
scannerPage.AutoFocus();
scannerPage.Title = "Scanner";
using (SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 1))
{
scannerPage.OnScanResult += (result) =>
{
scannerPage.IsScanning = false;
string resultado = Convert.ToString(result);
if (resultado.Contains("http") || resultado.Contains("https") || !resultado.Contains("\t"))
{
Navigation.PopAsync();
this.DisplayAlert("Error", "QR not valid", "OK");
}
else
Device.BeginInvokeOnMainThread(async () =>
{
try
{
await Application.Current.MainPage.Navigation.PopAsync();
subs = result.Text.Split('\t');
string cadena = "var 1: " + subs[0] + "\nvar 2: " + subs[1] + "\nvar 3: " + subs[2];
numEntrega.Text = "var 2: " + subs[1];
controlScanner = true;
await this.DisplayAlert("Data", cadena, "OK");
}
catch (Exception ex)
{
checkDoubleCalled = true;
controlScanner = false;
numEntrega.Text = "";
await DisplayAlert("Error", "QR not valid.\n try again.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
semaphoreSlim.Release();
});
};
await Navigation.PushAsync(scannerPage);
await semaphoreSlim.WaitAsync();
}
return;
}
catch(Exception ex)
{
checkDoubleCalled = true;
controlScanner = false;
numEntrega.Text = "";
await DisplayAlert("Error", "Sorry we had a problem.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
return;
}
Image of my problem:
How could I resolve this problem?
Thank you very much!
So i'm trying to import 2 configs from the localfolder with Windows.Storage. But at the second time it fails with no exception.
This is my Code:
public async Task<string> ImportLines(string filename)
{
try
{
Windows.Storage.StorageFile importFile = await StorageFolder.GetFileAsync(filename);
string savedString = await Windows.Storage.FileIO.ReadTextAsync(importFile);
return savedString;
}
catch (Exception)
{
//log
}
}
I call this methode with:
public async void LoadConfig()
{
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + PluginsFilename))
{
string tmp = await _textDataHandler.ImportLines(PluginsFilename);
Plugins = JsonConvert.DeserializeObject<PluginConfiguration>(tmp);
}
else
{
CreateDefaultPluginsConfiguration();
//log
_textDataHandler.CreateFile(_pluginsFilename);
string export = JsonConvert.SerializeObject(Plugins, Formatting.Indented);
_textDataHandler.ExportText(_pluginsFilename, export);
//log
}
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + _settingsFilename))
{
string tmp = await _textDataHandler.ImportLines(Settingsfilename);
Config = JsonConvert.DeserializeObject<Configuration>(tmp);
_textDataHandler.CreateFile(Config.DatabaseFilename);
}
else
{
CreateDefaultSettingsConfiguration();
//log
_textDataHandler.CreateFile(_settingsFilename);
string export = JsonConvert.SerializeObject(Config, Formatting.Indented);
_textDataHandler.ExportText(_settingsFilename, export);
//Log
}
}
If one config does not exist its fine but if both exist it fails at the second time
If you have created async method. please avoid synchronous invoke with GetResult. You could add await key word in front of calling line.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string tmp = await ImportLines(Filename);
}
Update
Please try use dataReader to read file content.
public async Task<string> ImportLines(string filename)
{
try
{
StorageFile importFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var buffer = await FileIO.ReadBufferAsync(importFile);
using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
{
return dataReader.ReadString(buffer.Length);
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I am creating a Xamarin Form PCL project for Android and IOS.
Is this possible to display multiple permission at once on the screen? My App is using Location, Storage and Camera permission. From my current code, this is displaying permission popup one by one on the different page like before use of camera i display camera permission popup. As I know three permission required for my App so i want to display a single popup for all three permission.
Below is my code for storage permission.
public static async Task<dynamic> CheckStoragePermission()
{
var result = "";
try
{
var Storagestatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
if (Storagestatus != PermissionStatus.Granted)
{
await Utils.CheckPermissions(Plugin.Permissions.Abstractions.Permission.Storage);
}
}
catch (Exception ex)
{
error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
return result;
}
Hope someone did this before in xamarin forms, I will thank for your help for this.
You could try using the following code to request multiple permissions at one time:
private async void Button_Clicked(object sender, EventArgs e)
{
await GetPermissions();
}
public static async Task<bool> GetPermissions()
{
bool permissionsGranted = true;
var permissionsStartList = new List<Permission>()
{
Permission.Location,
Permission.LocationAlways,
Permission.LocationWhenInUse,
Permission.Storage,
Permission.Camera
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
try
{
foreach (var permission in permissionsNeededList)
{
var status = PermissionStatus.Unknown;
//Best practice to always check that the key exists
if (results.ContainsKey(permission))
status = results[permission];
if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
{
permissionsGranted = true;
}
else
{
permissionsGranted = false;
break;
}
}
}
catch (Exception ex)
{
}
return permissionsGranted;
}
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++;
}
I am trying to capture "Audio only" through Windows MediaCapture API. I am using the following code but getting an Exception(HRESULT: 0xC00D36D5).
MediaCapture captureMgr = new MediaCapture();
MediaCaptureInitializationSettings captureSettings = new MediaCaptureInitializationSettings();
captureSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;
await captureMgr.InitializeAsync(captureSettings);
this.CaptureVideoElement.Source = captureMgr;// exception is thrown here...
await captureMgr.StartPreviewAsync();
please tell me what i am doing wrong? or please suggest a better wayout.
I am trying to do something similar and this is what I found looking through MSDN/Samples...
private async void OnStartRecordingBtnClick(object sender, RoutedEventArgs e)
{
try
{
m_mediaCaptureMgr = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
await m_mediaCaptureMgr.InitializeAsync(settings);
}
catch (Exception exception)
{
// Do Exception Handling
}
}
private async void OnStopRecordingBtnClick(object sender, RoutedEventArgs e)
{
try
{
String fileName;
if (!m_bRecording)
{
fileName = "audio.mp4";
m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
MediaEncodingProfile recordProfile = null;
recordProfile = MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto);
await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, this.m_recordStorageFile);
m_bRecording = true;
}
else
{
await m_mediaCaptureMgr.StopRecordAsync();
m_bRecording = false;
if (!m_bSuspended)
{
var stream = await m_recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
playbackElement.AutoPlay = true;
playbackElement.SetSource(stream, this.m_recordStorageFile.FileType);
}
}
}
catch (Exception exception)
{
// Do Exception Handling...
m_bRecording = false;
}
}
Hope this helps.
Here is the MSDN link:
enter link description here