C# creating a database programmatically with SMO - c#

I am trying to create a database, but once created, I cannot connect to it.
The server is Microsoft SQL Server 2008 and using .Net 4.5. We're creating the database with SMO, but we're usually using Dapper to connect and query the database.
This is the code I have so far, which works :
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connectionString);
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
var database = new Microsoft.SqlServer.Management.Smo.Database(srv, dbName);
database.Create(false);
database.Roles["db_datareader"].AddMember(???);
database.Roles["db_datawriter"].AddMember(???);
database.Roles["db_backupoperator"].AddMember(???);
srv.Refresh();
Noce the ??? ? I have tried
System.Environment.UserDomainName + "\\" + System.Environment.UserName
and
System.Environment.UserName
but it fails (update) with the error Add member failed for DatabaseRole 'db_datareader'. with both values.
The problem is that when I create the database, I cannot coonect to it for some reason (using Dapper), from the same program. (update) I get the error message : Cannot open database \"<database_name>\" requested by the login. The login failed.\r\nLogin failed for user '<domain>\\<username>' (where <database_name> is the database name, <domain> my logon domain, and <username> my Windows logon).
Am I missing something? Am I doing th right thing? I've tried searching the web, but it seems no one creates database this way. The methods are there, it should work, no?
** Update **
If I comment the database.Roles["..."].AddMember(...) lines, and I add a break point at srv.Refresh(), resuming the program from there solves everything.
Why a break point solves everything? I can't just break the program in production... nor break the program when creating the database everytime.

It sounds like the Dapper connection issue is a problem with SQL Server doing some of the SMO operations asynchronously. In all likelihood, the new Database is not ready for other users/connections immediately, but requires some small time for SQL Server to prepare it. In "human-time" (in SSMS, or a Breakpoint) this isn't noticeable, but "program-time" it too fast, so you probably need to give it a pause.
This may also be the problem with the Role's AddMember, but there a a number of things that could be wrong here, and we do not have enough information to tell. (specifically, does AddMember work later on? and are the strings being passed correct or not?)

This is happening because you've created the user, but no login for that user. Though I don't know the exact syntax, you're going to have to create a Login. You'll want to set its LoginType to LoginType.WindowsUser. Further, you'll likely need to set the WindowsLoginAccessType to WindowsLoginAccessType.Grant and you'll need to set the Credential by building one, probably a NetworkCredential with the user name you want.
To put a visual on this, the Login is under the Security node for the Server in Management Studio whereas the User is under the Security node for the Database. Both need to exist for access to the SQL Server.

Related

Local DB in Visual Studio 2015

After a few years, I have returned to writing in C# and I am really struggling here - I would like to have my app to have a local SQL database. I have added Service-based database and "Database1.mdf" was added to my project. I created a table and added some data just to see if it is working but I cannot connect to it. I tried numerous connection strings with no success (Server not accessible).
Do I need to run something else in the background? I thought that I might have a local database and with .NET client I can access it, and I hoped it would work whenever I bring my application (also not requiring any SQL server running). Is that wrong?
If you don't require any SQL server, take a look at SQLite. This is lite SQL database engine. Database is just one file. C# has a great library to SQLite on NuGet: https://www.nuget.org/profiles/mistachkin
SQLite is widely used, event in Android (as a native db engine).
here is what i use to connect. it appears as a Data Connection in Server Explorer.
string con2 = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Application.StartupPath + "\\jobfile_2017.mdf;Integrated Security=True;Connect Timeout=30";
when i first started working with these, i used this source 1
it works on PC's that i have nothing installed (not even office) but as i said i'd be interested to know of any shortcomings of this method
I experiencing same problem and decided to move mdf file to static c:\db directory. Connection string was changed to incorporate new file location (AttachDbFile).
But AttachDbFile has some issues also (by some reason one table in db is inaccesible and error is access denied).
So I decided to move to Sqlite. LocalDb has many issues to work with. I read good note to resolve problem: in command line stop/remove/start name of instance. But it nuissance.
Wish you good luck to work with these db files.

Can't store users in the default MVC application

I had some problems with using the authorization before so I got a brand new everything - new computer, new OS, fresh installation of VS, new app and DB in a new resource group on the Azure. The whole shabang.
I can confirm that I can log in to the Azure DB as the screenshots below show.
I can see the databases, tables, users etc.
The problem is that, although it works locally (using the default connection string provided automagically for me), it doesn't perform very well in the Azure (although I'm using the publish file from there). It said something about the file not being found and according to this answer, I needed to change the connection string.
After I've altered it, I get the following error. Please note that the firewall is open and that I can access the DB when I run the code of my applications. I feel that there's something that goes wrong when the authentication part is automatically configured. I'm out of ideas on how to trouble-shoot it, though.
[SqlException (0x80131904): Login failed for user 'Chamster'.
This session has been assigned a tracing ID of '09121235-87f3-4a92-a371-50bc475306ca'. Provide this tracing ID to customer support when you need assistance.]
The connection string I'm using is this.
Server=tcp:f8goq0bvq7.database.windows.net,1433;
Database=Squicker;
User ID=Chamster#f8goq0bvq7;
Password=Abc123();
Encrypt=True;
TrustServerCertificate=False;
Connection Timeout=10;
This issue's bothered me for a while and I'll be bounting it in two days. Any suggestion's warmly appreciated.
I believe I've managed to resolve this weird issue. It appears that the user I'm using, despite being admin with all bells and whistles isn't recognized as admin when used in the connection string and trying to create the tables (which is the case at the first registration).
My solution was to create two logins - one with db_owner role and one with db_datareader and db_datawriter. First, I've used the elevated user in my connection string and registered a single user. That created the tables in the database as shown below.
Then, while able to continue as admin, I realized that we should try the demoted user and tada!, it worked perfectly. Once the tables were there, the whole shabeling behaved as expected.
To be perfectly sure, I dropped the tables from the database and there it was - the same issues as before. When I changed to the elevated user, the tables were restored allowing me to get back to the demoted one.
I also tried dropping the tables, confirming the issues to re-appear and then creating the tables manually. That works too! So basically,the only gotcha that caused it all was the original admin who's not treated as admin.
It might have to do with the fact that my Azure account's getting a bit old, LiveID used there is ancient and that didn't have an updated version of DB in Azure (the pull-up to v12 was carried out the 18th of December, so it's possible that it also was a requirement to get it working). I'm too tired and lazy to check that out and I realize that I've no idea how to get an "old" type of account. Besides, the issue will decrease and gradually vanish because the old accounts get upgraded eventually.

Cannot open database "ASPState" requested by the login. The login failed. Login failed for user 'xxxx'

I am working on one project which is in Asp.Net web form and Sql server. When I run application I get the error Unable to connect Sql Server Session Database and inner exception is Cannot open database ASPState requested by the login.
I did some google search to fix this issue. I don't have sa password so i cannot logged in as sa to assign privileges to ASPState database for the newly created User.
I don't see any ASPState database on Sql Server when i logged in. So i thought I might need to run aspnet reg exe on my machine. So i tried to run aspnetreg_regsql.exe but i got the following error.
An error occurred during the execution of the SQL file
'InstallCommon.sql'. The SQL error number is 5170 and the SqlException
message is: Cannot create file 'C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\aspnetdb.mdf' because it
already exists. Change the file path or the file name, and retry the
operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Creating the aspnetdb database...
I am totally blank now to solve this issue, I will really appreciate your suggestion for this. This issue hold to publish on production.
Dont think that there is a simple answer to this with the permissions that you have, I think that what has happened is that the database HAS been created, but the user you are using does not have any access to it at all.
Without having an administrators credentials I dont think that you will be able to resolve the problem.
You can however work around it by re-creating the database with a different name:
aspnet_regsql -d[YourNewDBName] -RestOfYourParamaters
That should allow you to re-run the creation script, however there is no guarantee that you wont end up with the same issue on the newly created database.
You should issue the command DROP DATABASE aspnetdb and then re-run your script.
'InstallCommon.sql' surely ain't any database. It must be a script that installs a new Database, as the name suggests. Run the script, and then link the generated database

Why does the "drop user" command for SQL not work in C#?

Why does the drop user a_2 command not work when I try to use it in C#, while when I tried it in SQL Server Management Studio, it works there !!???
This is the code that I used it when I create the user & give it a permission:
use DataBaseName;
create login a_2 with password='Aa123';
create user a_2 for login a_2;
grant insert to a_2;
..........
The connection string used :
Data Source=TheServerName;Integrated Security=True;database=master
Note:
I tried to drop a database from C# and it works perfectly without any problem, but when I use it to drop a user the problem raised here !!!
This is the exception that gets raised
Exception is: Cannot drop the user
'a_2', because it does not exist or
you do not have permission.
I believe your problem is that "you do not have permission". Your application is running as a different user from you. You can solve this by either giving the default application user the necessary permissions on the database (not a good idea) or by creating a special user in the database for your application and having the application run as that user.
Be aware that giving your application (or any user, for that matter) permissions to drop users could be very risky if someone figures out how to hack your application. And you aren't actually including the ability to drop the database in your app, are you? Think about it. Instead of creating users in the database, consider creating a Users table just for your application. Then your users won't have such extensive rights to your actual database.
DROP USER would require use DataBaseName;
Or a different connection string
Data Source=TheServerName;Integrated Security=True;database=DataBaseName
That is, the DROP USER only makes sense in the context of your database. When you run it later you are in the context of master = fail.

User does not exist in MySQL , c# and asp.NET MVC

I am working on development machine without making any user account [i have three of four account who comes when i installed them].
so i open the connection everywhere by a globals variable who hold the connectionstring off-course value of variable can not be changed it's constant.
i open the connection using root account who come by default in mysql server. they work fine everywhere.
but my code try to run a command then server return the error that
The user specified as a definer ('admin'#'localhost') does not exist
i don't know why i got this error even in debug i found that connection open by root and they work fine everywhere else.
so the problem is why they tell me about admin#localhost even the connection my code open by root.
are their anything my code try to do who need authentication or need admin account even they not have then give me exception.
Are you know that what is gone wrong.
I got this error after DB was moved to another server.
There no such user 'admin' so I got the error.
Solution:
log into mysql as root
grant all on *.* to admin#localhost identified by "s!5_superp#ss!";
flush privileges;

Categories

Resources