how to reduce in multiple try catch - asp.net

hi i am beginner to develop a project, in my project i used try catch with in try catch so how i write the query professionally...
my code is....
try
{
//connection();
con = new SqlConnection(constr);
con.Open();
txtcusname.Text = "";
txtcusnumber.Text = "";
query = "sample_SP";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GetCusID", txtcusid.Text).ToString();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GrdCustomerDetails.DataSource = ds;
GrdCustomerDetails.DataBind();
con.Close();
try
{
//connection();
con = new SqlConnection(constr);
con.Open();
ViewState["VSCusID"] = txtcusid.Text;
cmd = new SqlCommand("select contname,mob from CustContacts_TB where cid='" + ViewState["VSCusID"] + " '", con);
dr = cmd.ExecuteReader();
dr.Read();
txtcusname.Text = dr["contname"].ToString();
txtcusnumber.Text=dr["mob"].ToString();
con.Close();
}
catch(Exception ex)
{
}
finally
{
//connection();
con = new SqlConnection(constr);
con.Open();
ViewState["VSCusID"] = txtcusid.Text;
//cmd = new SqlCommand("select compname from CustCreate_TB inner join CustContacts_TB on CustContacts_TB.'" + ViewState["VSCusID"] + "'=CustCreate_TB.'" + ViewState["VSCusID"] + "' ", con);
cmd = new SqlCommand("select compname from CustCreate_TB where cid='" + ViewState["VSCusID"] + " ' ", con);
dr = cmd.ExecuteReader();
dr.Read();
txtcompname.Text = dr["compname"].ToString();
con.Close();
//txtcusname.DataBind();
}
}
catch (Exception ex)
{
}
finally
{
//connection();
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("select compliantID,priorty,status from NewComp1 where customerid='" + ViewState["VSCusID"] + "' and status='open'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grdpending.DataSource = ds;
grdpending.DataBind();
cmd = new SqlCommand("select compliantID,priorty,status from NewComp1 where customerid='" + ViewState["VSCusID"] + "' and status='closed'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
grdClosed.DataSource = ds;
grdClosed.DataBind();
con.Close();
}
it possible to reduce code and it correct format.... thank you for helping and its useful to develop my coding skills

You essentially have:
try
{
[block1]
try
{
[block2]
}
catch(Exception ex)
{
}
finally
{
[block3]
}
}
catch (Exception ex)
{
}
finally
{
[block4]
}
}
They all seem to fetch data and populate controls or variables. You haven't specified what you would do in an exception, so you could simply have them all in a single try block, or put them all in individual blocks. I can't see why they have to be nested.
Finally is usually used for 'clean up' operations, like disposing of open connections but you seem to be using your Finally for a new select & populate operation, which is wrong.
so:
try
{
[block1]
[block2]
[block3]
[block4]
}
or if you needed to know when a specific block had failed but each in try/catch
try
{
[block1]
}
...
try
{
[block4]
}

why are you making all this connection =???
you may do it
try {
using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection()) {
if (cnn.State == ConnectionState.Closed)
cnn.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand()) {
//first task
}
using (System.Data.SqlClient.SqlCommand cmd1 = new System.Data.SqlClient.SqlCommand()) {
//second one
}
using (System.Data.SqlClient.SqlCommand cdm2 = new System.Data.SqlClient.SqlCommand()) {
//third task
}
}
} catch (SqlClient.SqlException sqlex) {
//catch exception sql
//to do
} catch (Exception ex) {
//generic exceptio
//to do some stuff
} finally {
//if need to do later
}

Related

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;
}
}

Binding Gridview from stored procedure

I bound my gridview (dgvresult2) reading data from a stored procedure. When I debug my gridview.rows.count it is zero though my DataSet table has 5 rows (ds.Tables[0].Rows.Count).
Kindly assist with this - below is my code:
private void ReturnResult ( )
{
try
{
string connetionString = null;
lblcino.Text = "1234";
connetionString = "Data Source= SLB-84NKBT1\\SQLEXPRESS;Initial Catalog=WireLine Tracking Assets; User=admin; pwd=password123";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand command = new SqlCommand("GetCIno", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#CustomerInvoiceNo", SqlDbType.NChar).Value = lblcino.Text; //((Label)dgvresult.FooterRow.FindControl("lblcino")).Text;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
dgvresult2.DataSource = ds;
dgvresult2.DataBind();
dgvresult2.Visible = true;
}
}
else
{
string message = "ds is Empty";
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
}
connection.Close();
}
catch (Exception)
{
throw;
}
}

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

Resources