How can I get the current user from Sqlconnection - asp.net

I am trying to determine what user my application is using to authenticate to my database, is there a way that I can get the user that is being used to execute the sql code?
string connection = WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand();
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.CommandText = "MySPName";
adapter.SelectCommand.Connection = conn;
using (DataSet ds = new DataSet())
{
try
{
adapter.SelectCommand.Connection.Open();
logULS("Connection Open");
//Want to log the user that has the connection open...
adapter.Fill(ds);
adapter.SelectCommand.Connection.Close();
}
catch (Exception ex)
{
logULS(ex.ToString());
}
}
}

Try this:
SELECT CURRENT_USER;
GO
The above returns the name of the current user. Check here
To see current users connected you could use sp_who
sp_who [ [ #loginame = ] 'login' | session ID | 'ACTIVE' ]

Execute following command against database
sp_who2
it lists all open connections including logins and host names.

Related

Nested Queries In ASP.Net Without Async

I have the following code and basically I want it go step by step using the If statements. When I run this however I get this asp error: "This command requires an asynchronous connection. Set "Asynchronous Processing=true" in the connection string."
On this bit of code:
"addToTable.BeginExecuteReader();"
However I do not want it to by async I want it to run the subsequent queries only if the previous conditions are met.
Full code is below:
string dataset="";
if (System.Web.HttpContext.Current.Session["user"] != null)
{
if (name != null && carId != null)
{
using (SqlConnection con = new SqlConnection(st))
{
string getCar = "SELECT * FROM [Car] WHERE CarId = #carId";
SqlCommand cmd = new SqlCommand(getCarData, con);
cmd.Parameters.AddWithValue("#carId", carId);
using (cmd)
{
con.Open();
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
{
while (data.Read())
{
if (data["available"].ToString() == "0")
{
data.Close();
SqlCommand getParts = new SqlCommand("SELECT * FROM [CarCustomer] WHERE UserId = #UserId AND car=#carId", con);
getParts.Parameters.AddWithValue("#userId", System.Web.HttpContext.Current.Session["userId"]);
getParts.Parameters.AddWithValue("#carId", carId);
SqlDataReader grabRows = getParts.ExecuteReader();
if (grabRows.HasRows)
{
grabRows.Close();
SqlCommand updateTable = new SqlCommand("UPDATE [Table1] SET salesAmount=5 WHERE UserId=1", con);
updateTable.BeginExecuteReader();
}
else
{
grabRows.Close();
SqlCommand addToTable = new SqlCommand("INSERT INTO [Table1] (salesAmount) Values("1")", con);
addToTable.BeginExecuteReader();
}
dataset="good"
}
}
}
}
}
}
}
return dataset;
Instead of BeginExecuteReader command use SqlCommand.ExecuteNonQuery , because ExecuteNonQuery is used to perform query like insert,update and delete where as for Gettting data Read method is used.
one more thing BeginExecuteReadermethod is used to perfrom asncy read operation so if you dont want that than just use ExecuteReadermethod to get data.
Read SqlCommand.ExecuteNonQuery -
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

Passing SqlParameter in webmethod asp.net

I am trying to create a web service which will help to execute stored procedure. And that web method I am calling in my code to execute a stored procedure. This is my web method -
[WebMethod(Description = des_ExecuteParamerizedSelectCommand)]
public DataTable ExecuteParamerizedSelectCommand(string CommandName, CommandType cmdType, SqlParameter[] param)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString()))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(param);
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch
{
throw;
}
}
}
return table;
}
Now this is my code in my data access layer - when I am trying to call this web method, its throwing compile time error.
Error 2 Argument 2: cannot convert from 'System.Data.CommandType' to 'DAL.sqlDBHelper.CommandType'
Error 3 Argument 3: cannot convert from 'System.Data.SqlClient.SqlParameter[]' to 'DAL.sqlDBHelper.SqlParameter[]'
My code to call the webmethod -
sqlDBHelper.ODCdbHelper mysqlDBHelper = new sqlDBHelper.ODCdbHelper();
public Login GetUserRoles(string _Idsid)
{
Login login = null;
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#UserName", _Idsid)
};
//Lets get the list of all employees in a datataable
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", CommandType.StoredProcedure, parameters))
Can you please tell me someone, where I am wrong??
Thanks in advance
Gulrej
Try like this
DAL.sqlDBHelper.SqlParameter[] parameters = new DAL.sqlDBHelper.SqlParameter[]//Change Here {
SqlParameter("#UserName", _Idsid)
};
//Lets get the list of all employees in a datataable
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", DAL.sqlDBHelper.CommandType.StoredProcedure, parameters))
I presume DAL.sqlDBHelper.CommandType will be an enumerator in your data access layer.
And the expected parameter is DAL.sqlDBHelper.SqlParameter[] instead of System.Data.SqlClient.SqlParameter[]
So you might call the select function as
DAL.sqlDBHelper.SqlParameter[] parameters = new DAL.sqlDBHelper.SqlParameter[]
{
new SqlParameter("#UserName", _Idsid)
};
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", DAL.sqlDBHelper.CommandType.StoredProcedure, parameters))
Please check what is the command type defined for stored procedures in your DAL.

SqDataReader closed issue in .net

i have created a function which executes query and returns SqlDataReader, now i am using that in another function work with the returned data, but i gets the error saying reader is already closed. here is the functions:
public static SqlDataReader ExecuteReader(string procedure, SqlParameter[] parameters, CommandType commandType)
{
SqlDataReader reader = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(procedure, connection))
{
connection.Open();
if(parameters != null)
{
if (commandType == CommandType.StoredProcedure)
command.Parameters.AddRange(parameters);
}
reader = command.ExecuteReader();
}
}
return reader;
}
here is the code where i am calling the SqlDataReader
using (SqlDataReader reader = SqlHelper.ExecuteReader("select top 10 username from users", null, System.Data.CommandType.Text))
{
Response.Write(reader.IsClosed); //This returns True
}
EDIT
ExecuteReader with CommanBehavior ( automatically close connection after reading data)
To over come connection closing proble just make use of CommandBheviour
- CommandBehavior.CloseConnection
When you pass above values as argument to ExecuteReader
1. there is no need to close connection explicitly connection get close when you close your reader.
code will be like this no need to close connection explicitly
public void CreateMySqlDataReader(string mySelectQuery,string myConnectionString)
{
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
//Implicitly closes the connection because CommandBehavior.CloseConnection was specified.
}
its causing problem because you are closing connection
SqlReader always make use of open connection i.e live connection which is open when you use this
using (SqlConnection connection = new SqlConnection(connectionString))
{
}
it dispose connection object which is used by reader object that why its returing IsColosed as true
If you wanto return value the objec than make use of DataTable which is disconnected data object and doens makse use of connection
Modified code
public static DataTable ExecuteReader(string procedure, SqlParameter[] parameters, CommandType commandType)
{
DataTable dt = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(procedure, connection))
{
connection.Open();
if(parameters != null)
{
if (commandType == CommandType.StoredProcedure)
command.Parameters.AddRange(parameters);
}
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
return dt;
}
DataReader needs an Open Connection. What you can do it either return a DataTable or Have custom class to represent the results of your SQL query and return an instance of that.
Create a Class to represent your Entity
public class Customer
{
public int ID { set;get;}
public string Name { set;get;}
}
And inside your method;
public List<Customer> GetCustomer()
{
List<Customer> custList=new List<Customer>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("yourParameterizedSQLQuery",
connection))
{
//Add parameters if needed
connection.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
cust=new Customer();
while(reader.Read())
{
var cust=new Customer();
// TO DO :Do db null checking before reading
cust.ID=reader.GetInt32(reader.GetOrdinal("ID"));
cust.Name=reader.GetString(reader.GetOrdinal("Name"));
custList.Add(cust);
}
}
}
}
}
return custList;
}
The problem is that you have using SqlConnection which closes the connection to your database when leaving the scope.
SqlDataReader needs a "still open" connection. Returning it to the parent does not keep the connection open.
Your choice are basically to return a DataSet, which is an "unconnected" data source or change the way you manage your connection to open it, use the SqlDataReader, close the connection.
You may have to leave the connection open and let the calling code close the connection associated with the reader.
I had this challenge so I change my return type to DataTable
reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
That way I don't have to worry about closing the connection outside that method

SQLiteException: Unable to open the database file

I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?
Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")

asp.net connection open and close

Let say i have one asp.net application that is having some page that uses the connection continuesly.....
i have open the connection in class file in construscter ......
and i m accessing it using the object of the class....when ever database operation are required...
in start the application is running fine....but after some operation with database in datagrid(ex. sorting,paging,other).... it's gets slow...and again start working after some time....
do you guys have any solution or any suggession for that.....
i have used the connection in following way....
public class student_operation
{
public SqlConnection cn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public SqlDataAdapter ad = new SqlDataAdapter();
public DataSet rs = new DataSet();
public DataSet rs1 = new DataSet();
public student_operation()
{
//
// TODO: Add constructor logic here
//
try
{
cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
cn.Open();
}
catch (Exception)
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
cn.Open();
}
}
}
}
Make sure you are opening AND closing your connection. Don't worry about "pooling" the connection. .Net will handle that for you automatically. Just open the connection, do your work and close the connection (even if that's done in the static part).
I don't see where you are closing your connection. I would implement IDisposable and clean everything up there. Then you can access your class in a using statement.

Resources