connection timeout in asp.net - asp.net

i build a web application and every thing works fine . but after i put it on real work i got a problem
after about 30 minutes working in it any connection will be loading and then through an exception :
request time out.
so i have to restart the server or restart the iis site to access the code again ?
why is that happened and how to fix it.
I use this connection class to connect to the database in the whole code :
public class Connection
{
public static SqlConnection Open()
{
try
{
string ConStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SARC.mdf;Integrated Security=True; Max Pool Size=100; User Instance=True";
SqlConnection con = new SqlConnection(ConStr);
con.Open();
return con;
}
catch (SqlException odbcEx)
{
return null;
}
}
public static SqlConnection Open(string ConStr)
{
try
{
SqlConnection con = new SqlConnection(ConStr);
con.Open();
return con;
}
catch (SqlException odbcEx)
{
return null;
}
}
public static void Close(SqlConnection ConStr)
{
try
{
ConStr.Close();
}
catch (SqlException odbcEx)
{
}
}
public static SqlDataReader Query(string query, bool isreader)
{
try
{
SqlConnection con = Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader rd = com.ExecuteReader();
return rd;
}
catch (SqlException odbcEx)
{
return null;
}
}
private static SqlConnection con;
public static int Query(string query)
{
try
{
con = (con == null ? new SqlConnection() : con);
if (con.State != System.Data.ConnectionState.Open)
con = Open();
SqlCommand com = new SqlCommand(query, con);
int result = com.ExecuteNonQuery();
con.Close();
return result;
}
catch (SqlException odbcEx)
{
return 0;
}
}
}
how can i fix this problem ??? plz help

Related

Populating a dropdown list from the database c# aspx

I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.

SQL Server connection in .net

Here is my code.
public Dataset ReturnDataset()
{
SqlConnection con = new SqlConnection(Proper connectionstring);
SqlCommand cmd = new SqlCommand(spname,con);
Dataset ds = new Dataset();
try
{
con.Open();
cmd.CommandType = CommandType.StoreProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,table);
return ds;
}
catch (TimeoutException Ex)
{
con.Close();
if (Ex.Message.Contains("Timeout expired"))
{
ds = null;
return ds;
}
else
{
throw;
}
}
catch (Exception)
{
throw;
}
Does I need to write finally clause to close connection if error occur or not?In first try block I closed connection and then throw exception.Does I need to do same in second block?What will happen If already closed connection and trying to close once again?
It is always good idea to close your connection on finally part of try catch as below, or use using statment and let .net to take care of it :
try{
}
catch{
}
finally{
conn.close();
}
or use using :
using (SqlConnection connection = new SqlConnection(connectionString))
{
}
You can close on error too. If you are worried about the state of connection before closing you can check if it is open and close it in finally:
if (conn != null && conn.State == ConnectionState.Open)
{
conn.close();
}
If not strictly necessary I avoid to create a structured catch cascade.
If necessary, I always try to define a catch cascade from the more specific exception to the more generic exception.
I always put any cleanup logic in the finally block:
SqlConnection con = new SqlConnection(Proper connectionstring);
SqlCommand cmd = new SqlCommand(spname,con);
Dataset ds = new Dataset();
try
{
con.Open();
cmd.CommandType = CommandType.StoreProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,table);
return ds;
}
catch(TimeoutException toEx)
{
//manage or log specific exception
}
catch(Exception ex)
{
//manage or log generic exception
}
finally
{
//cleanup
con.Close();
ds = null;
}
I would rewrite your code to be something like this:
public DataSet ReturnDataset()
{
// initialize return value
DataSet result = null;
// put SqlConnection and SqlCommand into using () { ....} blocks to ensure proper disposal
using (SqlConnection con = new SqlConnection(Proper connectionstring))
using (SqlCommand cmd = new SqlCommand(spname, con))
{
result = new DataSet();
try
{
con.Open();
// you had a typo: it's a StoredProcedure - not a StoreProcedure
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result, table);
con.Close();
}
catch (TimeoutException Ex)
{
if (Ex.Message.Contains("Timeout expired"))
{
result = null;
}
else
{
throw;
}
}
}
// return the result - null if an error happened, a valid DataSet otherwise
return result;
}
Points I improved:
declare the possible return value at the beginning, return only once at the very end
removed unnecessary "catch" on an exception you don't do anything with -> just let it happen
put SqlConnection and SqlCommand into using(...) { ... } blocks to ensure proper and speedy disposal
Why don't you use the Using Statement that ensures a proper closing and disposing of the disposable objects? I think you don't need to catch the exceptions at this level, just let them bubble up and, if needed take care of them at the upper level
Here you can simply
public Dataset ReturnDataset()
{
Dataset ds = new Dataset();
using(SqlConnection con = new SqlConnection(Proper connectionstring))
using(SqlCommand cmd = new SqlCommand(spname,con))
{
con.Open();
cmd.CommandType = CommandType.StoreProcedure;
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds,table);
}
}
return ds;
}
If this code raises an exception the dataset will be never returned and being a local variable will be quickly become eligible for garbage collection
A better option is to use the using keyword, that does the closing / disposing for you
public Dataset ReturnDataset()
{
using (SqlConnection con = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(spname,con))
{
Dataset ds = new Dataset();
try
{
con.Open();
cmd.CommandType = CommandType.StoreProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,table);
}
catch (TimeoutException Ex)
{
ds = null;
}
return ds;
}
}

Transaction Management in asp.net

I am doing a web application in asp.net.
I have a class CommonDB to save data.
public class CommonDB
{
private static string GetConnectionString = ConfigurationManager.ConnectionStrings["Db"].ToString();
public static SqlConnection GetConnection()
{
SqlConnection Con = new SqlConnection(GetConnectionString);
if (Con.State == ConnectionState.Open)
{
Con.Close();
}
return Con;
}
public static int ExecuteNonquery(SqlCommand cmd)
{
SqlConnection Con = GetConnection();
Con.Open();
try
{
cmd.Connection = Con;
Con.Close();
return ReturnVal;
}
catch
{
Con.Close();
return 0;
}
}
}
}
I am using the following function to save data
public int AddGroupMaster() //Inserting
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NV_Group_Master_Add";
cmd.Parameters.AddWithValue("#Group_ID", iGroupId);
cmd.Parameters.AddWithValue("#Group_Code", strGroupName);
cmd.Parameters.AddWithValue("#Group_Name", strGroupName);
cmd.Parameters.AddWithValue("#Created_On", strCreatedOn);
cmd.Parameters.AddWithValue("#Modified_On", strModifiedOn);
iReturn = CommonDB.ExecuteNonquery(cmd);
return iReturn;
}
catch { return 0; }
}
This function is called from code behind like :
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
objGroup.strGroupName = txtGroupName.Text.Trim();
objGroup.strCreatedOn = DateTime.Today.ToString();
objGroup.strModifiedOn = "";
objGroup.AddGroupMaster();
}
catch
{
}
}
I want to use Commit and rollback. How it is possible in my coding??
Please suggest a solution
In your scenario, you will have to do that in your CommonDB library.
For example, your ExecuteNonQuery method would look like this:
public static int ExecuteNonquery(SqlCommand cmd) {
int retVal;
SqlConnection Con = GetConnection();
DbTransaction tran;
try {
cmd.Connection = Con;
cmd.Connection.Open();
tran = cmd.Connection.BeginTransaction;
cmd.Transaction = tran;
retVal = cmd.ExecuteNonQuery;
tran.Commit()
} catch {
tran.Rollback();
throw;
} finally {
cmd.Connection.Close()
}
return retVal;
}
And yes, do not forget to get a reference to System.Data.Common.

ASP.NET Mysql Data Reader not working

I try to autentificate to a database, to create a Login function. Every time I press the button I receive this error: System.InvalidOperationException: The connection is not open. at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Prepare() at start.CheckUserLogin(String username, String password) in c:\Users\RARES\Documents\Visual Studio 2010\WebSites\tem1\start.aspx.cs:line 46
Please tell me how can I read the data and check if the user and pass are the same as the ThextBox texts.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
if (CheckUserLogin(Label2.Text, Label3.Text))
{
Response.Redirect("login.aspx");
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public Boolean CheckUserLogin(string username, string password)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
String query = "Select * from users where username= ?userName and password= ?passWord";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.Parameters.Add("?userName", TextBox1.Text);
cmd.Parameters.Add("?passWord", TextBox2.Text);
cmd.Prepare();
MySqlDataReader print = cmd.ExecuteReader();
bool read = print.Read();
if(username.Equals(print.GetString("1")) && password.Equals(print.GetString("2"))) return true;
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
return false;
}
You didn't open the connection before calling ExecuteReader method. Call con.Open. Your issue will be resolved.

Arithmetic operation resulted in an overflow

After updating my website on ii7 on window server 2008 from framework 3.5 to work with framework 4
i got my c# base database class stop working copmlitly with this error: "Arithmetic operation resulted in an overflow".
I am working with mysql server from different server.
I did not find any solution on this so i had very sadness to role bakce to framework 3.5
here is some of my logs for this error in the event viewr on my server:
Process information:
Process ID: 3680
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: OverflowException
Exception message: Arithmetic operation resulted in an overflow.
at DataAccess.ExecuteStringQuery(String strSQL) in d:\webSites\s2s\App_Code\DB\DataAccess.cs:line 214
at DataSelect.generalString(String rowName, String tableName, String idName, String ID) in d:\webSites\s2s\App_Code\DB\DataSelect.cs:line 48
at camsBaseShowWeb.OnPreInit(EventArgs e) in d:\webSites\s2s\App_Code\Bases\camsBaseShowWeb.cs:line 134
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
big thanks for any halp
i got this error - no matter wich function i try to call from this code
here is my code:
using System;
using System.Data;
//using Microsoft.Data.Odbc;
using System.Data.Odbc;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class DataAccess
{
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private string _strCon = "Driver={MySQL ODBC 5.1 Driver};Server=theIP;Database=theDatabase; UID=root;Password=thePassword;Option=3;";
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(_strCon);
myConnection.Open();
}
#endregion
#region Public Functions
public OdbcDataReader ExecuteQueryReader(string strSQL)
{
try
{
OdbcCommand myCommand = new OdbcCommand(strSQL, myConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQueryReader SQL s2s", strSQL, ex);
}
throw ex;
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public DataView ExecuteQueryDV(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return new DataView(dt);
}
public DataTable ExecuteLimitedQuery(string strSQL, int startRow, int rowNum)
{
DataTable dt;
DataSet ds = new DataSet();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(ds, startRow, rowNum, "rowTable");
dt = (DataTable)ds.Tables["rowTable"];
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteLimitedQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public object ExecuteScalarQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteScalarQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj;
}
public string ExecuteStringQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Open();
if (myCommand != null) myCommand.Dispose();
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex2)
{
if (Dict.IsRemote == true)
{
sendMail("error - לאחר ניסיון שני ExecuteStringQuery SQL s2s", strSQL, ex2);
}
throw ex2;
}
}
else
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteStringQuery SQL s2s", strSQL, ex);
}
throw ex;
}
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj != null ? obj.ToString() : string.Empty;
}
public int ExecuteNoneQuery(string strSQL)
{
OdbcCommand myCommand = null;
int i;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
i = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteNoneQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return i;
}
public int InsertGetLastID(string strSQL)
{
OdbcCommand myCommand = null;
int LastID = 0;
object objID = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
if (myCommand.ExecuteNonQuery() == 1)
{
myCommand = new OdbcCommand("SELECT LAST_INSERT_ID()", myConnection);
objID = myCommand.ExecuteScalar();
if (objID != null)
{
LastID = int.Parse(objID.ToString());
}
}
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error InsertGetLastID SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return LastID;
}
private void sendMail(string title, string sql, Exception ex)
{
string body = string.Empty +
"SQL:\n\n" + sql + "\n\n" +
"Exeption:\n\n" + ex.Message + "\n\n" +
"Stack Trace:\n\n" + ex.StackTrace + "\n\n" +
"Source:\n\n" + ex.Source + "\n\n";
mailSend mailS = new mailSend("theMail", "mailTo", title, body);
}
#endregion
}
I was getting this too since the upgrade to .Net 4.0
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcCommand.ExecuteScalar()
at Server.Engines.MyRunUO.DatabaseCommandQueue.Thread_Start() in d:\RunUO\Sec
ondAge\Scripts\Engines\MyRunUO\DatabaseCommandQueue.cs:line 117
OdbcConnection version is System.Data.dll, v4.0.30319
Using "{MySQL ODBC 5.1 Driver}" (actually 5.01.06.00) against MySQL 5.1.40-community via TCP/IP on localhost.
The query was any variation of:
SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='chardb'
The (apparently) offending lines:
command.CommandText = string.Format("SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='{0}'", m_timeStampName); // Line 116
object result = command.ExecuteScalar(); // Line 117
This occurred with an x64 compile only, i.e. using the x64 mySQL driver.
This was fixed by upgrading from mySQL ODBC driver 5.01.06.00 to 5.01.08.00
conver to boolean function does not work when
1. Development is done on 32 bit OS
2. Implementation is done on 64 bit OS
When I altered the code for Convert.ToBoolean function, It worked normally.

Resources