How get return from callback - c#

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

Related

Exception from HRESULT: 0x80004004 (E_ABORT) at Outlook.Mailitem.getHtmlBody()

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

Async Calls in Xamarins Forms

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.

how to save exception in txt file?

public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
DataTable GetListID = new DataTable();
try
{
SqlParameter[] arParams = new SqlParameter[4];
arParams[0] = new SqlParameter("#Date", typeof(DateTime));
arParams[0].Value = objFeedRetPL.requestdate;
}
catch (Exception ex)
{
string dir = #"C:\Error.txt"; // folder location
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
File.AppendAllText(Server.MapPath("~/Error.txt"), New);
}
}
}
Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In
C drive Error.txt
Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:
string filePath = #"C:\Error.txt";
Exception ex = ...
using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
writer.WriteLine( "-----------------------------------------------------------------------------" );
writer.WriteLine( "Date : " + DateTime.Now.ToString() );
writer.WriteLine();
while( ex != null )
{
writer.WriteLine( ex.GetType().FullName );
writer.WriteLine( "Message : " + ex.Message );
writer.WriteLine( "StackTrace : " + ex.StackTrace );
ex = ex.InnerException;
}
}
The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErrorLoggingSample
{
class Program
{
static void Main(string[] args)
{
try
{
string str = string.Empty;
if (string.IsNullOrEmpty(str))
{
throw new Exception("Wrong Data");
}
}
catch (Exception ex)
{
ErrorLogging(ex);
ReadError();
}
}
public static void ErrorLogging(Exception ex)
{
string strPath = #"D:\Rekha\Log.txt";
if (!File.Exists(strPath))
{
File.Create(strPath).Dispose();
}
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error Logging ===========");
sw.WriteLine("===========Start============= " + DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
sw.WriteLine("===========End============= " + DateTime.Now);
}
}
public static void ReadError()
{
string strPath = #"D:\Rekha\Log.txt";
using (StreamReader sr = new StreamReader(strPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
I use that one
catch (Exception e)
{
new MessageWriteToFile(e).WriteToFile();
}
public class MessageWriteToFile
{
private const string Directory = "C:\\AppLogs";
public string Message { get; set; }
public Exception Exception { get; set; }
public string DefaultPath
{
get
{
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var folder = $"{Directory}\\{appName}";
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
return $"{Directory}\\{appName}\\{fileName}";
}
}
public MessageWriteToFile(string message)
{
Message = message;
}
public MessageWriteToFile(Exception ex)
{
Exception = ex;
}
public bool WriteToFile(string path = "")
{
if (string.IsNullOrEmpty(path))
{
path = DefaultPath;
}
try
{
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
writer.WriteLine();
if (Exception != null)
{
writer.WriteLine(Exception.GetType().FullName);
writer.WriteLine("Source : " + Exception.Source);
writer.WriteLine("Message : " + Exception.Message);
writer.WriteLine("StackTrace : " + Exception.StackTrace);
writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
}
if (!string.IsNullOrEmpty(Message))
{
writer.WriteLine(Message);
}
writer.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}
}
Try This
try
{
int i = int.Parse("Prashant");
}
catch (Exception ex)
{
this.LogError(ex);
}
private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(message);
writer.Close();
}
}
string[] path1 = Directory.GetFiles(#"E:\storage", "*.txt");//it get the all textfiles from the folder
for (var i = 0; i < path1.Length; i++)
{
var file = Directory.GetDirectories(networkPath);
var path = file;
string temp_FilePath = "E:\\temp.txt";
string temp_FilePath1 = #"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
string temp_FilePath2 = #"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
string folder = #"E:\ExceptionFiles\Cs_regular";
string folder1 = #"E:\ExceptionFiles\CC_eBilling";
string[] lines;
var list = new List<string>();
var list1 = new List<string>();
var list2 = new List<string>();
var error = false;
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
var timenow1 = "2020/10/31 10:11";
if (res == timenow1)
{
string linesRemoved = "ERROR";
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list1.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if (line.Contains("Exception1") && error == false)
{
list1.Add(line);
error = true;
}
}
}
}
using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
{
string line;
while ((line = streamReader2.ReadLine()) != null)
{
string linesRemoved = "ERROR";
var res = line.Substring(20, 16);
//var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
var timenow1 = "2020/10/29 12:38";
if (res == timenow1)
{
if (!line.Contains(linesRemoved))
{
if (error == true)
{
if (line.Contains("at"))
{
list2.Add(line);
error = true;
}
else
{
error = false;
}
}
}
else
{
error = false;
}
if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
{
list2.Add(line);
error = true;
}
}
}
}
if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
{
int fileCount = Directory.GetFiles(folder).Length;
int fileCount1 = Directory.GetFiles(folder1).Length;
fileCount++;
fileCount1++;
temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";
}
{
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
System.IO.File.WriteAllLines(temp_FilePath, list);
System.IO.File.WriteAllLines(temp_FilePath1, list1);
System.IO.File.WriteAllLines(temp_FilePath2, list2);
}
}
}
catch (Exception ex)
{
}
return null;

ASPX get response headers back

I would appreciate some help because I am really new to C#. I need to return the response headers back, I need the 3 numbers of status code only actually. The code of the page for the web service is `
<%# Page Language="C#" ContentType="application/json;charset=utf-8"%>
<%# Import Namespace="System.Net" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="Newtonsoft.Json" %>
<%# Import Namespace="Newtonsoft.Json.Linq" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="log4net" %>
<script runat="server">
static readonly ILog m_Log = LogManager.GetLogger("getWebRequest");
String appUrlEncoded = "application/x-www-form-urlencoded";
String appJson = "application/json";
String textXml = "text/xml";
String appXml = "application/xml";
String textPlain = "text/plain";
/************************ fetchURL *******************/
String fetchURL(string url, string protocol, string enctype, string parameters,
string readWriteTimeout, string conTimeout,
string userName, string password, JObject CustomHeaders, JToken JsonContent)
{
m_Log.Debug("fetchURL(" + url + ", " + protocol + ", " + enctype + ", " + parameters + ", " +
readWriteTimeout + ", " + conTimeout + ", " + userName + ", " + password + ") in");
String result = "";
String method ="GET";
String loginCredentials = userName + ":" + password;
// Accepting self-signed certificates
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
try
{
if (protocol.EndsWith("get") || protocol.EndsWith("delete"))
{
url = url + (String.IsNullOrEmpty(parameters) ? "" : ("?" + parameters));
}
method = protocol.ToUpper();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = enctype;
request.Timeout = Int32.Parse(conTimeout);
request.ReadWriteTimeout = Int32.Parse(readWriteTimeout);
if (loginCredentials.Length>1)
{
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(loginCredentials)));
}
if (CustomHeaders != null)
{
//Custom HTTP headers
JEnumerable<JProperty> children = CustomHeaders.Children<JProperty>();
foreach (JProperty child in children)
{
string strKey = child.Name;
string strValue = "";
if (child == null || child.Value == null)
continue;
if (child.Value.Type.Equals(JsonTokenType.String))
{
strValue = (String)((JValue)child.Value).Value;
}
else
{
strValue = child.Value.ToString();
}
m_Log.Debug("request key: '" + strKey + "' -- value: '" + strValue + "'");
if (strKey.Trim().Equals("Accept"))
{
request.Accept = strValue;
}
else if (strKey.Trim().Equals("Connection"))
{
request.Connection = strValue;
}
else if (strKey.Trim().Equals("Content-Length"))
{
request.ContentLength = strValue.Length;
}
else if (strKey.Trim().Equals("Content-Type"))
{
request.ContentType = strValue;
}
else if (strKey.Trim().Equals("Expect"))
{
request.Expect = strValue;
}
else if (strKey.Trim().Equals("If-Modified-Since"))
{
request.IfModifiedSince = DateTime.Parse(strValue);
}
else if (strKey.Trim().Equals("Referer"))
{
request.Referer = strValue;
}
else if (strKey.Trim().Equals("Transfer-Encoding"))
{
request.TransferEncoding = strValue;
}
else if (strKey.Trim().Equals("User-Agent"))
{
request.UserAgent = strValue;
}
else
{
request.Headers.Add(strKey, strValue);
}
}
}
if (method.Equals("POST") || method.Equals("PUT"))
{
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
if (enctype.Equals(appJson))
{
if (JsonContent != null)
{
if (JsonContent is JObject)
{
JObject obj = (JObject)JsonContent;
m_Log.Debug(enctype + " encoding JObject: " + obj.ToString());
byte[] bytes = encoding.GetBytes(obj.ToString());
writeStream.Write(bytes, 0, bytes.Length);
}
else
{
JObject obj = new JObject();
obj.Add(new JProperty("content", JsonContent));
m_Log.Debug(enctype + " encoding: " + obj.ToString());
byte[] bytes = encoding.GetBytes(obj.ToString());
writeStream.Write(bytes, 0, bytes.Length);
}
}
}
else if (enctype.Equals(appUrlEncoded))
{
m_Log.Debug(enctype + " encoding parameters: " + parameters);
byte[] bytes = encoding.GetBytes(parameters);
writeStream.Write(bytes, 0, bytes.Length);
}
writeStream.Close();
}
}
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader input = new StreamReader(webResponse.GetResponseStream());
result = "";
result += convertToJson(input, webResponse.ContentType);
}
catch (Exception e)
{
Dictionary<string, string> d1 = new Dictionary<string, string>();
string value = "error.com.genesyslab.composer.servererror message= " + e.Message.ToString();
d1.Add("errorMsg", value);
result = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
Response.AppendToLog("GeneralException:" + result);
}
m_Log.Debug("result: " + result);
m_Log.Debug("fetchURL() out");
return result;
}
string parseResultData(StreamReader reader, JsonTextReader jsonReader, string initialData)
{
m_Log.Debug("parseResultData(" + initialData + ") In");
string json = "";
try
{
jsonReader.Read();
// JSON string
json += initialData;
Response.AppendToLog("ContentTypeUnkJSON");
m_Log.Debug("parseResultData() Out");
return json;
}
catch (JsonReaderException)
{
m_Log.Debug("parseResultData() JsonReaderException");
// not a valid JSON - check for XML
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(initialData);
reader.Close();
json = Newtonsoft.Json.JavaScriptConvert.SerializeXmlNode(doc.DocumentElement);
Response.AppendToLog("ContentTypeUnkXML");
m_Log.Debug("parseResultData() Out");
return json;
}
catch (Exception e)
{
m_Log.Debug("parseResultData() Exception: " + e.Message);
Response.AppendToLog("ContentTypeUnkTEXT");
Response.AppendToLog("Exception Occured: " +e.Message.ToString());
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("result", initialData);
string jsonText = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
return jsonText;
}
}
}
/**************convertToJson****************************/
string convertToJson(StreamReader reader, string contentType)
{
m_Log.Debug("convertToJson(" + contentType + ") In");
string json = "";
string data = reader.ReadToEnd();
// Parse into a JSON string
TextReader txReader = new StringReader(data);
Newtonsoft.Json.JsonTextReader jsonReader = new JsonTextReader(txReader);
if (contentType != null && contentType.Length != 0)
{
Response.AppendToLog("Content-Type:" + contentType.ToString());
if (contentType.ToLower().StartsWith(textXml) ||
contentType.ToLower().StartsWith(appXml))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
reader.Close();
json = Newtonsoft.Json.JavaScriptConvert.SerializeXmlNode(doc.DocumentElement);
m_Log.Debug("convertToJson() Out");
return json;
}
catch (XmlException e)
{
Response.AppendToLog("ContentTypeXMLFalse");
m_Log.Error("convertToJson() Error in decoding XML: " + e.Message);
throw new XmlException("Error in decoding XML: " + e.Message, e);
}
}
else if (contentType.ToLower().StartsWith(appJson))
{
jsonReader.Read();
// JSON string
json += data;
Response.AppendToLog("ContentTypeJSON");
m_Log.Debug("convertToJson() ContentTypeJSON Out");
return json;
}
else if (contentType.ToLower().StartsWith(textPlain))
{
Response.AppendToLog("ContentTypeTEXT");
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("result", data);
d1.Add("headers", "");
string jsonText = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
Response.AppendToLog("ContentTypeTEXT:" + jsonText);
m_Log.Debug("convertToJson() ContentTypeTEXT Out");
return jsonText;
}
else
{
Response.AppendToLog("unknown Content-Type:" + contentType);
m_Log.Debug("convertToJson() unknown Content-Type Out");
return (parseResultData(reader, jsonReader, data));
}
}
else
{
Response.AppendToLog("Content-Type NULL");
m_Log.Debug("convertToJson() Content-Type NULL");
return( parseResultData(reader, jsonReader, data) );
}
}
</script>
<%
log4net.Config.XmlConfigurator.Configure();
m_Log.Debug("_________________________________________________");
m_Log.Debug("getWebRequest() In");
// extract parameters
String WebUrl ="";
String Protocol= "";
String EncType = "";
Boolean AuthenAccess = false;
String UserName ="";
String Password ="";
String readWriteTimeout = "20000"; // timeout in milliseconds
String conTimeout = "20000"; // timeout in milliseconds
Stream ins = HttpContext.Current.Request.InputStream;
StreamReader reader = new StreamReader(ins);
string jsonStr = reader.ReadToEnd();
JObject requestObj = JObject.Parse(jsonStr);
m_Log.Debug("requestObj: " + requestObj.ToString());
WebUrl = (string)requestObj["WebUrl"];
Protocol = (string)requestObj["Protocol"];
EncType = (string)requestObj["Enctype"];
AuthenAccess = (Boolean)requestObj["AuthenAccess"];
if (AuthenAccess)
{
UserName = (string)requestObj["UserName"];
Password = (string)requestObj["Password"];
}
// the value passed from the block property overrides the
// global value in the composer.properties
String timeout = (string)requestObj["Timeout"];
if (timeout != null && timeout.Trim().Length > 0)
{
try
{
int timeoutInt = Int32.Parse(timeout);
if (timeoutInt != -1)
{
conTimeout = Convert.ToString(timeoutInt * 1000);
readWriteTimeout = Convert.ToString(timeoutInt * 1000);
}
}
catch (FormatException)
{
// ignore an invalid value
}
}
String ParamStr = "";
int QueryPos = WebUrl.IndexOf('?');
if ((Protocol.EndsWith("get") || Protocol.EndsWith("delete")) && (QueryPos > 0))
{
String QueryString = WebUrl.Substring(QueryPos + 1, WebUrl.Length - (QueryPos + 1));
WebUrl = WebUrl.Substring(0, QueryPos);
String[] Pairs = QueryString.Split('&');
foreach (String Pair in Pairs)
{
string strKey = "";
string strValue = "";
int Pos = Pair.IndexOf('=');
if (Pos == -1)
{
strKey = Pair;
strValue = null;
}
else
{
try
{
strKey = Server.UrlDecode(Pair.Substring(0, Pos));
strValue = Server.UrlDecode(Pair.Substring(Pos + 1, Pair.Length - (Pos + 1)));
}
catch (Exception ex)
{
m_Log.Error("Exception parsing queryString:" + ex.Message);
}
}
if (!ParamStr.Equals(""))
{
ParamStr = ParamStr + "&";
}
ParamStr = ParamStr + Server.UrlEncode(strKey) + "=" + Server.UrlEncode(strValue);
}
}
JObject Parameters = (JObject)requestObj["Parameters"];
if (Parameters != null)
{
JEnumerable<JProperty> children = Parameters.Children<JProperty>();
foreach (JProperty child in children)
{
string strKey = child.Name;
string strValue = "";
if (child == null || child.Value == null)
continue;
if (child.Value.Type.Equals(JsonTokenType.String))
{
strValue = (String)((JValue)child.Value).Value;
}
else
{
strValue = child.Value.ToString();
}
// add to map
if (!ParamStr.Equals(""))
{
ParamStr = ParamStr + "&";
}
ParamStr = ParamStr + Server.UrlEncode(strKey) + "=" + Server.UrlEncode(strValue);
}
}
m_Log.Debug("ParamStr: " + ParamStr);
JObject CustomHeaders = (JObject)requestObj["CustomHeaders"];
JToken JsonContent = (JToken)requestObj["JsonContent"];
//relative path processing
string relativePath = "http://localhost:";
if (WebUrl.StartsWith("."))
{
int slashindex = WebUrl.IndexOf("/");
if (slashindex != -1)
{
int n = WebUrl.Length;
WebUrl = WebUrl.Substring(slashindex + 1, n - slashindex-1);
}
relativePath += HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
relativePath = relativePath + HttpContext.Current.Request.RawUrl.ToString();
int boundary = relativePath.IndexOf("include");
if(boundary !=-1){
relativePath = relativePath.Substring(0, boundary);
}
WebUrl = relativePath + WebUrl;
m_Log.Debug("urlStr: " + WebUrl);
}
m_Log.Debug("WebUrl: " + WebUrl);
if (WebUrl.Length > 0)
{
Response.Write(fetchURL(WebUrl, Protocol, EncType, ParamStr, readWriteTimeout, conTimeout,
UserName, Password, CustomHeaders, JsonContent));
}
m_Log.Debug("getWebRequest() Out");
%>
`
As you can see I have inserted a "header" key-value pair in my returned json repsonse. How do I attach the value of the repsonse headers in the headers property? I have tried webResponse.Headers with no luck.
Thank you very much in advance!

ASP.net The process cannot access the file because it is being used by another process

i have the following error:
The process cannot access the file because it is being used by another process.
trying to save a file and then reading it, please can you help me to fix the code ?
protected void Button1_Click(object sender, EventArgs e)
{
string path = "\\\\nasouts01\\CodiceDiRete\\temp\\";
if (FileUpload1.HasFile)
{
string fileExt =
System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".csv")
{
try
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
finally
{
FileUpload1.PostedFile.InputStream.Flush();
FileUpload1.PostedFile.InputStream.Close();
FileUpload1.FileContent.Dispose();
//Release File from Memory after uploading
}
}
else
{
Label1.Text = "Selezionare soltanto file .csv";
gwreportpub.Visible = false;
ButtonConferma.Visible = false;
ButtonAnnulla.Visible = false;
ButtonPulisci.Visible = false;
return;
}
}
else
{
Label1.Text = "Inserire un file ";
gwreportpub.Visible = false;
ButtonConferma.Visible = false;
ButtonAnnulla.Visible = false;
ButtonPulisci.Visible = false;
return;
}
/*
Validazione nel file , dopo visualizzazione dei dati nella tabella
*/
int count = 0;
string line;
// Read the file and display it line by line.
using (System.IO.StreamReader file =
new System.IO.StreamReader(path+FileUpload1.FileName))
{
while((line = file.ReadLine()) != null)
{
count = line.Split(',').Length;
if(count != 12){
Label1.Text = "Il file non contiene il numero esatto di campi che servono al caricamento";
gwreportpub.Visible = false;
ButtonConferma.Visible = false;
ButtonAnnulla.Visible = false;
ButtonPulisci.Visible = false;
return;
}
}
file.Close();
}
/*
Prendo il valore della sequence
*/
OracleCommand sequenceCmd = new OracleCommand("select ls_seq_batchrequest.nextval from dual",connection);
OracleDataReader reader = sequenceCmd.ExecuteReader();
int sequenceVal=0;
while (reader.Read())
{
//dropdownlist1.Items.Insert(0, new ListItem(reader.GetString(0), reader.GetString(0)));
sequenceVal = reader.GetInt32(0);
}
reader.Close();
Session["sequenceVal"] = sequenceVal;
/*
Faccio l'inserimento a db dei dati e visualizzo la tabella
*/
OracleTransaction myTrans = null;
OracleCommand cmd = new OracleCommand("INSERT INTO ZTMP_SAM_TB_ELAB_PDR(facilityid,taxid,plantcode,ca_pdr, fullmeterkey_m1, corrmeterid_m1, " +
"stopreading_m1, corrstopreading_m1,fullmeterkey_m2, corrmeterid_m2, " +
"stopreading_m2, corrstopreading_m2, stopreadtime_m1,stopreadtime_m2,uidbatchrequest) " +
" VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15)", connection);
//myTrans = connection.BeginTransaction();
//cmd.Transaction = myTrans;
/*
( :facilityid,:taxid,
:plantcode,:capdr,:fullmetkeym2,
:corrmetidm2,:stopreadingm2,
:corrstopreadm2,:fullmetkeym1,
:corrmetidm1,:stopreadingm1,:corrstopreadm1,
:stopreadtimem2,:stopreadtimem1)
*/
using (System.IO.StreamReader file2 =
new System.IO.StreamReader(path+FileUpload1.FileName))
{
//System.IO.StreamReader file2 = new System.IO.StreamReader(path+FileUpload1.FileName);
try
{
while((line = file2.ReadLine()) != null)
{
string[] split = line.Split(',');
cmd.Parameters.Add("1", OracleType.VarChar, 64).Value = split[0];
cmd.Parameters.Add("2", OracleType.VarChar, 64).Value = "";
cmd.Parameters.Add("3", OracleType.VarChar, 64).Value = "";
cmd.Parameters.Add("4", OracleType.Number).Value = Convert.ToInt32(split[1]);
cmd.Parameters.Add("5", OracleType.VarChar, 64).Value = split[6];
cmd.Parameters.Add("6", OracleType.VarChar, 64).Value = split[7];
cmd.Parameters.Add("7", OracleType.Number).Value = Convert.ToInt32(split[8]);
cmd.Parameters.Add("8", OracleType.Number).Value = Convert.ToInt32(split[9]);
cmd.Parameters.Add("9", OracleType.VarChar, 80).Value = split[2];
cmd.Parameters.Add("10", OracleType.VarChar, 80).Value = split[3];
cmd.Parameters.Add("11", OracleType.Number).Value = Convert.ToInt32(split[4]);
cmd.Parameters.Add("12", OracleType.Number).Value = Convert.ToInt32(split[5]);
DateTime date1,date2;
DateTime.TryParseExact(split[10], "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out date1);
DateTime.TryParseExact(split[11], "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out date2);
cmd.Parameters.Add("13", OracleType.DateTime).Value = date1;
cmd.Parameters.Add("14", OracleType.DateTime).Value = date2;
cmd.Parameters.Add("15", OracleType.Number).Value = sequenceVal;
cmd.ExecuteNonQuery();
/*Per ogni elemento esegui l'insert*/
}
//myTrans.Commit();
}
catch(Exception ex){
//myTrans.Rollback();
Label1.Text = ex.Message;
return;
//"Si e' verificato un errore nell'inserimento dei dati nella tabella ZTMP_SAM_TB_ELAB_PDR";
}
file2.Close();
}
}
You can do two things to solve this
Save file with timestamp in name and work on that copy
Use File.ReadLine method if file is CSV.

Categories