Most people seem to have the opposite problem, but the solution is "grant access on the DB." I want to restrict access for one of two connections to the database (LocalDB). I'm afraid the answer is "create a database user and use that to connect." This is for testing only and I don't want to provision a user. Is there any way to enforce a readonly connection with LocalDB, say, through a connection string? I doubt it, but I thought I'd ask. Here's my current connection string:
<add name="readonlyConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Database=test;Trusted_Connection=True; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
The implementation is much more complicated but basically uses the System.Data.Entity.DbContext class, if that helps.
Short answer: No.
Longer answer:
You can find all of the options available for connection strings here; in short, the permissions assigned to a connection are not a concern of the ConnectionString class; they're a concern of the database.
People have tried to do this with Entity Framework and it has only resulted in a series of hacks that are more work than just creating the darn user in the first place.
Here's what you do (in a context that's not readonly):
using (var connection = (db as DbContext).Database.Connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = "sp_executesql";
command.CommandType = CommandType.StoredProcedure;
var param = command.CreateParameter();
param.ParameterName = "#statement";
param.Value = #"
CREATE LOGIN readonlyLogin WITH PASSWORD='testpassword'
CREATE USER readonlyUser FROM LOGIN readonlyLogin
EXEC sp_addrolemember 'db_datareader', 'readonlyUser';
";
command.Parameters.Add(param);
connection.Open();
try {
command.ExecuteNonQuery();
} catch (SqlException ex) { // user already exists
if (ex.Errors[0].Number.Equals(15025)) { } else throw ex;
}
}
}
And then, in your connection strings for your test project:
<add name="readonlyConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Database=test;Trusted_Connection=False;User Id=readonlyLogin;Password=testpassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Related
I'm attempting to insert some data into my local SQL database. The command seems to run successfully and I'm not getting any errors, but for some reason the data is not being inserted into the database. Have I forgotten something?
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String:
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\App_Data\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient" />
update:
SOLVED! I was trying to output to another directory for some reason. Ended up recreating the database which solved the issue.
Do
int affected = querySaveUser.ExecuteNonQuery();
and set a debug point and watch affected value.
According to MSDN "If a rollback occurs, the return value is also -1."
In case you are debugging a copy of your DB is created in bin/Debug folder, thus you might be checking different DB. Check this - https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx
I check your code and its working fine in my system but i have changed your connection string so please modified your connection string as mine then check i hope your problem solved
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String: web.config
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf; Initial Catalog=Database.mdf; Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
It might help someone looking for Entity Framework Core or ASP.NET Zero related solution.
In my case I was using ASP.NET Zero boiler plate templates for ASP.NET Core and it was not inserting into the database. After a few minutes exploration, I found out that ASP.NET Zero does not immediately execute the ef queries on db rather it inserts rows at end of the unit of work.
Usually, it fails to insert if there is an exception it will log that to Logs table, you can see the latest logs with exceptions if they were failed.
If you want to execute the queries immediately, you can force it to save changes by calling the SaveChanges() method like this:
await CurrentUnitOfWork.SaveChangesAsync();
I'm new to ASP.Net MVC 5 and have previously created two applications using ASP.Net Webforms and Ado.Net Database connections.
I've seen many articles explaining how to use Ado.Net connection in ASP.Net MVC, but all the tutorials are using Entity Framework. Is there any way to connect only Ado.Net?
In my WebForm application I've been using this connection code:
connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "SQL Statement";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
}
Is it possible to use this in ASP .Net MVC5?
When I tried I got this error:
Cannot open database "online_recharge" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\DefaultAppPool'.
This is the code I tried using:
public ActionResult Add_Balance()
{
string record;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from COMMISSION_PACKAGE",sqlConnection);
SqlDataReader reader = sqlCmd.ExecuteReader();
record = reader["PKG_NM"].ToString();
sqlConnection.Close();
}
ViewBag.Demo = record;
return View();
}
There's nothing stopping you from using ADO.NET in MVC.Entity Framework is a very popular ORM and it's really simple to set up that's why people like using it for tutorials.But if you need a more custom\controlled way of accessing your data you can still use ADO.NET.
Just a tip - don't store your connection in code, that's considered bad practice.If the database is moved to a different server you will need to change code and re-compile the whole application.You should store the connection string in the *.config file:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"/>
</connectionStrings>
And can access it from your code like this:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
My code works well but after trying to host it. Its database always response with the null value . I failed to host it. and now when i try to debug in my PC its also have the same problem of null response.
my class file and its scalar query code.
public Object ExecuteScalarQuery(String sp)
{
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
// string _ConnString = ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
SqlConnection myConnection = new SqlConnection(_ConnString);
SqlCommand cmd = new SqlCommand(sp, myConnection);
Object result = 0;
try
{
myConnection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
finally
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
return result;
}
And web.config file having connectionstring
<connectionStrings>
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True " providerName="System.Data.SqlClient"/>
while doing step by step debugging its connectionstring look like this which is not being working.
"Data Source=CHINTAN-PC\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True "
One thing to check is that results are being returned by your stored procedure. I copied your code, made a table and a stored procedure to query all records from it, and it returned null when the table was empty and the value of the first column of the first row when I added a couple records.
add the property 'pooling'.
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True; pooling=false;" providerName="System.Data.SqlClient"/>
go to server explorer, select you data base. in the right pane(Properties) copy connection string and paste it. if that doesn't work. go to sql management studio. its your windows authentication and sql authentication problem. make a new sql authentication login and give userid="" and password="" like "sa" and "sa123" in the connection string.
Use toString to retrieve the string value
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString.toString();
In window application, i am trying to work with database, how to write connection string in app.config. The below is connection string in app.config
<configuration>
<appSettings >
<add key ="mycon"
value ="server=192*****;database=*****;
uid=**;pwd=*****;"/>
</appSettings>
</configuration>
Code to connect database:
SqlConnection con = new SqlConnection(
ConfigurationSettings.AppSettings["mycon"].ToString()); con.Open();
SqlCommand cmd = new SqlCommand("Usp_chat_login", con);
cmd.CommandType = CommandType.StoredProcedure ;
cmd.Parameters.Add("#userid", SqlDbType.VarChar, 20);
cmd.Parameters["#userid"].Value = textBox1.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 20);
cmd.Parameters["#password"].Value = textBox2.Text;
int reslt = cmd.ExecuteNonQuery(); con.Close();
if (reslt > 0)
{
MessageBox.Show("Yes");
}
else
{
MessageBox.Show("No");
}
Every time i am getting reslt=-1, even if i pass correct credentials
Every time i am getting reslt=-1, even if i pass correct credentials
This has nothing to do with the credentials, nor does it pertain to the config file. If authentication/authorization to the database failed, an exception would be thrown.
The problem is likely in your Usp_chat_login procedure.
See the documentation for ExecuteNonQuery():
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1. If a rollback occurs, the return
value is also -1.
Other notes:
Types which implement IDisposable should be disposed of, especially types which interact with unmanaged resources (e.g. database connections). A simple way to do this is to wrap the instances of these types in a using statement.
Plain-text passwords are considered insecure/irresponsible in any application.
Write it in App.XAML
public partial class App : Application
{
public App()
{
string connectionStr = "Data Source=system\\SQLExpress;Initial Catalog=DBName; user id=sa; password=test123;";
Application.Current.Properties["conStr"] = connectionStr;
}
}
and Access it in main form
static string strCon = Application.Current.Properties["conStr"].ToString();
I'm trying to teach myself c#, and have found various examples on connecting to a MSSQL database. What I've done seems to be the simplest way to do it, but still seems overly complicated.
Is there a better way?
here's my code:
static void dbcon()
{
List<int> familyID = new List<int>();
String connString = "Server=[myServer]\\[myInstance];Database=[dbName];User Id=[userID};Password=[password];";
using (var sqlconn = new SqlConnection(connString))
{
using (var cmd = sqlconn.CreateCommand())
{
try
{
sqlconn.Open();
cmd.CommandText = "SELECT id FROM family";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
familyID.Add(Convert.ToInt32(reader["id"].ToString()));
}
}
foreach (int tempy in familyID)
{
Console.WriteLine("id: " + tempy);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
This is fine for an app that only runs one sql statement, but you wouldn't want to use all that code every time you wanted new data.
What you want to do is separate the code that creates the connection, from the code that gets and runs the sql, from the code that deals with the results.
This way, the connection code (and possibly the data display code) can be written once and called each time you want to execute different sql, and you only have to concentrate on how to write the code that gets the data you want.
hth
Details: First of all welcome to Stackoverflow. Just a few tips below
Having your connection string hard coded like that is bad practice. You should ALWAYS have it in your App.config (or Web.config if it is a web application). The reason is because if you have it hard coded and your boss ask you to change the Applications Database connection string you will need to recompile the entire application. If you have it in a App.config file you just need to change it (open it up with notepad) and save it.
Example on how to add it to the app.config
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB;
Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then to access it in your code (You will need to add a reference to System.Configuration as well as add using System.Configuration;)
string connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
In regards to your other code I would change your exception catching to include the Sql Exception first and then fall back to any other exceptions.
catch (SqlException ex)
{
// Handle the Sql Exception code
}
catch (Exception ex)
{
// Handle the Normal Exception code
}
The example contained in the docs for SqlConnectionStringBuilder is quite easy to follow and understand as an alternative way.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
Edit:
Actually, the example I copied above shows you how the SqlConnectionStringBuilder class handles an "...invalid value in a safe manner". Whoops. At least it gives you an idea of how it works.
For more info on the various methods of obtaining, storing and constructing your connection string within ADO.NET, look at the MSDN documentation on Connection Strings