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.
Related
I have a custom add-in which gets the body on clicking a button when it got installed. so I am getting this error on a customer machine. code is working fine on my side and for other customers but one customer is facing this problem.
this is my code
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Explorer olExp = olApp.ActiveExplorer();
Selection olSel = olExp.Selection;
string msg = "";
int iterate = 1;
MAPIFolder inbox = null;
if (olSel.Count > 1)
{
MessageBox.Show("Sorry! You can't report more then 1 email at a time", "Report Email");
return;
}
foreach (_MailItem mail in olSel)
{
inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
mail.GetInspector.Display(false);
Thread.Sleep(2100);
string screenShot = getScreenShot(mail);
mail.GetInspector.Close(OlInspectorClose.olDiscard);
String msgToShow = "Are you sure you want to report this email as suspicious?";
if (mail != null && mail.Subject != null)
msgToShow += "\n\nSubject : " + mail.Subject.ToString();
DialogResult dr = MessageBox.Show(msgToShow, "Please Confirm", MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
msg += reportMail(mail, screenShot, e);
}
else {
return;
}
iterate++;
break;
}
if (!msg.Equals(""))
MessageBox.Show(msg, "Report Email");
else
return;
if (!msg.Contains("Success"))
return;
MailItem moveMail = null;
MAPIFolder subfolder = null;
try
{
subfolder = inbox.Folders["Reported Emails"];
}
catch (System.Exception ex) {
subfolder = inbox.Folders.Add("Reported Emails", OlDefaultFolders.olFolderInbox);
}
foreach (MailItem eMail in olSel)
{
try
{
moveMail = eMail;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
moveMail.Move(subfolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private string reportMail(_MailItem mail, string screenShot, RibbonControlEventArgs e)
{
try
{
var m = Globals.ThisAddIn.Application.GetNamespace("MAPI");
var mailitem = mail;
if (mailitem != null)
{
// Console.WriteLine("Email body ::: " + mailitem.HTMLBody);
String reporterEmail = getReporterEmail(mailitem);
String senderEmailAddress = "";
String senderName = "";
AddressEntry mailsender;
if (reporterEmail.Equals(""))
{
MessageBox.Show("Sorry! This email can't be reported because you are not included in Recipients.", "Report Email");
}
else
{
if (mailitem.SenderEmailType == "EX")
{
mailsender = mailitem.Sender;
if (mailsender != null)
{
if (mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || mailsender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
ExchangeUser exchUser = mailsender.GetExchangeUser();
if (exchUser != null)
{
senderEmailAddress = exchUser.PrimarySmtpAddress;
senderName = exchUser.Name;
}
}
}
}
else
{
senderEmailAddress = mailitem.SenderEmailAddress;
senderName = mailitem.SenderName;
}
String emailHeader = mailitem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
String emailBody = mailitem.Body.Replace("%"," percent").Replace("#","").Replace("|", "");
//String res = HttpPost(Properties.Settings.Default.address, "ReporterEmail=" + reporterEmail + "&suspectedName=" + senderName + "&FromEmail=" + senderEmailAddress
// + "&ToEmail=" + mailitem.To + "&Subject=" + mailitem.Subject + "&EmailBody=" + emailBody + "&AttachmentName=" + GetAttachments(mailitem)
// + "&reporter=" + reporterEmail + "&emailHeader=" + emailHeader + "&mailImage=" + screenShot);
String htmlBody = mail.HTMLBody;
MessageBox.Show(htmlBody);
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("ReporterEmail", reporterEmail);
postParameters.Add("suspectedName", senderName);
postParameters.Add("FromEmail", senderEmailAddress);
postParameters.Add("ToEmail", mailitem.To);
postParameters.Add("Subject", mailitem.Subject);
postParameters.Add("EmailBody", emailBody);
List<String> attachmentDetails = GetAttachments(mailitem);
postParameters.Add("AttachmentName", attachmentDetails[0]);
postParameters.Add("reporter", reporterEmail);
postParameters.Add("emailHeader", emailHeader);
postParameters.Add("mailImage", screenShot);
string res = HttpPost(Properties.Settings.Default.serverAddress+ "/PhishRod-portlet/reporter", postParameters, htmlBody,attachmentDetails[1]);
return res + "\n";
}
}
}
catch (System.Exception ex)
{
log.Error(ex);
return "Error: " + ex + "-- - " + ex.StackTrace.ToString() + "\n";
}
return "";
}
In the event handler of your button I see the following lines of code:
Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
There is no need to create a new Outlook Application instance in the add-in. Instead, you need to use the Application property which doesn't trigger a security issue when dealing with OOM from external applications:
var app = Globals.ThisAddIn.Application
I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.
I try to send email, below code works fine but email sends twice at a time. I tried a lot but I don't know where I made a mistake.
RTElapsedTime.cs:
public void Elapsed()
{
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
T1.Interval = 60000;
T1.Enabled = true;
}
public void T1_Elapsed(object source, ElapsedEventArgs e)
{
try
{
MatchingTime = DateTime.Now.ToString("HH:mm");
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString());
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count);
foreach (DataRow r in dt.Rows)
{
T1.Enabled = false;
RTEmailManagement(r);
T1.Enabled = true;
}
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed.");
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message);
}
}
DataTable dataRPT1 = new DataTable();
public DataTable ReportGeneration2(EmailDTO EETO)
{
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType);
return dataRPT1;
}
public void RTEmailManagement(DataRow dr)
{
EDTO = null;
EDTO = new EmailDTO();
MatchingTime = DateTime.Now.ToString("HH:mm");
EDTO.SecondTime = MatchingTime;
EDTO.ScheduleTime = dr["rshtime"].ToString();
EDTO.ToEmails = dr["rsh_altrntmail"].ToString();
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
EDTO.Subject = dr["rsh_subjct"].ToString();
EDTO.ReportID = dr["reportid"].ToString();
EDTO.Departments = dr["rsh_dept"].ToString();
EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString());
EDTO.weekly = dr["rsh_day"].ToString();
EDTO.Monthly = dr["rsh_dayofmnth"].ToString();
EDTO.Day = dr["xday"].ToString();
EDTO.Body = dr["rsh_body"].ToString();
EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString());
CompanyID = Int32.Parse(dr["Company_id"].ToString());
dataRPT1 = ReportGeneration2(EDTO);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count);
foreach (DataRow r in dataRPT1.Rows)
{
EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray();
EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray();
//EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString();
EDTO.ToEmails1 = r["email_addr"].ToString();
EDTO.LateArrival = r["LateArrivals"].ToString();
if (EDTO.ScheduleTime == EDTO.SecondTime)
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched");
switch (Convert.ToInt32(EDTO.ReportType))
{
case 0:
case 1:
EmailConfiguration(CompanyID, EDTO);
break;
case 2:
//TraceImplogs.TraceLTService("tyoe 2 new");
EmailConfiguration(CompanyID, EDTO);
break;
case 3:
// TraceImplogs.TraceLTService("tyoe 3 new");
EmailConfiguration(CompanyID, EDTO);
break;
default:
break;
}
}
}
// else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching");
}
public void EmailConfiguration(int compid, EmailDTO EDTO)
{
try
{
ConfigDTO mlDTO = new ConfigDTO();
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid);
RTMailProcessing Mprocess = new RTMailProcessing();
mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString();
mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString();
mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString();
mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString());
Mprocess.EmailProcessing(mlDTO, EDTO);
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message + " Email Error");
}
}
Email processing cs code.
RtMailprocessing.cs:
public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO)
{
RTMsg.language(EDTO.langcode);
conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd);
// TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd);
SmtpClient smtp = new SmtpClient
{
Host = conDTO.ConfigHost,
Port = conDTO.ConfigPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd)
// Timeout = 30000,
};
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// TraceImplogs.TraceLTService("Entered inside");
if (EDTO.ToEmails != "")
{
using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body))
{
for (int k = 0; k < EDTO.CcEmails.Length; k++)
{
if (EDTO.CcEmails[k] != "")
{
message.CC.Add(EDTO.CcEmails[k].TrimEnd(';'));
}
else
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty");
}
}
message.CC.Add(EDTO.ToEmails);
message.Subject = ""; message.Body = "";
message.Subject = EDTO.Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// ReportGeneration(EDTO);
string EmailBody = "";
if (attach != null)
{
message.Attachments.Add(attach);
string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
/*****with attachment***/
foreach (string lines in RepBody)
{
EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>";
}
message.Body = "Email Testing";
message.BodyEncoding = System.Text.Encoding.UTF8;
//message.Attachments.Dispose();
//message.Dispose();
}
if (dataRPT.Rows.Count < 1)
{
message.Body ="Test Email";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Attachments.Clear();
}
message.IsBodyHtml = true; //Send this as plain-text
smtp.Send(message);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully.");
message.CC.Clear();
//((IDisposable)smtp).Dispose();
//message.Attachments.Dispose();
//message.Dispose();
}
}
}
When I debug with breakpoint loop run single time only but I got two email. I don't know where I made exactly mistake.
Thanks in advance.
I'm going to take a guess, you're not unsubscribing the event:
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
You need to unsubscribe it:
T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed);
The email server processed both messages and delivered them at the same time.
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);
} } }
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);