Sql helper class in asp.net - asp.net

Why should we use sql helper class in our application.What difference between sql helper class and simple class.In which situation sql Helper should used.Please define structure of class.

SqlHelper is intended to consolidate mundane, repetitive code that is written time and time again in data access layer components of ADO.NET applications, like this:
using Microsoft.ApplicationBlocks.Data;
SqlHelper.ExecuteNonQuery(connection,"INSERT_PERSON",
new SqlParameter("#Name",txtName.Text),
new SqlParameter("#Age",txtAge.Text));
Instead of this:
string connectionString = (string)
ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("INSERT_PERSON",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Name",SqlDbType.NVarChar,50));
command.Parameters["#Name"].Value = txtName.Text;
command.Parameters.Add(new SqlParameter("#Age",SqlDbType.NVarChar,10));
command.Parameters["#Age"].Value = txtAge.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
It is part of the Microsoft Application Blocks framework.

Related

Asp.net "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."

I am facing one problem in asp.net Application with sql server database.
I am getting Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
In my code stored procedure is taking around 43 seconds and after 30 seconds
I am getting this error. For Solving this I have analyzed many sites and found these solutions:
I need to set Connection Timeout=300 in connectionString in web.config file.
This point I have done, but still I get the same error.
I also need to set commandTimeout through code.
My problem : I am not able to modify the default commandTimeout
Because I am using DataTier_Using_SQLClient to connect to database.
This does not contain the commandTimeout property .
Actually default command timeout is 30 seconds only.
Assuming you are using an Adapter
DataSet dsData = new DataSet();
SqlConnection conn = new SqlConnection(GetConnection());
SqlDataAdapter adapter = new SqlDataAdapter(strQuery, conn);
adapter.SelectCommand.CommandTimeout = 120;
Thank you very much Tim B James and January Mmako
Actually I was solving one issue related to one application.
DataTier_Using_SQLClient is one class in my application to connect with Database.
Then forget this class.
I have solved this issue by creating connection using SqlConnection.
See the code below. Using this code you can solved the Time Expired Error
and can call retrieve stored procedure having one parameter that need to pass:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
use the below code where you want
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
//You can specify this connectionString in web.config or here
connetionString = "Data Source=servername;
Initial Catalog=PUBS;User ID=sa;
Password=yourpassword;
Connection Timeout=300";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_Retrieve_ProcedureName";
param = new SqlParameter("#paramName", ParamValue);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.Int32;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.SelectCommand.CommandTimeout = 120;
adapter.Fill(ds);
you can use this ds (DataSet) object where ever you want.

Can Glimpse provide diagnostics when using the SqlClient namespace classes

I've downloaded Glimpse and the Glimpse.ADO extension and installed it on my test instance.
I thought I'd get a capture of any sql that was executed, but it seems like it doesn't capture commands with the way our code is written.
using (var conn = new SqlConnection(cString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Select count(*) from table";
cmd.CommandType = CommandType.Text;
txtResult2.Text = cmd.ExecuteScalar().ToString();
conn.Close();
}
I CAN get it to provide information from a test page with the sql code written like so:
var factory =DbProviderFactories.GetFactory(cString.ProviderName);
using (var connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString.ConnectionString;
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM table";
command.CommandType = CommandType.Text;
txtResult1.Text = command.ExecuteScalar().ToString();
}
}
However I have too many places in my code to change if I can only capture data using this dbProviderFactories method.
Is there a way to get Glimpse.ADO to work with the System.Data.SqlClient.SqlConnection class? Is there another Glimpse extension that works with this namespace?
Is there another way to tackle this problem?
I agree with #StriplingWarrior, leveraging the provider factories will make your code more DRY and follow best practices. DbProviderFactories really is the best way to do this and your code won't explicitly rely on Glimpse.
However, if you really want to just move forward with your existing app code, Glimpse will support you with the following changes:
using (var conn = new GlimpseDbConnection(new SqlConnection(cString))
{
conn.Open();
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = "Select count(*) from table";
cmd.CommandType = CommandType.Text;
txtResult2.Text = cmd.ExecuteScalar().ToString();
conn.Close();
}
In the example above, the command is created with the CreateCommand() method, which removes the need to associate the command and the connection.
Alternatively, you could also still explicitly create the command like so:
conn.Open();
DbCommand cmd = new GlimpseDbCommand(new SqlCommand());
cmd.Connection = conn;
cmd.CommandText = "Select count(*) from table";
cmd.CommandType = CommandType.Text;
Finally, more documentation about the SQL tab is available by clicking the ? icon in the Glimpse UI when you have the tab selected, or by going to our SQL documentation on getGlimpse.com. (I'll be adding this info to that page for future reference.)
In problems section on Glimpse site...
Getting Glimpse to work with manual created SQL Connections/Commands
http://getglimpse.com/Docs/Manual-ADO-Integration

InsertCommand inside of code behind

I came across the followng code in the code behind and wondering
if this may be a good practice in terms of inserting a record
programmatically:
protected void ButtonMain_Click(object sender, EventArgs e)
{
string sConn = ConfigurationManager.ConnectionStrings["SQL1"].ConnectionString;
SqlDataSource dbQ = new SqlDataSource();
dbQ.ConnectionString = sConn;
dbQ.InsertCommand = "INSERT INTO data1_DropDownLists (ParamID, ddlValue) VALUES ('" + ddlAllParams.SelectedValue + "','" +
txtddl.Text + "')";
dbQ.Insert();
DropDownGrid.DataBind();
dbQ = null;
}
What I have seen is before is something like:
string query = "INSERT INTO data1_DropDownLists vALUES ...";
cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
so was not sure of what the benefit may be to using the above method using InsertCommand
The SqlDataSource is a control in the System.Web namespace. It can be used as datasource for web-databound controls like Repeater or GridView.
It is a control which should be used declaratively on the aspx markup and not in codebehind. It's like an interface between the GUI and the DAL. Normally you should avoid this kind of hardlinking. Instead you should separate GUI(ASPX), BLL(codebehind or class libraries etc.) and DAL (ADO.NET or Entity framework etc.).
I would suggest to use the most direct way, using an ADO.NET SqlCommand:
// use using-statement to ensure that the connection gets closed even in case of an error
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("INSERT INTO dbo.Table(Column)VALUES(#Column)", con))
{
// use parameters to avoid SQL-Injection
cmd.Parameters.AddWithValue("#Column", value);
con.Open();
cmd.ExecuteNonQuery();
}
}
The SqlDataSource class has four command properties, one for each sql action: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand.
Once an instance is created, each of the command property can be set.
The class also exposes a two arguments constructor SqlDataSource(String, String) where the second argument specifies the SELECT command text.

Execute SQL stored using ado.net

I am using ado.net to access sql server I have costum Stored Procedure I am executing it using ado.net :
SqlCommand command = new SqlCommand("Custom",con);
and i am sending the parameters like this :
command.Parameters.Add(new SqlParameter("#Parm1",SqlDbType.Int,0,"Parm1"));
command.Parameters.Add(new SqlParameter("#Parm2",SqlDbType.Int,0,"Parm2"))
it dose not work and it did not give me an error as well it is the first time to work without DAL generator
Please, use this pattern:
SqlCommand command = new SqlCommand("nameOfMyStoredProcedure", mySqlConnectionObject);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
to make it work add this line before set the params :
command.CommandType = CommandType.StoredProcedure;
and set the params using :
command.Parameters[0].Value=4;
command.Parameters[1].Value=2;
:)

How to connect to SQL Server with asp.net

I want to connect to SQL Server with ASP.NET. Can any one give me some sample program to do so?
Here's an example
http://www.beansoftware.com/ASP.NET-Tutorials/ASP.NET-SQL-Server.aspx
Good Luck!
June R's example is inserting data.
using System.Data;
using System.Data.SqlClient;
string Connection = "server=ALDAN; uid=sa; pwd=sa; database=GAZCAD; Connect Timeout=10000";
SqlConnection DataConnection = new SqlConnection(Connection);
// the string with T-SQL statement, pay attention: no semicolon at the end of //the statement
string Command = "Select * from myTable";
// create the SQLCommand instance
SQLCommand DataCommand = new SqlCommand(Command, DataConnection);
// open the connection with our database
DataCommand.Connection.Open();
// Data adapter
SqlDataAdapter da = new SqlDataAdapter(DataCommand);
// To fill data, i need a datatable.
DataTable dt = new DataTable();
// Filling my table
da.Fill(dt);

Resources