select command error on refreshing page continuously - c#

I am developing a banking application in which I have written a helper class.
What happens is whenever I continuously, 5 to 7 or more times, press the refresh button, it gives me this error: Fill: SelectCommand.Connection property has not been initialized.
Can any body specify what I am missing in my code, or what more could I do to make it better to perform without any error?
My helper class function is :
private static OdbcCommand cmd;
private static OdbcDataAdapter da;
private static DataTable dt;
public static void GetDataInDataGrid(string sp_Name, GridView gv)
{
dt = new DataTable();
try
{
using (cmd = new OdbcCommand(sp_Name))
{
cmd.Connection = Connection.ConnString.ConnectionString;
using (da = new OdbcDataAdapter(cmd))
{
da.Fill(dt);
if (dt.Rows.Count > 0)
{
gv.DataSource = dt;
gv.DataBind();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The error is occurring in the below code, at the throw statement
try
{
if (!IsPostBack)
{
herlperUtility.GetDataInDataGrid("{ CALL asp_sp_GetDataForSupervisor }", this.gvSuperviseDataGrid);
if (this.gvSuperviseDataGrid.DataSource == null)
{
this.divFailure.InnerText = "No Records Found!!!";
this.divFailure.Attributes.Add("style", "display:block;margin-top:20px;");
}
}
}
catch (Exception ex)
{
throw ex;
}

Write
using (cmd = new OdbcCommand(sp_Name,Connection.ConnString.ConnectionString))
inplace of
using (cmd = new OdbcCommand(sp_Name))
{
cmd.Connection = Connection.ConnString.ConnectionString;

Related

Memory leak in C# Code

I have a piece of code that going to the database every minute to check if there is any report that need to be run, and if there is any it runs it.
The issue is that my object initiation to a database class creates memory leak. If I look at task mgr "user Object" grown by 5 every time tick executing a code.
private void ReportRunTimer_Tick(object sender, EventArgs e)
{
DataConnection dataConnection = new DataConnection(); *<-- when executing this line User Object increasing.*
try
{
reportsToRun = dataConnection.GetListOfTheReportForReportRunTick();
if (reportsToRun.Count > 0)
foreach (string report in reportsToRun)
{
logs("Starting Automatic report generatin", "Successful");
Thread TicketReportMethodThread = new Thread(() => GenerateReport(report, 1));
TicketReportMethodThread.Start();
}
dataConnection = null;
} catch (Exception ex)
{
logs("Starting Automatic report generatin failed: " +ex.ToString(), "Error");
}
finally
{
reportsToRun.Clear();
}
}
DataConnection class
public List<string> GetListOfTheReportForReportRunTick()
{
List<string> RepoerList = new List<string>();
connString = "Server=xxx;Port=xxx;Database=xxx;Uid=xxx;password=xxxx;SslMode=none";
using (MySqlConnection mySqlConnection = new MySqlConnection(connString))
{
try
{
MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT reportname FROM reports WHERE nextruntime < NOW()";
mySqlConnection.Open();
MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
RepoerList.Add(mySqlDataReader["reportname"].ToString());
}
}
catch (MySqlException ex)
{
hd.logs("Failed to get reports with reportstorun_tick Error: " + ex.ToString(), "Error");
mySqlConnection.Close();
}
finally
{
mySqlConnection.Close();
mySqlConnection.Dispose();
}
}
return RepoerList;
}
DataConnection dataConnection = new DataConnection(); used in a few more places and this is the only one that causing an issue.
If I replace code in private void ReportRunTimer_Tick with code from public List GetListOfTheReportForReportRunTick() like bellow. Issue no longer exist, any ideas?
private void ReportRunTimer_Tick(object sender, EventArgs e)
{
List<string> reportsToRun = new List<string>();
try
{
connString = "Server=xxx;Port=xxx;Database=xxx;Uid=xxx;password=xxxx;SslMode=none";
using (MySqlConnection mySqlConnection = new MySqlConnection(connString))
{
try
{
MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT reportname FROM reports WHERE nextruntime < NOW()";
mySqlConnection.Open();
MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
reportsToRun.Add(mySqlDataReader["reportname"].ToString());
}
if (reportsToRun.Count > 0)
foreach (string report in reportsToRun)
{
logs("Starting Automatic report generatin", "Successful");
Thread TicketReportMethodThread = new Thread(() => GenerateReport(report, 1));
TicketReportMethodThread.Start();
}
}
catch (MySqlException ex)
{
logs("Failed to get reports with reportstorun_tick Error: " + ex.ToString(), "Error");
mySqlConnection.Close();
}
finally
{
mySqlConnection.Close();
mySqlConnection.Dispose();
}
}
}
catch (Exception ex)
{
logs("Starting Automatic report generatin failed: " + ex.ToString(), "Error");
}
finally
{
reportsToRun.Clear();
}
}
Issue is caused by
DataConnection dataConnection = new DataConnection(); *<-- when executing this line User Object increasing.*
reportsToRun = dataConnection.GetListOfTheReportForReportRunTick();
But I can't understand why.
I think the memory leak is because you're not disposing your MySqlDataReader. You can do this by just wrapping it in a using statement like this:
using(MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader()){
while (mySqlDataReader.Read())
{
RepoerList.Add(mySqlDataReader["reportname"].ToString());
}
}

OracleDataAdapter hangs on Fill method in Windows XP

OracleDataAdapter hangs on Fill method in Windows XP.
While debugging In windows 7 works fine but VS2008 hangs on Windows XP.
The same applies to the release versions of the app. The sql query used has nothing to do, I have tested the function using simple queries and they all fail.
Here is a code snippet illustrating the initial code:
public static string DBSelectString(string ssql)
{
try
{
OracleDataAdapter da = new OracleDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = new OracleCommand(ssql, Connection);
da.Fill(dt);
return dt.Rows[0].ItemArray[0].ToString();
}
catch (Exception ex)
{
Utils.Log(ex.Message);
return string.Empty;
}
}
Using OracleDataReader still hangs but I managed to find a workaround.
public static string DBSelectStringDR(string ssql)
{
OracleDataReader reader = null;
try
{
Connection.Open();
OracleCommand command = new OracleCommand(ssql, Connection);
reader = command.ExecuteReader();
if (reader.HasRows)
{
//reader.Read();
//return reader.GetValue(0).ToString(); <-------- normally hangs here
try
{
//workaround:
//force exception, since Read has not been executed
string test = reader.GetValue(0).ToString();
}
catch { }
// then, everything works fine
reader.Read();
return reader.GetValue(0).ToString();
}
else
{
return string.Empty;
}
}
catch (Exception ex)
{
Utils.Log(ex.Message);
return string.Empty;
}
finally
{
if (reader != null) reader.Close();
Connection.Close();
}
}
Any ideas ?

Error 3 'Survey.fillmydropdownlist()': not all code paths return a value

Thanks, i need some help, and theres error for DBOperation dbo = new DBOperation(); which they say type or namespace cannot be found.
public partial class Survey : System.Web.UI.Page
{
public DataTable fillmydropdownlist()
{
DataTable drpdt = new DataTable();
SqlConnection con= new SqlConnection();
try
{
con.ConnectionString = #"SurveyFdBk_DB";
con.Open();
string q = "SELECT * FROM [Survey]";
SqlCommand cmd = new SqlCommand(q,con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
return drpdt;
}
catch { }
finally{ con.Close(); }
}
protected void Page_Load(object sender, EventArgs e)
{
DBOperation dbo = new DBOperation();
DataTable dt = new DataTable();
dt = dbo.fillmydropdownlist();
DataTable drpdt= new DataTable();
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = drpdt;
DropDownList1.DataTextField="SurveyName";
DropDownList1.DataValueField="SurveyID";
DropDownList1.DataBind();
}
}
}
All the paths of execution must return something. In your method above there are 2 paths:
public DataTable fillmydropdownlist()
{
try
{
//path 1
return drpdt;
}
catch
{
//path 2
return null; //need return value here
}
}
In the event of an exception being thrown you need to return some sort of value, perhaps null?
That being said catching all errors with no logging or handling is not an advisable practice. You should consider adding some error handling and you should dispose of your DataAdapter in your finally block as well.

How can I query datetime in SQLite database

Here is my code:
string sql = string.Format("select * from StockInTb ");
DataTable dt = dataAccess.GetDataTable(sql);
UploadService.UploadClient client = new UploadService.UploadClient();
if (client.UpdateTest(dt))
{
MessageBox.Show("suceess");
}
else
{
MessageBox.Show("fail");
}
Here is my dataaccess class:
private static string connString;
private static SQLiteConnection conn;
public SQLiteDataAccess()
{
connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
private void OpenConn()
{
try
{
if (conn == null)
{
conn = new SQLiteConnection(connString);
}
if (conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
private void CloseConn()
{
try
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
public System.Data.DataTable GetDataTable(string sql)
{
DataTable dtResult = new DataTable();
try
{
OpenConn();
SQLiteDataAdapter adpter = new SQLiteDataAdapter(sql, conn);
DataSet ds = new DataSet();
adpter.Fill(ds);//here,I got the error.
if (ds.Tables.Count > 0)
{
dtResult = ds.Tables[0];
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
finally
{
CloseConn();
}
return dtResult;
}
I got the error:
String was not recognized as a valid DateTime.
The database is SQLite, and table StockInTb contains some columns which type is datetime.
I've found some solutions like datetime.toString(s), but that's not what I need.
I don't know how to solve this odd problem. If somebody knows the answers, please tell me.
Thanks.
You can use parameter as below, Assume You have Column called MyDateTime and type is DateTime in your StockInTb Table then your query should be change as below.
Note that #InputDate going to add bay using Command.Parameters.Add method. Need to give the same name in both places and you can directly set parameter from DateTime object ( here it is named as InputDate
Command.CommandText = "select * from StockInTb where MyDateTime = #InputDate";
Command.Parameters.Add("#InputDate", InputDate);

StackOverflowException unhandled on SqlDataAdapter.Fill()

StackOverflowException was unhandled. I need help on this. I get the error on the line
adp.Fill(ds)
Also I'm not sure why, but I can't remove throw, it says not all codes returning a value.
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustConn"].ToString();
string cmdStr = "Select * from MainDB";
public DAL() // default parameter. Use?
{
}
public DataTable Load() // what is this for? (loads all the records from the database)
{
SqlConnection conn = new SqlConnection(connStr);
//SqlCommand cmd = new SqlCommand(cmdStr, connStr);
SqlDataAdapter adp = new SqlDataAdapter(cmdStr, connStr); // SqlDataAdapater? Load all?
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
return ds.Tables[0];
}
catch
{
throw;
}
finally
{
ds.Dispose();
adp.Dispose();
conn.Close();
conn.Dispose();
}
}
public DataTable Load() // what is this for? (loads all the records from the database)
{
SqlDataAdapter adp = new SqlDataAdapter(cmdStr, connStr); // SqlDataAdapater? Load all?
DataSet ds = new DataSet();
using(SqlConnection conn = new SqlConnection(connStr))
{
adp.Fill(ds);
return ds.Tables[0];
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
MasterCust.DataSource = GridDataSource();
MasterCust.DataBind();
//DetailCust.DataSource = ds2;
//DetailCust.DataBind();
}
private DataTable GridDataSource()
{
BAL p = new BAL();
DataTable dTable = new DataTable();
try
{
dTable = p.Load();
}
catch (StackOverflowException ee)
{
string message = ee.Message.ToString();
}
finally
{
p = null;
}
return dTable;
}
First, I think the issue is probably in MasterCust. I think that however that is defined may be causing your issues. If you update your question on how this is defined, that may shed some additional light.
Second, you have a lot of extraneous code that could be confusing the issue. Here is what I think that you need to do to pare it down the bare minimum:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
BindGrid();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// Note that this is for debug purposes only. Production code should log
// this exception somewhere so that it can be observed and dealt with
}
}
private void BindGrid()
{
MasterCust.DataSource = BAL.Load();
MasterCust.DataBind();
}
Then your business access class:
public class BAL
{
private static string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustConn"].ToString();
private static string cmdStr = "Select * from MainDB";
public static DataTable Load() // what is this for? (loads all the records from the database)
{
using (var adp = new SqlDataAdapter(cmdStr, connStr))
{
var ds = new DataSet();
adp.Fill(ds);
return ds.Tables[0];
}
}
}

Categories