Transaction Management in asp.net - 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.

Related

"Cannot implicitly convert type 'Lab06.Attendance' to 'System.Collections.Generic.List<Lab06.Attendance>" How to solve this error

AssignmentAttendance.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06 {
public partial class AssignmentAttendance : System.Web.UI.Page
{
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Attendance> attendancelist = new List<Attendance>();
attendancelist = aAttendance.getAttendanceAll();
GridView1.DataSource = attendancelist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string attributename = tb_classcode.ToString();
List<Attendance> attendanceList = new List<Attendance>();
attendanceList = aAttendance.getAttendance(attributename);
GridView1.DataSource = attendanceList;
GridView1.DataBind();
}
/* protected void edit_attendance(object sender, GridViewEditEventArgs e)
{
}*/
}
}
AssignmentContentUploadClass.cs
public class Attendance {
string _connStr =ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _ClassCode = null;
private string _Teacher_ID = "";
private string _TeachingSessions = "";
private string _Remarks = "";
public Attendance()
{
}
// Constructor that take in all data required to build a Product object
public Attendance(string ClassCode, string Teacher_ID, string TeachingSessions, string Remarks)
{
_ClassCode = ClassCode;
_Teacher_ID = Teacher_ID;
_TeachingSessions = TeachingSessions;
_Remarks = Remarks;
}
public string ClassCode
{
get { return _ClassCode; }
set { _ClassCode = value; }
}
public string Teacher_ID
{
get { return _Teacher_ID; }
set { _Teacher_ID = value; }
}
public string TeachingSessions
{
get { return _TeachingSessions; }
set { _TeachingSessions = value; }
}
public string Remarks
{
get { return _Remarks; }
set { _Remarks = value; }
}
public int createAttendance()
{
int result = 0;
string queryStr = "INSERT INTO Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks)"
+ " values (#ClassCode, #Teacher_ID, #TeachingSessions, #Remarks)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", this.ClassCode);
cmd.Parameters.AddWithValue("#Teacher_ID", this.Teacher_ID);
cmd.Parameters.AddWithValue("#TeachingSessions", this.TeachingSessions);
cmd.Parameters.AddWithValue("#Remarks", this.Remarks);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}//end Insert
public Attendance getAttendance(string ClassCode)
{
Attendance attendanceDetail = null;
string Teacher_ID, TeachingSessions, Remarks;
string queryStr = "Select * From Attendance Where ClassCode = #ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", ClassCode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
attendanceDetail = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
}
else
{
attendanceDetail = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return attendanceDetail;
}
public List<Attendance> getAttendanceAll()
{
List<Attendance> attendancelist = new List<Attendance>();
string ClassCode, Teacher_ID, TeachingSessions, Remarks;
string queryStr = "SELECT * FROM Attendance Order By ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ClassCode = dr["ClassCode"].ToString();
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
Attendance a = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
attendancelist.Add(a);
}
conn.Close();
dr.Close();
dr.Dispose();
return attendancelist;
}
}
I am not sure of the error and thus I am not able to provide much
I am trying use the getAttendance(ClassCode) function to retrieve the data based off my input of my classcode in the textbox of my AssignmentAttendance.aspx.
I am thinking of using the getAttendance function in my AssignmentAttendance.aspx file by passing in the data of my classcode entry from the textbox to retrieve the details of the Attendance based off classcode.
However, I am not too sure how that works and might need some help
My database has:
ClassCode
Teacher_ID
TeachingSessions
Remarks
If anything is missing or I did not make things clear do let me know
-Edit-
I am getting an error from my AssignmentAttendance.aspx.cs file
attendanceList = aAttendance.getAttendance(attributename);

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.

How to call a procedure if the procedure does not have parameter

create proc sp_dropdown
as
begin
SELECT r1.regid, r.registration
FROM table1 as r1
INNER JOIN table2 as r ON r1.regid=r.registration and r1.status=r.status
end
this above class is my sp return type,
public class GetAllTableNames_Result
{
public string Name { get; set; }
}
and i can call this like
public List<GetAllTableNames_Result> GetTableNames()
{
List<GetAllTableNames_Result> gatnr = new List<GetAllTableNames_Result>();
SqlCommand cmd = new SqlCommand(
"GetAllTableNames", _connection) {CommandType = CommandType.StoredProcedure};
try
{
_connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//do something with data
gatnr.Add(new GetAllTableNames_Result()
{
Name = rdr[0].ToString()
});
}
_connection.Close();
return gatnr;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
_connection.Close();
}
}
i believe you can get point

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

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