IndexOutOfRangeException: Cannot find table 0 while filling dataset - c#

when i want to run this code I get an error which throws "IndexOutOfRangeException" on for loop condition. I have tried to use breakpoints and after my DataSet populated clicked on magnifying glass on it. The Visualizer says that it was an empty DataSet. I would appreciate it if someone can help me!
My PageLoad function includes if(!IsPostBack) like this: (freeQuery.aspx.cs)
if (!IsPostBack
{
ViewState["sortColumn"] = " ";
ViewState["sortDirection"] = " ";
string pageURL = HttpContext.Current.Request.RawUrl;
DataSet tables = new DataSet();
string queryString2 = "show tables;";
tables = connectHive(queryString2, pageURL);
List<string> list = new List<string>();
for (int i = 0; i < tables.Tables[0].Rows.Count; i++)
{
list.Add(tables.Tables[0].Rows[i][0].ToString());
}
ListBox1.DataSource = list;
ListBox1.DataBind();
ListBox1.Rows = (ListBox1.Items.Count / 2) + 3;
}
and connectHive function in BasePage.cs below:
protected DataSet connectHive(string query, string pageURL)
{ // Hadoop Hive Connection
var page = HttpContext.Current.CurrentHandler as Page;
OdbcConnection DbConnection = new OdbcConnection("DSN=Hive2");
DbConnection.ConnectionTimeout = 20000000;
try
{
DbConnection.Open();
}
catch (OdbcException exep)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('Error in Query!');window.location ='" + pageURL.Replace("/", "") + "';", true);
}
OdbcCommand cmd = DbConnection.CreateCommand();
OdbcDataAdapter adapter = new OdbcDataAdapter(query, DbConnection);
adapter.SelectCommand.CommandTimeout = 20000000;
DataSet data = new DataSet();
data.EnforceConstraints = false;
try
{
adapter.Fill(data);
}
catch (Exception ex)
{
List<string> parameters = new List<string>();
string pageName = findNameByUrl(HttpContext.Current.Request.RawUrl);
parameters.Add("UserID:");
parameters.Add(Session["sicil"].ToString());
parameters.Add("Exception:");
parameters.Add(ex.ToString());
string parameterString = castParameters(parameters);
string exception = "";
string[] sep = new string[] { "\r\n" };
string[] lines = ex.ToString().Split(sep, StringSplitOptions.RemoveEmptyEntries);
int position = lines[0].ToString().LastIndexOf("FAILED:");
if (position > -1)
exception = lines[0].ToString().Substring(position, lines[0].Length - position);
Session["Exception"] = exception.Replace("'", "");
Log(query, "Select Table(BasePage)", pageName, "Failed", parameterString);
}
DbConnection.Close();
return data;
}

Related

Importing data from excelsheet file into the mysql database C#

I have the following lines of code:
protected void btnUpload_Click(object sender, EventArgs e)
{
MySqlTransaction transaction;
string ex_id = "";
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();//just added
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if (dtExceldata.Rows.Count > 0)
{
//foreach (DataRow row in dtExceldata.Rows)
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
//string ex_dir = row["website_a"].ToString();
string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
// string ex_email = row["email_id"].ToString();
string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
//string ex_email1 = row["email_id2"].ToString();
string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
//string ex_email2 = row["email_id3"].ToString();
string ex_company = dtExceldata.Rows[i]["company"].ToString();
//string ex_company = row["company"].ToString();
string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
//string ex_contact = row["contact_name"].ToString();
string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
// string ex_proposal = row["proposal_status"].ToString();
string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
//string ex_reason = row["reason"].ToString();
int chk = 0;
int type = 0;
int dup = 0;
int dir = 0;
if (ddlwebsites.SelectedIndex != 0)
{
dir = Convert.ToInt32(ddlwebsites.SelectedValue);
if (dir == 8)
{
type = 1;
}
}
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
chk = 1;
}
}
if (type == 1 && chk == 0)
{
evyerror.Text = "Please Select the Event!!";
return;
}
else
{
string querycomp = "", compID = "";
querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr);
connect.Open();
transaction = connect.BeginTransaction();
try
{
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(querycomp);
if (dt.Rows.Count > 0)
{
compID = dt.Rows[0]["comp_id"].ToString();
ViewState["comp_id"] = compID;
if (type == 1)
{
dup = checkforDuplicates(Convert.ToInt32(compID));
if (dup == 1)
{
//Confirm_MP.Show();
// ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
}
}
//return;
}
else
{
string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?website", ex_dir);
cmd.ExecuteNonQuery();
cmd.CommandText = "Select LAST_INSERT_ID()";
compID = cmd.ExecuteScalar().ToString();
transaction.Commit();
connect.Close();
}
}
catch
{
transaction.Rollback();
}
if (dup == 0)
{
// create a connection string with your sql database
string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr1);
connect.Open();
DateTime date = new DateTime();
date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
//DateTime date = new DateTime();
//if (!string.IsNullOrEmpty(ex_date))
// {
//DateTime date = new DateTime();//added by chetan
//ex_date = ex_date.Split(' ')[0];//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
//string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
//DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
//// DateTime date = DateTime.Parse(ex_date);//added by chetan
// }
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
// string SentDateString = date.ToString("yyyy/MM/dd");
transaction = connect.BeginTransaction();
try
{
string ex_uid = Session["session_barterUser_id"].ToString();
MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);
cmd.Parameters.AddWithValue("?uid", ex_uid);
cmd.Parameters.AddWithValue("?comp", compID);
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
// command.Parameters.AddWithValue("?event", eventname);
cmd.Parameters.AddWithValue("?dir", dir);
// command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
// command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
//cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?cont_name", ex_contact);
cmd.Parameters.AddWithValue("?email", ex_email);
cmd.Parameters.AddWithValue("?email2", ex_email1);
cmd.Parameters.AddWithValue("?email3", ex_email2);
cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
cmd.Parameters.AddWithValue("?reason", ex_reason);
cmd.Parameters.AddWithValue("?type", type);
// command.Parameters.AddWithValue("?type", type);
cmd.ExecuteNonQuery();
if (type == 1)
{
cmd.CommandText = "Select LAST_INSERT_ID()";
Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
int eventAssignID;
string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
eventAssignID = Convert.ToInt32(lstAssign.Value);
cmd.Parameters.AddWithValue("?event_id", eventAssignID);
cmd.ExecuteNonQuery();
}
}
}//end of if
transaction.Commit();
connect.Close();
Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
}//end of try
catch (Exception ex)
{
transaction.Rollback();
Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
}
finally
{
connect.Close();
}
}//ifdupzero
}//else
}//for//foreach
}//while //if
// dr.Close();//commented by chetan
my_con.Close();
if (System.IO.File.Exists(Excel_path))
{
System.IO.File.Delete(Excel_path);
}
}
suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
OleDbDataReader dr = command.ExecuteReader();
dr.Read();
while (dr[0].ToString() != String.Empty)
{
ex_id = dr[0].ToString();
string ex_uid = dr[1].ToString();
//get second row data and assign it ex_name variable
string ex_date = dr[2].ToString();
//get thirdt row data and assign it ex_name variable
string ex_dir = dr[3].ToString();
//get first row data and assign it ex_location variable
string ex_email = dr[4].ToString();
string ex_email1 = dr[5].ToString();
string ex_email2 = dr[6].ToString();
//string ex_company = dr[7].ToString();
string ex_company = dr[7].ToString();
string ex_contact = dr[8].ToString();
string ex_proposal = dr[9].ToString();
string ex_reason = dr[10].ToString();
...............
//Insert operation
...............
dr.Read();
}
dr.close();
my_con.close();
The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended
Properties=Excel 8.0;Persist Security Info=False");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if(dtExceldata.Rows.Count>0)
{
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
see this excel file
and the datatable in c#
this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}

"No value given for one or more required parameters." Access C# Simple Select

Error Returned:
"No value given for one or more required parameters."
String Array to pass to function:
String[,] arrParams = new String[1, 2] {
{"#ToUpper_user_id", id}
};
Value of id:
"test" (without the quotes)
SQL:
strSQL = "select * from users where ToUpper_user_id = ?;";
SQL Function Call:
if (jdb.getdb_data(strSQL, arrParams, strTableName, out dsGet, out strTechMessage))
{
...
}
Function that calls to get data from the db:
public static bool getdb_data(String strSQL, String[,] arrParams, String strTableName, out DataSet dsGet, out String strTechMessage)
{
bool boolRC = true;
String key = String.Empty;
String val = String.Empty;
dsGet = new DataSet();
strTechMessage = String.Empty;
String strSQL_Empty = String.Empty;
string connectionString = jdb.getConnString();
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
if (arrParams.GetLength(0) > 0)
{
for (int i = 0; i < arrParams.GetLength(0); i++)
{
for (int j = 0; j < arrParams.GetLength(1); j++)
{
if (j.Equals(0)) { key = arrParams[i, j]; }
if (j.Equals(1)) { val = arrParams[i, j]; }
}
command.Parameters.AddWithValue(key, val);
}
}
else
{
boolRC = false;
strTechMessage = "No parameters found";
}
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
if (boolRC)
{
try
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
adapter.Fill(dsGet, strTableName);
}
catch (Exception ex)
{
boolRC = false;
strTechMessage = ex.Message;
}
}
}
return boolRC;
}
Please help - I think I am goin' insane! (The Update CRUD all works with parameters . . . just the select code is giving me the error.)
In "get_dbdata(...)" above, I should have have had:
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
instead of:
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
In the code, both the sql and parameters have already been added to the command above.
Works now!

C# Executemultiplerequest For Two Entities

I'm creating web application for uploading/importing excel file into ms dynamics CRM. This web application work fine if there is only a single entity within the excel file. But the web application won't import if there are two entities within excel file.
Here is the code that I have:
protected void btnOne_Click(object sender, EventArgs e)
{
Stopwatch st = new Stopwatch();
st.Start();
if (FileUpload1.HasFile)
{
string Filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string Folderpath = ConfigurationManager.AppSettings["FolderPath"];
string Filepath = Server.MapPath(Folderpath + Filename);
FileUpload1.SaveAs(Filepath);
DataTable dt = ImportData(Filepath, Extension);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
Entity contractline = new Entity("new_contractline");
contractline["new_contractid"] = dt.Rows[i][1].ToString();
contractline["new_lineitem"] = dt.Rows[i][2].ToString();
Entity productitem = new Entity("new_productitem");
productitem["new_instanceid"] = dt.Rows[i][3].ToString();
productitem["new_productnumber"] = dt.Rows[i][4].ToString();
var multiplerequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = true
},
Requests = new OrganizationRequestCollection()
};
CreateRequest createcontractline = new CreateRequest { Target = contractline };
CreateRequest createproductitem = new CreateRequest { Target = productitem };
multiplerequest.Requests.Add(createcontractline);
multiplerequest.Requests.Add(createproductitem);
ExecuteMultipleResponse multirespon = (ExecuteMultipleResponse)service.Execute(multiplerequest);
}
catch (Exception ex)
{
//Label1.Text = ex.Message;
}
}
st.Stop();
TimeSpan ts = st.Elapsed;
Label1.Text = dt.Rows.Count + "Records created, total time consume is " + ts;
}
else
{
Label1.Text = "Tidak ada data yang dipilih";
}
}
}
private DataTable ImportData(string Filepath, string Extension)
{
string connString = "";
DataTable dt = new DataTable();
switch (Extension)
{
case ".xls":
connString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
connString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
connString = string.Format(connString, Filepath, 1);
try
{
OleDbConnection excelConn = new OleDbConnection(connString);
OleDbCommand excelCmd = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
excelCmd.Connection = excelConn;
excelConn.Open();
DataTable dtexcelschema;
dtexcelschema = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtexcelschema.Rows[0]["TABLE_NAME"].ToString();
excelConn.Close();
excelConn.Open();
excelCmd.CommandText = "Select * from [" + SheetName + "]";
oda.SelectCommand = excelCmd;
oda.Fill(dt);
excelConn.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
return dt;
}
}
My question is how to use createrequest for two entities. As you can see above, i tried to call createrequest twice. But it won't work after all.

The given value of type DateTime from the data source cannot be converted to type decimal of the spe

I am trying to migrate data from Oracle to SQL.
I already created Table name and field Name.
Type and Size are same on both: e.g.
at Oracle Varchar2(11), On SQL VARCHAR(11)
at Oracle Date, On SQL datetime2(0).
In my application I'm using SqlBulkCopy function. But I face the above error on Date filed.
private void Processing(string sPath)
{
string AppPath = Application.StartupPath.ToString();
IniFile myIni = new IniFile(sPath);
string allTable = myIni.IniReadValue("TABLENAME", "TABLE");
string[] alltables = allTable.Split(',');
foreach (var tableName in alltables)
{
string whereSqlQuery = string.Empty;
string sOrderBySqlQuery = string.Empty;
string sSQLSelect = string.Empty;
string sRCount = string.Empty;
whereSqlQuery = myIni.IniReadValue(tableName, "WHERE");
TableName = tableName;
sOrderBySqlQuery = myIni.IniReadValue(tableName, "ORDERBY");
sSQLSelect = myIni.IniReadValue(tableName, "SQLSELECT");
//sRCount = myIni.IniReadValue(tableName, "RCOUNT");
if (radAuto.Checked == true)
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery, sSQLSelect, sRCount);
else
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery);
}
}
private void ConnectAndQuery(string strTableName, string strWhere, string strOrderBy, string sSqlSelect, string sRcount)
{
Cursor.Current = Cursors.WaitCursor;
string connectionString = GetConnectionString();
// Using
OracleConnection connection = new OracleConnection();
SqlConnection oConn = default(SqlConnection);
DataTable dtSQL = null;
DateTime dtLog = DateTime.Now;
try
{
//Opening Oracle DB Connection
connection.ConnectionString = connectionString;
connection.Open();
ShownLog(string.Format("Table = {0} , -- STARTING --", strTableName));
ShownLog("Oracle Connection Opened, OK");
OracleCommand command = connection.CreateCommand();
if (!string.IsNullOrEmpty(strWhere))
SqlQuery = "SELECT * FROM " + strTableName + " WHERE "+ strWhere;
else
SqlQuery = string.Format("SELECT * FROM {0} ", strTableName);
if (!string.IsNullOrEmpty(strOrderBy))
SqlQuery += " ORDER BY " + strOrderBy;
command.CommandText = SqlQuery;
System.DateTime startTime = System.DateTime.Now;
ShownLog("Starting Date Time : " + startTime);
DataTable dtTotalInsertCount = new DataTable(strTableName);
if (!string.IsNullOrEmpty(sRcount))
{
//OracleDataAdapter adpCount = new OracleDataAdapter(sRcount, connectionString);
////adpCount.FillSchema(dtTotalInsertCount, SchemaType.Source);
//adpCount.Fill(dtTotalInsertCount);
}
OracleDataAdapter adapter = new OracleDataAdapter(SqlQuery, connectionString);
DataTable dt = new DataTable(strTableName);
adapter.FillSchema(dt, SchemaType.Source);
bool valid = true;
bool bCheck = true;
int count = 1000;
int start = 0;
string sLogQuery = SqlQuery.Replace("'", "");
dtLog = DateTime.Now;
//Insert to SQL Log Table
Insert(strTableName, dtLog, sLogQuery);
int iLogCount = 0;
int iActualCount = 0;
do
{
int iEnd = 0;
adapter.Fill(start, count, dt);
valid = dt.Rows.Count > 0 ? true : false;
if (valid)
{
iLogCount += dt.Rows.Count;
iEnd = start + dt.Rows.Count;
ShownLog("No of data Rows retrieved from Oracle, Count = " + dt.Rows.Count);
//Create the SQL Server Table
oConn = new SqlConnection(txtDestinationConnString.Text);
oConn.Open();
ShownLog("SQL Connection Opened, OK");
if (string.IsNullOrEmpty(sSqlSelect))
bCheck = false;
if (bCheck)
{
ShownLog("Data Comparision Start : " + System.DateTime.Now);
//If SQL Select Statement has
if (!string.IsNullOrEmpty(sSqlSelect))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sSqlSelect;
cmd.Connection = oConn;
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
dtSQL = new DataTable();
dtSQL.Load(reader);
cmd = null;
reader = null;
//Return record has more than 0
ShownLog("Start Duplicate Checking : " + System.DateTime.Now);
if (dtSQL.Rows.Count > 0)
{
foreach (DataRow dr in dtSQL.Rows)
{
DataRow[] result;
if (strTableName == "ITK_STAFF" || strTableName == "ITK_FLIGHT")
{
result = dt.Select("URNO='" + dr[0].ToString() + "'");
}
else
result = dt.Select("URNO=" + dr[0]);
if (result.Length > 0)
{
foreach (var drRemove in result)
{
dt.Rows.Remove(drRemove);
}
}
}
}
ShownLog("End Duplicate Checking : " + System.DateTime.Now);
}
ShownLog("Actual No.s of records to insert : " + dt.Rows.Count);
if (dt.Rows.Count == count)
bCheck = false;
ShownLog("Data Comparision End : " + System.DateTime.Now);
}
if (valid)
{
ShownLog(System.DateTime.Now + " Copying " + strTableName + " From : " + start.ToString() + " To : " + iEnd);
}
start += count;
if (dt.Rows.Count > 0)
{
iActualCount += dt.Rows.Count;
CopyData(dt, oConn);
dt.Rows.Clear();
}
oConn.Close();
oConn = null;
}
} while (valid);
System.DateTime endTime = System.DateTime.Now;
ShownLog("Ending DateTime: " + endTime);
//msgOut("No of rows copied from oracle to SQL Server , Count = " + dt.Rows.Count);
TimeSpan diffTime = endTime.Subtract(startTime);
ShownLog(String.Format("Time Difference is Days : {0}, Hours : {1}, Minites : {2}, seconds : {3} ,Milliseconds : {4}", diffTime.Days, diffTime.Hours, diffTime.Minutes, diffTime.Seconds, diffTime.Milliseconds));
ShownLog(string.Format("Table = {0} , -- FINISHED --", strTableName));
ShownLog(string.Empty);
Update(iLogCount, iActualCount, strTableName, dtLog, sLogQuery, " ", true);
Cursor.Current = Cursors.Default;
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
ShownLog(ex.ToString());
ShownLog(string.Empty);
Update(0, 0, strTableName, dtLog, "", ex.ToString(), false);
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
finally
{
Cursor.Current = Cursors.Default;
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
}
private void CopyData(DataTable sourceTable, SqlConnection destConnection)
{
// Using
SqlBulkCopy s = new SqlBulkCopy(destConnection);
try
{
s.DestinationTableName = TableName;
s.NotifyAfter = 10000;
s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
s.WriteToServer(sourceTable);
s.Close();
}
finally
{
((IDisposable)s).Dispose();
}
}

Generic list not being populated by db

I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}

Categories