Creating a PDF with itextsharp works fine in development but fails when deployed to IIS 7 - iis-7

I am deploying and testing an application using IIS 7. It creates a PDF using ITextSharp, which works fine when running from VS2010. When running from IIS, I get an error: The document has no pages.
Using the same data with the VS2010 development server, the PDF is printed OK. The error has nothing to do with a lack of pages.
The itextsharp.dll is included in the bin folder under the IIS Web Site.
What am I missing?
Here is my code (though I do not tjhink it is relevant);
protected void TextSharpMethod()
{
// get order details
#region getOrdersData
var ordersData = DataAccessLayer.OrdersDataHelpers.getOrderDataByOrderId(_intOrderId);
#endregion
if (ordersData != null)
{
#region getSupplierDetails
// get supplier details
var rowSupplier = (from s in _dataContextOrders.FMSSuppliers
where s.ID == ordersData.SupplierID
select new
{
s.ID,
s.CommonShortName,
s.ExternalRef,
s.Name,
s.Address,
s.SupplierDetail.Telephone,
s.SupplierDetail.WebAddress,
s.SupplierDetail.Email,
s.SupplierDetail.Fax
}).FirstOrDefault();
#endregion
#region getOrderLineData
var orderLineData = (from ol in _dataContextOrders.OrderLines
join o in _dataContextOrders.Orders on ol.OrderID equals o.ID
join ec in _dataContextOrders.FMSExpenseCodes on ol.OrderLineExpenseCodeID equals ec.ID into group1
from g1 in group1.DefaultIfEmpty()
join cc in _dataContextOrders.FMSCostCentres on ol.OrderLineCostCentreID equals cc.ID into group2
from g2 in group2.DefaultIfEmpty()
select new
{
ol.ID,
ol.OrderID,
ol.OrderLineNumber,
ol.OrderLineQty,
ol.OrderLineDescription,
ol.OrderLineUnitCost,
ol.OrderLineUnitTax,
ol.OrderLineTotal,
ol.OrderLineExpenseCodeID,
ol.GoodsReceivedQty,
ol.InvoicedQty,
ol.OrderLineCostCentreID,
ol.OrderLineVatRate,
ol.OrderLineUnitGross,
ExpenseCode = g1.ExternalRef == null ? "" : g1.ExternalRef,
CostCodeRef = g2.ExternalRef == null ? "" : g2.ExternalRef
}).Where(ol => ol.OrderID == _intOrderId).OrderBy(ol => ol.OrderLineNumber);
#endregion
using (MemoryStream ms = new MemoryStream())
using (Document document = new Document(PageSize.A4, 25, 25, 30, 30))
using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
{
document.AddCreator("SVSIT");
document.AddTitle("PURCHASE ORDER");
document.Open();
#region setupPdfDoc
// LOGO
string path = Server.MapPath("/");
string imageLocation = path + "/Images/southView_integration_logo_applications.jpg";
imageLocation = imageLocation.Replace("\\", "/");
iTextSharp.text.Image bmp =
iTextSharp.text.Image.GetInstance(imageLocation);
// caution - image may not work if app is moved
bmp.Alignment = Element.ALIGN_LEFT;
bmp.ScalePercent(50f);
document.Add(bmp);
// COMPANY ADDRESS
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
//actual width of table in points (A4=595points)
table.TotalWidth = 550f;
table.LockedWidth = true;
float[] widths = new float[] {2.75f, 2.75f};
table.SetWidths(widths);
// 0=no border, 1=border
table.DefaultCell.BorderWidth = 0;
PdfBlankCell(table);
PdfAddTableCell(table, "PURCHASE ORDER", _bold);
PdfBlankCell(table);
float flXPos = 842; // 842 - height of A4 in points
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// CONTACT PERSON
table = new PdfPTable(4);
//actual width of table in points (A4=595points)
table.TotalWidth = 550f;
table.LockedWidth = true;
widths = new float[] {1f, 1.75f, 1.35f, 1.35f};
table.SetWidths(widths);
// 0=no border, 1=border
table.DefaultCell.BorderWidth = 0;
PdfAddTableCell(table, "Contact Person", _norm);
PdfAddTableCell(table, ordersData.OrderContactName, _norm);
PdfAddTableCell(table, "Tel: " + ordersData.OrderContactTel, _norm);
PdfAddTableCell(table, "Fax: " + ordersData.OrderContactFax, _norm);
flXPos = 715;
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// SUPPLIER DETAILS
table = new PdfPTable(1);
table.TotalWidth = 270f;
table.LockedWidth = true;
table.DefaultCell.BorderWidth = 1; // has border
PdfAddTableCell(table, "To (Supplier)", _bold);
table.AddCell(ordersData.SupplierName);
if (rowSupplier != null)
{
table.AddCell(rowSupplier.Address); // might want to break this up by line breaks
}
else
{
table.AddCell(" ");
}
flXPos = 695;
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// ORDER NO
table = new PdfPTable(1);
table.TotalWidth = 275f;
table.LockedWidth = true;
table.DefaultCell.BorderWidth = 0;
table.DefaultCell.BorderWidthTop = 1;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
PdfAddTableCell(table, "Order No: " + ordersData.PORef + " / 100630", _bold);
table.DefaultCell.BorderWidthTop = 0;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
PdfAddTableCell(table, " ", _bold);
PdfBlankCell(table);
PdfAddTableCell(table, "Date: " + ordersData.CreatedDate.ToShortDateString (), _bold);
PdfAddTableCell(table, "Your ref: " + ordersData.OtherRef, _bold);
PdfAddTableCell(table, " ", _bold);
PdfAddTableCell(table, "PURCHASE ORDER NUMBER MUST BE", _bold);
table.DefaultCell.BorderWidthTop = 0;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
table.DefaultCell.BorderWidthBottom = 1;
PdfAddTableCell(table, "QUOTED ON INVOICE TO ENSURE PAYMENT", _bold);
table.WriteSelectedRows(0, -1, document.Left + 275, flXPos, writer.DirectContent);
flXPos = 595;
// DELIVERY ADDRESS
table = new PdfPTable(1);
table.TotalWidth = 270f;
table.LockedWidth = true;
table.DefaultCell.BorderWidth = 1; // has border
PdfAddTableCell(table, "Delivery Address:", _bold);
table.AddCell(ordersData.DeliveryContactName);
table.AddCell(ordersData.DeliveryAddress);
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// INVOICE ADDRESS
table = new PdfPTable(1);
table.TotalWidth = 275f;
table.LockedWidth = true;
table.DefaultCell.BorderWidth = 0;
table.DefaultCell.BorderWidthTop = 1;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
PdfAddTableCell(table, "Invoice Address:", _bold);
table.DefaultCell.BorderWidthTop = 0;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
PdfAddTableCell(table, " CVCHA", _norm);
PdfAddTableCell(table, " 11 High Street", _norm);
PdfAddTableCell(table, " Castle Vale", _norm);
PdfAddTableCell(table, " Birmingham", _norm);
table.DefaultCell.BorderWidthTop = 0;
table.DefaultCell.BorderWidthLeft = 1;
table.DefaultCell.BorderWidthRight = 1;
table.DefaultCell.BorderWidthBottom = 1;
PdfAddTableCell(table, " B35 7PR", _norm);
table.WriteSelectedRows(0, -1, document.Left + 275, flXPos, writer.DirectContent);
// ORDER LINES
table = new PdfPTable(5);
table.TotalWidth = 550f;
table.LockedWidth = true;
widths = new float[] {2.70f, .7f, .7f, .7f, .7f};
table.SetWidths(widths);
table.DefaultCell.BorderWidth = 1;
PdfAddTableCell(table, "Description", _bold);
PdfAddTableCell(table, "Code", _bold);
PdfAddTableCell(table, "Quantity", _bold);
PdfAddTableCell(table, "Unit Cost", _bold);
PdfAddTableCell(table, "Total Cost", _bold);
// 13 rows
// get order lines data
int i1 = 0;
foreach (var orderLine in orderLineData)
{
if (orderLine != null)
{
PdfAddTableCell(table, orderLine.OrderLineDescription, _norm);
PdfAddTableCell(table, orderLine .CostCodeRef +", " + orderLine.ExpenseCode , _norm); // code - to do
PdfAlignRightTableCell(table, orderLine.OrderLineQty.ToString(), _norm);
PdfAlignRightTableCell (table, orderLine.OrderLineUnitCost.ToString(), _norm);
PdfAlignRightTableCell(table, orderLine.OrderLineTotal.ToString(), _norm);
i1++;
}
}
// fill remaining grid
for (int i = i1; i <= 13; i++)
{
PdfAddTableCell(table, " ", _norm);
PdfAddTableCell(table, " ", _norm);
PdfAddTableCell(table, " ", _norm);
PdfAddTableCell(table, " ", _norm);
PdfAddTableCell(table, " ", _norm);
}
// DELIVERY DATE / TOTAL LINE
PdfAddTableCell(table, "Required Delivery Date: " + ordersData.ExpectedDeliveryDate, _bold);
_chunk = new Chunk("Total: £", _bold );
cell = new PdfPCell(new Phrase(_chunk));
cell.Colspan = 3;
table.DefaultCell.BorderWidth = 1;
table.AddCell(cell);
_chunk = new Chunk(ordersData.TotalAmount.ToString("0.00"), _bold);
cell = new PdfPCell(new Phrase(_chunk));
cell.Colspan = 1;
table.DefaultCell.VerticalAlignment = Element.ALIGN_RIGHT;
table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.AddCell(cell);
flXPos = 490;
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// PREPARED BY / AUTHORISED BY
table = new PdfPTable(3);
table.TotalWidth = 550f;
table.LockedWidth = true;
widths = new float[] {1.83f, 1.83f, 1.83f};
table.SetWidths(widths);
table.DefaultCell.BorderWidth = 1;
PdfAddTableCell(table, "Prepared By:" + "", _bold);
PdfAddTableCell(table, "Signature:" + "", _bold);
PdfAddTableCell(table, "Date:" + "", _bold);
PdfAddTableCell(table, "Authorised By:" + "", _bold); // ApproverPersonID
PdfAddTableCell(table, "Signature:" + "", _bold);
PdfAddTableCell(table, "Date:" + "", _bold);
flXPos = 195;
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
// FOOTER
table = new PdfPTable(1);
table.TotalWidth = 550f;
table.LockedWidth = true;
table.DefaultCell.BorderWidth = 0;
PdfAddTableCell(table, "Distibution of Copies", _norm);
PdfAddTableCell(table,
"1. White - Supplier 2. Yellow - Finance Section 3. Pink - Originator (Budget Holder)",
_norm);
PdfAddTableCell(table, "Industrial & Provident Society No. 28414R Housing Corporation No. L4118",
_norm);
flXPos = 95;
table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent);
#endregion
document.Close();
writer.Close();
#region writeToDatabase
MemoryStream ms2 = new MemoryStream(ms.ToArray());
WritePdfToDatabase(ms2);
#endregion
Response.ContentType = "pdf/application";
Response.AddHeader("content-disposition", "attachment;filename=PurchaseOrder.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
}
}
protected void WritePdfToDatabase(MemoryStream ms2)
{
BinaryReader br = new BinaryReader(ms2);
Byte[] bytes = br.ReadBytes((Int32)ms2.Length);
br.Close();
DocumentsDataHelper.UpdateDocument(bytes, "pdf/application", "Purchase Order",_intOrderId ,1);
}
protected void PdfBlankCell(PdfPTable table)
{
_chunk = new Chunk("", _norm);
_phrase = new Phrase(_chunk);
table.AddCell(_phrase);
}
protected void PdfAddTableCell(PdfPTable table, string s, Font f)
{
_chunk = new Chunk(s, f);
_phrase = new Phrase(_chunk);
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(_phrase);
}
protected void PdfAlignRightTableCell(PdfPTable table, string s, Font f)
{
_chunk = new Chunk(s, f);
_phrase = new Phrase(_chunk);
table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.AddCell(_phrase);
}
protected void PdfTableFieldAndHeader(string heading, string value, PdfPTable table)
{
PdfAddTableCell(table, heading, _bold);
PdfAddTableCell(table, value, _norm);
}
protected void PdfBoldAndNormLine(string text1, string text2, Document document)
{
Chunk c1 = new Chunk(text1, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD));
Chunk c2 = new Chunk(text2, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.NORMAL));
Phrase p1 = new Phrase();
p1.Add(c1);
p1.Add(c2);
Paragraph p = new Paragraph();
p.Add(p1);
p.Alignment = Element.ALIGN_LEFT;
document.Add(p);
}

Related

while export to pdf using itexsharp it shows blank page

i made one desktop application using asp.net which convert html to PDF.
basically this application used for generate users PDF from database.
process: first of all i am converting all data to html and then convert to PDF using itextsharp but after generating some PDFs it shows blank pages
any idea or anyone face this type of issue
public static void converttopdf(string HtmlStream, List<Tuple<string, string>> tifffiles, List<Tuple<string, string>> pdffilestomerge, string filename, string patientfirstpagestr, string TableofContent, string patientheader, SqlConnection con, string sectiondetails)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlStream);
Document document = new Document(PageSize.A4, 30, 30, 42, 44);
string filetogenerate = string.Empty;
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
filetogenerate = temppath + filename + "_Temp1.pdf";
}
else
{
filetogenerate = temppath + filename + "_Temp.pdf";
}
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(filetogenerate, System.IO.FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
string[] separator = new string[] { #"<br clear='all' style='page-break-before:always'>" };
string[] pages = HtmlStream.Split(separator, StringSplitOptions.None);
foreach (string page in pages)
{
document.NewPage();
System.Collections.ArrayList htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
}
using (var ms = new MemoryStream())
{
if (tifffiles != null)
{
int docid = 0;
foreach (var obj in tifffiles)
{
string filepath = obj.Item2.ToString();
WriteLogEntry("bitmap file path : " + filepath);
if (filepath != string.Empty)
{
try
{
Bitmap myBitmap = new Bitmap(filepath);
System.Drawing.Color pixelColor = myBitmap.GetPixel(50, 50);
if (pixelColor.Name == "ff808080")
{
WriteLogEntry("convert image by irfanview :" + filepath);
LaunchCommandLineApp(filepath, temppath + "Test.jpg");
document.NewPage();
var imgStream = GetImageStream(temppath + "Test.jpg");
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
File.Delete(temppath + "Test.jpg");
}
else
{
document.NewPage();
var imgStream = GetImageStream(filepath);
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
WriteLogEntry("Image added successfully" + filepath);
}
}
catch
{
document.NewPage();
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
WriteLogEntry("Image not valid" + filepath);
}
docid = Convert.ToInt32(obj.Item1);
}
}
}
}
worker.EndDocument();
worker.Close();
document.Close();
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
string file = temppath + filename + "_Temp.pdf";
mergepdf(file, pdffilestomerge, filetogenerate);
}
PdfReader pdfreader = new PdfReader(temppath + filename + "_Temp.pdf");
Document document1 = new Document(PageSize.A4, 30, 30, 42, 44);
PdfWriter writer1 = PdfWriter.GetInstance(document1, new FileStream(FinalOutputPath + filename + ".pdf", FileMode.Create));
//HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
//footer.Alignment = Element.ALIGN_RIGHT;
//footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Footer = footer;
//HeaderFooter header = new HeaderFooter(new Phrase(""), true);
//header.Alignment = Element.ALIGN_LEFT;
//header.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Add(header);
document1.Open();
PdfContentByte cb1 = writer1.DirectContent;
PdfImportedPage page1;
string test1 = TableofContent; int TableofContentPageCount = 0; int SectionPageStartNumber = 0;
string lastdocnamestr = "";
for (int t = 1; t <= pdfreader.NumberOfPages; t++)
{
document1.NewPage();
HeaderFooter header = new HeaderFooter(new Phrase(""), true);
header.Alignment = Element.ALIGN_LEFT;
header.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header1 = new HeaderFooter(new Phrase(" "), true);
header1.Alignment = Element.ALIGN_LEFT;
header1.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header2 = new HeaderFooter(new Phrase(" "), true);
header2.Alignment = Element.ALIGN_LEFT;
header2.Border = iTextSharp.text.Rectangle.NO_BORDER;
document1.Add(header);
document1.Add(header1);
document1.Add(header2);
page1 = writer1.GetImportedPage(pdfreader, t);
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
byte[] pdfcontent = pdfreader.GetPageContent(t);
//PdfDictionary dict = pdfreader.GetPageN(t);
string contentStream = System.Text.Encoding.Default.GetString(pdfcontent);
var contentByte = writer1.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 8);
var multiLineString = "";
var multiLineString1 = "";
string test = getBetween(contentStream, "#~#", "#~#");
if (test.Length > 0)
{
test1 = test1.Replace(test + ".", t.ToString());
DataTable dt = getdocdetailforheader(Convert.ToInt32(test.Replace("DID", "")), con);
if (dt.Rows.Count > 0)
{
multiLineString = dt.Rows[0]["DocumentName"].ToString() + " - " + Convert.ToDateTime(dt.Rows[0]["EncounterDTTM"].ToString()).ToString("MM/dd/yyyy") + " | Owner : " + dt.Rows[0]["Ownername"].ToString();
lastdocnamestr = multiLineString;
WriteLogEntry(multiLineString);
}
if (TableofContentPageCount == 0)
{
TableofContentPageCount = t;
}
}
//if (contentStream.Contains("sectionstart") && SectionPageStartNumber == 0) SectionPageStartNumber = t;
if (lastdocnamestr != string.Empty)
{
multiLineString = lastdocnamestr;
}
//else
//{
// if (TableofContentPageCount == 0)
// {
// multiLineString = "Table of Content";
// }
//}
multiLineString1 = patientheader;
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString, 15, 820, 0);
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString1, 15, 810, 0);
contentByte.EndText();
string relLogo = Directory.GetCurrentDirectory().ToString().Replace("bin", "").Replace("Debug", "").Replace("\\\\", "") + "\\Image\\MFA_LOGO.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(relLogo);
jpg.ScaleAbsolute(38f, 38f);
jpg.SetAbsolutePosition(document1.PageSize.Width - 70, 806);
jpg.Alignment = Element.ALIGN_RIGHT;
document1.Add(jpg);
cb1.MoveTo(0, 805);
cb1.LineTo(document1.PageSize.Width, 805);
cb1.Stroke();
cb1.AddTemplate(page1, 0, 0);
}
SectionPageStartNumber = pdfreader.NumberOfPages + 1;
System.Collections.ArrayList htmlarraylist1 = HTMLWorker.ParseToList(new StringReader(sectiondetails), null);
document1.NewPage();
for (int k = 0; k < htmlarraylist1.Count; k++)
{
document1.Add((IElement)htmlarraylist1[k]);
}
document1.Close();
FinalPDF(FinalOutputPath + filename + ".pdf", FinalOutputPath + filename + "_1.pdf", patientfirstpagestr, test1, TableofContentPageCount, patientheader, SectionPageStartNumber);
File.Delete(temppath + filename + "_Temp.pdf");

Issue while working in server asp.net web application

I have an web application name travel. Every thing is working fine while working in test database even if i connect it to live database it works fine in local server but not working in live server.for ex.. I have a grid view to show the details where i can insert,delete,update and view but its working fine in my local server but in live server, my file are updating for the first time but if i try to update for the second time its not working. I have no idea whats happening can any one help me in this.
travel.cs
protected void gv_food_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_food.ShowFooter = true;
gv_food.EditIndex = -1;
Loadgv_food();
}
protected void gv_food_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AddConfirmDelete((GridView)sender, e);
hdnAmtvalue.Value = Convert.ToString((e.Row.RowIndex + 1) + (gv_food.PageSize * gv_food.PageIndex));
hdnAmtvalue.Value = Convert.ToString(Convert.ToInt16(hdnAmtvalue.Value) + 3);
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList drp = (DropDownList)e.Row.FindControl("drpfood");
sqlq = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sqlq += "\n UNION";
sqlq += "\n select DESCRIPTION,regionid from regionmaster";
ds = db.fillDataset(sqlq);
drp.DataSource = ds.Tables[0];
drp.DataTextField = "description";
drp.DataValueField = "regionid";
drp.DataBind();
DropDownList drpC = (DropDownList)e.Row.FindControl("drp_currency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = 2;
Load_CurrencyRate();
DropDownList ddlcurrency = (DropDownList)e.Row.FindControl("drp_currency");
int foodamt = Convert.ToInt32(hdnAmtvalue.Value);
TextBox ticketamount = (TextBox)e.Row.FindControl("txtamount");
TextBox inrate = (TextBox)e.Row.FindControl("txt_inrrate");
TextBox dollarrate = (TextBox)e.Row.FindControl("txt_dollarrate");
TextBox inramount = (TextBox)e.Row.FindControl("txt_inramount");
TextBox dollaramount = (TextBox)e.Row.FindControl("txt_dollaramount");
TextBox txtdate = (TextBox)e.Row.FindControl("txtfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ticketamount.Attributes.Add("ontextchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ddlcurrency.Attributes.Add("onchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
//inrate.Text = hdnAdvInrRate.Value.ToString();
inrate.Text = hdnAdvUsdRate.Value.ToString();
dollarrate.Text = hdnAdvUsdRate.Value.ToString();
//ddlcurrency.SelectedIndex = ddlcurrency.Items.IndexOf(ddlcurrency.Items.FindByText(hdnAdvCurrency.Value));
drp.SelectedIndex = drp.Items.IndexOf(drp.Items.FindByText(hdnRegion.Value));
}
}
protected void gv_food_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
sql = "delete from tmpintfoodexpenses where detailid=" + gv_food.DataKeys[e.RowIndex].Values[0].ToString() + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully deleted');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully deleted";
}
protected void gv_food_RowEditing(object sender, GridViewEditEventArgs e)
{
lblFoodException.Text = string.Empty;
try
{
gv_food.ShowFooter = false;
gv_food.EditIndex = e.NewEditIndex;
Loadgv_food();
//changes made on 25/jan/2012
DropDownList drp1 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEhr1");
DropDownList drp2 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEmin1");
DropDownList drp3 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEahr1");
DropDownList drp4 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEamin1");
sql = "select ARRIVALTIME,DEPATURETIME from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
//ds1 = db.fillDataset(sql);
DataTable dt = new DataTable();
dt = db.fillTable(sql);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["DEPATURETIME"].ToString().Contains(":"))
{
string[] _dhhmm = dt.Rows[0]["DEPATURETIME"].ToString().Trim().Split(new char[] { ':' });
if (_dhhmm[0].Trim() != null)
{
drp1.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[0].ToString()));
drp2.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[1].ToString()));
}
if (dt.Rows[0]["ARRIVALTIME"].ToString().Contains(":"))
{
string[] _ahhmm = dt.Rows[0]["ARRIVALTIME"].ToString().Trim().Split(new char[] { ':' });
if (_ahhmm[0].Trim() != null)
{
drp3.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[0].ToString()));
drp4.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[1].ToString()));
}
}
}
}
//End
sql = "select currencydescription,foodorperdiems from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds1 = db.fillDataset(sql);
currflag = ds1.Tables[0].Rows[0].ItemArray[0].ToString();
DropDownList drp = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpefood");
sql = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sql += "\n UNION";
sql += "\n select description,regionid from regionmaster";
setDataSource(drp, sql);
DropDownList ddlFood = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("ddlFoodOrPerdiems");
ddlFood.SelectedValue = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Label lblregion = (Label)gv_food.Rows[e.NewEditIndex].FindControl("lblf");
lblregion.Visible = false;
drp.SelectedIndex = (drp.Items.IndexOf(drp.Items.FindByText(lblregion.Text.ToString())));
DropDownList drpC = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = drpC.Items.IndexOf(drpC.Items.FindByText(currflag));
indexrow = gv_food.Rows[e.NewEditIndex].RowIndex.ToString();
rowindex = int.Parse(indexrow);
rowindex = rowindex + 2;
DropDownList ddlcurrency = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
TextBox ticketamount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUamount");
TextBox inrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einrrate");
TextBox dollarrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollarrate");
TextBox inramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einramount");
TextBox dollaramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollaramount");
TextBox txtdate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ddlcurrency.Attributes.Add("onchange", "Calculatefoodedit(" + rowindex + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
}
catch (Exception ex)
{
}
}
protected void gv_food_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
indexrow = "";
rowindex = 0;
GridViewRow row1 = gv_food.Rows[e.RowIndex];
TextBox tfromdate = row1.FindControl("txtUfromdate") as TextBox;
TextBox ttodate = row1.FindControl("txtUtodate") as TextBox;
DropDownList ddlfood = (DropDownList)row1.FindControl("ddlFoodOrPerdiems");
DropDownList ddl = (DropDownList)row1.FindControl("drpefood");
TextBox txtdescription = row1.FindControl("txtUdescription") as TextBox;
TextBox txtreference = row1.FindControl("txtUreference") as TextBox;
TextBox tAmt = row1.FindControl("txtUAmount") as TextBox;
//DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
Label tid = row1.FindControl("lblEid") as Label;
DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
DropDownList eddl_curr = (DropDownList)row1.FindControl("drp_ecurrency");
TextBox edcurrentrate = (TextBox)row1.FindControl("txt_edollarrate");
TextBox edamount = (TextBox)row1.FindControl("txt_edollaramount");
TextBox eicurrentrate = (TextBox)row1.FindControl("txt_einrrate");
TextBox eiamount = (TextBox)row1.FindControl("txt_einramount");
//changes made on 25/jan/2012
TextBox txtENoOfDays = row1.FindControl("txtENoOfDays") as TextBox;
DropDownList drpEhr1 = row1.FindControl("drpEhr1") as DropDownList;
DropDownList drpEmin1 = row1.FindControl("drpEmin1") as DropDownList;
DropDownList drpEahr1 = row1.FindControl("drpEahr1") as DropDownList;
DropDownList drpEamin1 = row1.FindControl("drpEamin1") as DropDownList;
//End
if (tfromdate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the From Date');</script>");
lblFoodException.Text = "* Enter the From Date";
tfromdate.Focus();
return;
}
//changes made on 25/jan/2012
if (drpEhr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Hours.";
drpEhr1.Focus();
return;
}
if (drpEmin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Minute.";
drpEmin1.Focus();
return;
}
//End
if (ttodate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the To Date');</script>");
lblFoodException.Text = "* Enter the To Date";
ttodate.Focus();
return;
}
if (drpEahr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Hours.";
drpEahr1.Focus();
return;
}
if (drpEamin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Minue.";
drpEahr1.Focus();
return;
}
//End
if (ddlfood.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the Food or Perdiems');</script>");
lblFoodException.Text = "* Select the Food or Perdiems";
ddl.Focus();
return;
}
if (ddl.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the region');</script>");
lblFoodException.Text = "* Select the region";
ddl.Focus();
return;
}
if (txtdescription.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Description');</script>");
lblFoodException.Text = "* Enter the Description";
txtdescription.Focus();
return;
}
if (txtreference.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Reference');</script>");
lblFoodException.Text = "* Enter the Reference";
txtreference.Focus();
return;
}
if (eddl_curr.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Currencyid');</script>");
lblFoodException.Text = "* Successfully Updated";
eddl_curr.Focus();
return;
}
if (edcurrentrate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edcurrentrate.Focus();
return;
}
if (edamount.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edamount.Focus();
return;
}
if (eicurrentrate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eicurrentrate.Focus();
return;
}
if (eiamount.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eiamount.Focus();
return;
}
//changes made on 25/jan/2012
if (Convert.ToInt32(drpEhr1.SelectedItem.Text) >= 12)
{
Ehh = "PM";
}
else
{
Ehh = "AM";
}
if (Convert.ToInt32(drpEahr1.SelectedItem.Text) >= 12)
{
Emm = "PM";
}
else
{
Emm = "AM";
}
DateTime t1 = Convert.ToDateTime(tfromdate.Text.ToString() + " " + drpEhr1.SelectedItem.Text.ToLower() + ":" + drpEmin1.SelectedItem.Text.ToString() + " " + Ehh);
DateTime t2 = Convert.ToDateTime(ttodate.Text.ToString() + " " + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + " " + Emm);
tp1 = t2.Subtract(t1);
string[] EgetInfo = Convert.ToString(tp1).Split(new char[] { '.' });
if (EgetInfo.Length > 1) // Day calculating
{
Enodays = EgetInfo[0];
string[] EgetHours = EgetInfo[1].ToString().Split(new char[] { ':' });
if (Convert.ToInt32(EgetHours[0].ToString()) >= 6 && Convert.ToInt32(EgetHours[0].ToString()) < 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 0.50;
}
else if (Convert.ToInt32(EgetHours[0].ToString()) >= 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 1;
}
else
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString());
}
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " PM";
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " AM";
}
else//Hours Calculating
{
string[] EgetHours = EgetInfo[0].ToString().Split(new char[] { ':' });
Enodays = "0";
hh = EgetHours[0];
mm = EgetHours[1];
if (Convert.ToInt32(hh.ToString()) >= 6 && Convert.ToInt32(hh.ToString()) < 12)
{
EtotalDays = 0.50;
}
else if (Convert.ToInt32(hh.ToString()) >= 12)
{
EtotalDays = 1;
}
if (Convert.ToInt32(hh.ToString().Length) > 12)
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " PM";
}
else
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " AM";
}
}
txtENoOfDays.Text = Convert.ToString(EtotalDays);
//End
sqlq = "select min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds3 = db.fillDataset(sqlq);
if (ds3.Tables[0].Rows.Count > 0)
{
fromdate = ds3.Tables[0].Rows[0].ItemArray[0].ToString();
todate = ds3.Tables[0].Rows[0].ItemArray[1].ToString();
}
string from = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
string to = Convert.ToDateTime(ttodate.Text).ToString("dd/MMM/yyyy");
//string date = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
bool x = ((Convert.ToDateTime(from) >= Convert.ToDateTime(fromdate)) && (Convert.ToDateTime(to) <= Convert.ToDateTime(todate)));
if (x == false)
{
//ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('Date should be between departure date and arrival date '); </script>");
lblFoodException.Text = "* Date should be between departure date and arrival date";
tfromdate.Text = "";
return;
}
bool y = (Convert.ToDateTime(from) <= Convert.ToDateTime(todate));
if (y == false)
{
// ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('invalid date '); </script>");
tfromdate.Text = "";
lblFoodException.Text = "Invalid Date";
return;
}
int curr8 = 1;
//Poovaragavan P changes made on 25/jan/2012
sqlq = "select min(DEPATURETIME),max(ARRIVALTIME),min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds5 = db.fillDataset(sqlq);
if (ds5.Tables[0].Rows.Count > 0)
{
EDepTime = ds5.Tables[0].Rows[0].ItemArray[0].ToString();
EArrTime = ds5.Tables[0].Rows[0].ItemArray[1].ToString();
EDepDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[2].ToString()).ToString("dd/MM/yyy");
EArrDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[3].ToString()).ToString("dd/MM/yyyy");
}
if (EDepDate == Convert.ToDateTime(from.ToString()).ToString("dd/MM/yyyy") && EArrDate.ToString() == Convert.ToDateTime(to.ToString()).ToString("dd/MM/yyy"))
{
if ((EDepTime != drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString()) || (EArrTime != drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString()))
{
lblFoodException.Text = "Time should be Equal to departure Time and arrival Time";
lblFoodException.ForeColor = System.Drawing.Color.Red;
drpEhr1.SelectedIndex = 0;
drpEmin1.SelectedIndex = 0;
drpEahr1.SelectedIndex = 0;
drpEamin1.SelectedIndex = 0;
drpEhr1.Focus();
return;
}
}
//End
sql = " Update tmpintfoodexpenses set Expensedate=to_Date('" + tfromdate.Text + "','dd/mon/yyyy'),";
sql += " Expensetodate=to_Date('" + ttodate.Text + "','dd/mon/yyyy'),";
sql += " FOODORPERDIEMS='" + ddlfood.SelectedItem.Value.ToString() + "',";
sql += " region=" + ddl.SelectedItem.Value.ToString() + ",";
sql += " DESCRIPTION='" + mod.checkforapostrophe(txtdescription.Text) + "',";
sql += " REFERENCE='" + mod.checkforapostrophe(txtreference.Text) + "',";
sql += " amount=" + mod.checkforapostrophe(tAmt.Text) + ",";
sql += " Currencyid=" + eddl_curr.SelectedItem.Value + ",";
sql += " currencydescription='" + mod.checkforapostrophe(eddl_curr.SelectedItem.Text) + "',";
sql += " dollarcurrentrate=" + mod.checkforapostrophe(edcurrentrate.Text) + ",";
sql += " dollaramount=" + mod.checkforapostrophe(edamount.Text) + ",";
sql += " inrcurrentrate=" + mod.checkforapostrophe(eicurrentrate.Text) + ",";
sql += " inramount=" + mod.checkforapostrophe(eiamount.Text) + ",";
//Poovaragavan P changes made on 25/jan/2012
sql += " NOOFDAYS='" + mod.checkforapostrophe(txtENoOfDays.Text) + "',";
sql += " ARRIVALTIME='" + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + "',";
sql += " DEPATURETIME='" + drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString() + "',";
sql += " TOTALTIME='" + EtotTime.ToString() + "'";
//End
sql += " where detailid =" + mod.checkforapostrophe(tid.Text) + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_halting();
Loadgv_ticket();
Loadgv_local();
Loadgv_other();
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully Updated');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully Updated";
}

import excel file to database using EPPlus

I am having a hard time understanding what should be a simple task. I am now using EPPlus to help me with this task. However, I am at a point of where I can't track what is going on. (per the comment below and days of google searching) I'm trying to read in an excel file and pass that to my EF model. It breaks down at line 159 where I am trying to put in the values from the excel file but keeps coming across as null. However when looking at the values past line 159 they all have the correct information. I am not sure how to even track a bug like this.
TruckController.cs
// POST: Trucks/Import
[HttpPost]
public ActionResult Import(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["file"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
file.SaveAs(Server.MapPath("~/" + "test.xlsx"));
//string fileName = file.FileName;
// string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
// var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
var MyImport = new List<string>();
MyImport = ImportDataRecords(new FileInfo(Server.MapPath("~/" ) + "test.xlsx"));
}
}
return View("Import");
}
public List<string> ImportDataRecords(FileInfo file)
{
var resultMessages = new List<string>();
var totalImported = 0;
try
{
using (var excelPackage = new ExcelPackage(file))
{
string DeliveryColumn,
ItemNoColumn,
MaterialColumn,
MaterialDescriptionColumn,
DeliveryQtytoPickColumn,
PickedQuantityColumn,
SalesUoMColumn,
BatchPickedColumn,
BinNoColumn,
BagWeightColumn,
PalletNoColumn,
PalletStackingNoColumn,
StageNoColumn,
SubStopNoColumn,
PickStatusColumn,
PackStatusColumn,
SoldToColumn,
SoldToNameColumn,
ShipToNameColumn;
if (!file.Name.EndsWith("xlsx"))
{
resultMessages.Add("File selected is not an Excel file");
return resultMessages;
}
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null)
{
resultMessages.Add("File was empty");
return resultMessages;
}
using (var headers = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
var expectedHeaders = new[]
{
"Delivery", "Item No.", "Material", "Material Description", "Delivery Qty to Pick",
"Picked Quantity", "Sales UoM", "Batch Picked", "BIN No.", "Bag Weight", "Pallet No.",
"Pallet Stacking No", "Stage No", "Sub Stop No", "Pick Status", "Pack Status", "Sold-To",
"Sold-To Name", "Ship-To Name"
};
if (!expectedHeaders.All(e => headers.Any(h => h.Value.Equals(e))))
{
resultMessages.Add("Some columns are missing from the file");
return resultMessages;
}
DeliveryColumn = headers.First(h => h.Value.Equals("Delivery")).Address[0].ToString();
ItemNoColumn = headers.First(h => h.Value.Equals("Item No.")).Address[0].ToString();
MaterialColumn = headers.First(h => h.Value.Equals("Material")).Address[0].ToString();
MaterialDescriptionColumn = headers.First(h => h.Value.Equals("Material Description")).Address[0].ToString();
DeliveryQtytoPickColumn = headers.First(h => h.Value.Equals("Delivery Qty to Pick")).Address[0].ToString();
PickedQuantityColumn = headers.First(h => h.Value.Equals("Picked Quantity")).Address[0].ToString();
SalesUoMColumn = headers.First(h => h.Value.Equals("Sales UoM")).Address[0].ToString();
BatchPickedColumn = headers.First(h => h.Value.Equals("Batch Picked")).Address[0].ToString();
BinNoColumn = headers.First(h => h.Value.Equals("BIN No.")).Address[0].ToString();
BagWeightColumn = headers.First(h => h.Value.Equals("Bag Weight")).Address[0].ToString();
PalletNoColumn = headers.First(h => h.Value.Equals("Pallet No.")).Address[0].ToString();
PalletStackingNoColumn = headers.First(h => h.Value.Equals("Pallet Stacking No")).Address[0].ToString();
StageNoColumn = headers.First(h => h.Value.Equals("Stage No")).Address[0].ToString();
SubStopNoColumn = headers.First(h => h.Value.Equals("Sub Stop No")).Address[0].ToString();
PickStatusColumn = headers.First(h => h.Value.Equals("Pick Status")).Address[0].ToString();
PackStatusColumn = headers.First(h => h.Value.Equals("Pack Status")).Address[0].ToString();
SoldToColumn = headers.First(h => h.Value.Equals("Sold-To")).Address[0].ToString();
SoldToNameColumn = headers.First(h => h.Value.Equals("Sold-To Name")).Address[0].ToString();
ShipToNameColumn = headers.First(h => h.Value.Equals("Ship-To Name")).Address[0].ToString();
using (var context = new EPPlusTruckContext())
{
var lastRow = worksheet.Dimension.End.Row;
for (var row = 2; row <= lastRow; row++)
{
-----------Line 159-------------> var truck = new Truck()
{
Delivery = worksheet.Cells[DeliveryColumn + row].Value.ToString(),
ItemNo = worksheet.Cells[ItemNoColumn + row].Value.ToString(),
Material = worksheet.Cells[MaterialColumn + row].Value.ToString(),
MaterialDescription = worksheet.Cells[MaterialDescriptionColumn + row].Value.ToString(),
DeliveryQtyToPick = worksheet.Cells[DeliveryQtytoPickColumn + row].Value.ToString(),
PickedQuantity = worksheet.Cells[PickedQuantityColumn + row].Value.ToString(),
SalesUoM = worksheet.Cells[SalesUoMColumn + row].Value.ToString(),
BatchPicked = worksheet.Cells[BatchPickedColumn + row].Value.ToString(),
BinNo = worksheet.Cells[BinNoColumn + row].Value.ToString(),
BagWeight = worksheet.Cells[BagWeightColumn + row].Value.ToString(),
PalletNo = worksheet.Cells[PalletNoColumn + row].Value.ToString(),
PalletStackingNo = worksheet.Cells[PalletStackingNoColumn + row].Value.ToString(),
StageNo = worksheet.Cells[StageNoColumn + row].Value.ToString(),
SubStopNo = worksheet.Cells[SubStopNoColumn + row].Value.ToString(),
PickStatus = worksheet.Cells[PickStatusColumn + row].Value.ToString(),
PackStatus = worksheet.Cells[PackStatusColumn + row].Value.ToString(),
SoldTo = worksheet.Cells[SoldToColumn + row].Value.ToString(),
SoldToName = worksheet.Cells[SoldToNameColumn + row].Value.ToString(),
ShipToName = worksheet.Cells[ShipToNameColumn + row].Value.ToString(),
};
db.Trucks.Add(truck);
try
{
db.SaveChanges();
totalImported++;
}
catch (Exception ex)
{
resultMessages.Add(string.Format("Record on line#{0} failed: {1}\n", row, ex.Message));
}
}
}
}
resultMessages.Insert(0, string.Format("{0} records successfully imported.\n", totalImported));
return resultMessages;
}
}
catch (IOException ex)
{
resultMessages.Add("File still open. Please close Excel file before importing.");
return resultMessages;
}
}
A simple example here:
Reff: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}

Adding eventHandler in each label from the code behind for Pager numbers

My page structure is like this:
<div style="BORDER-BOTTOM: black 1px solid; BORDER-LEFT: black 1px solid; OVERFLOW-Y: auto; WIDTH: 100%; ; HEIGHT: expression(document.body.clientHeight-270); BORDER-TOP: black 1px solid; BORDER-RIGHT: black 1px solid"id="divGrid">
<asp:datalist id="dlResults" runat="server" Width="100%" CellSpacing="0" CellPadding="0" RepeatDirection="Vertical">
...
</asp:datalist>
</div>
<table class="bodytext8pt" border="0" width="100%">
<tr>
<td><asp:panel id="pnlPager" Runat="server" CssClass="GridFooter"></asp:panel></td>
</tr>
</table>
In the code behind pager is build by the BuildPager function:
private void BuildPager(DataTable dt)
{
pnlPager.Controls.Clear();
Label l = new Label();
l.Text = " (" + pgResults.PageCount.ToString("#,##0") + " pages, " + dt.Rows.Count.ToString("#,##0") + " records ) ";
pnlPager.Controls.Add(l);
for (int i = 0; i < pnlPager.Controls.Count; i++)
{
if (pnlPager.Controls[i].ToString() == "System.Web.UI.WebControls.DataGridLinkButton")
{
try
{
LinkButton c = (LinkButton) pnlPager.Controls[i];
c.CssClass = "GridFooter";
}
catch (Exception ex) { }
}
}
pnlPager.Attributes.Add("class", "GridFooter");
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(0, l);
LinkButton lb = null;
lb = new LinkButton();
lb.Text = "Previous";
lb.Attributes.Add("OnClick", "goPage(" + Convert.ToString(Convert.ToInt32(pgResults.CurrentPageIndex) - 1) + ");");
lb.CommandArgument = Convert.ToString(Convert.ToInt32(pgResults.CurrentPageIndex) - 1);
if (pgResults.CurrentPageIndex == 0)
{
lb.Enabled = false;
lb.Style.Add("cursor", "default");
}
else
{
lb.Attributes.Add("class", "GridFooter");
}
**lb.Click += new EventHandler(Pager_Click);
pnlPager.Controls.AddAt(0, lb);**
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(0, l);
lb = new LinkButton();
lb.Text = "First";
lb.Attributes.Add("OnClick", "goPage(0);");
lb.CommandArgument = Convert.ToString(0);
if (pgResults.CurrentPageIndex == 0)
{
lb.Enabled = false;
lb.Style.Add("cursor", "default");
}
else
{
lb.Attributes.Add("class", "GridFooter");
}
**lb.Click += new EventHandler(Pager_Click);
pnlPager.Controls.AddAt(0, lb);**
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(0, l);
//Build the numeric links..
for(int i=0; i< pgResults.PageCount; i++)
{
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, l);
lb = new LinkButton();
lb.Text = Convert.ToString(i+1);
lb.Attributes.Add("OnClick", "goPage(" + Convert.ToString(i) + ");");
lb.CommandArgument = Convert.ToString(i);
if (pgResults.CurrentPageIndex == i)
{
lb.Enabled = false;
lb.Style.Add("cursor", "default");
}
else
{
lb.Attributes.Add("class", "GridFooter");
**lb.Click += new EventHandler(Pager_Click);**
}
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, lb);
}
//End of numeric links
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, l);
lb = new LinkButton();
lb.Text = "Next";
lb.Attributes.Add("OnClick", "goPage(" + Convert.ToString(Convert.ToInt32(pgResults.CurrentPageIndex) + 1) + ");");
lb.CommandArgument = Convert.ToString(Convert.ToInt32(pgResults.CurrentPageIndex) + 1);
if (pgResults.CurrentPageIndex == pgResults.PageCount - 1)
{
lb.Enabled = false;
lb.Style.Add("cursor", "default");
}
else
{
lb.Attributes.Add("class", "GridFooter");
}
**lb.Click += new EventHandler(Pager_Click);**
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, lb);
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, l);
lb = new LinkButton();
lb.Text = "Last";
lb.Attributes.Add("OnClick", "goPage(" + Convert.ToString(Convert.ToInt32(pgResults.PageCount) - 1) + ");");
lb.CommandArgument = Convert.ToString(Convert.ToInt32(pgResults.PageCount) - 1);
if (pgResults.CurrentPageIndex == pgResults.PageCount - 1)
{
lb.Enabled = false;
lb.Style.Add("cursor", "default");
}
else
{
lb.Attributes.Add("class", "GridFooter");
}
**lb.Click += new EventHandler(Pager_Click);**
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, lb);
l = new Label();
l.Width = Unit.Pixel(5);
pnlPager.Controls.AddAt(pnlPager.Controls.Count - 1, l);
}
Number labels are added with the clicking events:
private void Pager_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton) sender;
pgResults.CurrentPageIndex = Convert.ToInt32(lb.CommandArgument);
BindList(false);
}
But when i am clicking these numbers or 'next','previous' this pager_click is not firing.
Have i added eventhandlers in a correct way.
Please suggest
Thanks
Found out the reasion.
Dynamically created controls are lost on the page load,
so we need to again load them in postback.

emptydatatext is not displaying when binding datatable to gridview

I am creating a datatable and adding rows dynamically and am binding datatable to gridview when there are no records am displaying as no records found using emptydatatext but this is not working.Here is my code
protected void show_fence_report(object sender, EventArgs e)
{
int drp_fence_id = common.make_int(common.get_request("drp_fence"));
string fence_start_date_time1 = common.get_request("fence_start_date_time");
string fence_end_date_time1 = common.get_request("fence_end_date_time");
//Delete data from datatable and gridview
dt_fence.Clear();
if (gridview_fence.DataSource != null)
{
((DataView)gridview_fence.DataSource).Table.Clear();
}
gridview_fence.DataBind();
gridview_fence.EmptyDataText = "Records Not Found";
hid_fence_id.Value = drp_fence_id.ToString();
hid_fence_start_datetime.Value = fence_start_date_time1;
hid_fence_end_datetime.Value = fence_end_date_time1;
display_fence_report();
gridview_fence.EmptyDataText = "Records Not Found";
}
public void display_fence_report()
{
string fence_id1 = "", fence_name1, fence_type1 = "", fence_status;
float default_size = 100000, landmark_latitude1 = 0, landmark_longitude1 = 0, fence_latitude1 = 0, fence_longitude1 = 0, fence_size1 = 0, longitude_x = 0, latitude_y = 0;
int points_polygon = 0;
ArrayList vertices_x = new ArrayList();
ArrayList vertices_y = new ArrayList();
query = "select latitude,longitude,added_date_time,speed,location,(select object_value from tracking_master_objects where object_id = a.object_id) as object from tracking_data_domain a where object_id in(select object_id from tracking_assign_fence a where fence_id = '" + hid_fence_id.Value + "' and is_active = '1') and (added_date_time between convert(datetime, '" + hid_fence_start_datetime.Value + "', 105) and convert(datetime, '" + hid_fence_end_datetime.Value + "', 105)) order by gps_id asc";
dr = common.run_query(query, db, cm, dr, 0);
if (dr.HasRows)
{
//To Build Fence Latitudes and Longitudes
query = "select fence_id,fence_name,fence_type,landmark_latitude,landmark_longitude,fence_latitude,fence_longitude,fence_size from tracking_master_fences where domain_id = '" + domain_id1 + "' and fence_id = '" + hid_fence_id.Value + "' and is_active = '1'";
dr2 = common.get_row(query, db2, cm2, dr2, 0);
if (dr2.HasRows)
{
fence_id1 = dr2["fence_id"].ToString();
fence_name1 = dr2["fence_name"].ToString();
fence_type1 = dr2["fence_type"].ToString();
landmark_latitude1 = common.make_float(dr2["landmark_latitude"].ToString());//fs_lat
landmark_longitude1 = common.make_float(dr2["landmark_longitude"].ToString());//fs_long
fence_latitude1 = common.make_float(dr2["fence_latitude"].ToString());//sec_lat
fence_longitude1 = common.make_float(dr2["fence_longitude"].ToString());//sec_long
fence_size1 = common.make_float(dr2["fence_size"].ToString());
}
dr2.Close();
//Build POlygon Vertices
if (fence_type1 == "4")
{
query = "select polygon_latitude,polygon_longitude from tracking_master_fence_polygons where fence_id = '" + hid_fence_id.Value + "' and domain_id = '" + domain_id1 + "'";
dr1 = common.run_query(query, db1, cm1, dr1, 0);
if (dr1.HasRows)
{
while (dr1.Read())
{
vertices_x.Add(dr1["polygon_latitude"]);
vertices_y.Add(dr1["polygon_longitude"]);
}
}
dr1.Close();
points_polygon = vertices_x.Count;
}
//Create a Datatable of 14 rows
dt_fence.Columns.Add("fence_id", typeof(string));
dt_fence.Columns.Add("Date", typeof(string));
dt_fence.Columns.Add("Speed", typeof(string));
dt_fence.Columns.Add("Location", typeof(string));
dt_fence.Columns.Add("landmark_latitude", typeof(string));
dt_fence.Columns.Add("landmark_longitude", typeof(string));
dt_fence.Columns.Add("fence_latitude", typeof(string));
dt_fence.Columns.Add("fence_longitude", typeof(string));
dt_fence.Columns.Add("latitude", typeof(string));
dt_fence.Columns.Add("longitude", typeof(string));
dt_fence.Columns.Add("fence_size", typeof(string));
dt_fence.Columns.Add("fence_type", typeof(string));
dt_fence.Columns.Add("fence_status", typeof(string));
dt_fence.Columns.Add("object", typeof(string));
while (dr.Read())
{
fence_status = "";
float latitude = common.make_float(dr["latitude"].ToString());
float longitude = common.make_float(dr["longitude"].ToString());
if (fence_type1 == "1" || fence_type1 == "2")
{
if (((landmark_latitude1 * 100000) < (latitude * 100000) && (fence_latitude1 * 100000) > (latitude * 100000)) && ((landmark_longitude1 * 100000) < (longitude * 100000) && (fence_longitude1 * 100000) > (longitude * 100000)))
{
fence_status = "Inside";
}
else
{
fence_status = "Outside";
}
}
else if (fence_type1 == "3")
{
float ft = ((latitude * 100000) - (landmark_latitude1 * 100000));
float st = ((longitude * 100000) - (landmark_longitude1 * 100000));
float sqrt = common.make_float(Math.Sqrt((ft * ft) + (st * st)).ToString());
if (fence_size1 < sqrt)
{
fence_status = "Out Side";
}
else
{
fence_status = "In Side";
}
}
else if (fence_type1 == "4")
{
longitude_x = common.make_float(dr["latitude"].ToString());
latitude_y = common.make_float(dr["longitude"].ToString());
int i = 0, j = 0, c = 0;
for (i = 0, j = points_polygon - 1; i < points_polygon; j = i++)
{
float vertices_y_i_val = common.make_float(vertices_y[i].ToString());
float vertices_y_j_val = common.make_float(vertices_y[j].ToString());
float vertices_x_i_val = common.make_float(vertices_x[i].ToString());
float vertices_x_j_val = common.make_float(vertices_x[j].ToString());
if (((vertices_y_i_val > latitude_y != (vertices_y_j_val > latitude_y)) &&
(longitude_x < (vertices_x_j_val - vertices_x_i_val) * (latitude_y - vertices_y_i_val) / (vertices_y_j_val - vertices_y_i_val) + vertices_x_i_val)))
{
c = 1;
}
}
if (c == 1)
{
fence_status = "In Side";
}
else
{
fence_status = "Out Side";
}
}
dt_fence.Rows.Add(fence_id1, dr["added_date_time"], dr["speed"], dr["location"], landmark_latitude1, landmark_longitude1, fence_latitude1, fence_longitude1, latitude, longitude, fence_size1, fence_type1, fence_status, dr["object"]);
}//End of while Loop
//hid_ds_fence.Value = dt_fence.ToString();
gridview_fence.DataSource = dt_fence;
gridview_fence.DataBind();
}
dr.Close();
fence_modalpopup.Show();
}
In your code you're assigning EmptyDataText value after DataBind. It should be before DataBind. If "Message" is not going to change, you should rather define in HTML source as suggested.
You can use something like this
<Columns>
<Columns>
<EmptyDataTemplate>
<asp:Label ID="lblEmptydata" runat="server" Text="No Data here"></asp:Label>
</EmptyDataTemplate>
</asp:GridView>
Or can try this
in my remark gridview's row_databoundevent i wrote
if (e.Row.Cells[0].Text == " ") // to display text when there is no data
{
e.Row.Cells[0].Text = "No Data Found";
}
Or can try this too
dt.Rows.Add(dt.NewRow());
grid1.DataSource = dt;
grid1.DataBind();
int totalcolums = grid1.Rows[0].Cells.Count;
grid1.Rows[0].Cells.Clear();
grid1.Rows[0].Cells.Add(new TableCell());
grid1.Rows[0].Cells[0].ColumnSpan = totalcolums;
grid1.Rows[0].Cells[0].Text = "No Data Found";

Resources