Records grouped in a Matrix SDK C# [closed] - c#

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 9 days ago.
Improve this question
Estoy realizando una matrix que haga lo siguiente (Adjunto imagen), tener la funcion de esa flecha negra al darle clic todos los sub datos se ocultan.
https://i.stack.imgur.com/dbu7r.png
/*CODIGO */
`
``private void addItem()
{
try
{
/EJECUTAR EL PROCEDIMIENTO ALMACENADO/
SAPbouiCOM.DataTable exp;
exp = oForm.DataSources.DataTables.Item("Execute_DT");
string Query = string.Format("select 'Y' as "Column1",'Y'as "Column2",T0."Location" as "Codigo de la localidad", " +
"T1."Location" as "Localidad",T0."WhsCode" as "Código de almacén", " +
"T0."WhsName" as "Nombre del almacén", '' AS "header" " +
"FROM "OWHS" T0 "+
"INNER JOIN "OLCT" T1 "+
"ON T1."Code" = T0."Location" ");
exp.ExecuteQuery(Query);
/FIN DE EJECUCION DE PROCEDIMIENTO ALMACENADO/
SAPbouiCOM.DataTable udt = oForm.GetDataTable("DB_Arbol");
oMatrix = oForm.GetMatrix("38");
SAPbouiCOM.Columns oColumns;
oColumns = oMatrix.Columns;
SAPbouiCOM.Column oColumn;
var colItems = udt.Columns;
if (udt.Columns.Count == 0)
{
colItems.Add("Column1", BoFieldsType.ft_AlphaNumeric);
colItems.Add("Column2", BoFieldsType.ft_AlphaNumeric);
colItems.Add("Codigo de la localidad", BoFieldsType.ft_AlphaNumeric);
colItems.Add("Localidad", BoFieldsType.ft_AlphaNumeric);
colItems.Add("Código de almacén", BoFieldsType.ft_AlphaNumeric);
colItems.Add("Nombre del almacén", BoFieldsType.ft_AlphaNumeric);
colItems.Add("header", BoFieldsType.ft_AlphaNumeric);
}
int a = udt.Rows.Count;
if (oMatrix.RowCount > 0)
a = udt.Rows.Count;
for (int oRow = 0; oRow < exp.Rows.Count; oRow++)
{
udt.Rows.Add();
udt.SetValue("Column1", oRow, exp.GetString("Column1", oRow));
udt.SetValue("Column2", oRow, exp.GetString("Column2", oRow));
udt.SetValue("Codigo de la localidad", oRow, exp.GetString("Codigo de la localidad", oRow));
udt.SetValue("Localidad", oRow, exp.GetString("Localidad", oRow));
udt.SetValue("Código de almacén", oRow, exp.GetString("Código de almacén", oRow));
udt.SetValue("Nombre del almacén", oRow, exp.GetString("Nombre del almacén", oRow));
udt.SetValue("header", oRow, exp.GetString("header", oRow));
}
oMatrix.Columns.Item("1").DataBind.Bind("DB_Arbol", "Column1");
oMatrix.Columns.Item("2").DataBind.Bind("DB_Arbol", "Column2");
oMatrix.Columns.Item("3").DataBind.Bind("DB_Arbol", "Codigo de la localidad");
oMatrix.Columns.Item("4").DataBind.Bind("DB_Arbol", "Localidad");
oMatrix.Columns.Item("5").DataBind.Bind("DB_Arbol", "Código de almacén");
oMatrix.Columns.Item("6").DataBind.Bind("DB_Arbol", "Nombre del almacén");
oMatrix.Columns.Item("7").DataBind.Bind("DB_Arbol", "header");
oColumn = oColumns.Item("1");
oMatrix.LoadFromDataSource();
oMatrix.AutoResizeColumns();
}
catch (Exception)
{
throw;
}
}`
`
Al ejecutar tengo el siguiente Resultado. (Adjunto Imagen), agradeceria mucho su ayuda
enter image description here
Gracias.

Related

Selenium translate class not working correctly c#

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";
}
}

Return ScanPage Xamarin

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.

Json.Net doesn't work in Xamarin [duplicate]

This question already has answers here:
Newtonsoft.Json deserialize object in Xamarin iOS project
(6 answers)
Closed 4 years ago.
I have this code in a Xamarin type solution
public async Task<Response> GetList<Publication>(string urlBase, string servicePrefix, string controller)
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return new Response
{
IsSuccess = false,
Message = result,
};
}
var list = JsonConvert.DeserializeObject<List<Publication>>(result);
return new Response
{
IsSuccess = true,
Message = "Ok",
Result = list,
};
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
};
}
}
when I debug it, JsonConvert.DeserializeObject<List<Publication>>(result); doesn't work, return null...
DEBUG IN XAMARIN
I'm sure result is not null
But if I run the same code in a console type solution, It Works!!!
I'm using the same class, there is my Publication class
public class Publication
{
public int IdPublicacion { get; set; }
public string UrlVideo { get; set; }
public object UrlImagen { get; set; }
public string Text { get; set; }
public string Titulo { get; set; }
public DateTime Fecha { get; set; }
public string Sacerdote { get; set; }
}
And there is my Json Code
[
{
"IdPublicacion": 1,
"UrlVideo": "https://www.youtube.com/watch?v=mQR0bXO_yI8",
"UrlImagen": null,
"Text": "Para fomentar la lectura en los niños es recomendable empezar con cuentos infantiles cortos que traten de aventuras divertidas y que capten la atención de los niños. De esta forma, los niños se divertirán a la vez que empiezan a cogerle el gusto a la lectura.\r\n \r\nLos relatos cortos con son los mejores para empezar a leer con los niños. Aunque hay multitud de cuentos tradicionales que son esenciales y que todo niño debería conocer, ya que han ido pasando de generación en generación.\r\n\r\nEn pequelandia.org se han seleccionado una serie de cuentos infantiles cortos para leer con niños. Son relatos cortos para hacer de la lectura un momento agradable y divertido, de forma que los niños empiecen a familiarizarse con la lectura y los libros.",
"Titulo": "Fly me to the moon",
"Fecha": "2018-03-07T00:00:00",
"Sacerdote": "Julian"
},
{
"IdPublicacion": 2,
"UrlVideo": "https://www.youtube.com/watch?v=mQR0bXO_yI8",
"UrlImagen": null,
"Text": "Para fomentar la lectura en los niños es recomendable empezar con cuentos infantiles cortos que traten de aventuras divertidas y que capten la atención de los niños. De esta forma, los niños se divertirán a la vez que empiezan a cogerle el gusto a la lectura.\r\n \r\nLos relatos cortos con son los mejores para empezar a leer con los niños. Aunque hay multitud de cuentos tradicionales que son esenciales y que todo niño debería conocer, ya que han ido pasando de generación en generación.",
"Titulo": "Titulo 2",
"Fecha": "2018-03-06T00:00:00",
"Sacerdote": "Julian"
}]
Additional information, when I see the List, show a message
"Unable to cast object of type 'System.RuntimeType' to type 'Mono.Debugger.Soft.TypeMirror'."
Finally there is my GitHub project https://github.com/solartes/VesApp
SOLVED.
THE PROBLEM? JSON.NET has problem with the Xamarin Live Player, so it doesn't works if you play it in Xamarin Live Player, you have to run it in Android Simulator.
Try to add Preserve attribute to the Publication class:
[Preserve(AllMembers = true)]
public class Publication
It might happen that the build strips out the properties of the class and hence they are missing and cannot be deserialized.
I realized that in your Debug you did not specify the type that you want to deserialize your json to List< T >. However, in your test that worked, you did specify that you need a list of Publications back "List< Publication >" .

Convert C# soap client to PHP (issues in casting complex types)

Good day all. I'm creating a PHP SOAP client using a C# as a reference and example (this is the only documentation I recieved).
actually I've got some problems with this C# code (I don't know C# at all):
SI = SessionID.SessionId.ToString();
My_Arx_Search.ARX_SearchSoapClient arx_Search = new My_Arx_Search.ARX_SearchSoapClient();
//Estrazione della Dm_Profile_Search data il codice della classe documentale
var search = arx_Search.Dm_Profile_Search_Get_New_Instance_By_TipiDocumentoCodice(SI, "MEDICINA.REFERTO");
//imposto i parametri AOO
search.Aoo.Operatore = My_Arx_Search.Dm_Base_Search_Operatore_String.Uguale;
search.Aoo.Valore = "001"; //001 (che sta per sant andrea)
// imposto il filtro campo aggiuntivo
var aggSearch = (from x in search.Aggiuntivi where x.ExternalId == "codicefiscale" select x).FirstOrDefault();
if (aggSearch == null) throw new Exception(string.Format("Impossibile trovare il campo aggiuntivo con externalId= '{0}' (Search)", "codicefiscale"));
//Per Esempio: imposto il filtro sapendo che il campo aggiuntivo è string
My_Arx_Search.Field_String campo = ((My_Arx_Search.Field_String)aggSearch); //that's a php cast (int)$foo;
campo.Operatore = My_Arx_Search.Dm_Base_Search_Operatore_String.Uguale;
campo.Valore = "DFLMHLD15GGFD...";
Actually I've translate in PHP this part:
$resSearch = $cSearch->Dm_Profile_Search_Get_New_Instance_By_TipiDocumentoCodice(array('sessionId' => $sesId, 'DmTipiDocumentoCodice' => "MEDICINA.REFERTO"));
if (is_soap_fault($resSearch)) {
echo "must login again<br>";
}
$resSearch->Aoo->Operatore ="Uguale";
$resSearch->Aoo->Valore ="001";
but honestly, I feel I'm loosing something.
is there a method or something that could help me translating this client?
These are the lines I really can't convert:
// imposto il filtro campo aggiuntivo
var aggSearch = (from x in search.Aggiuntivi where x.ExternalId == "codicefiscale" select x).FirstOrDefault();
if (aggSearch == null) throw new Exception(string.Format("Impossibile trovare il campo aggiuntivo con externalId= '{0}' (Search)", "codicefiscale"));
//Per Esempio: imposto il filtro sapendo che il campo aggiuntivo è string
My_Arx_Search.Field_String campo = ((My_Arx_Search.Field_String)aggSearch); //that's a php cast (int)$foo;
campo.Operatore = My_Arx_Search.Dm_Base_Search_Operatore_String.Uguale;
campo.Valore = "DFLMHLD15GGFD...";
Try something like this:
$aggSearch = '';
foreach ($row as $resSearch->Aggiuntivi) {
if ($row->ExternalId == 'codicefiscale') {
$aggSearch = $row;
break;
}
}
if (empty($aggSearch)) {
throw new \Exception(sprintf("Impossibile trovare il campo aggiuntivo con externalId= '%s' (Search)", 'codicefiscale' ));
}

Rotate a BitmapImage in c#

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;
}

Categories

Resources