Using MiniProfiler for direct ADO.net calls - c#

This question will be silly for those who are geeks in C# and profilers.
I am new to c# (basically a c++ developer) . I can profile the database queries if it use dbproviderfactory , but i cannot profile the ado.net calls when it is used directly(raw SqlConnection & SqlCommand). I came across the Miniprofiler code where they also profile direct ADO.net calls. I just dont know how to use it ( integrate it in my profiler ).
My code is
SqlConnection myConn = new SqlConnection(#"Server=192.168.23.99;Initial Catalog=cat1;User ID=user21;Password=userpwd");
SqlCommand myCommand = new SqlCommand("select * from table1", myConn);
SqlDataReader dataReader;
System.Threading.Thread.Sleep(5000);
try
{
myConn.Open();
dataReader = myCommand.ExecuteReader();
GridView1.DataSource = dataReader;
GridView1.DataBind();
dataReader.Close();
myCommand.Dispose();
myConn.Close();
}
catch (System.Exception ex)
{
Response.Write(ex.ToString());
}
When the above code gets executed , how will the classes in MiniProfiler will be called? How to make those classes(hope the class name is SimpleProfiledDbCommand) called when my web application calls SqlCommand(..).?
Need a better clarification on this.

According to the documentation, you need to wrap your SqlConnection with the provided ProfiledDbConnection that is able to track your queries:
SqlConnection underlyingConn = new SqlConnection(#"Server=192.168.23.99;Initial Catalog=cat1;User ID=user21;Password=userpwd");
SqlConnection myConn = new StackExchange.Profiling.Data.ProfiledDbConnection(underlyingConn, MiniProfiler.Current);

Related

C# DataTable and SqlDataAdapter open, close connection and performance issue

This is a function which I used to get data from database
public static DataTable getDataTable(string sql, string tableName)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, new SqlConnection(strConn));
da.Fill(dt);
dt.TableName = tableName;
}
catch (Exception)
{
dt = null;
}
return dt;
}
The questions are:
Does it open and close connection automatically? because it seems we only pass the sql query to SqlDataAdapter and it has no open or close the connection.
Does it will cause any performance to slow down the application?
Does it will cause any performance issue the server (Memory)?
Thanks in advance.
i hope this help you
Answer 1 :
If I remember correctly the SQLConnection manages connection pooling behind the scenes.
Here is a nice article about this very subject:
https://msdn.microsoft.com/en-us/library/ms971481.aspx
Also, a best practice is to use the "using" keyword to wrap your connection because it will automatically close your connection once the scope exits (with or without an exception)
using(SqlConnection conn = new SqlConnection())
{
conn.Open();
//Do Work with connection
} //Connection automatically closes here without the need to call conn.Close()
Answer 2:
Sql Connection open slow down or make application performance better
Answer 3 :
What is Best Approach for Opening/Closing SqlConnection in C#

how to delete data in Sql Server 2012 using c#?

i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Why does my application hang while trying to close a SqlConnection object?

I am trying to get column information in C# from a SQL table on SQL Server. I am following the example in this link: http://support.microsoft.com/kb/310107 My program strangely gets hung up when it tries to close the connection. If the connection is not closed, the program exits without any Exceptions. Here's my code:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
Putting the SqlConnection inside a using block also causes the application to hang unless CommandBehavior.KeyInfo is changed to CommandBehavior.SchemaOnly.
using (SqlConnection connection = new SqlConnection(#"MyConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast even here in the using
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
}
The table in question has over 3 million rows, but since I am only obtaining the Schema information, I would think this wouldn't be an issue. My question is: Why does my application get stuck while trying to close a connection?
SOLUTION: Maybe this isn't optimal, but it does work; I inserted a command.Cancel(); statement right before Close is called on connection:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
command.Cancel(); // <-- This is it.
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
I saw something like this, long ago. For me, it was because I did something like:
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader();
// here, I started looping, reading one record at a time
// and after reading, say, 100 records, I'd break out of the loop
connection.Close(); // this would hang
The problem is that the command appears to want to complete. That is, go through the entire result set. And my result set had millions of records. It would finish ... eventually.
I solved the problem by adding a call to command.Cancel() before calling connection.Close().
See http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=610 for more information.
It looks right to me overall and I think you need a little optimization. In addition to the above suggestion regarding avoiding DataReader, I will recommend to use connection pooling. You can get the details from here :
http://www.techrepublic.com/article/take-advantage-of-adonet-connection-pooling/6107854
Could you try this?
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand("SET FMTONLY ON; " + yourQueryString + "; SET FMTONLY OFF;",conn);
conn.Open();
dt.Load(cmd.ExecuteReader());
}
SET FMTONLY ON/OFF from MSDN seems the way to go
There is an specific way to do this, using SMO (SQL Server management objects)
You can get the collection of tables in the database, and then read the properties of the table you're interested in (columns, keys, and all imaginable properties)
This is what SSMS uses to get and set properties of all database objects.
Look at this references:
Database.Tables Property
Table class
This is a full example of how to get table properties:
Retrieving SQL Server 2005 Database Info Using SMO: Database Info, Table Info
This will allow you to get all the possible information from the database in a very easy way. there are plenty of samples in VB.NET and C#.
I would try something like this. This ensures all items are cleaned up - and avoids using DataReader. You don't need this unless you have unusually large amounts of data that would cause memory issues.
public void DoWork(string connectionstring)
{
DataTable dt = new DataTable("MyData");
using (var connection = new SqlConnection(connectionstring))
{
connection.Open();
string commandtext = "SELECT * FROM MyTable";
using(var adapter = new SqlDataAdapter(commandtext, connection))
{
adapter.Fill(dt);
}
connection.Close();
}
Console.WriteLine(dt.Rows.Count);
}

When using an OracleCommand in .net must the OracleClient be installed on the machine or does .net cover this?

I want to make a simple query on an Oracle database from .net using similar code to this.
using System;
using System.Data;
using Oracle.DataAccess.Client;
class Sample
{
static void Main()
{
// Connect to Oracle
string constr = "User Id=scott;Password=tiger;Data Source=AKI1.WORLD";
OracleConnection con = new OracleConnection(constr);
con.Open();
// Display Version Number
Console.WriteLine("Connected to Oracle " + con.ServerVersion);
// Read REF CURSOR into DataSet
DataSet ds = new DataSet();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "GetComplexTabPkg.GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_dep", OracleDbType.Int16).Value = 20;
cmd.Parameters.Add("p_ref", OracleDbType.RefCursor).Direction
= ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.TableMappings.Add("Emp", "Emp");
da.Fill(ds);
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
// Show Message
Console.WriteLine("DataSet filled");
}
}
My only concern is does the Oracle Client need to be installed on the web server that is running this code? It's my first time using this and I would like to avoid any obvious issues that can be prevented. Thanks.
Yes, Oracle Client need to be installed in web server. The work around will be to ship your application with Instant Oracle Client
On my Own I just install 64-bit Oracle Data Access Components (ODAC) Downloads, which seems to be lighter than Oracle Client.

Categories