Break in Foreach after 3 rows - c#

I am trying to after each 3 loops in my foreach do a page break but can't seem to get it to trigger. Any help is welcome here is my code it prints fine but I'd like 3 GridView rows per page.
int i = 0;
// for each row in Gridview do this part of the PDF print
foreach (GridViewRow row in poGridview.Rows)
{
if ((i++) % 3 == 0)
{
pdfDoc.NewPage();
}
// Declare all values
String itemNum = row.Cells[0].Text;
String house = row.Cells[2].Text;
String staic = row.Cells[4].Text;
String description = row.Cells[1].Text.Replace("&", "");
String qtOrd = row.Cells[5].Text;
String serial = row.Cells[12].Text.Replace(" ", " ");
String dkQty = row.Cells[8].Text;
String stQty = row.Cells[9].Text;
String deptNum = row.Cells[11].Text.Replace(" ", " "); ;
String whBarCode = row.Cells[13].Text.Replace(" ", " ");
String turnA = row.Cells[19].Text;
String turnN = row.Cells[20].Text;
String turnC = row.Cells[21].Text;
String conversion = row.Cells[7].Text;
String unit = row.Cells[6].Text;
decimal ucorq = decimal.Parse(qtOrd) - decimal.Parse(stQty);
// Warehouse barcode
Barcode39 whlsc = new Barcode39();
whlsc.Code = whBarCode.Replace(" ", " ");
// Turn around barcode
Barcode39 turnAr = new Barcode39();
turnAr.Code = (poNum + "$I" + itemNum + "$M");
// Set up lines for paragraph
Paragraph itemLine1 = new Paragraph(#"" + itemNum + " " + house + " " + description, body);
Paragraph itemLine2 = new Paragraph(#" Status -> " + staic + " Ordered: " + qtOrd + " " + unit, body);
Paragraph itemLine3 = new Paragraph(#"STOCKING: " + stQty + " EA CONVERSION FACTOR: " + conversion + " ", body);
Paragraph itemLine4 = new Paragraph(#"Dock: " + dkQty + " Stock: " + stQty + " Open: " + ucorq.ToString(), body);
Paragraph itemLine5 = new Paragraph(#"Serial #: " + serial, body);
Paragraph itemLine6 = new Paragraph(#"VND CATALOG: " + serial + " ", body);
Paragraph itemLine7 = new Paragraph(#"JOB NUMBER: " + " DEFAULT STOCK LOC: ", body);
Paragraph itemLine8 = new Paragraph(#" ", body);
// Select command for the comments for each item
OleDbCommand comtSearch = new OleDbCommand("SELECT CAST(POCOMT.CMNT1 as char(40) ccsid 37) as cmt1, CAST(POCOMT.CMNT2 as char(40) ccsid 37) as cmt2 FROM POCOMT LEFT OUTER JOIN POITEM ON POITEM.ITNBR = POCOMT.ITNBR"
+ $" AND POITEM.ORDNO = POCOMT.ORDNO AND POITEM.HOUSE = POCOMT.HOUSE AND POITEM.LINSQ = POCOMT.LINSQ WHERE POCOMT.ITNBR = '{itemNum}' AND POCOMT.ORDNO = '{poNum}'", cn);
OleDbDataAdapter adp = new OleDbDataAdapter(comtSearch);
DataTable dt = new DataTable();
adp.Fill(dt);
commentGridview.DataSource = dt;
commentGridview.DataBind();
// Add Lines to page
p.Add(itemLine1);
p.Add(new Paragraph("\n"));
p.Add(new Paragraph("\n"));
p.Add(new Paragraph("\n"));
p.Add(new Chunk(turnAr.CreateImageWithBarcode(cb, null, null), 0, 0));
p.Add(new Paragraph("\n"));
p.Add(itemLine2);
p.Add(new Paragraph("\n"));
p.Add(itemLine3);
//p.Add(new Chunk(turnAr.CreateImageWithBarcode(cb, null, null), 0, 0));
p.Add(new Paragraph("\n"));
p.Add(itemLine4);
p.Add(new Paragraph("\n"));
//p.Add(itemLine5);
// loop through the comment fields on each item and print
foreach (GridViewRow cmtRow in commentGridview.Rows)
{
String cmnt1 = cmtRow.Cells[0].Text.Replace(" ", " "); ;
String cmnt2 = cmtRow.Cells[1].Text.Replace(" ", " "); ;
Paragraph cmt1 = new Paragraph(#"" + cmnt1, body);
Paragraph cmt2 = new Paragraph(#"" + cmnt2 + " ", body);
p.Add(cmt1);
p.Add(new Paragraph("\n"));
p.Add(cmt2);
}
p.Add(new Paragraph("\n"));
p.Add(itemLine6);
p.Add(new Paragraph("\n"));
p.Add(itemLine7);
p.Add(new Paragraph("\n"));
p.Add(itemLine8);
p.Add(new Chunk(whlsc.CreateImageWithBarcode(cb, null, null), 0, 0));
p.Add(new Paragraph("\n"));
p.Add(hr);
p.Add(new Paragraph("\n"));
}
p.Add(end);
p.Add(new Paragraph("\n"));
pdfDoc.Add(p);
pdfDoc.NewPage();
}
// Close Document
pdfDoc.Close();
Response.Write(pdfDoc);
Response.ContentType = "Application/pdf";
Response.End();

int i = 0; //initiate variable outside foreach loop
foreach (GridViewRow row in poGridview.Rows)
{
if (i == 3)
{
pdfDoc.NewPage();
i=0; //when i=3, resets to 0 and calls newPage method
}
i++; //+1 to i
}

You're setting i to zero at the beginning of every iteration of the loop. So, it never gets to 3. You probably want something like this:
int i = 0;
foreach( GridViewRow row in poGridview.Rows )
{
if( i % 3 == 0 && i > 0 )
{
pdfDoc.Add(p);
pdfDoc.NewPage();
p = <Create a new p>
}
i++;
}

int i = 0;
foreach(GridViewRow row in poGridview.Rows)
{
if ((i++) % 3 == 0)
{
pdfDoc.NewPage();
}
}

Related

Margin options in Pdf with Rotativa Mvc

I have been reading that to put or remove the margins of a PDF the following line is used:
PageMargins = new Rotativa.Core.Options.Margins(0,0,0,0)
But, when I enter them I get the following:
'ViewAsPDF' does not contain a definition for 'PageMargins'
Any solution?
This is the complete code:
return new ViewAsPdf("Pdf48", c.cargarDatosPDF(solicitud))
{
CustomSwitches = "--header-html " + _headerUrl + " --header-spacing 0 " +
"--footer-html " + _footerUrl + " --footer-spacing 0",
PageMargins = new Rotativa.Core.Options.Margins(0,0,0,0)
};
Solution:
return new PartialViewAsPdf("Pdf48", c.cargarDatosPDF(solicitud))
{
RotativaOptions = new Rotativa.Core.DriverOptions
{
CustomSwitches = "--header-html " + _headerUrl + " --header-spacing 0 " +
"--footer-html " + _footerUrl + " --footer-spacing 0",
PageMargins = new Rotativa.Core.Options.Margins(0, 0, 0, 0)
}
};
This should help.
var pdfdoc= new Rotativa.ViewAsPdf(){
PageHeight=30.00,
PageWidth=30.00,
PageMargins=new Rotativa.Options.Margins(0,0,0,0)
};

The process cannot access the file "XXX.txt" because it is being used by another process

I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.

How to add image on the top while exporting to excel in DataTable?

I have a report to export in excel. Everything is working fine but I cannot export the image MyImage.jpg ? How can I add the iamge to column so that the report looks like https://www.screencast.com/t/xxVdQjLmL5G. My only issue is that i cannot export the image. How Can I do this?
My Code in DataTable is :
public IActionResult WorkOrderExportToExcel([FromBody] WorkOrderViewModel model)
{
var uploadPath = string.Format("uploads\\" + CurrentUserDetails.SellerID + "\\Excel\\");
var targetDirectory = Path.Combine(_iconfiguration["BManageFolder"], uploadPath);
if (!Directory.Exists(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}
var filename = "workOrderReport" + DateTime.Now.ToShortDateString().Replace('/', '_') + ".xlsx";
var savePath = Path.Combine(targetDirectory, filename);
var loadURL = _iconfiguration["BManageUrl"] + uploadPath + filename;
DataTable MissingSingedDocumentList = ReportService.ExportWorkOrderExcel(model);
DataTable dtt = new DataTable();
dtt.Columns.Add("POSTING ORDER : INSTRUCTIONS & CONFIRMATION OF RECEIPT OF MATERIALS");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Columns.Add(" ");
dtt.Rows.Add("Date : " + DateTime.Now.ToShortDateString());
dtt.Rows.Add("From : " + model.Name);
dtt.Rows.Add("Email : " + model.Email);
dtt.Rows.Add("To : " + model.productionVendorOne + " " + model.productionVendorTwo);
dtt.Rows.Add("RE : " + model.JobName);
dtt.Rows.Add(" ");
dtt.Rows.Add("Market",/*,"Posting Date"*/model.OrderType + " Date","Unit #", "Media Owner", "Media Type", "Size", "Design", "Date Materials Received");
DataRow[] rows = MissingSingedDocumentList.Select();
foreach (DataRow dr in rows)
{
dtt.Rows.Add(dr.ItemArray);
}
dtt.Rows.Add("");
DataSet ds = new DataSet();
dtt.TableName = "Work Order Report";
ds.Tables.Add(dtt);
ExcelHelper.AppendMultipleSheetWhileDoingExportToExcel(ds, savePath);
return Ok(loadURL);
}
My AppendMultipleSheetWhileDoingExportToExcel function is
using (var workbook = SpreadsheetDocument.Create(Savepath, SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook();
workbook.WorkbookPart.Workbook.Sheets = new Sheets();
//declare our MergeCells here
MergeCells mergeCells = null;
foreach (DataRow dsrow in table.Rows)
{
int innerColIndex = 0;
rowIndex++;
Row newRow = new Row();
foreach (String col in columns)
{
Stylesheet stylesheet1 = new Stylesheet();
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString());
cell.CellReference = excelColumnNames[innerColIndex] + rowIndex.ToString();
if (table.TableName == "Work Order Report")
{
string cellNameWorkOrder = dsrow[col].ToString();
if (cellNameWorkOrder == "POSTER: 10% MUST HAVE APPROACH AND CLOSE-UP SHOTS - PHOTO OF EACH CREATIVE" || cellNameWorkOrder == "BULLETINS: 100% CLOSE-UP AND APPROACH OF EACH UNIT")
{
if (mergeCells == null)
mergeCells = new MergeCells();
var cellAddress = cell.CellReference;
var cellAddressTwo = "I" + rowIndex.ToString();
mergeCells.Append(new MergeCell() { Reference = new StringValue(cellAddress + ":" + cellAddressTwo) });
}
}
newRow.AppendChild(cell);
innerColIndex++;
}
sheetData.AppendChild(newRow);
}
//add the mergeCells to the worksheet if we have any
if (mergeCells != null)
sheetPart.Worksheet.InsertAfter(mergeCells, sheetPart.Worksheet.Elements<SheetData>().First());
}

Efficient method to increase "code" by 1 - HtmlAgilityPack

I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}

Html.ActionLink does not display new lines

I have this problem
string text = Html.Raw(immobileTmp.Localita + "\n" + immobileTmp.PrezzoVendita).ToString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
but then no new line is in output just <br /> between the 2 strings.
Then I tried
string text = Html.Raw(HttpUtility.HtmlEncode(immobileTmp.Localita + "\n" + immobileTmp.PrezzoVendita).Replace("\n", "<br/>")).ToHtmlString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
but had no better luck.
Any ideas?
I guess you need to insert two </ br>, did you tried that ?
UPDATE
Try Environment.NewLine, like that:
string text = Html.Raw(immobileTmp.Localita + Environment.NewLine + immobileTmp.PrezzoVendita).ToString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
Try this:
String s1 = (immobileTmp.Localita).ToString() + " ";
String s2 = (immobileTmp.PrezzoVendita).ToString();
String s = s1 + s2
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + s1.Length)) != -1) {
sb.replace(i, i + 1, "\n");
}
string text = Html.Raw(s);
If you join the strings with Environment.NewLine wrapping the tag in a <pre> splits the lines as you want, as in this sample:
#{
string sep = Environment.NewLine;
string text = Html.Raw(immobileTmp.Localita + sep + immobileTmp.PrezzoVendita).ToString();
}
<pre>
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
</pre>
Gotcha: the text will be formatted as monospaced (because of the <pre>) but CSS can take care of that (<pre class="blah">...).

Categories

Resources