Improving with Array instead of IF - c#

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

Related

Can't log string using NLOG

I can't log a string from an HTTP request using NLOG. Here's the code:
HttpResponseMessage res = client.PostAsync(path, content).Result;
if (!res.IsSuccessStatusCode)
{
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
String responseStr = res.Content.ReadAsStringAsync().Result;
//TODO(nassim) : Remplacé ce try catch par juste un retour d'erreur dans les log
//ErrorReponse error = JsonConvert.DeserializeObject<ErrorReponse>(responseStr);
Logger.Debug("Taille du log : " + responseStr.Length);
if(responseStr.Length > 200)
{
Logger.Debug(" 1");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 200));
}
else
{
Logger.Debug(" 2");
Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 10));
}
if (responseStr.Contains("Invalid credentials.") || responseStr.Contains("Token is expired."))
{
refreshToken(vault, storedValues);
storeDocInReciTAL(env);
}
throw new Exception("Erreur d'envoi du document vers reciTAL.");
And here's the stacktrace:
As you can see, the line concatening with the responseStr doesn't show anywhere. At first I thought it was because the string was too long, but it's only 37 characters.
What am I doing wrong?
Using structured logging resolves the problem. I don't understand why it doesn't work with a simple concatenation.

couldnt find the path in merging pdf files in one single pdf document

im trying in c# to merge 2 pdf in a single one using the pdfsharp library, it shows an error that it couldnt find the path in the path where im going to save it, this is where i put my paths
string directorio = #"C:\Users\Usuario\Documents\PDF\";//Directorio donde buscara los archivos pdf
string destino = #"C:\Users\Usuario\Documents\Prueba\";//Directorio donde estara el archivo unido
string[] archivo = Directory.GetFiles(directorio);
Unir(destino, archivo);
if (MessageBox.Show("Espere un momento mientras su solicitud es procesada", "INFORMACION" + MessageBoxButtons.OK + MessageBoxIcon.Information) == DialogResult.OK)
{
MessageBox.Show("Su documento se ha unido con exito, fue enviado a la direccion: " + destino);
}
this is where my merge method
private void Unir(string outfilePath , string[] pdfFiles){
PdfDocument documento = new PdfDocument();
foreach(string pdfFile in pdfFiles)
{
PdfDocument inputDocumento = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
documento.Version = inputDocumento.Version;
foreach(PdfPage page in inputDocumento.Pages)
{
documento.AddPage(page);
}
documento.Options.CompressContentStreams = true;
documento.Options.NoCompression = false;
documento.Save(outfilePath);
}
}
A file name is needed to save a PDF file, not a folder.
The Save should be made after the foreach loop to save only once.

Acceso denegado a la ruta de acceso C# [closed]

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

It's posible print PDF when PDF is open in memorystream?

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

Show Data on Google Map using C# / DataTable

what am I doing wrong? I'm trying to load Google Maps with data from the database and I am using the following code, but am having an error when I enter the foreach:
"An exception of type 'System.Exception' occurred in GMaps.dll but was not handled in user code"
"Additional information: Latitude must be beetwen -90 and 90"
if (!IsPostBack)
{
GLatLng mainLocation = new GLatLng(-18.8533, -41.9450);
GMapMyFriends.setCenter(mainLocation, 15);
XPinLetter xpinLetter = new XPinLetter(PinShapes.pin_star, "C", Color.Green, Color.White, Color.Chocolate);
GMapMyFriends.Add(new GMarker(mainLocation, new GMarkerOptions(new GIcon(xpinLetter.ToString(), xpinLetter.Shadow()))));
DataTable MyFriends = db.ExecuteSelect("SELECT lat ,lng FROM tblAdress;");
PinIcon p;
GMarker gm;
foreach (DataRow dtRow in MyFriends.Rows)
{
foreach (DataColumn dc in MyFriends.Columns)
{ p = new PinIcon(PinIcons.home, Color.Cyan);
gm = new GMarker(new GLatLng(Convert.ToDouble(dtRow["lat"]), Convert.ToDouble(dtRow["lng"])),
new GMarkerOptions(new GIcon(p.ToString(), p.Shadow())));
}
}
}
}
One of the values coming back from your database is either greater than 90 or less than -90. Create a breakpoint on your code and step through the values coming back from the database to determine which one.
You should also trap bad values and set them to something else (either don't display or default to some other value)
you have to change the "." by "," to accept the correct variable parameters
example
-18.8533 -18.8533 by substituting for the value of the variable is correct
hola
tienes que cambiar las "." por las "," para que la variable acepte los parámetros correcto
ejemplo
sustituir -18.8533 por -18,8533 para que el valor de la variable sea correcto

Categories