I have a button for sending e-mails, it uses some variables from the app like RadioGroups and a EditText field.
I want to send on the email body the radiobuttons on the first paragraph and the EditText comment on the second paragraph.
My question is: how can I separate them to automatically the buttons go on the first paragrah and the EditText variable that is nammed as comentario goes on the second paragraph, just like if the user "clicked on the enter button"
Should I use something like   if so, how do I do it?
void enviar_Click(object sender, EventArgs e)
{
try
{
RadioButton rdbgrupo1 = FindViewById<RadioButton>(rdgconquiste.CheckedRadioButtonId);
RadioButton rdbgrupo2 = FindViewById<RadioButton>(rdgcrie.CheckedRadioButtonId);
RadioButton rdbgrupo3 = FindViewById<RadioButton>(rdgviva.CheckedRadioButtonId);
RadioButton rdbgrupo4 = FindViewById<RadioButton>(rdgentregue.CheckedRadioButtonId);
int RadioGroupIsChecked(RadioGroup radioGroup)
{
//-1 means empty selection
return radioGroup.CheckedRadioButtonId;
}
//When user doesn't check a radio button, show a Toast
if (RadioGroupIsChecked(rdgconquiste) == -1 || RadioGroupIsChecked(rdgcrie) == -1 || RadioGroupIsChecked(rdgviva) == -1 || RadioGroupIsChecked(rdgentregue) == -1)
{
string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido";
Toast.MakeText(this, excecao, ToastLength.Long).Show();
}
else
{
String emailescolhido = spinner.SelectedItem.ToString();
String campocomentario = comentário.Text;
var email = new Intent(Android.Content.Intent.ActionSend);
//send to
email.PutExtra(Android.Content.Intent.ExtraEmail,
new string[] { "" + emailescolhido });
//cc to
email.PutExtra(Android.Content.Intent.ExtraCc,
new string[] { "" });
//subject
email.PutExtra(Android.Content.Intent.ExtraSubject, "SABIA QUE VOCÊ FOI RECONHECIDO?");
//content
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text + " " + campocomentario);
email.SetType("message/rfc822");
StartActivity(email);
Android.App.AlertDialog.Builder alertdialog = new Android.App.AlertDialog.Builder(this);
alertdialog.SetTitle("Confirmação de envio");
alertdialog.SetMessage("Email enviado com sucesso");
alertdialog.SetNeutralButton("Ok", delegate {
alertdialog.Dispose();
});
alertdialog.Show();
}
}
catch (Java.Lang.Exception ex)
{
showbox(ex.Message);
} } }
I did it by using System.Environment.NewLine
void enviar_Click(object sender, EventArgs e)
{
try
{
RadioButton rdbgrupo1 = FindViewById<RadioButton>(rdgconquiste.CheckedRadioButtonId);
RadioButton rdbgrupo2 = FindViewById<RadioButton>(rdgcrie.CheckedRadioButtonId);
RadioButton rdbgrupo3 = FindViewById<RadioButton>(rdgviva.CheckedRadioButtonId);
RadioButton rdbgrupo4 = FindViewById<RadioButton>(rdgentregue.CheckedRadioButtonId);
int RadioGroupIsChecked(RadioGroup radioGroup)
{
//-1 means empty selection
return radioGroup.CheckedRadioButtonId;
}
//When user doesn't check a radio button, show a Toast
if (RadioGroupIsChecked(rdgconquiste) == -1 || RadioGroupIsChecked(rdgcrie) == -1 || RadioGroupIsChecked(rdgviva) == -1 || RadioGroupIsChecked(rdgentregue) == -1)
{
string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido";
Toast.MakeText(this, excecao, ToastLength.Long).Show();
}
else
{
String emailescolhido = spinner.SelectedItem.ToString();
if (emailescolhido == "Escolha um colaborador abaixo")
{
string excecao = "Por favor, escolha um colaborador";
Toast.MakeText(this, excecao, ToastLength.Long).Show();
}
else {
String campocomentario = comentário.Text;
var email = new Intent(Android.Content.Intent.ActionSend);
//send to
email.PutExtra(Android.Content.Intent.ExtraEmail,
new string[] { "" + emailescolhido });
//cc to
email.PutExtra(Android.Content.Intent.ExtraCc,
new string[] { "" });
//subject
email.PutExtra(Android.Content.Intent.ExtraSubject, "SABIA QUE VOCÊ FOI RECONHECIDO?");
//content
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
email.SetType("message/rfc822");
StartActivity(email);
Android.App.AlertDialog.Builder alertdialog = new Android.App.AlertDialog.Builder(this);
alertdialog.SetTitle("Confirmação de envio");
alertdialog.SetMessage("Email enviado com sucesso");
alertdialog.SetNeutralButton("Ok", delegate {
alertdialog.Dispose();
});
alertdialog.Show();
}
}
}
catch (Java.Lang.Exception ex)
{
showbox(ex.Message);
} } }
Related
I am using Microsoft.Office.Interop.Outlook and I am trying to loop trough all the appointments that match a particular set of conditions:
To reduce the items I limit the search between two knows maximum dates
It has to contain an "ID"
Beside the additional regex that I don't know if it can be fitted in the .Restrict, the foreach loop interrupts at the first entry
DateTime start = DateTime.Now.AddDays(-1);
string filter1 = "[Start] >= '" + start.ToString("g") + "' AND [End] <= '" + DateTime.MaxValue.ToString("g") + "'";
Outlook.Items calendarItems = personalCalendar.Items.Restrict(filter1);
calendarItems.IncludeRecurrences = true;
calendarItems.Sort("[Start]", Type.Missing);
string filter3 = "#SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " LIKE '%" + AppCode + "%'";
Outlook.Items restrictedItems = calendarItems.Restrict(filter3);
bool error_free = true;
foreach (Outlook.AppointmentItem apptItem in restrictedItems)
{
MessageBox.Show(apptItem.Subject);
try
{
if (Regex.IsMatch(apptItem.Subject, #"^.*##ManaOrdini\d{1,}##.*$"))
{
apptItem.Move(newCalendarFolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show("Si è verificato un errore durante la creazione dell'appuntamento. Errore: " + ex.Message);
error_free = false;
}
}
Can anybody explain me why? Do I have to add a goto method to iterate untill no entry found?
EDIT
The variable restrictedItems contains the following entries:
Subject "Reminder Ordine Numero:1\t##ManaOrdini1#" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini##" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini1222##" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini1##" System.String
EDIT 2
Ended up with this, basically I had to split in two parts:
Clone the results of the filters
Loop and move
DateTime start = DateTime.Now.AddDays( - 2);
string filter1 = "[Start] >= '" + start.ToString("g") + "' AND [End] <= '" + DateTime.MaxValue.ToString("g") + "'";
Outlook.Items calendarItems = personalCalendar.Items.Restrict(filter1);
calendarItems.IncludeRecurrences = true;
calendarItems.Sort("[Start]", Type.Missing);
string filter3 = "#SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " LIKE '%" + AppCode + "%'";
Outlook.Items restrictedItems = calendarItems.Restrict(filter3);
bool error_free = true;
int c = 0;
List < Outlook.AppointmentItem > listaApp = new List < Outlook.AppointmentItem > ();
foreach(Outlook.AppointmentItem apptItem in restrictedItems) {
if (Regex.IsMatch(apptItem.Subject, #"^.*##ManaOrdini\d{1,}##.*$")) {
listaApp.Add(apptItem);
c++;
}
}
for (int i = 0; i < c; i++) {
try {
listaApp[i].Move(newCalendarFolder);
}
catch(System.Exception ex) {
MessageBox.Show("Si è verificato un errore durante la creazione dell'appuntamento. Errore: " + ex.Message);
error_free = false;
}
}
Hi I'm doing an applicative and it has an Send E-mail button.
So on that button I want to send some variables that will recieve the value of some RadioGroups.
I did some "If/ElseIf" to allow the user to pick just one RadioGroup and then to send an email (so far so good) to the person that will be in a spinner.
But when I try to choose 2 RadioGroups or more when I click on the "Send E-mail Button" Idk why, the program just pass the value of the last clicked button and don't pass all values that I selected like the following imagesEmail Screen
So how can I send 2 or more variables on the e-mail
Here is the code
using Android.App;
using Android.Content.PM;
using Android.Content.Res;
using Android.OS;
using Android.Support.V4.Widget;
using Android.Views;
using Android.Widget;
using System.Collections;
using Android.Support.V7.App;
using Android.Support.V4.View;
using Android.Support.Design.Widget;
using Auth0.OidcClient;
using Android.Content;
using IdentityModel.OidcClient;
using Android.Graphics;
using System.Net;
using System;
using Android.Runtime;
using Android.Text.Method;
using System.Text;
using System.Threading;
using System.Collections.Generic;
namespace whirlpoolgratitudeapp
{
[Activity(Label = "whirlpoolgratitudeapp", MainLauncher = true, Icon = "#drawable/icon")]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataScheme = "whirlpoolgratitudeapp.whirlpoolgratitudeapp",
DataHost = "lucasmsantos.auth0.com",
DataPathPrefix = "/android/whirlpoolgratitudeapp.whirlpoolgratitudeapp/callback")]
public class MainActivity : Activity
{
private ArrayList enderecos;
TextView queroreconhecer;
TextView crie;
TextView conquiste;
TextView entregue;
TextView viva;
TextView comentar;
EditText comentário;
Spinner spinner;
ArrayAdapter adapter;
RadioGroup rdgcrie;
RadioGroup rdgconquiste;
RadioGroup rdgentregue;
RadioGroup rdgviva;
Button enviar;
private Auth0Client client;
private AuthorizeState authorizeState;
ProgressDialog progress;
List<RadioGroup> lista = new List<RadioGroup>();
protected override void OnResume()
{
base.OnResume();
if (progress != null)
{
progress.Dismiss();
progress.Dispose();
progress = null;
}
}
protected override async void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
var loginResult = await client.ProcessResponseAsync(intent.DataString, authorizeState);
var sb = new StringBuilder();
if (loginResult.IsError)
{
sb.AppendLine($"An error occurred during login: {loginResult.Error}");
}
else
{
sb.AppendLine($"ID Token: {loginResult.IdentityToken}");
sb.AppendLine($"Access Token: {loginResult.AccessToken}");
sb.AppendLine($"Refresh Token: {loginResult.RefreshToken}");
sb.AppendLine();
sb.AppendLine("-- Claims --");
foreach (var claim in loginResult.User.Claims)
{
sb.AppendLine($"{claim.Type} = {claim.Value}");
}
}
}
private async void LoginButtonOnClick(object sender, EventArgs eventArgs)
{
progress = new ProgressDialog(this);
progress.SetTitle("Log In");
progress.SetMessage("Please wait while redirecting to login screen...");
progress.SetCancelable(false); // disable dismiss by tapping outside of the dialog
progress.Show();
// Prepare for the login
authorizeState = await client.PrepareLoginAsync();
// Send the user off to the authorization endpoint
var uri = Android.Net.Uri.Parse(authorizeState.StartUrl);
var intent = new Intent(Intent.ActionView, uri);
intent.AddFlags(ActivityFlags.NoHistory);
StartActivity(intent);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
client = new Auth0Client(new Auth0ClientOptions
{
Domain = Resources.GetString(Resource.String.auth0_domain),
ClientId = Resources.GetString(Resource.String.auth0_client_id),
Activity = this
});
//preenche o arraylist com os dados
GetEmails();
//cria a instância do spinner declarado no arquivo Main
spinner = FindViewById<Spinner>(Resource.Id.spnDados);
//cria textview
queroreconhecer = FindViewById<TextView>(Resource.Id.txtReconhecer);
crie = FindViewById<TextView>(Resource.Id.txtCrie);
conquiste = FindViewById<TextView>(Resource.Id.txtConquiste);
entregue = FindViewById<TextView>(Resource.Id.txtEntregue);
viva = FindViewById<TextView>(Resource.Id.txtViva);
comentar = FindViewById<TextView>(Resource.Id.txtComentário);
comentário = FindViewById<EditText>(Resource.Id.edtComentario);
rdgcrie = FindViewById<RadioGroup>(Resource.Id.rdgCrie);
rdgconquiste = FindViewById<RadioGroup>(Resource.Id.rdgConquiste);
rdgentregue = FindViewById<RadioGroup>(Resource.Id.rdgEntregue);
rdgviva = FindViewById<RadioGroup>(Resource.Id.rdgViva);
adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, enderecos);
spinner.Adapter = adapter;
spinner.ItemSelected += Spinner_ItemSelected;
enviar = FindViewById<Button>(Resource.Id.button1);
enviar.Click += enviar_Click;
lista.Add(rdgconquiste);
lista.Add(rdgcrie);
lista.Add(rdgentregue);
lista.Add(rdgviva);
void GetEmails()
{
enderecos = new ArrayList();
enderecos.Add("Escolha um colaborador");
enderecos.Add("alexandre_bonfim#whirlpool.com");
enderecos.Add("alexandre_t_pires#whirlpool.com");
enderecos.Add("ana_carolina_simoes #whirlpool.com");
enderecos.Add("ana_claudia_s_belarmino#whirlpool.com");
enderecos.Add("andre_costa#whirlpool.com");
enderecos.Add("andre_l_teixeira#whirlpool.com");
enderecos.Add("andreza_a_valle#whirlpool.com");
enderecos.Add("anna_carolina_b_ferreira#whirlpool.com");
enderecos.Add("bruno_b_souza#whirlpool.com");
enderecos.Add("bruno_c_castanho#whirlpool.com");
enderecos.Add("bruno_s_lombardero#whirlpool.com");
enderecos.Add("caio_c_sacoman#whirlpool.com");
enderecos.Add("carla_sedin#whirlpool.com");
enderecos.Add("cassia_r_nascimento#whirlpool.com");
enderecos.Add("celia_r_araujo#whirlpool.com");
enderecos.Add("cesar_leandro_de_oliveira#whirlpool.com");
enderecos.Add("daniel_b_szortyka#whirlpool.com");
enderecos.Add("denis_caciatori#whirlpool.com");
enderecos.Add("elisabete_c_ferreira#whirlpool.com");
enderecos.Add("erick_c_senzaki#whirlpool.com");
enderecos.Add("erika_g_souza#whirlpool.com");
enderecos.Add("fabiana_monteiro#whirlpool.com");
enderecos.Add("fernando_v_santos#whirlpool.com");
enderecos.Add("gabriel_roveda#whirlpool.com");
enderecos.Add("herivelto_alves_jr#whirlpool.com");
enderecos.Add("jefferson_s_pecanha#whirlpool.com");
enderecos.Add("josiane_a_teles#whirlpool.com");
enderecos.Add("juliana_g_saito#whirlpool.com");
enderecos.Add("juliano_ventola#whirlpool.com");
enderecos.Add("leonardo_l_costa#whirlpool.com");
enderecos.Add("leonardo_r_silva#whirlpool.com");
enderecos.Add("lucas_m_santos#whirlpool.com");
enderecos.Add("luiz_perea#whirlpool.com");
enderecos.Add("norma_raphaeli#whirlpool.com");
enderecos.Add("patricia_f_prates#whirlpool.com");
enderecos.Add("priscila_l_dattilo#whirlpool.com");
enderecos.Add("priscila_m_konte#whirlpool.com");
enderecos.Add("reider_a_bernucio#whirlpool.com");
enderecos.Add("renato_occhiuto#whirlpool.com");
enderecos.Add("ricardo_a_fernandes#whirlpool.com");
enderecos.Add("ricardo_matos_campaneruti #whirlpool.com");
enderecos.Add("rogerio_pagotto#whirlpool.com");
enderecos.Add("ruben_c_anacleto#whirlpool.com");
enderecos.Add("taise_azevedo#whirlpool.com");
enderecos.Add("vinicius_marques_assis#whirlpool.com");
enderecos.Add("wanderly_t_limeira#whirlpool.com");
}// fim getEmails
void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
string toast = string.Format("Colaborador selecionado: {0}", spinner.GetItemAtPosition(e.Position));
string welcome = "Bem vindo ao aplicativo de agradecimento";
if (toast.Equals("Escolha um colaborador") )
{
Toast.MakeText(this, welcome, ToastLength.Long).Show();
}
else {
Toast.MakeText(this, toast, ToastLength.Long).Show();
}
}
void showbox(string msg)
{
var progressDialog = ProgressDialog.Show(this, "Mensagem", msg, true);
new System.Threading.Thread(new ThreadStart(delegate
{
//LOAD METHOD TO GET ACCOUNT INFO
RunOnUiThread(() => Toast.MakeText(this, msg, ToastLength.Long).Show());
//HIDE PROGRESS DIALOG
RunOnUiThread(() => progressDialog.Dismiss());
RunOnUiThread(() => progressDialog.Hide());
})).Start();
}
void enviar_Click(object sender, EventArgs e)
{
try
{
RadioButton rdbgrupo1 = FindViewById<RadioButton>(rdgconquiste.CheckedRadioButtonId);
RadioButton rdbgrupo2 = FindViewById<RadioButton>(rdgcrie.CheckedRadioButtonId);
RadioButton rdbgrupo3 = FindViewById<RadioButton>(rdgviva.CheckedRadioButtonId);
RadioButton rdbgrupo4 = FindViewById<RadioButton>(rdgentregue.CheckedRadioButtonId);
int RadioGroupIsChecked(RadioGroup radioGroup)
{
//-1 means empty selection
return radioGroup.CheckedRadioButtonId;
}
//When user doesn't check a radio button, show a Toast
if (RadioGroupIsChecked(rdgconquiste) == -1 & RadioGroupIsChecked(rdgcrie) == -1 & RadioGroupIsChecked(rdgviva) == -1 & RadioGroupIsChecked(rdgentregue) == -1)
{
string excecao = "Ao menos um botão deve ser selecionado e o comentário deve ser preenchido";
Toast.MakeText(this, excecao, ToastLength.Long).Show();
}
else
{
String emailescolhido = spinner.SelectedItem.ToString();
if (emailescolhido == "Escolha um colaborador abaixo")
{
string excecao = "Por favor, escolha um colaborador";
Toast.MakeText(this, excecao, ToastLength.Long).Show();
}
else {
String campocomentario = comentário.Text;
string emailchefe = "acursio_maia#whirlpool.com";
var email = new Intent(Android.Content.Intent.ActionSend);
//send to
email.PutExtra(Android.Content.Intent.ExtraEmail,
new string[] { "" + emailescolhido });
//if (emailescolhido == "andreza_a_valle" || emailescolhido.Equals("lucas_m_santos") || emailescolhido == "erika_g_souza#whirlpool.com" || emailescolhido == "caio_c_sacoman")
//{
// //cc to
// email.PutExtra(Android.Content.Intent.ExtraCc,
// new string[] { "comite_clima_ti#whirlpool.com" + emailchefe });
//}
//cc to
email.PutExtra(Android.Content.Intent.ExtraCc,
new string[] { "comite_clima_ti#whirlpool.com" + emailchefe });
//subject
email.PutExtra(Android.Content.Intent.ExtraSubject, "SABIA QUE VOCÊ FOI RECONHECIDO?");
//content
if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgviva) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgcrie) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo2.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgviva) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo3.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgcrie) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgviva) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo2.Text + " , " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgviva) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo3.Text + " , " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgviva) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " +rdbgrupo1.Text + " , " + rdbgrupo2.Text + " e " + rdbgrupo3.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " e " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgconquiste) != -1 & RadioGroupIsChecked(rdgviva) != -1 & RadioGroupIsChecked(rdgviva) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo3.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
else if (RadioGroupIsChecked(rdgcrie) != -1 & RadioGroupIsChecked(rdgviva) != -1 & RadioGroupIsChecked(rdgentregue) != -1)
{
email.PutExtra(Android.Content.Intent.ExtraText,
"Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text + "" + System.Environment.NewLine + "" + System.Environment.NewLine + campocomentario + System.Environment.NewLine);
}
email.SetType("message/rfc822");
StartActivity(email);
Android.App.AlertDialog.Builder alertdialog = new Android.App.AlertDialog.Builder(this);
alertdialog.SetTitle("Confirmação de envio");
alertdialog.SetMessage("Email enviado com sucesso");
alertdialog.SetNeutralButton("Ok", delegate {
alertdialog.Dispose();
});
alertdialog.Show();
}
}
}
catch (Java.Lang.Exception ex)
{
showbox(ex.Message);
} } }
}
}
Based on your code, I think you tried to use a click event of Button to get checked RadioButton of each RadioGroup, then for example if the layout is like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/group1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="This is group 1" />
<RadioButton
android:id="#+id/radio11"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="radio1" />
<RadioButton
android:id="#+id/radio12"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="radio2" />
</RadioGroup>
<RadioGroup
android:id="#+id/group2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="This is group 2" />
<RadioButton
android:id="#+id/radio21"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="radio3" />
<RadioButton
android:id="#+id/radio22"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="radio4" />
</RadioGroup>
<Button
android:id="#+id/checkBtn"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="get checked radiobutton" />
</LinearLayout>
You can code like this:
private string result;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.layout1);
RadioGroup group1 = FindViewById<RadioGroup>(Resource.Id.group1);
RadioGroup group2 = FindViewById<RadioGroup>(Resource.Id.group2);
Button enviar = FindViewById<Button>(Resource.Id.checkBtn);
enviar.Click += (sender, e) =>
{
var itemOfGroup1 = group1.CheckedRadioButtonId;
var itemOfGroup2 = group2.CheckedRadioButtonId;
if (itemOfGroup1 != -1) //if one of the group radio is checked
{
var radiobtn1 = FindViewById<RadioButton>(itemOfGroup1);
result = "group1:" + radiobtn1.Text;
}
if (itemOfGroup2 != -1)
{
var radiobtn2 = FindViewById<RadioButton>(itemOfGroup2);
result = result + " group2:" + radiobtn2.Text;
}
//if there're more groups, codes are the same, for example: result = result + "group3: "+ radiaobtn3.Text;
var email = new Intent(Android.Content.Intent.ActionSend);
email.PutExtra("message", result);
//more email relative codes goes here
};
}
You don't need to have that complex logic, and I only used a simple string to combine all Text of checked RadioButton in the variable value result, you should be able to change the format of this string. Good luck.
I have a problem I can't figure out. Hope you can help me.
I have an advanced search function, where I first have to choose if I want to search in menus or events by selecting a radiobutton. The problem is, that when I have chosen there is a postback, and I have to fill a dropdownlist with items.
It works fine, but if I search multiple times, the items are filled in again, because it's not in my if(!IsPostback){...} block, but I can't put it there, because there is a postback.
So how do I resolve this? I have tried to clear my items in different places, but that only results in the dropdownlist being empty. Here is some of my code:
if (!IsPostBack)
{
PnlMenu.Visible = false;
PnlEvents.Visible = false;
PnlResult.Visible = false;
//søgemuligheder
RblSearch.Items.Add(new ListItem("MENU", "1"));
RblSearch.Items.Add(new ListItem("EVENTS", "2"));
string _search = Request.QueryString["search"];
DataTable dt = objsearch.Search(_search);
if (!string.IsNullOrEmpty(_search))
{
if (dt.Rows.Count > 0)
{
if (dt.Rows.Count > 1)
{
if (RblSearch.SelectedValue == "1")
{
LitResult.Text += "<h4>Du har søgt på <span style='color: green;'>" + Session["search"].ToString() + "</span> - Der er " + dt.Rows.Count + " menuer, som matcher din søgning:</h4>";
}
if (RblSearch.SelectedValue == "2")
{
LitResult.Text += "<h4>Du har søgt på <span style='color: green;'>" + Session["search"].ToString() + "</span> - Der er " + dt.Rows.Count + " events, som matcher din søgning:</h4>";
}
}
else
{
if (RblSearch.SelectedValue == "1")
{
LitResult.Text += "<h4>Du har søgt på <span style='color: green;'>" + Session["search"].ToString() + "</span> - Der er " + dt.Rows.Count + " menu, som matcher din søgning:</h4>";
}
if (RblSearch.SelectedValue == "2")
{
LitResult.Text += "<h4>Du har søgt på <span style='color: green;'>" + Session["search"].ToString() + "</span> - Der er " + dt.Rows.Count + " event, som matcher din søgning:</h4>";
}
}
foreach (DataRow dr in dt.Rows)
{
LitResult.Text += "<div class='searchresult'><h3>" + dr["fldName"] + "</h3><img style='width: 55%;' src='../img/band/" + dr["fldImg"] + "' /></div>";
}
}
else
{
LitResult.Text += "<h4>Du har søgt på <span style='color: red;'>" + Session["search"].ToString() + "</span> - Der er ingen resultater! Prøv igen!";
}
}
}
//DdlMenu.Items.Clear();
//DdlEvents.Items.Clear();
//Menu
if (RblSearch.SelectedValue == "1")
{
DdlMenu.Items.Add(new ListItem("- - - VÆLG MENU - - -", "0"));
foreach (DataRow drmenu in objdiner.GetAllDinerCats().Rows)
{
DdlMenu.Items.Add(new ListItem(drmenu["fldName"].ToString(), drmenu["fldId"].ToString()));
}
}
//Events
TxtDatoFra.Attributes.Add("min", DateTime.Now.ToString("yyyy-MM-dd"));
if (RblSearch.SelectedValue == "2")
{
DdlEvents.Items.Add(new ListItem("- - - VÆLG TYPE - - -", "0"));
foreach (DataRow drevent in objevent.GetAllEventKats().Rows)
{
DdlEvents.Items.Add(new ListItem(drevent["fldName"].ToString(), drevent["fldId"].ToString()));
}
}
}
protected void RblSearch_SelectedIndexChanged(object sender, EventArgs e)
{
if (RblSearch.SelectedValue == "1")
{
PnlMenu.Visible = true;
PnlEvents.Visible = false;
DdlEvents.Items.Clear();
}
if (RblSearch.SelectedValue == "2")
{
PnlEvents.Visible = true;
PnlMenu.Visible = false;
DdlMenu.Items.Clear();
}
}
I'm making an data import to SQLite in Android, using Xamarin Forms C#, and I have problems with this.
To make the data import, i'm using an API, that I developed, and each table has a link, in this case, I'm importing 5 tables, with aproximately 1.000 records each table, I need to make 5 calls (call Table1API, call Table2API, call Table3API, call Table4API, call Table5API)
This is working correctly, but showing this error in DDMS, "I/Choreographer(1273): Skipped 259 frames! The application may be doing too much work on its main thread" and the app crash.
What am I doing wrong?
Follow links to help:
Methos, and button click event:
https://1drv.ms/u/s!AlRdq6Nx4CD6g4ouw1F1KJzmnfx5zg
My Method to consume API:
public async Task<string> ConsumeRestAPI(string url, string tkn)
{
url += "?" + tkn;
string retString = string.Empty;
try
{
using (var client = new HttpClient())
{
var result = await client.GetAsync(url);
retString = await result.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
retString = ex.Message + "\n\nErro ao tentar se conectar com o servidor.";
}
return retString;
}
Methods and button clicked event:
private async Task AsyncTaskTPRE(string pSYNC_DescTabela, string pSYNC_NomeTabela)
{
string pUrl = string.Empty;
string content = string.Empty;
string jsonMsgError = string.Empty;
int qtdReg = 0;
ServiceWrapper sw = new ServiceWrapper();
JArray jsonArray = null;
if (!actLoading.IsRunning)
actLoading.IsRunning = true;
lblTitulo.Text = "Conectando à API...";
pUrl = pAPIURL + "TabelaPrecoAPI.aspx";
content = await sw.ConsumeRestAPI(pUrl, pAPITKN);
if (!ErroRetornoJSON(content, pSYNC_DescTabela, out jsonMsgError))
{
#region Importação tbTPRE
content = sw.Html2JSON(content);
jsonArray = JArray.Parse(content);
qtdReg = 1;
foreach (var itemJSON in jsonArray)
{
PreencherTPRE(itemJSON);
lblTitulo.FontSize = 12;
lblTitulo.HorizontalOptions = LayoutOptions.Start;
lblTitulo.VerticalOptions = LayoutOptions.Start;
lblTitulo.Text = "Importando " + "\"" + pSYNC_DescTabela + "\"...\n"
+ " (Registro " + qtdReg.ToString() + " de " + jsonArray.Count() + " importado(s))";
await Task.Delay(10);
TPRE TPRE_Atual = pTPRE.GetTPRE(objTPRE.TPRE_Codigo, objTPRE.TPRE_SQEM_Id);
if (TPRE_Atual == null)
{
pTPRE.Insert(objTPRE);
if (pTPRE.HasError)
{
await DisplayAlert("Error", "Erro ao importar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objTPRE.TPRE_Id + "\n"
+ "Erro: " + pTPRE.MsgError, "OK");
break;
}
}
else
{
pTPRE.Update(objTPRE);
if (pTPRE.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objTPRE.TPRE_Id + "\n"
+ "Erro: " + pTPRE.MsgError, "OK");
break;
}
}
qtdReg++;
}
#endregion
#region Insert/Update tbSYNC
SYNC objSYNC = pSYNC.GetSYNC(pSYNC_NomeTabela);
if (objSYNC == null)
{
objSYNC = new SYNC()
{
SYNC_NomeTabela = pSYNC_NomeTabela,
SYNC_DescTabela = pSYNC_DescTabela,
SYNC_DataImportSync = DateTime.Now,
SYNC_DataExportSync = null,
CreatedBy = string.Empty,
CreatedOn = DateTime.Now,
UpdatedBy = string.Empty,
UpdatedOn = DateTime.Now
};
pSYNC.Insert(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao incluir registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
else
{
objSYNC.SYNC_DataImportSync = DateTime.Now;
objSYNC.UpdatedBy = string.Empty;
objSYNC.UpdatedOn = DateTime.Now;
pSYNC.Update(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
#endregion
}
else
{
await DisplayAlert("Atenção", jsonMsgError, "OK");
}
}
private async Task AsyncTaskITTP(string pSYNC_DescTabela, string pSYNC_NomeTabela)
{
string pUrl = string.Empty;
string content = string.Empty;
string jsonMsgError = string.Empty;
int qtdReg = 0;
ServiceWrapper sw = new ServiceWrapper();
JArray jsonArray = null;
if (!actLoading.IsRunning)
actLoading.IsRunning = true;
lblTitulo.Text = "Conectando à API...";
pUrl = pAPIURL + "ItensTabelaPrecoAPI.aspx";
content = await sw.ConsumeRestAPI(pUrl, pAPITKN);
if (!ErroRetornoJSON(content, pSYNC_DescTabela, out jsonMsgError))
{
#region Importação tbITTP
content = sw.Html2JSON(content);
jsonArray = JArray.Parse(content);
qtdReg = 1;
foreach (var ITTPjson in jsonArray)
{
PreencherITTP(ITTPjson);
lblTitulo.FontSize = 12;
lblTitulo.HorizontalOptions = LayoutOptions.Start;
lblTitulo.VerticalOptions = LayoutOptions.Start;
lblTitulo.Text = "Importando " + "\"" + pSYNC_DescTabela + "\"...\n"
+ " (Registro " + qtdReg.ToString() + " de " + jsonArray.Count() + " importado(s))";
await Task.Delay(10);
ITTP ITTP_Atual = pITTP.GetITTP(objITTP.ITTP_Id);
if (ITTP_Atual == null)
{
pITTP.InsertWithChildren(objITTP);
if (pITTP.HasError)
{
await DisplayAlert("Error", "Erro ao importar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objITTP.ITTP_Id + "\n"
+ "Erro: " + pITTP.MsgError, "OK");
break;
}
}
else
{
pITTP.UpdateWithChildren(objITTP);
if (pITTP.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objITTP.ITTP_Id + "\n"
+ "Erro: " + pITTP.MsgError, "OK");
break;
}
}
qtdReg++;
}
#endregion
#region Insert/Update tbSYNC
SYNC objSYNC = pSYNC.GetSYNC(pSYNC_NomeTabela);
if (objSYNC == null)
{
objSYNC = new SYNC()
{
SYNC_NomeTabela = pSYNC_NomeTabela,
SYNC_DescTabela = pSYNC_DescTabela,
SYNC_DataImportSync = DateTime.Now,
SYNC_DataExportSync = null,
CreatedBy = string.Empty,
CreatedOn = DateTime.Now,
UpdatedBy = string.Empty,
UpdatedOn = DateTime.Now
};
pSYNC.Insert(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao incluir registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
else
{
objSYNC.SYNC_DataImportSync = DateTime.Now;
objSYNC.UpdatedBy = string.Empty;
objSYNC.UpdatedOn = DateTime.Now;
pSYNC.Update(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
#endregion
}
else
{
await DisplayAlert("Atenção", jsonMsgError, "OK");
}
}
private async Task AsyncTaskPLPG(string pSYNC_DescTabela, string pSYNC_NomeTabela)
{
string pUrl = string.Empty;
string content = string.Empty;
string jsonMsgError = string.Empty;
int qtdReg = 0;
ServiceWrapper sw = new ServiceWrapper();
JArray jsonArray = null;
if (!actLoading.IsRunning)
actLoading.IsRunning = true;
lblTitulo.Text = "Conectando à API...";
pUrl = pAPIURL + "PlanoPagamentoAPI.aspx";
content = await sw.ConsumeRestAPI(pUrl, pAPITKN);
if (!ErroRetornoJSON(content, pSYNC_DescTabela, out jsonMsgError))
{
#region Importação tbPLPG
content = sw.Html2JSON(content);
jsonArray = JArray.Parse(content);
qtdReg = 1;
foreach (var PLPGjson in jsonArray)
{
PreencherPLPG(PLPGjson);
lblTitulo.FontSize = 12;
lblTitulo.HorizontalOptions = LayoutOptions.Start;
lblTitulo.VerticalOptions = LayoutOptions.Start;
lblTitulo.Text = "Importando " + "\"" + pSYNC_DescTabela + "\"...\n"
+ " (Registro " + qtdReg.ToString() + " de " + jsonArray.Count() + " importado(s))";
await Task.Delay(10);
PLPG PLPG_Atual = pPLPG.GetPLPG(objPLPG.PLPG_Id);
if (PLPG_Atual == null)
{
pPLPG.Insert(objPLPG);
if (pPLPG.HasError)
{
await DisplayAlert("Error", "Erro ao importar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objPLPG.PLPG_Id + "\n"
+ "Erro: " + pPLPG.MsgError, "OK");
break;
}
}
else
{
pPLPG.Update(objPLPG);
if (pPLPG.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro da tabela " + pSYNC_DescTabela + "!\n"
+ "ID do Registro: " + objPLPG.PLPG_Id + "\n"
+ "Erro: " + pPLPG.MsgError, "OK");
break;
}
}
qtdReg++;
}
#endregion
#region Insert/Update tbSYNC
SYNC objSYNC = pSYNC.GetSYNC(pSYNC_NomeTabela);
if (objSYNC == null)
{
objSYNC = new SYNC()
{
SYNC_NomeTabela = pSYNC_NomeTabela,
SYNC_DescTabela = pSYNC_DescTabela,
SYNC_DataImportSync = DateTime.Now,
SYNC_DataExportSync = null,
CreatedBy = string.Empty,
CreatedOn = DateTime.Now,
UpdatedBy = string.Empty,
UpdatedOn = DateTime.Now
};
pSYNC.Insert(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao incluir registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
else
{
objSYNC.SYNC_DataImportSync = DateTime.Now;
objSYNC.UpdatedBy = string.Empty;
objSYNC.UpdatedOn = DateTime.Now;
pSYNC.Update(objSYNC);
if (pSYNC.HasError)
{
await DisplayAlert("Error", "Erro ao atualizar registro na tabela de sincronização!\n" + pSYNC.MsgError, "OK");
}
}
#endregion
}
else
{
await DisplayAlert("Atenção", jsonMsgError, "OK");
}
}
private async void BtnImport_Clicked(object sender, EventArgs e)
{
List<SYNC> listSYNC = lvwTabelas.ItemsSource.Cast<SYNC>().ToList();
bool confirmacaoProcessamento = false;
PopularStatusConexao();
#region Validação de Campos/Parâmetros
var regSelecionado = listSYNC.Where(s => s.SYNC_IsToggled).Any();
if (!regSelecionado)
{
await DisplayAlert("Atenção", "Selecione pelo menos uma tabela para importar!", "OK");
}
else if (!pConnStatus)
{
await DisplayAlert("Atenção", "Sem conexão com internet!\nPara prosseguir com o processamento é necessário que esteja conectado em alguma rede.", "OK");
}
else if (!pConnWifiStatus)
{
var confirm = await DisplayAlert("Confirmação", "Para prosseguir com o processo de importação, recomendamos "
+ "que esteja conectado em uma rede WiFi.\n\nDeseja prosseguir?", "Sim", "Não");
confirmacaoProcessamento = confirm;
}
else if (pAPIURL == string.Empty)
{
await DisplayAlert("Atenção", "Parâmetro \"URL\" inválido!\nVerifique o parâmetro na parametrização da API.", "OK");
}
else if (pAPITKN == string.Empty)
{
await DisplayAlert("Atenção", "Parâmetro \"Token\" inválido!\nVerifique o parâmetro na parametrização da API.", "OK");
}
else
{
var confirm = await DisplayAlert("Confirmação", "Para prosseguir com o processo de importação, recomendamos "
+ "que esteja conectado em uma rede WiFi, atualmente você possui essa conexão.\n\nDeseja prosseguir?", "Sim", "Não");
confirmacaoProcessamento = confirm;
}
#endregion
#region Operação
if (confirmacaoProcessamento)
{
lvwTabelas.IsEnabled = false;
btnImport.IsEnabled = false;
swtSelecionarTodos.IsVisible = false;
listSYNC = listSYNC.Where(s => s.SYNC_IsToggled).ToList();
foreach (var item in listSYNC)
{
//int pPEFJ_Codigo = 0;
//int pPEFJ_SQEM_Id = 0;
#region Importação de Tabelas
switch (item.SYNC_NomeTabela)
{
#region tbPEFJ - Pessoa Física/Jurídica
case "tbPEFJ":
await AsyncTaskPEFJ(item.SYNC_DescTabela, item.SYNC_NomeTabela);
break;
#endregion
#region tbPROD - Produtos
case "tbPROD":
//qtdReg = 1;
//lblTitulo.FontSize = 15;
//lblTitulo.HorizontalOptions = LayoutOptions.Start;
//lblTitulo.Text = "Importando " + "\"" + item.SYNC_DescTabela + "\"...";
//await Task.Delay(1000);
break;
#endregion
//
#region tbTPRE - Tabela de Preço
case "tbTPRE":
await AsyncTaskTPRE(item.SYNC_DescTabela, item.SYNC_NomeTabela);
break;
#endregion
#region tbITTP - Itens da Tabela de Preço
case "tbITTP":
await AsyncTaskITTP(item.SYNC_DescTabela, item.SYNC_NomeTabela);
break;
#endregion
#region tbPLPG - Plano de Pagamento
case "tbPLPG":
await AsyncTaskPLPG(item.SYNC_DescTabela, item.SYNC_NomeTabela);
break;
#endregion
#region tbFOPG - Forma de Pagamento
case "tbFOPG":
await AsyncTaskFOPG(item.SYNC_DescTabela, item.SYNC_NomeTabela);
break;
#endregion
//
#region tbPEDI - Pedidos
case "tbPEDI":
//lblTitulo.FontSize = 15;
//lblTitulo.HorizontalOptions = LayoutOptions.Start;
//lblTitulo.Text = "Importando " + "\"" + item.SYNC_DescTabela + "\"...";
//await Task.Delay(1000);
break;
#endregion
#region tbITPD - Itens do Pedido
case "tbITPD":
//lblTitulo.FontSize = 15;
//lblTitulo.HorizontalOptions = LayoutOptions.Start;
//lblTitulo.Text = "Importando " + "\"" + item.SYNC_DescTabela + "\"...";
//await Task.Delay(1000);
break;
#endregion
default:
break;
}
#endregion
}
swtSelecionarTodos.IsVisible = true;
actLoading.IsRunning = false;
//if (!erroProc)
// await DisplayAlert("Aviso", "Importação realizada com sucesso!", "OK");
lblTitulo.FontSize = 22;
lblTitulo.Text = "Importação de Tabelas";
lblTitulo.HorizontalOptions = LayoutOptions.Center;
lvwTabelas.IsEnabled = true;
btnImport.IsEnabled = true;
Popular_lvwTabelas();
PopularStatusConexao();
}
#endregion
}
It seems you are not actually launching a new thread when you click that button. And if so, all that work is being done on the main thread, hence perhaps causing the error. To start a new thread, you do need to call Task.Run(...) or use some other API that will actually start a new thread. As the code is, unless I am missing it, you never start a new thread. You do await some other async operations, i.e. DisplayAlert but because you never use Task.ConfigureAwait(false) you are always being returned to the main thread. IOW if when calling the first async method that you are awaiting, you do the following (in the AsyncTaskTPRE method):
content = await sw.ConsumeRestAPI(pUrl, pAPITKN).ConfigureAwait(false);
when that method returns, you will not be on the UI/Main thread anymore. Without ConfigureAwait(false) when that method returns you are back on the main thread as the default for ConfigureAwait(...) is true.
See MS's guide on using async and await: https://msdn.microsoft.com/en-us/library/mt674882.aspx
In the section titled "Threads" it says the following:
The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.
I'm using callback to execute a string function, but I can't display the return on a label.
look:
protected void ASPxUploadControl1_FileUploadComplete(object sender,
FileUploadCompleteEventArgs e)
{
try
{
e.CallbackData = SaveNewFile(e.UploadedFile);
lblret.Text = ????
}
catch (Exception ex)
{
String error = ex.ToString();
lbleret.Text = error;
}
}
string SaveNewFile(UploadedFile upfile)
{
if (!upfile.IsValid)
return string.Empty;
String RMSG = "Houve um erro ao enviar o arquivo!";
Guid nid = Guid.NewGuid();
String extOK = "0";
const String updir = "~/tempIMGS/";
String[] extensao = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };//extensões
FileInfo finfo = new FileInfo(upfile.FileName);
long fmaxsize = 2097152;//tamanho do arquivo
String filext = System.IO.Path.GetExtension(upfile.FileName);
for (int i = 0; i < extensao.Length; i++)
{
if (filext == extensao[i])//se a extensão for permitida
{
if (upfile.ContentLength <= fmaxsize)//se o arquivo tiver no máximo 2mbs
{
extOK = "1";
}
else
{
RMSG = "O arquivo selecionado ultrapassa o tamanho máximo por arquivo (2Mbs) \n " + upfile.FileName.ToString();
}
}
else
{
RMSG = "O arquivo não se encaixa no quadro de extensões permitiras! (.gif , .png , .jpeg , .jpg , .bmp";
}
}
if (extOK == "1")
{
string resFileName = MapPath(updir) + nid + filext;
upfile.SaveAs(resFileName);
//Response.Write("<script>alert('arquivo enviado com sucesso');</script>");
RMSG = "Arquivo enviado com sucesso!";
}
return RMSG;
}
I'm trying execute a function and in the execution define the VAR RMSG with a message, when function ends return the last error message.
see in the 'TRY', e.CallbackData = EXECUTE_FUNCTION; once the return will be stored in e.CallbackData,
How do I get this return from e.callbackdata?
You can store the result first in a variable and then assign it to CallbackData and/or do some transformation with it and assign it to your label like so:
string result = SaveNewFile(e.UploadedFile);
e.CallbackData = result;
lblret.Text = String.Format(
"processed at {0} with a result of: {1}",
DateTime.Now,
result);