Restore a Database Programatically (SQL Server) - c#

I recently found this link which shows a great example of backing up and restoring a sql server database. However, my SQL Server only uses WindowsAuthentication and so it does not really require a UserName and Password. To be able to do this, I turned the line srvConn.LoginSecure = false; into srvConn.LoginSecure = true;
I was expecting to connect succesfully to the Server. However, this example returns an exception saying that it was unable to connect to the server.
Can anybody help me please? I have to learn this application for me to be able to apply the same concept to a project i'm working on. Thank you very much.

First of all if you want to enable remote connection to your server (I'm not sure if this is what you're after), Try this: http://support.microsoft.com/kb/914277 . You will also want to make sure the mixed authentication option is enabled.

Related

Could not create database using package manager console in .NET 7.0

Im learning .net now and following along the course,my goal is to create CRUD app so i need a database to work with it, i have succesfuly created initial migration but database-update doesnot work
(provider: SNI_PN11, error: 50 - Local Database Runtime error
occurred. Cannot create an automatic instance. See the Windows
Application event log for error details.
im getting this error if connection strings look like this
"ConnectionStrings": {
"QuotesAppContext": "Server=(localdb)\\mssqllocaldb;Database=QuotesAppContext-811c920d-aeb7-4d04-8ba6-5c9a48d8b492;Trusted_Connection=True;MultipleActiveResultSets=true"
}
i have installed both sql server and sql management on windows 11 without problem
and if i change connection string to this
"ConnectionStrings": {
"QuotesAppContext": "Server=(localdb)\mssqllocaldb;Database=QuotesAppContext-811c920d-aeb7-4d04-8ba6-5c9a48d8b492;Trusted_Connection=True;MultipleActiveResultSets=true"
}
deleting \ problem now is
Unable to create an object of type 'QuotesAppContext'.
so it seems like an endless circle to me, thanks you for your help
write database-update and get database instance working
I find the answer which have worked for me,find this folder in regedit
"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\UserInstances"
and delete everything inside of it,and after that run Update-Database command again everything should work fine
P.S
i have tried reinstalling sql server,adding ports, but this solution worked for me

What Is the Syntax for Including the Service Name in a Connection String?

I have a C# ASP.Net MVC web application. I am trying to successfully connect to an Oracle database.
I am getting a "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" error.
I do not have access to the server the database is on. But I do have access to Oracle SQL Developer, which I have installed on my machine.
In my C# code I am setting the connection string like this:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd,1521;User ID=userid;Password=password;";
abcd should be the service name. and 1521 is the port number.
I understand that my connection string might not be the cause of the error, but I want to rule it out. Also, I know the more proper way of doing things is probably to set the connection string in web.config and retrieve it as needed, but I am doing it this way just for ease of testing until I know I am able to connect to the database successfully.
What is weird to me, is that I was able to connect to the database using Oracle SQL Developer using the same IP address, port number, service name, username, and password I am using in my connection string.
Primarily, I would like help knowing if my connection string looks valid. If you have additional thoughts about what the issue could be, that would also be appreciated.
using this command in Oracle SQL Developer:
select sys_context('userenv','service_name') from dual;
I am able to determine that the service name I am using in my connection string is one that exists, although I guess this does not guarantee that the service is up.
I am not a DBA by any means. In fact, I am still new to .Net and web development in general, but I have been assigned to troubleshoot this issue. Any help is appreciated.
I don't recall seeing the following format
DataSource=XXX.XX.XXX.XXX/abcd,1521
as valid (which doesn't mean its not, I've just not seen it).
The more common ones I've seen are:
DataSource=XXX
where XXX is a reference to your tnsnames.ora file
DataSource=//nnn.nnn.nnn.nnn/service_name
DataSource=//nnn.nnn.nnn.nnn:port/service_name
So maybe try those variants and see how you go. There's also more definitive list of alternatives at https://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
I ended up figuring this out. My connection string format I don't t think was correct. I changed it to be:
ConnectionString = "DataSource=XXX.XX.XXX.XXX/abcd;User ID=userid;Password=password;";
Basically, I just took off the port number. In my case, the default port was what I needed anyway. Not sure what I would have done had I needed to specify the port number.
As new to Oracle I struggled a few days finding solution to this
this article helped me alot
As of Oracle 21 c
This is my Connection string for C#
Password=dev;Persist Security Info=True;User ID=Dev;Data Source=localhost:1521/XEPDB1
Keep in mind Dev is Username which is also the Schema name for Oracle

How to avoid connections against empty/null database by Entity Framework

We use entity framework to read from an existing database.
This is a simplified version of our code.
using (my context context = new mycontext())
{
if(context.Database.Connection.State == System.Data.ConnectionState.Closed)
{
_logger.Info(" Opening the connection to the database");
context.Database.Connection.Open();
}
context.Configuration.LazyLoadingEnabled = false;
IQueryable<mymodel> people;
people = context.People.OrderBy(x => x.Firstname);
_lstContacts = people.ToList();
if (context.Database.Connection.State != System.Data.ConnectionState.Closed)
{
context.Database.Connection.Close();
context.Database.Connection.Dispose();
_logger.Info(" Connection to the database Closed");
}
}
It works 100% of the time, but...
On our UAT environment we can see failed connections to the Microsoft SQL server with the error:
Login failed for user "my user". Reason: Failed to open the explicitly
specified database "null". Client my IP.
For us, these are ghost connections because at the time when we see the errors in the SQL server, our code is not executed.
Initially we didn't close and open the connection explicitly, we just added it trying to control when EF open and closes the connection, but it didn't fix the issue.
Our connection string is using the following format:
<add name="MYCN" connectionString="metadata=res://*/CVs.Cvs.csdl|res://*/CVs.Cvs.ssdl|res://*/CVs.Cvs.msl;provider=System.Data.SqlClient;provider connection string="data source=myserver\;initial catalog=mydatabase;Integrated Security=;User ID=myuser;Password=XXXXXXX;MultipleActiveResultSets=True;App=EntityFramework"/>
As you can see, we are specifying the database in the connection string and our user only have access to our database, so we understand the error when EF doesn't include the database in the connection string, but we don't understand why it's trying to perform these connections.
We know the connections are coming from our application, because we are the only one using that specific user, the IP is the IP of our server, and because the logs in SQL server tell us that the application is "EntityFramewrok"
I didn't personally see the error before, but researched for you and seen that many people suffered from the same problem discussed here: https://blogs.msdn.microsoft.com/sql_protocols/2006/02/21/understanding-login-failed-error-18456-error-messages-in-sql-server-2005/
I read all the messages in the website specified, and here are the solutions offered and at least one other user confirmed that it worked. You might not use 2005 as you didn't specify your version in your question, some solutions I believe will still work for you. Try the list below.
Solution list:
1) Please check the state number of this error and search solution by the state number in addition to the message, might give your more accurate solution proposals. Most common states are listed:
All state-error descriptions you can find here: https://sqlblog.org/2011/01/14/troubleshooting-error-18456
2) Make sure the username and password are correct.
3)
Logon to SQL Server using windows authentication.
Right click in the query window that appears and select "Open Server in Object Explorer"
Go to object explorer and open the "Security" folder and then the "Logins" folder.
Double-click the "sa" user and change the password. Also, like another user mentioned above, untick the "Enforce Password Policy" in
addition to resetting the password.
4) Try to change the password and turn off the policy, and try with new password.
exec sp_password #new = ‘sqlpassword’, #loginame = ‘sa’
alter login sa
with password = ‘sqlpassword’ unlock,
check_policy = off,
check_expiration = off
5) Run your application/browser and SSMS (if you work on it) in administration mode.
6)
Open Windows Services
Configure Microsoft Single Sign-on Service to use the proper account
Open Central Administration >> Operations >> Manage settings for single sign-on
Configure properties to use the same account used for Microsoft ‘Single Sign-on Service
7) Go to Sql server configuration manager and Enable TCP/IP and named pipes
8)
go to sql server
right click on server, choose properties
click on security
on server authentication, enable SQL Server authentication
These might help:
https://www.wikitechy.com/errors-and-fixes/sql/login-failed-error-18456-severity-14-state-38-reason-failed-to-open-the-explicitly-specified-database
https://dba.stackexchange.com/questions/90445/login-failed-for-user-error-18456-severity-14-state-38
I think this is just an access issue for myuser in the UAT environment. Just make sure myuser has access in the UAT environment for UAT database and you should be good.

Missing Server and User in Credentials

I'm currently working with VS'13 for making c# metro forms and mysql workbench for database. The problem occurring is that it shows the error of
Missing Server and User in Credentials.
Host 'WAJiHA' is not allowed to connect to this MySQL server
(as you can see in the picture as well).
DataAccess file has following settings
"Server=localhost;Database=sbhd_v13;Uid=root;password=test123";
The database is connected with the project and executes query but doesnot allows to access the connection to the current project or any other project.
It was working good last night idk which configurations i had edited by mistake which is causing such error.
Kindly help me! I'm unable to find the right solution for this problementer image description here
Change your posted connection string to be like
string myConnectionString = "server=127.0.0.1;uid=root;pwd=test123;database=sbhd_v13;";

C# creating a database programmatically with SMO

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.

Categories

Resources