Arithmetic operation resulted in an overflow - asp.net

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.

Related

Stored procedure executing even with the error message

I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.
If the user gets this error message:
This invoice num was already dispatched!
then it shouldn't move on to this aspect of the function
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
//CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
myReader.Close();
}
}
else if (invoice1=="1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
**int a = cmd.ExecuteNonQuery();**
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
//Button2.Visible = false;
//showData();
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:
REFACTOR REFACTOR REFACTOR
It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.
Here is an example of how to organize things. We remove most of the code from the click handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
if (IsChecked(row))
{
var result = ProcessRow(row, i);
DisplayResult(i, result);
}
}
}
Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.
protected TransactionResult ProcessRow(GridViewRow row, int index)
{
var SID = GridView2.Rows[index].Cells[3].Text.Trim();
var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
var loadSheetNum = txtDispatchNum.Text;
var removeUser = lblUsername.Text.Replace("Welcome", "");
return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}
And
public void DisplayResult(int rowIndex, TransactionResult result)
{
switch result
{
case TransactionResult.Success:
dt.Rows.RemoveAt(rowIndex);
DisplayTotals(rowIndex);
DisplaySuccess("Selected record(s) successfully updated");
break;
case TransactionResult.AlreadyDispatched;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
break;
case TransactionResult.RecordNotRecorded;
DisplayError("Record has not yet been recorded");
break;
case TransactionResult.AlreadyRemoved:
DisplayError("This invoice number was remove from dispatch sheet before!!");
break;
}
}
These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.
Here's the rest of the methods:
enum TransactionResult
{
Success,
AlreadyDispatched,
RecordNotRecorded,
AlreadyRemoved
}
private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", invoiceNum);
command.Parameters.AddWithValue("#custPONum", custPONum);
using (var myReader = command.ExecuteReader())
{
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
return false;
}
}
}
return true;
}
}
private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
try
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", loadSheetNum);
cmd.Parameters.AddWithValue("#invoiceNum", invoiceNum);
cmd.Parameters.AddWithValue("#removeUser", removeUser);
return cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) //Primary key violation
{
return -1;
}
}
}
protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
if (!ok) return TransactionResult.AlreadyDispatched;
var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
switch a
{
case -1:
return TransactionResult.AlreadyRemoved;
case 0:
return TransactionResult.RecordNotRecorded;
default:
transaction.Commit();
return TransactionResult.Success;
}
}
}
}
public void DisplayTotals(int i)
{
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text;
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
}
public void DisplaySuccess(string message)
{
lblError.ForeColor = Color.Green;
lblError.Text = message;
}
public void DisplayError(string message)
{
lblError.ForeColor = Color.Red;
lblError.Text = message;
}
A few things to note:
You don't need to call Dispose() if you are using using.
You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.
See if this works. Moved your if/else together:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
else if (invoice1 == "1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
int a = cmd.ExecuteNonQuery();
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
}

ODBC connection to an .accdb file

I am trying to access a microsoft Access database file from a unity project i've been working on, but it keeps throwing an exception because it is unable to find the file and there has been no standard river has been selected.
The Code:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Data;
using System.Data.Odbc;
public class AccDBReader : MonoBehaviour {
public string FileName;
public string Table_Name;
public string Column_name;
public DataTable Dt;
public string text;
public Text testtext;
public void Start()
{
FileName = "FestoMES.accdb";
Table_Name = "tblResource";
Column_name = "ResourceName";
ReadACCDB(Application.dataPath + "/" + FileName);
}
internal void ReadACCDB(string fileToReadFrom)
{
//string connection = "Driver = {FestoODBCTest}; Dbq = " + fileToReadFrom +"; Uid = ; Pwd = ;";
string connection = "Driver ={ Microsoft Access Driver(*.mdb, *.accdb)}; Dbq = " + fileToReadFrom + ";";
Debug.Log("The connection string");
Debug.Log(connection);
string sqlQuery = "SELECT "+Column_name+" FROM "+Table_Name;
OdbcConnection con = new OdbcConnection(connection);
OdbcCommand cmd = new OdbcCommand(sqlQuery, con);
try{
con.Open();
OdbcDataReader reader = cmd.ExecuteReader();
Dt.Load(reader);
reader.Close();
con.Close();
}
catch(Exception ex)
{
Debug.Log("Throws an exception");
Debug.Log(ex.ToString());
}
finally
{
if(con.State != ConnectionState.Closed)
{
con.Close();
}
con.Dispose();
}
if(Dt.Rows.Count > 0 && Dt.Columns.Count > 0)
{
Debug.Log(Dt.ToString());
testtext.text = Dt.ToString();
}
else
{
Debug.Log("Didnt find a table");
testtext.text = "Didnt Find a table";
}
}
}
This is the console log after the program has attempted to run:
The connection string
Driver ={ Microsoft Access Driver(*.mdb, *.accdb)}; Dbq = C:/Users/ASJ/Desktop/ODBC connections and Access/Assets/FestoMES.accdb;
System.Data.Odbc.OdbcException: Error [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. at System.Data.Odbc.OdbcConnection.Open()[0x00000] in <filename unkown>:0
Didnt find a table
It doesnt seem to be able to find the file, yet the file exists at that position, does anyone have an idea of why the driver doesnt work in my case?
Figured out a way to solve it using a custom System DSN instead
internal void ReadACCDB()
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "FIL=MS ACCESS;DSN=FestoACCDBTest";
try
{
conn.Open();
OdbcCommand dbCommand = conn.CreateCommand();
dbCommand.CommandText = "SELECT ONo FROM tblFinOrder";
OdbcDataReader dbReader = dbCommand.ExecuteReader();
for (int i = 1; i < dbReader.FieldCount; i++)
{
testtext.text += " | " + dbReader.GetName(i);
}
}
catch(Exception ex)
{
testtext.text = ex.ToString();
}
finally
{
conn.Close();
}
}

connection timeout in 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

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.

Is it properly closing connection from ASP.Net to SQL SERVER

Is the below piece of code closing the connection properly..
public static bool Hello(string sqlQuery)
{
SqlDataReader dataReader = null;
var isExist = false;
using (var aeConnection = new SqlConnection(ConnectionString))
{
try
{
var aeCommand = new SqlCommand(sqlQuery, aeConnection)
{
CommandType = CommandType.Text
};
aeConnection.Open();
dataReader = aeCommand.ExecuteReader(CommandBehavior.Default);
while (dataReader.Read())
{
int vinCount;
int.TryParse(dataReader["VINCount"].ToString(), out vinCount);
if (vinCount == 0)
{
isExist = true;
}
}
}
catch (Exception ex)
{
if (dataReader != null)
{
dataReader.Close();
}
}
}
return isExist;
}
Yes it is properly closing connection.When the using block is exited (either by successful completion or by error) it is closed.
The using statement gets compiled into a try/finally block
using (var aeConnection = new SqlConnection(ConnectionString))
{
}
It will treated as
SqlConnection aeConnection = null;
try
{
aeConnection = new SqlConnection(ConnectionString);
}
finally
{
if(aeConnection!= null)
((IDisposable)aeConnection).Dispose();
}

Resources