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
Related
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)?
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.
Can anybody give me a hand, i am traying to create a pdf file who has a table of employees inside, i get the employee data form a database, so the table could be occupied one o serveral pages of the document.
I set the margin of the table
table.SetMarginTop(100);
table.SetMarginBottom(20);
But as soon the employee data generates another page of the pdf documetn the margins get lost
Here is my complete code of how i am generating the pdf and some screenshots
internal bool CreatePdfInspectorDelegates(string storeName, DateTimePicker date, string inspector, DataTable delegateStoreDT, DataTable delegateEmployeeDT)
{try
{
string auxPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
auxPath = auxPath + #"\PDF\Creados\notifacionInspectorDelegados" + storeName + ".pdf";
PdfWriter writer = new PdfWriter(auxPath);
PageSize ps = PageSize.LETTER;
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf, ps);
//Fuentes de texto
PdfFont fontNormal = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
PdfFont fontBold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD);
//Datos
string dateIn = String.Format("Fecha{0}", date.Value.ToString("dd/MM/yyyy"));
string instpector = String.Format("{0}", date.Value.ToString("dd/MM/yyyy"));
//Cuerpo
Paragraph pTittel = new Paragraph();
pTittel.SetPaddingTop(70);
pTittel.SetFixedLeading(25);
Text text = new Text("NOTIFICACIÓN AL INSPECTOR O INSPECTORA DEL TRABAJO\n DE LA VOLUNTAD DE LOS TRABAJADORES Y LAS TRABAJADORAS\n DE ELEGIR A LOS DELEGADOS Y A LAS DELEGADAS DE PREVENCIÓN").SetFont(fontBold).SetTextAlignment(TextAlignment.CENTER);
pTittel.SetTextAlignment(TextAlignment.CENTER);
pTittel.Add(text);
Paragraph pBody = new Paragraph();
pBody.SetFixedLeading(22);
Text text2 = new Text("\nFecha: ").SetFont(fontNormal);
Text textDate = new Text(date.Value.ToString("dd/MM/yyyy")).SetFont(fontNormal).SetUnderline();
Text text3 = new Text("\n\nCiudadano(a):\n").SetFont(fontNormal);
Text textInspector = new Text(inspector).SetFont(fontNormal).SetUnderline();
Text text4= new Text("\n\nNosotros, los(as) trabajadores(as), en cumplimiento a lo señalado en el artículo 41 de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(Lopcymat) y del artículo 58 de su Reglamento Parcial, nos dirigimos a Usted con el objeto de manifestarle nuestra voluntad de elegir a los Delegados y / o Delegadas de Prevención correspondientes a la entidad de trabajo: ").SetFont(fontNormal);
Text textCenter = new Text("GRUPO TOTAL 99 C.A.").SetFont(fontBold).SetUnderline();
Text text5 = new Text(" cuya dirección es: ").SetFont(fontNormal);
Text textCenterAddress = new Text("CALLE LAS VEGAS CRUCE CON SOLEDAD EDIFICIO CLARIANT VENEZUELA, ZONA INDUSTRIAL DE LA TRINIDAD, CARACAS. ").SetFont(fontNormal).SetUnderline();
Text text6 = new Text(" , específicamente los correspondientes al centro de trabajo: ").SetFont(fontNormal);
Text textBranch = new Text(GetStoreBranch(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
Text text7 = new Text(" , ubicado en: ").SetFont(fontNormal);
Text textBranchAddress = new Text(GetStoreAddress1(delegateStoreDT).ToUpper() + ", " + GetStoreAddress2(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
Text text8 = new Text("\n\nNotificación que se hace para efectos del artículo 59 del Reglamento Parcial de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(RLopcymat).\n\nA continuación firman los(as) trabajadores(as) solicitantes:\n").SetFont(fontNormal);
pBody.Add(text2);
pBody.Add(textDate);
pBody.Add(text3);
pBody.Add(textInspector);
pBody.Add(text4);
pBody.Add(textCenter);
pBody.Add(text5);
pBody.Add(textCenterAddress);
pBody.Add(text6);
pBody.Add(textBranch);
pBody.Add(text7);
pBody.Add(textBranchAddress);
pBody.Add(text8);
pBody.SetTextAlignment(TextAlignment.JUSTIFIED);
doc.Add(pTittel);
doc.Add(pBody);
//Segunda pagina
doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
//Empleados
float[] columnWidths = { 5, 5, 5, 5, 4 };
Table table = new Table(UnitValue.CreatePercentArray(columnWidths));
table.SetWidth(UnitValue.CreatePercentValue(100));
Cell[] header =
{
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Nombres y Apeliidos").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cedula\nIdentidad N°").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cargo Actual").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Firma").SetTextAlignment(TextAlignment.CENTER).SetBold()),
new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Huella").SetTextAlignment(TextAlignment.CENTER).SetBold())
};
foreach (Cell cells in header)
{
table.AddCell(cells);
}
foreach (DataRow row in delegateEmployeeDT.Rows)
{
if (row[0].ToString() == "True")
{
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[2].ToString().ToUpper() + "\n" + row[3].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[4].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[5].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));
table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));
}
}
table.SetMarginTop(100);
table.SetMarginBottom(20);
doc.Add(table);
doc.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
Top and bottom margins are not supposed to be applied to parts of the table that breaks across several pages. They only define space between previous element and current one (top margin) and between current element and next one (bottom margin).
If you want to preserve spacing on top of a table when it splits across pages you can use header and footer functionality. Table headers and footers are repeated on each page occupied by a table, and you can add a cell without borders with fixed height which will result in spacing on each page. Here is an example:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc, PageSize.A4.rotate());
doc.add(new Paragraph("Starting text"));
Table table = new Table(UnitValue.createPercentArray(5)).useAllAvailableWidth();
table.addHeaderCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
table.addHeaderCell(new Cell(1, 5).
add(new Paragraph("Header")));
table.addFooterCell(new Cell(1, 5).
add(new Paragraph("Footer")));
table.addFooterCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
for (int i = 0; i < 350; i++) {
table.addCell(new Cell().add(new Paragraph(String.valueOf(i + 1))));
}
doc.add(table);
doc.close();
Here is what the result looks like:
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 have 3 DataGridViews, each bound to a specific table in my MySQL database, when the user changes a cell value in the grid, i use the CellValidated event to send the data back to the table using the dataAdapter's Update() function.
The odd thing is, there is one of those 3 datagridviews that is taking like 1-2 seconds to update a single record, while the other two do it in a blink of an eye. I'm highly suspecting its because i have a DataGridViewComboBoxColumn in the problematic grid that receives its DataSource from the BindingSource of a DIFFERENT DataGridView. The other grids dont have that sort of column.
This is how the problematic grid looks like
The "Mensalistas" tab contains the personal info data of the company clients, and on the "Recibos de Mensalistas" tab i have the problematic grid that is responsible for generating receipts to the company's clients by basing each entry on the "Mensalista" DataGridViewComboBoxColumn there.
That dgv column is bound to a FK (uneeded maybe? since im always making sure that the DB column receives a valid ID from the "Mensalistas" tab/db) indexed column in the DB whose Reference Table and FoireignColumn is the Mensalista.Id field from the Mensalista table that is bound to the "Mensalistas" dataGridView
This is the code that is used on the Form_Load function to fill the problematic datagridView
//DataGridViewRecibosMensalistas
try
{
MySqlConnection connection = AccessControl.BuildMySQLConnection("database");
connection.Open();
string selectCommand = "SELECT * FROM `recibosmensalistas`;";
dataAdapterRecibosMensalistas = new MySqlDataAdapter(selectCommand, connection.ConnectionString);
dataTableRecibosMensalistas = new DataTable();
dataTableRecibosMensalistas.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapterRecibosMensalistas.Fill(dataTableRecibosMensalistas);
SendMessage(dataGridViewRecibosMensalistas.Handle, WM_SETREDRAW, false, 0);
// Prolly the culprit?
DataGridViewComboBoxColumn idMensalista = new DataGridViewComboBoxColumn();
idMensalista.ValueType = typeof(uint);
idMensalista.DataPropertyName = "IdMensalista";
idMensalista.HeaderText = "Mensalista";
idMensalista.Name = "colunaIdMensalista";
idMensalista.ValueMember = "Id"; // dataAdapter will use the Id field from Mensalistas table to run the update query but...
idMensalista.DisplayMember = "Nome"; // ...the combobox should display the names in the list, not the Ids, so this is needed
idMensalista.DataSource = bindingSourceMensalistas; // Fills the comboboxes with data from the mensalistas table (the one that holds personal data info)
dataGridViewRecibosMensalistas.Columns.Add(idMensalista);
DataGridViewMaskedTextColumn colunaDataEmissao = new DataGridViewMaskedTextColumn("00/00/0000");
colunaDataEmissao.DataPropertyName = "DataEmissao";
colunaDataEmissao.HeaderText = "Data de Emissão";
colunaDataEmissao.Name = "colunaDataEmissao";
dataGridViewRecibosMensalistas.Columns.Add(colunaDataEmissao);
dataGridViewRecibosMensalistas.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dataGridViewRecibosMensalistas.RowHeadersVisible = false;
dataGridViewRecibosMensalistas.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(dataGridViewRecibosMensalistas, true);
bindingSourceRecibosMensalistas = new BindingSource();
bindingSourceRecibosMensalistas.DataSource = dataTableRecibosMensalistas;
dataGridViewRecibosMensalistas.DataSource = bindingSourceRecibosMensalistas;
dataGridViewRecibosMensalistas.CellFormatting += dataGridView_CellFormatting;
SendMessage(dataGridViewMensalistas.Handle, WM_SETREDRAW, true, 0);
connection.Close();
}
And here is the code for the CellValidated event:
private void dataGridViewRecibosMensalistas_CellValidated(object sender, DataGridViewCellEventArgs e)
{
bindingSourceRecibosMensalistas.EndEdit();
if (!string.IsNullOrEmpty(dataGridViewRecibosMensalistas[(int)ColumnIndexRecibosMensalistas.COLUNA_ID, e.RowIndex].FormattedValue.ToString()))
{
try
{
dataAdapterRecibosMensalistas.Update((DataTable)bindingSourceRecibosMensalistas.DataSource);
}
catch (MySqlException ex)
{
DialogResult result = MessageBox.Show("Occoreu um erro de índice ao validar uma linha de dados.\nPara evitar que esse erro aconteça no futuro, procure preencher ao menos uma célula da linha (de prefeência, a primeira célula da linha).\n\nCaso o erro persista, contate o desenvolvedor do sistema. Erro: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (result == DialogResult.OK)
{
// Shitty function i use just to force a rebind in the datagridview in case anything goes wrong
UpdateDataGridViewOnRequest((int)DataGridViewIndex.DATAGRIDVIEW_RECIBOS_MENSALISTAS);
return;
}
}
catch (DBConcurrencyException ex)
{
string message = "Ocorreu um erro de concurrência de dados ao tentar salvar as suas mudanças na linha.\n\n";
message = message + "Erros de concurrência de dados ocorrem quando uma linha tenta ser alterada ao mesmo tempo por duas ou mais pessoas.\n\n";
message = message + "As prováveis causas para isso são:\n1) Algum outro usuário editou a linha antes das suas alterações serem salvas.\n2) Falha no banco de dados.\n\n";
message = message + "A tabela agora será atualizada contendo os valores atuais para a linha, caso o erro persista, contate o desenvolvedor do sistema.\n\n";
message = message + "Erro: " + ex.Message;
DialogResult result = MessageBox.Show(message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (result == DialogResult.OK)
{
UpdateDataGridViewOnRequest((int)DataGridViewIndex.DATAGRIDVIEW_RECIBOS_MENSALISTAS);
return;
}
}
}
}
Maybe i should try to either remove the FK or/and get the Mensalistas ID and Name fields to populate the combobox in the SELECT command in the code up there instead of using a different binding source?
Thanks in advance.