I'm experiencing some trouble with BitmapImage here. I have a WP8.1 app in which I can take photo, preview it and upload it. The preview is well displayed, good rotation and size but the problem is that, to upload it, I pass the byte[] corresponding to the storageFile wich is a big and not so well oriented picture.. I would like to rotate and shrink the storageFile BEFORE getting the byte[] from it.
Here is the snippet I use to preview/take/convert the picture :)
//Récupère la liste des camèras disponibles
private static async Task<DeviceInformation> GetCameraID(Windows.Devices.Enumeration.Panel desiredCamera)
{
DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredCamera);
if (deviceID != null) return deviceID;
else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desiredCamera));
}
//Initialise la caméra
async private void initCamera()
{
//Récupération de la caméra utilisable
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
//Initialise l'objet de capture
captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
var maxResolution = captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) => (i1 as VideoEncodingProperties).Width > (i2 as VideoEncodingProperties).Width ? i1 : i2);
await captureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);
}
//Évènmenet pour le bouton de prise de photo.
async private void previewpicture_Click(object sender, RoutedEventArgs e)
{
//Si la prévisualisation n'est pas lancée
if (EnPreview == false)
{
//On cache les élèments inutilisés.
tfComment.Visibility = Visibility.Collapsed;
vbImgDisplay.Visibility = Visibility.Collapsed;
//On met la prévisualisation dans le bon sens.
captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
//On charge la prévisualisation dans l'élèment de l'image de la fenêtre.
capturePreview.Source = captureManager;
//On rend la prévisualisation possible.
capturePreview.Visibility = Visibility.Visible;
//Démarre le flux de prévisualisation
await captureManager.StartPreviewAsync();
//On précise que la prévisualisation est lancée.
EnPreview = true;
//On change le label du bouton
previewpicture.Label = "Prendre photo";
}
//Si la prévisualisation est lancée
else if (EnPreview == true)
{
//Créer le fichier de la photo depuis la mémoire interne de l'application
StorageFile photoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myFirstPhoto.jpg", CreationCollisionOption.ReplaceExisting);
//Récupère la photo avec le format d'encodage décidé.
await captureManager.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoFile);
// we can also take a photo to memory stream
InMemoryRandomAccessStream memStream = new InMemoryRandomAccessStream();
await captureManager.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpegXR(), memStream);
//Debug.WriteLine(memStream.ToString());
//Récupère l'image dans un objet image qu'on peut mettre dans le container d'affichage
BitmapImage bitmapToShow = new BitmapImage(new Uri(photoFile.Path));
//Met l'image dans le container d'affichage
imgDisplay.Source = bitmapToShow;
vbImgDisplay.RenderTransform = new RotateTransform() {CenterX = 0.5, CenterY = 0.5, Angle = 90 };
//Cache la previsualisation
capturePreview.Visibility = Visibility.Collapsed;
//Arrête le flux de prévisualisation
await captureManager.StopPreviewAsync();
//rend visible les composants
tfComment.Visibility = Visibility.Visible;
vbImgDisplay.Visibility = Visibility.Visible;
//Converti l'image en tableau de byte
photoByte = await GetByteFromFile(photoFile);
//Précise qu'on est plus en prévisualisation
EnPreview = false;
previewpicture.Label = "Prévisualiser";
}
}
//Converti un storageFile en Byte[]
private async Task<byte[]> GetByteFromFile(StorageFile storageFile)
{
var stream = await storageFile.OpenReadAsync();
using (var dataReader = new DataReader(stream))
{
var bytes = new byte[stream.Size];
await dataReader.LoadAsync((uint)stream.Size);
dataReader.ReadBytes(bytes);
return bytes;
}
}
Thx in advance for your help!
I'd suggest you to use the Lumia (Nokia) Imaging SDK to rotate the image, it's much easier.
You can get them here:
https://www.nuget.org/packages/LumiaImagingSDK/2.0.184
And you can rotate the image like this:
using (var filterEffect = new FilterEffect(source))
{
// Initialize the filter and add the filter to the FilterEffect collection to rotate for 15 degrees
var filter = new RotationFilter(15.0);
filterEffect.Filters = new IFilter[] { filter };
// Create a target where the filtered image will be rendered to
var target = new WriteableBitmap(width, height);
// Create a new renderer which outputs WriteableBitmaps
using (var renderer = new WriteableBitmapRenderer(filterEffect, target))
{
// Render the image with the filter(s)
await renderer.RenderAsync();
// Set the output image to Image control as a source
ImageControl.Source = target;
}
await SaveEffectAsync(filterEffect, "RotationFilter.jpg", outputImageSize);
}
//this method will rotate an image any degree
public static Bitmap RotateImage(Bitmap image, float angle)
{
//create a new empty bitmap to hold rotated image
double radius = Math.Sqrt(Math.Pow(image.Width, 2) + Math.Pow(image.Height, 2));
Bitmap returnBitmap = new Bitmap((int)radius, (int)radius);
//make a graphics object from the empty bitmap
using (Graphics graphic = Graphics.FromImage(returnBitmap))
{
//move rotation point to center of image
graphic.TranslateTransform((float)radius / 2, (float)radius / 2);
//rotate
graphic.RotateTransform(angle);
//move image back
graphic.TranslateTransform(-(float)image.Width / 2, -(float)image.Height / 2);
//draw passed in image onto graphics object
graphic.DrawImage(image, new Point(0, 0));
}
return returnBitmap;
}
Related
I have written a class in C# that opens a website and translates the inputted text. This class uses selenium which I use for the entire project.
I don't use an API because with the website I can translate all characters for free and with the API I've to pay for it. It's a small business so...
What's the problem: most of the time this class works perfectly fine, however when you set a long string as input I get an error message OpenQA.Selenium.WebDriverException: 'target frame detached (Session info: chrome=102.0.5005.63). This happens also when the internet connection is not stable enough (regular Wi-Fi for example). I can't figure out how to program it so that the program waits for the translation. Anyone a solution?
main code
public MainWindow()
{
InitializeComponent();
String[] franseZinnen = { "S’il vous plaît", "Je suis désolé", "Madame/Monsieur/Mademoiselle", "Excusez-moi", "Je ne comprends pas", "Je voudrais...", "Non, pas du tout", "Où sommes-nous?", "Pourriez-vous m’aider?", "Répétez s'il vous plaît.", "Où puis-je trouver un bon restaurant/café/la plage/le centre-ville?", "Je cherche cette adresse.", "J'ai besoin d'une chambre double..", "Je voudrais annuler ma réservation.", "Où est la boutique duty-free?", "Comment puis-je vous aider?", "Je cherche des chaussures.", "C’est combien?", "C’est trop cher!" };
List<String> uitkomsten = new List<string>();
String LangefranseTekst = "Temps ouais merde bière parce que du apéro. Vin vin croissant quelque manger. Quand même passer saucisson meilleur dans fromage quelque parce que.\r\nÀ la camembert boulangerie part omelette meilleur. Grève camembert fromage. Manger fois du coup carrément.\r\nEnée est juste le moyen de décorer l'oreiller de la vie. Duis eu tincidunt orci, de CNN. Tous mes besoins sont grands. Jusqu'à ce qu'il reçoive la messe et que l'urne flatte le laoreet. Proin reçoit beaucoup de rires. Suspendisse feugiat eros id risus vehicula lobortis. Vivamus ullamcorper orci a ligula pulvinar convallis.\r\nManger. Carrément guillotine saucisson épicé un apéro. Croissant boulangerie son du coup du coup moins quand même et paf le chien mais évidemment à révolution. À la du faire voila du coup. Évidemment entre et aussi voila.\r\nBaguette devoir camembert voila se disruptif disruptif et paf le chien se fais chier. Frenchtech se révolution monsieur du coup avec putain. Falloir disruptif grève comme même.\r\nVin omelette épicé. Comme même tout comme même. Peu camembert fromage parce que comme même voir ouais.\r\nDemander vin et aussi saucisson nous putain. De merde voila carrément et paf le chien il y a du coup aussi apéro.\r\nLe client est très important merci, le client sera suivi par le client. Énée n'a pas de justice, pas de résultat, pas de ligula, et la vallée veut la sauce. Morbi mais qui veut vendre une couche de contenu triste d'internet. Être ivre maintenant, mais ne pas être ivre maintenant, mon urne est d'une grande beauté, mais elle n'est pas aussi bien faite que dans un livre. Mécène dans la vallée de l'orc, dans l'élément même. Certaines des exigences faciles du budget, qu'il soit beaucoup de temps pour dignissim et. Je ne m'en fais pas chez moi, ça va être moche dans le vestibule. Mais aussi des protéines de Pour avant la fin de la semaine, qui connaît le poison, le résultat.";
/* // short translations
foreach (var item in franseZinnen)
{
ChromeDriver driver = new ChromeDriver();
String translation = vertalenNu.translateText(new ChromeDriver(), item, "fr", "en");
uitkomsten.Add(translation);
driver.Close();
}*/
// long translation
ChromeDriver driver = new ChromeDriver();
String translation = vertalenNu.translateText(new ChromeDriver(), LangefranseTekst, "fr", "en");
uitkomsten.Add(translation);
driver.Close();
String stringVoorBreakpoint = "";
}
code in class
[Serializable]
public class vertalenNu
{
public static String translateText(IWebDriver driver, String text, String languageSource, String languageDestination)
{
// nl - en - de - fr -es -it
driver.Url = "https://www.vertalen.nu/zinnen/";
driver.FindElement(By.Id("vertaaltxt")).SendKeys(text);
SelectElement testt = new SelectElement(driver.FindElement(By.Id("tselectfrom")));
testt.SelectByValue(languageSource);
SelectElement test = new SelectElement(driver.FindElement(By.Id("tselectto")));
test.SelectByValue(languageDestination);
driver.FindElement(By.XPath("//input[#title='Vertaal']")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(driver => driver.FindElement(By.ClassName("mt-translation-content")).Text != "");
IWebElement technicalSheet = driver.FindElement(By.ClassName("mt-translation-content"));
String technicalSheettext = technicalSheet.Text;
driver.Close();
driver.Quit();
return technicalSheettext;
}
}
You could try this solution:
First create a class that will handle translations
public interface ITranslator : IDisposable
{
void ClearInput();
string Translate(string text);
}
public class Translator : ITranslator
{
private const string Url = "https://www.vertalen.nu/zinnen/";
private const int Timeout = 20;
private By _source = By.Id("vertaaltxt");
private By _destination = By.Id("resulttxt");
private By _submit = By.XPath("//input[#type = 'submit']");
private readonly WebDriverWait _wait;
private readonly IWebDriver _driver;
public Translator()
{
_driver = new ChromeDriver();
_wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(Timeout));
_driver.Navigate().GoToUrl(Url);
}
public string Translate(string text)
{
_driver.FindElement(_source).SendKeys(text);
_driver.FindElement(_submit).Click();
_ = _wait.Until(d => d.FindElement(_destination).Text.Length > 0);
return _driver.FindElement(_destination).Text;
}
public void ClearInput()
{
_wait.Until(d => d.FindElement(_source)).Clear();
}
public void Dispose()
{
_driver.Dispose();
}
}
The next sample focuses on a WinForms solution but you can adjust it to whatever UI app you like:
public partial class MainWindow : Form
{
private readonly ITranslator _translator;
private const int MaxChars = 1500;
private int _currentCharsCount;
public MainWindow()
{
InitializeComponent();
_translator = new Translator();
}
private void translateBtn_Click(object sender, EventArgs e)
{
destinationTextBox.Text = _translator.Translate(sourceTextBox.Text);
_translator.ClearInput();
// or for better user experience use bellow code
// if you decide to use this code don't forget to mark async this method
//await Task.Run(() =>
//{
// destinationTextBox.Text = _translator.Translate(sourceTextBox.Text);
// _translator.ClearInput();
//});
}
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
_translator.Dispose();
}
private void clickBtn_Click(object sender, EventArgs e)
{
sourceTextBox.Clear();
destinationTextBox.Clear();
charsCounter.Text = $"{MaxChars} characters remaining";
}
private void sourceTextBox_TextChanged(object sender, EventArgs e)
{
_currentCharsCount = MaxChars - sourceTextBox.TextLength;
charsCounter.Text = $"{_currentCharsCount} characters remaining";
}
}
I'm trying to save two images in the azure blob, but I can only save one.
follow my example:
In the example I have two fields with an image, the idea is to select an image for each card
enter image description here
But my control is prepared to save only one image, how can I add only two images?
my blob flow:
inside the service folder I have a folder called blob that contains 3 classes ( blob, FileUpload, IBlob )
Image of the blob structure
Class Blob:
namespace Services.Blob
{
public class Blob
{
private static string _connectionAzure = "DefaultEndpointsProtocol=*******";
/// <summary>
/// Uploads de arquivos / blob assíncronos.
/// </summary>
/// <returns>Método que vai efetuar o upload da foto da pessoa no Blob Storage.</returns>
/// <param name="file"></param>
/// <returns></returns>
public static async Task<string> UploadBlobFileAsync(IFormFile file)
{
// Recupera a connection string da variável de ambiente que definimos no appsettings.
var contaStorage = CloudStorageAccount.Parse(_connectionAzure);
string empresa = "tijoforte";
//Variável que representa o endpoint do blob storage account.
var endPointBlob = contaStorage.CreateCloudBlobClient();
//Tenta recuperar o container em que será salvo o blob, se não existir ele cria.
// Regras: O nome do container não deve conter letras maíuscúlas.
var container = endPointBlob.GetContainerReference(empresa); // Nota que aqui vamos passar o nome de cada empresa para criar o contatiner no azure.
await container.CreateIfNotExistsAsync();
//Recupera a referência do endereço do blob e faz o upload do mesmo.
var blockBlob = container.GetBlockBlobReference(file.FileName);
using (var fileStream = file.OpenReadStream())
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
return blockBlob.Uri.ToString();
}
/// <summary>
/// Salva o nome, e-mail e documento específico.
/// </summary>
/// <returns>Método que salva os dados cadastrados nas tabelas do Storage do Azure</return>
/// <param name="nome">Nome</param>
/// <param name="email">E-mail</param>
/// <param name="documentoUrl">Documento.</param>
/// <returns></returns>
public static async Task Salvar(string id, string nome, string documentoUrl, string tabela)
{
//Recupera a connection strung da variável de ambiente que definimos no appsettings
var contaStorage = CloudStorageAccount.Parse(_connectionAzure);
//Cria o client para a tabela.
var tableClient = contaStorage.CreateCloudTableClient();
//Tenta recuperar objeto que representará a tabela, se não existir ela cria.
//O nome da tabela não deve conter letras maíuscúlas.
var table = tableClient.GetTableReference(tabela.ToLower());
await table.CreateIfNotExistsAsync();
//Cria o objeto da entidade.
var retorno = new BlobStorage(id, nome);
retorno.FotoBlob = documentoUrl;
//Efetua a inserção da tabela no azure do CDevs.
var tableOperation = TableOperation.InsertOrReplace(retorno);
await table.ExecuteAsync(tableOperation);
}
}
}
Class FileUpload:
namespace Services.Blob
{
public class FileUpload
{
public string UploadBase64Image(string base64Image, string container)
{
// Gerra um nome randomico para a imagem.
var fileName = Guid.NewGuid().ToString() + ".jpg";
// Limpa o has enviado
var data = new Regex(#"^data:image\/[a-z]+;base64,").Replace(base64Image, "");
// Gera um array de bytes
byte[] imageBytes = Convert.FromBase64String(data);
// Define o blob no qual a imagem será armazenada.
var blobClient = new BlobClient("DefaultEndpointsProtocol=****", container, fileName);
using (var stream = new System.IO.MemoryStream(imageBytes))
{
blobClient.Upload(stream);
}
// retorna a url do blob
return blobClient.Uri.AbsoluteUri;
}
}
}
Interface IBlob
namespace Services.Blob
{
public interface IBlob
{
/// <summary>
/// Criação do métodos de uploads, salvar e listar.
/// </summary>
public interface IBlob
{
Task<string> UploadBlobFileAsync(IFormFile file);
Task Salvar(string nome, string email, string documentoUrl);
Task<List<BlobStorage>> Lista();
}
}
}
After this process, the blob is ready to use.
But it doesn't work if I want it for just two images
Controller WEB:
Web application structure
Controller:
try
{
// tratamento para salvar no blob
if (file != null)
{
//THE PROBLEM IS HERE ONLY SAVES ONE IMAGE
var urlBlob = await Blob.UploadBlobFileAsync(file);
await Blob.Salvar(blog.BlogId.ToString(), blog.Nome, urlBlob, nameof(Blog).ToLower());
blog.ImagemPequena = urlBlob;
}
// Realiza processo de alteração
var retorno = await Blog().Alterar(blogId, blog);
return RedirectToAction("Formulario", new { mensagem = $"Registro alterado com sucesso! {blog.Nome}" });
}
catch (Exception)
{
throw;
}
**
WHAT AM I DOING WRONG?
**
To achieve the above requirement you can find the sample code here in this GitHub , which saves four files together in blob storage , Instead of that you can use two images to be saved in your blob storage as well.
OUTPUT FOR REFERENCE:-
For more information please refer the below links:-
SO THREAD:- How to upload Multiple Files in Blob storage in DotNetCore as suggested by #Gaurav Mantri
BLOG:- Upload Multiple Images In Azure Blob Storage
I'm working on an Xamarin Forms application and I have added some code to select multiple images from the phone gallery, I then need to send all selected images to file steam.
Selecting multiple images from the gallery is working fine, but only the last selected image is being sent.
Below is my code
private async Task OnGetExistingPhotoAsync() {
try {
// Selecting multiple images with the MediaGallery plugin
var results = await MediaGallery.PickAsync(3, MediaFileType.Image);
var parameter = new NavigationParameters();
if (results?.Files == null) {
return;
}
foreach(var photo in results.Files) {
if (photo == null) {
PhotoPath = null;
return;
}
string newFile = Path.Combine(FileSystem.CacheDirectory, photo.NameWithoutExtension);
using(var stream = await photo.OpenReadAsync())
using(var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);
PhotoPath = newFile;
// This here is only sending the PATH of the last selected image from the gallery
parameter.Add("PhotoPath", PhotoPath);
// In my attempt here, I tried to add each image PATH to a list Array
// But this is not working!
/*
List<string> imageFiles = new List<string>();
imageFiles.Add(Path.Combine(FileSystem.CacheDirectory, photo.NameWithoutExtension));
String[] newFile = imageFiles.ToArray();
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile)) // This here says that it cannot convert ( string[] to string )
await stream.CopyToAsync(newStream);
parameter.Add("PhotoPath", PhotoPath);
*/
}
//OUTPUT : The PATH is : /data/user/0/se.company.trret.cyn/cache/IMG_20220307_005342
Console.WriteLine("The PATH is : " + PhotoPath);
await _navigationService.GoBackAsync(parameter);
} catch (FeatureNotSupportedException fnsEx) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Den här funktionen stöds inte av din enhet.", "Ok");
} catch (PermissionException pEx) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Cykelstaden saknar rättigheter för att läsa dina filer.", "Ok");
} catch (Exception e) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Ett oväntat fel inträffade. Var god försök igen.", "Ok");
Crashes.TrackError(e);
}
}
I have a button with open a scan (as a modal). When I scan a QRCode i have a display alert with 2 buttons. When I click on "no" I want to return on my scan and not in my page (listPeoplePage).
So I have a button ScanClicked (when I open the scan)
private async Task BtnScanClicked(object sender, EventArgs e)
{
// Ouverture de la page de scan
scanPage = DependencyService.Get<IScanPage>(); // new ZXingScannerPage();
if (scanPage.scannerPage.IsScanning)
return;
scanPage.scannerPage.IsScanning = true;
if (scanPage.scannerPage.Parent == null)
{
// On affiche la page
await Navigation.PushModalAsync(scanPage.scannerPage); //.PushAsync(scanPage.scannerPage);
}
// Le check des résultats
scanPage.scannerPage.OnScanResult += (result) =>
{
// Pour éviter de le faire tant que le client n'a pas validé
if (scanPage.scannerPage.IsScanning == false)
return;
// On stoppe le scan
scanPage.scannerPage.IsScanning = false;
// On retire la page et on montre le résultat
Device.BeginInvokeOnMainThread(async () =>
{
// On essaye de récupérer le code IdA09 si il existe et on appelle le WS
string paramA09 = getParameterByName(result.Text, "IdA09");
if (!string.IsNullOrEmpty(paramA09))
{
//await DisplayAlert("Scanned barcode", paramA09, "OK");
await SendPresenceAck(paramA09,sender,e); //, this.idPrestation);
}
else
{
// Message d'erreur
await this.DisplayAlert("Attention", "Erreur de la validation d'un invité par QR Code.", "Cancel");
}
await Navigation.PopModalAsync(); //.PopAsync();
});
};
}
And there is a method SendPresenceAck when I have scan a QrCode
private async Task SendPresenceAck(string paramA09, object sender, EventArgs e) //, int? idPrestation)
{
int idParticipant;
if (!int.TryParse(paramA09, out idParticipant))
{
//await this.ShowAlert("Attention", "Problème de lecture du QR Code.");
await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
return;
}
// On appelle le WS pour signifier la présence
// On passe par validateService
// On prépare la validation de la présence
var validateService = new ValidatePresenceService(this.Token);
// On ajoute la ligne à valider
var validate = validateService.AddNewPresence(idParticipant, this.idPrestation, true);
// On déclenche l'envoi au WS (si besoin)
if (validate != null)
{
// On envoie uniquement en cas de connexion
if (!Global.GetSettingsBool(TypeSettings.IsHorsConnexion))
{
//await validateService.SendAll();
// Attention : si participant déjà enregistré : erreur 403
try
{
await validateService.Send(await validate);
await this.DisplayAlert("OK", "Le billet est validé.", "OK");
}
catch (WebException ex)
{
HttpWebResponse objresponse = ex.Response as HttpWebResponse;
if (objresponse.StatusCode == HttpStatusCode.Forbidden)
{
// 403 : le participant a déjà été enregistré aujourd'hui
// Message d'erreur
await this.DisplayAlert("Attention", "Le billet a déjà été enregistré, le numéro du billet a déjà été scanné auparavant.", "Yes", "No");
return;
}
else if (objresponse.StatusCode == HttpStatusCode.NotFound)
{
// 404 : billet non valide
var alert = await this.DisplayAlert("Attention", "Le billet n'est pas valide.", "Yes","No");
if (alert==true)
return;
else
{
}
}
else if (objresponse.StatusCode == HttpStatusCode.Unauthorized)
{
// 401 : impossible d'identifier le numéro du billet
var alert = await this.DisplayAlert("Attention", "Impossible d'identifier le numéro du billet, veuillez vérifier les informations de celui ci.", "Yes", "No");
if (alert==true)
return;
else
{
Debug.WriteLine(alert);
}
}
}
catch (Exception exception)
{
// Erreur
await this.DisplayAlert("Attention", exception.Message, "Yes", "No");
return;
}
}
else
{
// Hors connexion : on vérifie juste si l'utilisateur n'est pas déjà présent dans la table SQL
// Attention : si pas de prestation : on a le droit d'enregistrer plusieurs fois la présence
// Si il y a une prestation, en revanche, on doit vérifier qu'il n'est pas déjà inscrit
if (validate.Result.IdPrestation.HasValue &&
validateService.IsInscriptionAlreadyRecorded(await validate))
{
// Déjà trouvé : message d'erreur
await this.DisplayAlert("Attention", "Le participant a déjà été enregistré.", "Yes", "No");
return;
}
}
}
else
{
// Pb à l'insertion des données ??
}
//return;
await BtnScanClicked(sender, e);
}
So I want, on my scan to click on a button to return on a scan for scan an other QrCode. A sort of a button "do you want scan an other time?"
Edit: For the moment the only important message is `"await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
In English ("Alert", Problem to read QR Code." "Yes", "No");
I try to call again at the end of the SendPresenceAck function but it doesn't work.
For the moment if you answer "yes" or "no" it do nothing. I want to return on scan if you answer "yes" and return to the page if you answer "no".
Might need to see more code, but you are always popping your scanner page at the end of the OnScanResult by calling:
await Navigation.PopModalAsync();
at the end of the OnScanResult method, so no matter what you do in SendPresenceAck when you return from that method, you are popping the modal scanner page.
The non-english (french?) text makes it hard for me to know which alert is asking if the user wants to scan another code, but regardless no matter what they respond, the page will be popped.
Oh, wait, it looks like you have some recursion going on? i.e. BtnScanClicked calls SendPresenceAck and SendPresenceAck calls BtnScanClicked at the end... I'd have to dig though all of your logic to see if this may be an issue, but again that is hard because of the non-english language makes it hard for me to follow code flow after user responses to the multiple alerts.
I am using httpclient to get data from an Api Rest through Xamarin. My problem happens when I'm going to run httpclient again on a new page to get back the api information, that is, this works only once, how do I solve it?
Code:
private async void ObterNoticiasXbox()
{
var respXbox = string.Empty;
try
{
var uriXbox = new HttpClient()
{
BaseAddress = new Uri("http://api.newsplay.com.br")
};
var urlXbox = "/post/";
var resultXbox = await uriXbox.GetAsync(urlXbox);
if (!resultXbox.IsSuccessStatusCode)
{
await DisplayAlert("Erro de Conexão", "Não foi possível obter as notícias do servidor, Tente novamente mais tarde!", "OK");
return;
}
respXbox = await resultXbox.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
await DisplayAlert("Erro de Conexão com o Servidor", ex.Message, "OK");
return;
}
// transformando o retorno em objeto através do json e deserealize e retornando em lista
var NXbox = JsonConvert.DeserializeObject<List<XboxModels>>(respXbox);
//Adicionando os itens ao ListView na Home.xaml
XboxList.ItemsSource = NXbox;
}
}