I run an Admin site that manages client machines. Each client machine is assigned a specific Sql Server database user. Up to this point I've had to go into Management Studio and create the users. I'd like to do this automatically when I setup a client machine on the Admin site.
Any suggestions on the best way to do this? I'm using ASP.NET MVC 2(old, I know) and Entity Framework 6.
You can set up a feed that automatically imports the credentials to the existing user table in SQL if you have write-back capabilites.
create a SQL connection to the server and create the users via TSQL
Web.Config
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
C#
CreateUser()
{
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "tsql to create users here";
cmd.ExecuteNonQuery();
}
}
}
You could do this via SQL directly when the client machine is set up by using the CREATE USER / CREATE LOGIN statement (and assigning its privileges accordingly). You can get the SQL to guide you in doing so if you start adding the user in management studio then hit the script button at the top left of the dialog it will show you the SQL script to dynamically create the user account. Create User SQL Docs Create Login SQL Docs
Related
I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();
I am kinda new at Asp.net and I have been trying to create a simple Transaction based system wherein users with different roles will have different menus and categories available for them. Currently, I am using this tutorial for my authenticated based login.
The code is working but I have noticed that the database being used is the default connection. What I wanted to do was create my own database and use it as the default connection (MyOwnConnectionString). How can I do that?
I am using VS 2015 and Sql Server 2016. I have a two tables namely Tbl_User and Tbl_Roles where the two tables are linked with the role_id
UPDATE
The tutorial above is about using the default registration of Asp.net wherein if the username to be used for registration matches the declared variable (in this case Admin), the user is given the role of Administrator in the Default Connection under tables AspNetUser, AspNetUserRoles, AspNetRoles.
I have a table named Tbl_User with columns "Name, Username, Password, Role"
Whenever I try to login, the database to be used is my created database(DB_Transaction) and not the default connect of Asp(DefaultConnection DB) and search for the corresponding roles in Tbl_Roles whether Admin or User then redirect them to their corresponding pages.
What should happen
If you want to use Asp.net Identity authentication and authorization then we need not to create table own self,the identity does it for us after user is registered.
And login is handelled along with the authorization.Just specify the database name in ConnectionString and for now you can use DefaultConnection as ConnectionString Key.Add the register a dummy user.You should see tables in your specified database.
Create database in SQL 2016 Add that connection string in WEB config file.
After pass that connection string to your SQL Connection Object or Database Context for Entity framework.here is reference link
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
you can change the default connection from web.config file open it an go to connection string and remove the default connection and copy your server name connection at SQL and paste in the connection string and u can change the database name
as u can see in this image start remove the default connection from the local word
enter image description here
enter image description here
this is the server name connection
You can use the web.config file to update your connection string
or
use it in your code as well
using System.Data.SqlClient;
SqlConnection connection = new SqlConnection();
connection.ConnectionString ="Data Source=ServerName;" +"InitialCatalog=DataBaseName;" +
"Integrated Security=SSPI;";
connection.Open();
I have an requirement to develop windows form application in C# to connect with ODBC, select tables and its columns and at last get their data.
My exact need is to show list of DSN available on system and after selection that show its database and then show list of tables inside following with its column. Now after that I need to map all those columns with my local db column and periodically fetch data.
When I come to programming (refer below code) I see while I create an ODBC connection it ask for Username and password of database I need to connect (configured with DSN) even if I already provide those credentials while setting up DSN in control panel.
OdbcConnection conn = new OdbcConnection("Dsn=MyDSN;Uid=***;Pwd=****;");
string query = "";
OdbcCommand cmd = new OdbcCommand(query, conn);
conn.Open();
I need your help to confirm is it correct way or there is some other way also to connect db directly by DSN without using username and password as my customer is saying why I should provide credential in window application even if I already provided in DSN configuration.
I think that credentials, which you are providing in DSN Configuration wizard, are used only to fetch database list.
why I should provide credential in window application even if I already provided in DSN configuration
It is not necessary to provide credentials in DSN configuration.
Also you might want to create some service (proxy) on server, which could be configured to use specific credentials.
If you know in advance that your connection is safe, you can make your program use the stored DNS credentials (if they were previously configured) in Windows by adding the property/value "Trusted_Connection=Yes" within your config file in the label:
<connectionStrings>
<add name="myConString" connectionString="Dsn=myDsnName;Trusted_Connection=Yes" providerName="System.Data.Odbc">
</connectionStrings>
Regards.
http://www.c-sharpcorner.com/UploadFile/8ef97c/odbc-dsn-using-in-Asp-Net/
A step by step article of ODBC DSN Using in ASP.Net.
I have followed this and tested. It works fine-
my code to pull a list of customer from db -
OdbcDataAdapter da = new OdbcDataAdapter(
"SELECT * FROM [SH_Customer]",
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
and my connection string in web config -
<add name="ConnectionString" connectionString="Dsn=NayansUserDsn" providerName="System.Data.Odbc" />
currently I am using this connection string inside the app.config file of the application
add name="LightSailEntities" connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=abc.xyz.com;initial catalog=LightSail;user id=LightSail; password=yourpasswordhere;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient"
The domain of .Net application and the domain of client, using .Net application, is different from domain of SQL server. I mentioned "using widows authentication" only because of, I have the access of the server machine(means I can use Remote Desktop Connection) on which the SQL server is installed.
For Windows Auth you don't need to set the User Id and Password but you do need to include 'Integrated Security=SSPI;'
Try:
add name="LightSailEntities" connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=dev.shopcube.com;initial catalog=LightSail;Integrated Security=SSPI;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient"
There's a bit more info here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(VS.71).aspx
You have to change ConnectionString to use Integrated Security=SSPI insetad of user and password
add name="LightSailEntities"
connectionString="metadata=res://*/LightSailEntities.csdl|res://*/LightSailEntities.ssdl|res://*/LightSailEntities.msl;
provider=System.Data.SqlClient;
provider connection string='data source=dev.shopcube.com;initial catalog=LightSail;Integrated Security=SSPI;MultipleActiveResultSets=True;App=EntityFramework'"
providerName="System.Data.EntityClient"
After that, look at the Identity set for the Application Pool of you application.
That user must be authorized to access your DB using Security\Logins inside Object Explorer pan of Management Studio.
Youo can use following code:
SqlConnection conn = new SqlConnection(Configuration.DBConn);
or if you use Linq2SQL:
DBContext ctx = new DBContext(Configuration.DBConn);
where in Configuration class DBConn string contains connection string to sql ie:
Data Source=XYZ\\DEV;Initial Catalog=YOURDB;Integrated Security=True;Connect Timeout=600;connection lifetime=600
Integrated Security=True tells that you want to use windows auth.
I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.