create Excel Sheet with drop down list Using EPplus - c#

I'm working on Mvc web app, I want to create new excel sheet with two drop down lists filled with data from database. I want the second drop down list to be dependent on selection changed of first one. I already create file and fill drop down list but I can't find a way to make them dependent.
Any clue how to do this?
Here's my code
public void ExportToXlsx(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
// ok, we can run the real code of the sample now
using (var xlPackage = new ExcelPackage(stream))
{
// get handle to the existing worksheet#region
#region MyRegion Create Main File
var worksheet = xlPackage.Workbook.Worksheets.Add("Beneficiary");
var properties = new string[]
{
" الاسم "," رقم الهوية " ," رقم الجوال "," نوع المستفيد "," IBAN " ," نوع الوظيفة "," الرتبة/ المرتبة "
};
for (var i = 0; i < properties.Length; i++)
{
worksheet.Cells[1, i + 1].Value = properties[i];
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.AliceBlue);
worksheet.Cells[1, i + 1].Style.Font.Bold = true;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.View.RightToLeft = true;
#endregion
#region Ismilitry List
ExcelWorksheet isMilitryddList = xlPackage.Workbook.Worksheets.Add("IsMilitry");
var ismilitryValues = new string[]
{
"مدنى","عسكرى" ,"أخرى"
};
var valismilitry = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 4, 10000, 4].Address);
for (int index = 1; index <= ismilitryValues.Length; index++)
{
isMilitryddList.Cells[1,index].Value = ismilitryValues[index - 1];
}
var addressismilitry = isMilitryddList.Cells[1, 1, 1, ismilitryValues.Count()].Address;
var arrismilitry = addressismilitry.Split(':');
var ismilitrychar1 = arrismilitry[0][0];
var ismilitrynum1 = arrismilitry[0].Trim(ismilitrychar1);
var ismilitrychar2 = arrismilitry[1][0];
var ismilitrynum2 = arrismilitry[1].Trim(ismilitrychar2);
valismilitry.Formula.ExcelFormula = string.Format("=IsMilitry!${0}${1}:${2}${3}", ismilitrychar1, ismilitrynum1, ismilitrychar2, ismilitrynum2);
valismilitry.ShowErrorMessage = true;
valismilitry.Error = "Select from List of Values ...";
#endregion
#region Ranktype List
ExcelWorksheet ddList = xlPackage.Workbook.Worksheets.Add("DropDownList");
var brokerBranchs = new RankTypeBl().SelectAllRankTypes();
var val = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 6, 10000, 6].Address);
for (int index = 1; index <= brokerBranchs.Count; index++)
{
ddList.Cells[index, 1].Value = brokerBranchs[index - 1].Name;
}
var address = ddList.Cells[1, 1, brokerBranchs.Count(), 1].Address.ToString();
var arr = address.Split(':');
var char1 = arr[0][0];
var num1 = arr[0].Trim(char1);
var char2 = arr[1][0];
var num2 = arr[1].Trim(char2);
val.Formula.ExcelFormula = string.Format("=DropDownList!${0}${1}:${2}${3}", char1, num1, char2, num2);
val.ShowErrorMessage = true;
val.Error = "Select from List of Values ...";
#endregion
#region rank list
ExcelWorksheet ddList1 = xlPackage.Workbook.Worksheets.Add("ranks");
var ranks = new BeneficiaryRankBl().SelectAllBeneficiaryRank();
var val1 = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 7, 10000, 7].Address);
for (int index = 1; index <= ranks.Count; index++)
{
ddList1.Cells[index, 1].Value = ranks[index - 1].ArName;
}
var address1 = ddList1.Cells[1, 1, ranks.Count(), 1].Address;
var arr1 = address1.Split(':');
var char11 = arr1[0][0];
var num11 = arr1[0].Trim(char11);
var char22 = arr1[1][0];
var num21 = arr1[1].Trim(char22);
val1.Formula.ExcelFormula = string.Format("=ranks!${0}${1}:${2}${3}", char11, num11, char22, num21);
val1.ShowErrorMessage = true;
val1.Error = "Select from List of Values ...";
#endregion
xlPackage.Save();
}
}

Related

I am trying to export an excel and make it password protected. My code is given below.But i am getting error

I am trying to export an excel and make it password protected.
My code is given below.
But i am getting error:
Excel completed file level validation and repair.
Some parts of this workbook may have been repaired or discarded.
I DON'T KNOW WHAT I AM DOING WRONG .
In-case i do it without the save As line for package then this error doesn't appear.
In my controller:
[HttpGet]
public FileStreamResult ExportToExcel()
{
_objService = new ServiceBAL();
List<ReconcilationEntity> Objmodel = new List<ReconcilationEntity>();
Objmodel = _objService.GetCreditsudharLeads();
String URL = string.Empty;
if (!Directory.Exists(Server.MapPath("~/TempExcel")))
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/TempExcel"));
}
String Filepath = Server.MapPath("~/TempExcel");
string date = DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToShortTimeString().Replace(" ", "_").Replace(":", "_").Trim();
String FileName = "Creditsudhar_" + date + ".xlsx";
Filepath = Filepath + "\\" + FileName;
string[] columns = { "AffName", "AffPhone", "AffEmail", "ProductName", "ContactName", "Status", "CreatedOn", "Commission", "IsCommissionPaid", "Accountname", "AccountNumber", "BankName", "BankBranch", "IFSCCode", "PanNumber" };
var file = ExcelExportHelper.ExportExcel(ExcelExportHelper.ListToDataTable(Objmodel), Filepath, "Creditsudhar Reconcillation Sheet " + DateTime.Now.ToShortDateString(), true, columns);
var memStream = new MemoryStream(file);
return this.File(memStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName);
}
public static string ExcelContentType
{
get
{ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
}
public static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static byte[] ExportExcel(DataTable dataTable, String Filepath, string heading = "", bool showSrNo = false, params string[] columnsToTake)
{
string fullPath = string.Empty;
byte[] ret;
DeleteUploadedFile(Filepath);
String result = String.Empty;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
// add the content into the Excel file
workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
// autofit width of cells with small content
int columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
try
{
ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
int maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
if (maxLength < 150)
{
workSheet.Column(columnIndex).AutoFit();
}
columnIndex++;
}
catch (Exception ex)
{
if (!(ex is System.Threading.ThreadAbortException))
{
//Log other errors here
}
}
}
// format header - bold, yellow on black
using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
{
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
}
// format cells - add borders
using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
// removed ignored columns
for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
{
if (i == 0 && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + 1);
}
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 5;
}
System.IO.FileInfo fileinfo2 = new System.IO.FileInfo(Filepath);
DeleteUploadedFile(Filepath);
workSheet.Protection.SetPassword("myPassword");
workSheet.Protection.IsProtected = true;
workSheet.Protection.AllowSelectUnlockedCells = false;
workSheet.Protection.AllowSelectLockedCells = false;
package.SaveAs(fileinfo2, "myPassword");
ret = package.GetAsByteArray();
return ret;
}
}
public static void DeleteUploadedFile(String filePath)
{
try
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
catch (Exception ex)
{ }
}
public static byte[] ExportExcel<T>(List<T> data, String Filepath, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
{
return ExportExcel(ListToDataTable<T>(data), Filepath, Heading, showSlno, ColumnsToTake);
}
An answer mentioned SaveAs close the package, so the correct steps will be returning the saved file as array instead of using GetAsByteArray afterwards. Or simply use GetAsByteArray(passwords) without SaveAs.

Can we create drop down list with check box option using epplus library

Initialize the worksheet:
public HttpResponseMessage ER_GenerateWBLWorksheet2()
{
ExcelPackage ExclPkg = new ExcelPackage();
ExcelWorksheet wsSheet1 = ExclPkg.Workbook.Worksheets.Add("Sheet1");
wsSheet1.Cells["A1"].Value = "ProductName";
wsSheet1.Cells["B1"].Value = "Price";
wsSheet1.Cells["C1"].Value = "ProductImageUrl";
wsSheet1.Cells["D1"].Value = "ProductUrl";
wsSheet1.Cells["E1"].Value = "StoreId";
wsSheet1.Cells["G1"].Value = "CategoryId";
wsSheet1.Cells["I1"].Value = "ColorId";
wsSheet1.Cells["K1"].Value = "FabricId";
wsSheet1.Cells["M1"].Value = "Gender";
Create Category list:
var categorylist = wsSheet1.DataValidations.AddListValidation(wsSheet1.Cells["G2:G500"].Address);
var categories = _categoryServices.GetAllCategory();
var categoryEntities = (categories != null) ? categories.ToList() : new List<CategoryEntity>();
for (int i = 0; i < categoryEntities.Count; i++)
{
categorylist.Formula.Values.Add(categoryEntities[i].CategoryName.ToString());
}
categorylist.ShowErrorMessage = true;
categorylist.ErrorTitle = "Error";
categorylist.Error = "Please select the Category from Dropdown";
wsSheet1.Cells["G2:G500"].Style.Locked = false;
Create color list:
var colorlist = wsSheet1.DataValidations.AddListValidation(wsSheet1.Cells["I2:I500"].Address);
var colors = _colorServices.GetAllColor();
var colorsEntities = (colors != null) ? colors.ToList() : new List<ColorEntity>();
for (int i = 0; i < colorsEntities.Count; i++)
{
colorlist.Formula.Values.Add(colorsEntities[i].ColorName.ToString());
}
colorlist.ShowErrorMessage = true;
colorlist.ErrorTitle = "Error";
colorlist.Error = "Please select the Color from Dropdown";
wsSheet1.Cells["I2:I500"].Style.Locked = false;
wsSheet1.Cells[wsSheet1.Dimension.Address].AutoFitColumns();
var filename = #"Inventory_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xlsx";
//string sPath = #"e:\" + filename;
var sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/exportedfiles/" + filename);
Stream stream = File.Create(sPath);
ExclPkg.SaveAs(stream);
stream.Close();
string strServerPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["excelserverpath"]);
var sPathURL = (strServerPath + "exportedfiles/" + filename);
List<fileinfo> filelst = new List<fileinfo>();
fileinfo file = new fileinfo();
file.filename = filename;
file.fileurl = sPathURL;
//file.fileurl = sPath;
filelst.Add(file);
return new ResponseWrapper<fileinfo>(filelst, HttpStatusCode.OK, null, 0);
}
Using the above code I have created excel with drop down list, but my requirement is to select multiple values from drop down list. Is it possible using epplus library?

Using a join statement to link data together from 2 different datatables into one in C#

I am trying to get some data from one datatable (facilData) and data from another datatable (ownerData) and write it to another datatable (dataStore). The second is not identical to the first. When I attempted my code below, I get the following error: "Unable to case object of type System.DBnull to System.String". Then the debugger takes me back and highlights (int)table2["rowIndex"] in the code below.
public void Write2Sheet(DataTable dt1, DataTable dt2, DataTable dt3, String newFilePath)
{
try
{
//Merge the three Datatables into the single Datatable source
var mdata = from table1 in facilData.AsEnumerable()
join table2 in ownerData.AsEnumerable() on (int)table1["rowIndex"] equals (int)table2["rowIndex"]
select new
{
rowIndex = (int)table1["rowIndex"],
Prog = (string)table1["Prog"],
cStatus = (string)table1["cStatus"],
bStatus = (string)table1["bStatus"],
fID = (string)table1["fID"],
fNam = (string)table1["fNam"],
fAdd = (string)table1["fAdd"],
fCity = (string)table1["fCity"],
fState = (string)table1["fState"],
fCode = (string)table1["fCode"],
oInfo = (string)table2["oInfo"],
pgRecId = (string)table1["pgRecId"],
lAct = (string)table1["lAct"]
};
foreach (var rec in mdata)
{
var row = dataStore.NewRow();
row["rowIndex"] = rec.rowIndex;
row["Prog"] = rec.Prog;
row["cStatus"] = rec.cStatus;
row["bStatus"] = rec.bStatus;
row["fID"] = rec.fID;
row["fNam"] = rec.fNam;
row["fAdd"] = rec.fAdd;
row["fCity"] = rec.fCity;
row["fState"] = rec.fState;
row["fCode"] = rec.fCode;
row["oInfo"] = rec.oInfo;
row["pgRecId"] = rec.pgRecId;
row["lAct"] = rec.lAct;
dataStore.Rows.Add(row);
}
}
catch (Exception e)
{
Write2LogFile("The data tables couldn't merge because: " + e.Message);
}
//Write from the Datatable source to the new spreadsheet and save it
try
{
FileInfo newSheet = new FileInfo(fileName);
using (ExcelPackage xPkg = new ExcelPackage(newSheet))
{
ExcelWorksheet worksheet = xPkg.Workbook.Worksheets[1];
var cell = worksheet.Cells;
int rI = 2;
foreach (DataRow dr in dataStore.Rows)
{
string iDX = rI.ToString();
worksheet.Cells["A" + iDX].Value = dr["Prog"].ToString();
worksheet.Cells["B" + iDX].Value = dr["cStatus"].ToString();
worksheet.Cells["C" + iDX].Value = dr["bStatus"].ToString();
worksheet.Cells["D" + iDX].Value = dr["fID"].ToString();
worksheet.Cells["E" + iDX].Value = dr["fNam"].ToString();
worksheet.Cells["F" + iDX].Value = dr["fAdd"].ToString();
worksheet.Cells["G" + iDX].Value = dr["fCity"].ToString();
worksheet.Cells["H" + iDX].Value = dr["fState"].ToString();
worksheet.Cells["I" + iDX].Value = dr["fCode"].ToString();
worksheet.Cells["J" + iDX].Value = dr["oInfo"].ToString();
worksheet.Cells["K" + iDX].Value = dr["pgRecId"].ToString();
worksheet.Cells["L" + iDX].Value = dr["lAct"].ToString();
rI++;
}
xPkg.Save();
}
}
catch (Exception ex)
{
Write2LogFile("Data was not written to spreadsheet because: " + ex.Message);
}
}
So, I figured it out. Instead of trying to do the query syntax, I went with the method syntax. I added an additional class as a container for my objects I wanted to add to the single datatable. Although none of the row-indices were null, I added a null check anyway. Here is my updated code:
public void Write2Sheet(DataTable dt1, DataTable dt2, DataTable dt3, String newFilePath)
{
try
{
//Merge the three Datatables into the single Datatable source
//method syntax
var mdata = facilData.AsEnumerable().Where(f => f[0] != typeof(DBNull)).Join(ownerData.AsEnumerable(),
table1 => table1.Field<int>(0),
table2 => table2.Field<int>(0),
(table1, table2) => new Class1 //container class
{
rowIndex = (int)table1[0],
Prog = table1[1].ToString(),
cStatus = table1[2].ToString(),
bStatus = table1[3].ToString(),
fID = table1[4].ToString(),
fNam = table1[5].ToString(),
fAdd = table1[6].ToString(),
fCity = table1[7].ToString(),
fState = table1[8].ToString(),
fCode = table1[9].ToString(),
oInfo = table2[1].ToString(),
pgRecId = table1[10].ToString(),
lAct = table1[11].ToString()
});
foreach (var rec in mdata)
{
var row = dataStore.NewRow();
row["rowIndex"] = rec.rowIndex;
row["Prog"] = rec.Prog;
row["cStatus"] = rec.cStatus;
row["bStatus"] = rec.bStatus;
row["fID"] = rec.fID;
row["fNam"] = rec.fNam;
row["fAdd"] = rec.fAdd;
row["fCity"] = rec.fCity;
row["fState"] = rec.fState;
row["fCode"] = rec.fCode;
row["oInfo"] = rec.oInfo;
row["pgRecId"] = rec.pgRecId;
row["lAct"] = rec.lAct;
dataStore.Rows.Add(row);
}
}
catch (Exception e)
{
Write2LogFile("The data tables couldn't merge because: " + e.Message);
}
//Write from the Datatable source to the new spreadsheet and save it
try
{
FileInfo newSheet = new FileInfo(fileName);
using (ExcelPackage xPkg = new ExcelPackage(newSheet))
{
ExcelWorksheet worksheet = xPkg.Workbook.Worksheets[1];
var cell = worksheet.Cells;
int rI = 2;
foreach (DataRow dr in dataStore.Rows)
{
string iDX = rI.ToString();
worksheet.Cells["A" + iDX].Value = dr["Prog"].ToString();
worksheet.Cells["B" + iDX].Value = dr["cStatus"].ToString();
worksheet.Cells["C" + iDX].Value = dr["bStatus"].ToString();
worksheet.Cells["D" + iDX].Value = dr["fID"].ToString();
worksheet.Cells["E" + iDX].Value = dr["fNam"].ToString();
worksheet.Cells["F" + iDX].Value = dr["fAdd"].ToString();
worksheet.Cells["G" + iDX].Value = dr["fCity"].ToString();
worksheet.Cells["H" + iDX].Value = dr["fState"].ToString();
worksheet.Cells["I" + iDX].Value = dr["fCode"].ToString();
worksheet.Cells["J" + iDX].Value = dr["oInfo"].ToString();
worksheet.Cells["K" + iDX].Value = dr["pgRecId"].ToString();
worksheet.Cells["L" + iDX].Value = dr["lAct"].ToString();
rI++;
}
xPkg.Save();
MessageBox.Show("Data was successfully added to the current spreadsheet.");
}
}
catch (Exception ex)
{
Write2LogFile("Data was not written to spreadsheet because: " + ex.Message);
}
}

Error , invalid Regular expression in c# console application

private static void PizzaHutPizzaScrapper()
{
try
{
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex r = new Regex("(<p class=\"MenuDescHead\">[A-Za-z\\s*]+[0-9]*)");
// Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[A-Za-z.\\s?]+[0-9]*[A-Za-z\\s?]*[0-9]*[A-Za-z.\\s?]*)");
Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[0-9]*)");
mclName = r.Matches(pageContent);
mclPrice = r1.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
string name = "";
string price = "";
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
price = ml.Value.Remove(0, ml.Value.IndexOf(">") + 1).Trim();
if (price != "")
{
menuPriceList.Add(ml.Value);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
name = mclName[i].Value.Remove(0, mclName[i].Value.IndexOf(">") + 1);
if (i == 0 || i == 4)
{
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}`
i want to select numeric values only...but it fetch alphabets as well..
i want to select only numeric values from HTML and using [0-9]* as regular expression, but its not working and show alphabets as well. i want only numeric values, what is correct regular expression? any idea??
Here you go, what you're looking for are Grouping Constructs:
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex nameRegex = new Regex("<p class=\"MenuDescHead\">([A-Za-z\\s]+[0-9]*)");
Regex priceRegex = new Regex("<p class=\"MenuDescPrice\">[^0-9]*([0-9]*)");
mclName = nameRegex.Matches(pageContent);
mclPrice = priceRegex.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
string price = ml.Groups[1].ToString();
if (price != "" && price != "0")
{
menuPriceList.Add(price);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
string price;
string name = mclName[i].Groups[1].ToString();
if (i == 0 || i == 4)
{
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}
Console.WriteLine(strBuilder.ToString());

System.Data.OleDb.OleDbException(0x80004005): Unspecified Error

Through a series of loops and Database calls (Select statements only) saved as datatables I am generating a .txt file with the values. It runs fine for a little while (19 rows...19 full loop cycles) then I get a runtime exception being thrown by connection.Open()
I have the entire loop inside a try catch block in order to catch the exception and produce the message then 2 blank lines then the stack trace.
I have tried to read this and figure out what to do but I am a bit of a Novice when it comes to DB connections. I have looked elsewhere but do not seem to find a question that quite fits my situation.
FYI: C# 4.0 Windows Form Application, Access DB
I am hoping to find some suggestions on where to begin looking. I am positive that my connection is closed when this error is thrown due to the validation i implemented as shown here:
internal IDbConnection GetConnection()
{
try
{
var connection = _assemblyProvider.Factory.CreateConnection();
connection.ConnectionString = _connectionString;
_connectionState = connection.State.ToString();
if (_connectionState == "Open")
GetConnection();
else
{
connection.Open();
}
return connection;
}
catch (Exception exept)
{
throw new Exception(exept.ToString() + "\n\n" + exept.StackTrace.ToString());
}
}
This method is being called from here:
public DataTable ExecuteDataTable(string commandText, string tableName, DbParameterCollection paramCollection, CommandType commandType)
{
DataTable dtReturn;
IDbConnection connection = null;
try
{
connection = _connectionManager.GetConnection();
dtReturn = _dbAdapterManager.GetDataTable(commandText, paramCollection, connection, tableName, commandType);
}
finally
{
if (connection != null)
{
connection.Close();
connection.Dispose();
}
}
return dtReturn;
}
public DataTable ExecuteDataTable(string commandText, string tableName, CommandType commandType)
{
return ExecuteDataTable(commandText, tableName, new DbParameterCollection(), commandType);
}
public DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(commandText, string.Empty, CommandType.Text);
}
and
//read from DB using a SQL statement and return a DataTable
internal static DataTable readDB(string SQL)
{
var dbHelper = new DbHelper();
using (IDbConnection connection = dbHelper.GetConnObject())
{
return dbHelper.ExecuteDataTable(SQL);
}
}
Here is the loop (its kinda long and could probably be done better but I just want to find why its breaking after its worked several times)
The exception is thrown from the line that Reads:
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
inside this:
SQLString = "SELECT * FROM Claim WHERE ClaimStatus <> 1";
DataTable allRecsFromClaimNotStatus1 = dbConnect.readDB(SQLString);
if (allRecsFromClaimNotStatus1.Rows.Count == 0)
return;
else
{
string path = txtExtractFileLocation.Text;
if (txtExtractFileLocation.Text.Substring(txtExtractFileLocation.Text.Length - 2) == "\\\\")
{
path = path.Substring(0, path.Length - 1);
}
if (path.Substring(path.Length - 1) == "\\")
path += "DI_Extract.txt";
else
path += #"\DI_Extract.txt";
using (StreamWriter sw = new StreamWriter(#path))
{
for (int i = 0; i < allRecsFromClaimNotStatus1.Rows.Count; i++)
{
rNum = allRecsFromClaimNotStatus1.Rows[i][2].ToString().Trim();//Claim.InsuredRecNum
SQLString = "SELECT * FROM Insured WHERE RecNum = " + rNum;
DataTable allInsuredByRecNum = dbConnect.readDB(SQLString);
lossDate = allRecsFromClaimNotStatus1.Rows[i][11].ToString().Trim();//Claim.LossDate
lossDate = (Convert.ToDateTime(lossDate)).Date.ToString("MM/dd/yyyy");
reportedDate = allRecsFromClaimNotStatus1.Rows[i][9].ToString().Trim();//Claim.ReportedDate
reportedDate = (Convert.ToDateTime(reportedDate)).Date.ToString("MM/dd/yyyy");
claim = allRecsFromClaimNotStatus1.Rows[i][0].ToString().Trim();//Claim.ClaimNumber
if (chkIncludePaymentsForCurrentMonth.Checked == true)
{
direct = allRecsFromClaimNotStatus1.Rows[i][4].ToString().Trim();//Claim.DirectReserve
WP = allRecsFromClaimNotStatus1.Rows[i][5].ToString().Trim();//Claim.WPReserve
ceded = allRecsFromClaimNotStatus1.Rows[i][6].ToString().Trim();//Claim.CededReserve
}
else
{
direct = allRecsFromClaimNotStatus1.Rows[i][29].ToString().Trim();//Claim.MonthEndDirect
WP = allRecsFromClaimNotStatus1.Rows[i][30].ToString().Trim();//Claim.MonthEndWP
ceded = allRecsFromClaimNotStatus1.Rows[i][31].ToString().Trim();//Claim.MonthEndCeded
}
ced = Convert.ToDecimal(ceded);
wav = Convert.ToDecimal(WP);
ceded = ced.ToString("#.##");
WP = wav.ToString("#.##");
if (ceded == "")
ceded = "0";
if (WP == "")
WP = "0";
if ((allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != null) &&
(allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != ""))//Claim.WaiverDate
{
onWaiver = "YES";
}
else
{
onWaiver = "NO";
}
reinsPreNotice = "NO";
reinsCeded = "NO";
switch (allRecsFromClaimNotStatus1.Rows[i][7].ToString().Trim())//Claim.CededPre
{
case "1":
{
reinsPreNotice = "YES";
break;
}
case "2":
{
reinsCeded = "YES";
break;
}
}//end switch
state = allRecsFromClaimNotStatus1.Rows[i][8].ToString().Trim();//Claim.LossState
lName = allInsuredByRecNum.Rows[0][1].ToString().Trim();//Insured.LastName
fName = allInsuredByRecNum.Rows[0][0].ToString().Trim();//Insured.FirstName
mi = allInsuredByRecNum.Rows[0][2].ToString().Trim();//Insured.MI
policy = allInsuredByRecNum.Rows[0][43].ToString().Trim();//Insured.PolicyNumber
DOB = allInsuredByRecNum.Rows[0][10].ToString().Trim();//Insured.DOB
DOB = (Convert.ToDateTime(DOB)).Date.ToString("MM/dd/yyyy");
age = allInsuredByRecNum.Rows[0][11].ToString().Trim();//Insured.TrueAge
issueAge = calculateAge(Convert.ToDateTime(allInsuredByRecNum.Rows[0][10].ToString().Trim()), //Insured.DOB
Convert.ToDateTime(allInsuredByRecNum.Rows[0][45].ToString().Trim()));//Insured.EffectiveDate
SQLString = "SELECT InsuredRecNum, RecNum FROM Claim WHERE InsuredRecNum = " + rNum;
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
rNum = iRecNum2ClaimRecNumFromClaim.Rows[0][1].ToString().Trim();
issueDate = allInsuredByRecNum.Rows[0][45].ToString().Trim();//Insured.EffectiveDate
issueDate = (Convert.ToDateTime(issueDate)).Date.ToString("MM/dd/yyyy");
sex = allInsuredByRecNum.Rows[0][13].ToString().Trim();//Insured.Gender
planCode = allInsuredByRecNum.Rows[0][44].ToString().Trim();//Insured.PlanMnemonic
issueAmt = allInsuredByRecNum.Rows[0][49].ToString().Trim();//Insured.BenefitAmount (Monthly Benefit Amount before Offset)
benefitPeriod = allInsuredByRecNum.Rows[0][50].ToString().Trim();//Insured.BenefitPeriod
if (allInsuredByRecNum.Rows[0][54].ToString().Trim().Length == 2)//Insured.EliminationPeriod
eliminationPeriod = "0" + allInsuredByRecNum.Rows[0][54].ToString().Trim();
else
eliminationPeriod = allInsuredByRecNum.Rows[0][54].ToString().Trim();
premiumAmount = allInsuredByRecNum.Rows[0][48].ToString().Trim();//Insured.AnnualPremium
occupationClass = allInsuredByRecNum.Rows[0][55].ToString().Trim();//Insured.OccupationClass
//select only status = EXEC (0)
SQLString = "SELECT * FROM Offset WHERE ClaimRecNum = " + rNum + " AND Status = 0";
DataTable allOffsetByClaimRecNumAndStatus0 = dbConnect.readDB(SQLString);
offsetAmt = 0;
dblSTDOffsetAmount = 0;
dblRecOffsetAmount = 0;
RECOffsetOcc = "0";
RECOffsetExecuted = "0";
int offsetCount = allOffsetByClaimRecNumAndStatus0.Rows.Count;
if (offsetCount != 0)
{
for (int j = 0; j < offsetCount; j++)
{
//accumulate standard offset (STD) and Recovery offset (REC)
if (allOffsetByClaimRecNumAndStatus0.Rows[0][1].ToString().Trim() == "0")//Offset.Type
{
//Standard Type
dblSTDOffsetAmount += Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
}
else
{
//Recovery type
dblRecOffsetAmount = Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
RECOffsetOcc = allOffsetByClaimRecNumAndStatus0.Rows[j][5].ToString().Trim();//Offset.Occurance
RECOffsetExecuted = allOffsetByClaimRecNumAndStatus0.Rows[j][6].ToString().Trim();//Offset.Executed
}//end if
}//end for loop
}//end if
STDOffsetAmount = dblSTDOffsetAmount.ToString();
RECOffsetAmount = dblRecOffsetAmount.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + DateTime.Today.Date.Year + "# AND IssueDate <= #" + DateTime.Today.Date.ToShortDateString() + "#";
else
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + endDate.Substring(endDate.Length - 4) + "# AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByIRecNumAndIssDateInRange = dbConnect.readDB(SQLString);
YTDPmt = 0;
if (allPaymentByIRecNumAndIssDateInRange.Rows.Count == 0)
YTDPmt = 0;
else
{
int paymentCount = allPaymentByIRecNumAndIssDateInRange.Rows.Count;
double issAmt;
for (int k = 0; k < paymentCount; k++)
{
issAmt = Convert.ToDouble(allPaymentByIRecNumAndIssDateInRange.Rows[0][30].ToString().Trim());//Payment.IssueAmount
YTDPmt += issAmt;
}// end loop
}//end if
YTDPmts = YTDPmt.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum;
else
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum + " AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByRNum = dbConnect.readDB(SQLString);
totalPmt = 0;
if (allPaymentByRNum.Rows.Count == 0)
totalPmt = 0;
else
{
double issAmt = Convert.ToDouble(allPaymentByRNum.Rows[0][30].ToString().Trim());
for (int m = 0; m < allPaymentByRNum.Rows.Count; m++)
{
totalPmt += issAmt;
}
}
allPmts = totalPmt.ToString();
//set spacing for output
string block1 = policy + claim + planCode;
block1 = setSpacing(block1, 28);
string block2 = setSpacing(benefitPeriod, 3) + eliminationPeriod + occupationClass;
block2 = setSpacing(block2, 11);
issueAmt = setSpacing(issueAmt, 8);
STDOffsetAmount = setSpacing(STDOffsetAmount, 8);
RECOffsetAmount = setSpacing(RECOffsetAmount, 8);
RECOffsetOcc = setSpacing(RECOffsetOcc, 3);
RECOffsetExecuted = setSpacing(RECOffsetExecuted, 3);
string block3 = lossDate + age;
block3 = setSpacing(block3, 13);
issueAge = setSpacing(issueAge, 3);
string block4 = issueDate + DOB + sex + onWaiver + premiumAmount;
block4 = setSpacing(block4, 32);
reinsPreNotice = setSpacing(reinsPreNotice, 3);
reinsCeded = setSpacing(reinsCeded, 4);
double ap = Convert.ToDouble(allPmts);
allPmts = ap.ToString("#.#");
allPmts = setSpacing(allPmts, 8);
YTDPmts = setSpacing(YTDPmts, 8);
lName = setSpacing(lName, 19);
fName = fName + " " + mi;
fName = setSpacing(fName, 20);
string block5 = state + direct;
block5 = setSpacing(block5, 10);
ceded = setSpacing(ceded, 8);
WP = setSpacing(WP, 8);
reportedDate = setSpacing(reportedDate, 10);
//save row data for text file
dataOutput = (block1 + block2 + issueAmt + STDOffsetAmount + RECOffsetAmount + RECOffsetOcc + RECOffsetExecuted +
block3 + issueAge + block4 + reinsPreNotice + reinsCeded + allPmts + YTDPmts + lName + fName +
block5 + ceded + WP + reportedDate);
//Write to the output record DI_Extract.txt
sw.WriteLine(dataOutput);
counter++;
pbrRecordsProcessed.Value = counter;
}//end for loop
}//end streamwriter
}//end if
After looking deeper into the code I realized that the connection was trying to open 3 times before it closed. Not sure why I was not getting exceptions all the time but correcting this issue not only sped up the application tremendously it cleared the exception.

Categories

Resources