SQL Server connection in .net - asp.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;
}
}

Related

Connecting MS_SQL DB IN asp.net

I was trying to connectMs_sql database in asp.net but server error of network path not found... it is not able to establish connection to sql server...comes while in gridview it is taking it as sqldatasource perfectly
This for customized class to call the ADO.Net. Please use this and let me know if you have any doubts.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = # "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}

data source does not support server-side data paging

i am currently trying to do paging for my gridview but once i allow paging in my gridview it will give me this error : The data source does not support server-side data paging.
this is my code for gridview :
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
conn.Close();
SqlDataReader is forward-only. Server-side Paging needs to be able to traverse the datasource both backward and forward. Use a different datasource, like SqlDataAdapter, which supports bi-directional traversal.
Example (as requested):
string query = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter da = null;
DataSet ds = null;
try {
query = "SELECT * FROM table WHERE field = #value";
conn = new SqlConnection("your connection string");
cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("value", SqlDbType.VarChar, 50).Value = "some value";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
GridView1.DataSource = ds.Tables(0);
GridView1.AllowPaging = true;
GridView1.DataBind();
}
} catch (SqlException ex) {
//handle exception
} catch (Exception ex) {
//handle exception
} finally {
if (da != null) {
da.Dispose();
}
if (cmd != null) {
cmd.Dispose();
}
if (conn != null) {
conn.Dispose();
}
}
SqlDataAdapter is also from the System.Data.SqlClient Namespace.
Have you tried using a SqlDataAdapter to fill a DataSet/DataTable with your SQL results? Then use that DataTable as your data source for the GridView. Basic framework for filling your DataTable:
public DataTable GetDataTable(String connectionString, String query)
{
DataTable dataTable = new DataTable();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
}
}
catch
{
}
return dataTable;
}
And then you can use that DataTable as your GridView DataSource:
String connectionString = "Data Source=<datasource>;Initial Catalog=<catalog>;User Id=<userID>;Password=<password>;";
String query = "SELECT * FROM TABLE_NAME WHERE ID=BLAH";
GridView1.DataSource = GetDataTable(connectionString, query);
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
Hopefully this will help.
You can apply paging to a gridview in two ways
(1) Use an object datasource with your gridview
(2) Use jquery Datatable

Creating DAL for ASP.NET website

I am working on Microsoft Visual Studio DAL in which I am doing the traditional method of fetching/updating the data to show the reviews of the listed items of website by retrieving data from the ItemDetails table of the website database, for creating the ItemDetails.aspx file. I added a DropDownList Control to displaying all items within its categories.
On selection of category from Drop-down list, it shows all items within that category, with a hyperlink attached "Show Details" to it to show details in a grid-view.
i am newbie i have no idea to create DAL for asp.net website. Need easy guidelines to create DAL for asp.net website. Help will be appreciated. What are the other ways to create DAL rather than SQLadapter.
So for example here is a DAL I've used before for calling SPs.
It allows you to execute stored procedures and return dataset, datatables, success responses etc.
Really it depends on how you intend to access the data, will you be writing Stored Procedures or will you have queries in your code. You also have the option of using Entity Framework/LINQ.
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public class _DataInteraction
{
#region "Stored Procedures"
public static DataTable stdReturnDataTableQuery(string procedureName, string db)
{
DataTable myDataTable;
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
cmd.CommandText = procedureName;
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.SelectCommand = cmd;
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((cmd != null))
cmd.Dispose();
}
return myDataTable;
}
// Return a datatable from the database
public static DataTable stdReturnDataTable(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataTable myDataTable = default(DataTable);
string connString = null;
// -----------------------------------------------------------------------
// create instance of connection
// -----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return myDataTable;
}
// Return a dataset from the database
public static DataSet stdReturnDataset(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataSet ds = new DataSet();
string connString = null;
//-----------------------------------------------------------------------
// create instance of connection
//-----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(ds);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return ds;
}
// Return success from a query from the database
public static bool db_NonQuerySuccessResponse(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
string Value = "";
bool success = false;
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
success = true;
}
catch (Exception ex)
{
success = false;
return success;
}
return success;
}
// General non query, no results no success
public static bool db_NonQuery(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
//// Execute scalar on db
//public static string db_Scalar(string strCommandText, ref List<SqlParameter> myParameters, string db)
//{
// SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
// SqlCommand SQLCommand = new SqlCommand();
// string Value = "";
// SQLCommand.CommandText = strCommandText;
// SQLCommand.CommandType = CommandType.StoredProcedure;
// SQLCommand.Parameters.Clear();
// if ((myParameters != null))
// {
// foreach (SqlParameter myParm in myParameters)
// {
// // add the parameter to the command
// SQLCommand.Parameters.Add(myParm);
// }
// }
// SQLCommand.Connection = SQLConnection;
// SQLConnection.Open();
// Value = SQLCommand.ExecuteScalar;
// SQLConnection.Close();
// return Value;
//}
#endregion
}
Below is 1 sample for reference............
public List<T> GetRequests(string strNo)
{
List<T> objlstMapping = null;
Mapping objMapping = null;
try
{
Database objDbInstance = CreateSQLDatabase(DbConnection.MF);
using (DbCommand objDbCommand = objDbInstance.GetStoredProcCommand(Constants.SP_QUESTS))
{
DALBase.AddDbParam(objDbInstance, objDbCommand, "#No", DbType.AnsiString, ParameterDirection.Input, strFolioNo);
objDbCommand.Connection = objDbInstance.CreateConnection();
objDbCommand.Connection.Open();
using (DbDataReader dr = objDbCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
objMapping = new List<T>();
if (dr.HasRows)
{
while (dr.Read())
{
objMapping = new BrokerFolioMapping();
objMapping .Brok_Code = SProposedValue(dr, "Code");
objMapping .Active = SProposedValue(dr, "Status");
objMapping .AccStmt_Active = SProposedValue(dr, "PortfolioStatus");
objlstFolioMapping.Add(objMapping );
}
}
}
}
}
catch (Exception ex)
{
}
return objlstFolioMapping;
}

Reusable code to retrieve data

i have found an very good method for retrieving any result set from the database just by specifying the stored procedure name.i think the code is very much reusable.code is as follows
using System.Data;
using System.Data.SqlClient;
private DataSet GetFreshData(string sprocName)
{
using ( SqlConnection conn = new SqlConnection() )
{
using ( SqlDataAdapter da = new SqlDataAdapter() )
{
da.SelectCommand = new SqlCommand();
da.SelectCommand.CommandText = sprocName;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Connection = conn;
DataSet ds = new DataSet();
try
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
}
catch
{
return null;
}
finally
{
// do other things...calling Close() or Dispose()
// for SqlConnection or SqlDataAdapter objects not necessary
// as its taken care of in the nested "using" statements
}
return ds;
}
}
}
my question is can someone suggest a modification to this method when the stored procedure need to specify several parameters
Easy! :) take a SqlParameter[] as the second argument to the function.
Then make sure da.SelectCommand.Parameters is filled with the list of SqlParameter objects in the SqlParameter[]

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