I would like to use an Array instead of IF, I think that is more efficient but I don't how exactly do it sorry, I am new in C#, can someone just give me an good example please? I have a lot of Cliente.Contains and I think "If" is not the correct way, this is the code:
if (Cliente.Contains("0003919026"))
{
nombreCliente = "TELMOV";
}
if (Cliente.Contains("0002402248"))
{
nombreCliente = "Workplay S.A. DE C.V.";
}
if (Cliente.Contains("0009206605"))
{
nombreCliente = "SISTEMAS Y SERVICIOS DE (SYSCOM)";
}
CadenaRes = "Se proceso el archivo el dia " + DateTime.Now.ToString() + "\n" + "El archivo con nombre: " + nombreCliente;
Console.WriteLine("Carga Satisfactoria: {0} ", transfer.FileName);
I think you can achieve your task using Dictionary like following:
var dic = new Dictionary<string, string>();
dic.Add("0003919026", "TELMOV");
dic.Add("0002402248", "Workplay S.A. DE C.V.");
dic.Add("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)");
dic.Add("0009206605", "Se proceso el archivo el dia" + DateTime.Now.ToString() + "\n" + "El archivo con nombre: " + nombreCliente);
nombreCliente = dic.FirstOrDefault(x => Cliente.contains(x));
You can also use list of a class containing your key and value. Then use linq to get your required value.
Technically, you can organize substitution pairs (what to find and what to show) into a collection, say an array and implement something like this:
using System.Linq;
...
string nombreCliente = ...
(string find, string show)[] subs = new[] {
("0009206605", "SISTEMAS Y SERVICIOS DE (SYSCOM)"),
("0002402248", "Workplay S.A. DE C.V."),
//TODO: Add more pairs here
};
// Reverse: according to the code in the question, the later pair should prevail;
// if it's not possible we can drop .Reverse()
foreach (var pair in subs.Reverse())
if (Cliente.Contains(pair.find)) {
nombreCliente = pair.show;
break;
}
CadenaRes = string.Join(Environment.NewLine,
$"Se proceso el archivo el dia {DateTime.Now}",
$"El archivo con nombre: {nombreCliente}",
);
Console.WriteLine($"Carga Satisfactoria: {transfer.FileName}");
But I doubt in underlying logic: we are looking for just a fragment, and the assign nombreCliente;
what if Cliente is combined, say 0009206605 and (0002402248)?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
//English
Im newbie coding... i want to edit some text files in this path D:.
The problem is if one text file has been used my app throw error saying "Access Denied"...
I want to skip that error and continue with the next file... help me please...
Suppose the file United3.txt throw access denied and i cant edit.
//Español
Soy nuevo programador y quiero editar varios archivos de texto en un disco duro D.
El problema es que si uno esta siendo usado me dice acceso denegado por ende quiero omitir la edicion a el y que siga con el proximo archivo.
Este es mi método.
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
(Hola GBY)
You should capture Exception and proceed with the next file.
Find below an example.
More info about try-catch structure --> https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/keywords/try-catch
De nada!
public void startAction3()
{
string DiscoDuroD = "D:\\";
if (Directory.Exists(DiscoDuroD))
{
string text = "Hello My Friend";
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United3.txt"), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero United3: "+ ex.Message)
}
string text2 = "EYY";
using (StreamWriter outputFile = new StreamWriter(Path.Combine(DiscoDuroD,
"United4.txt"), true))
{
outputFile.WriteLine(text);
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco Duro D no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
Perdon por la falta de puntuacion y cualquier error de espanol. Hace un tiempo sin usar espanol con regularidad.
Sorry for the lack of punctuation and mistakes in my Spanish. It's been a while since I used Spanish regularly.
Si tu programa tiene que procesar varios archivos en una manera igual, podrias implementar un metodo asi con 'try-catch' igual que el respuesta de David:
If your application has to process several files in a similar way, you could implement a method like this with a 'try-catch' block similar to David's answer:
public void OutputToFile(string discPrefix, string fileName, string text)
{
if (Directory.Exists(discPrefix))
{
try
{
using (StreamWriter outputFile = new StreamWriter(Path.Combine(discPrefix,
fileName), true))
{
outputFile.WriteLine(text);
}
}
catch (IOException ex)
{
// do something in case any error occurs, leave a trace or write a console warning...
console.WriteLine("Error fichero" + fileName + ": " + ex.Message)
}
}
else
{
MessageBox.Show("Ruta innexistente.", "Disco no detectado", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
...y usarlo entre StartAction3 asi:
...and call it from within your StartAction3 like this:
OutputToFile("D://", "United3.txt", "Hello my friend");
OutputToFile("D://", "United4.txt", "EYY");
Its posible open print dialog when is open in memorystram?
Actually I save the pdf in "~/App_Data/Rep_PDF/" and after show a pdf in an iframe but I cant do it because I recive a message :
"Not allowed to load local resource: file:///C:/Users/andres.martinez/Documents/TFS%20Monterrey%20Gob/InterfaceMonterrey%20PROD/Interface%20Monterrey%20PROD/InterfaceMonterrey/App_Data/Rep_PDF/Copia_C_Administrativa%2030-04-2019.pdf"
Could you help me How to print a pdf in asp mvc?
this is part of my code:
public ActionResult ImprimeReporte()
{
//Indicamos donde vamos a guardar el documento
string directorioRaiz = "~/App_Data/Rep_PDF/";
string NombreArchivoPDF = "C_Administrativa " + DateTime.Today.ToString("dd-MM-yyyy") + ".pdf";
string path_Original=Server.MapPath(directorioRaiz+NombreArchivoPDF);
string path_Copia = Server.MapPath(directorioRaiz + "Copia_"+NombreArchivoPDF);
if (System.IO.File.Exists(path_Original))
{
//SI EXISTE EL ARCHIVO EN LA CARPETA, LO MANDA A IMPRIMIR
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
// System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
else
{
//SI NO EXISTE MANDA LLAMAR AL METODO PARA DESCARGAR EL ARCHIVO Y DESPUES IMPRIMIRLO
Genera_Pdf_Administrativo();
Inicia_PrintScript(path_Original, path_Copia);
ViewData["path_Copia"] = path_Copia;
//Elimina los archivos , despues de que se imprimio
//System.IO.File.Delete(path_Original);
//System.IO.File.Delete(path_Copia);
}
return View();
}
second part
public static void Inicia_PrintScript(string Original, string Copia)
{
PdfReader reader = new PdfReader(Original);
PdfStamper stamper = new PdfStamper(reader, new FileStream(Copia, FileMode.Create));
AcroFields fields = stamper.AcroFields;
stamper.JavaScript = "this.print(true);\r";
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
View
<iframe src="#ViewData["path_Copia"].ToString()" id="myFrame" frameborder="0" style="border:0;" width="700" height="300"></iframe>
Well, it's possible to open a PDF with print dialog in another tab.
In your controller you need to get the file in memory just to return it, or generate the file on fly.
public FileResult PDFToReturn()
{
string filePath = Server.MapPath("Path_to_PDF");
return File(System.IO.File.ReadAllBytes(filePath), System.Web.MimeMapping.GetMimeMapping(filePath));
}
javascript does the magic.
function printPDF() {
let link = 'javascript:w=window.open("/Controller/PDFToReturn"); w.print();';
location.href = link;
}
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 trying to redirect to an external website when everything is done, but firefox changes the http word on the url for a weird set of characters. This is my server side code:
[HttpPost]
public ActionResult Postular(INFO_BASE_POSTULACION_model pInfoPostulacion) {
string rutMD5 = Request["rutMD5"];
int idRegion = Convert.ToInt32(Request["idRegion"]);
int idInstrumento = Convert.ToInt32(Request["idInstrumento"]);
string urlDestino = "";
try
{
#region VALIDACION DE DATOS
if (!ModelState.IsValid) {
TempData["ModelState"] = ModelState;
return RedirectToAction("Index", new { data = Utilidades.Base64Encode(rutMD5 + ";" + idRegion + ";" + idInstrumento) });
}
#endregion
INFO_BASE_POSTULACION nuevaInfoBasePostulacion = new INFO_BASE_POSTULACION();
nuevaInfoBasePostulacion = pInfoPostulacion.modeloToDTO(pInfoPostulacion);
nuevaInfoBasePostulacion.TOKEN = Utilidades.GenerarStringUnico();
nuevaInfoBasePostulacion.INFO_REGISTRO_ELIMINADO = false;
nuevaInfoBasePostulacion.FECHA_CREACION = DateTime.Now;
Boolean todoOK = new InfoBasePostulacionBO().Agregar(nuevaInfoBasePostulacion);
if (!todoOK)
{
ModelState.AddModelError(String.Empty, "Ocurrió un error al intentar guardar la información.");
TempData["ModelState"] = ModelState;
return RedirectToAction("Index", new { data = Utilidades.Base64Encode(rutMD5 + ";" + idRegion + ";" + idInstrumento) });
}
string token = nuevaInfoBasePostulacion.TOKEN;
string idFormulario = Convert.ToString(nuevaInfoBasePostulacion.ID_FORMULARIO_POSTULACION);
string nombreParamToken = ConfigurationManager.AppSettings["ProActiveOffice-paramNombre-Token"];
string nombreParamIdFormulario = ConfigurationManager.AppSettings["ProActiveOffice-paramNombre-IdFormulario"];
urlDestino = ConfigurationManager.AppSettings["ProActiveOffice-URL"] + "?" + nombreParamToken + "=" + token + "&" + nombreParamIdFormulario + "=" + idFormulario;
//Here i had yo use the uriBuilder because i couldn't make it work on any other way.
UriBuilder uri = new UriBuilder(urlDestino.Trim());
//Here i redirect to an external website.
return Redirect(uri.Uri.ToString());
}
catch (Exception ex)
{
log.Error("Error al intentar guardar info base de postulación", ex);
ModelState.AddModelError(String.Empty, "Ocurrió un error al intentar guardar la información.");
TempData["ModelState"] = ModelState;
return RedirectToAction("Index", new { data = Utilidades.Base64Encode(rutMD5 + ";" + idRegion + ";" + idInstrumento) });
}
}
Here you can see the debug:
1-Here you can see the url string that i have (i had to remove the "http://" because it wasn't working correctly with the uri builder):
2-Here you see the value of the uri builder with the string url in it:
3-Here you see the toString() method apply to the uri (I have already use the absolute uri property):
4-And now finally the error. The http word has been change for a set of characters:
I have had lots of problems with the redirection. These code is currently working on Chrome, but on firefox gives me these error.
What could it be ?
By the way i am using visual studio 2013 + .NET Framerowk 4.5 + MVC4
%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.