I have created a web service which is saving some data into to db. But I am getting this error:
Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'.
My connection string is
Data Source=.\SQLExpress;Initial Catalog=IFItest;Integrated Security=True
Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user "xyz/ASPNET" - that's the account your ASP.NET app is running under.
This account is not allowed to connect to SQL Server - either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.
Can you show us your connection string (by updating your original question)?
UPDATE: Ok, you're using integrated Windows authentication --> you need to create a SQL Server login for "xyz\ASPNET" on your SQL Server - or change your connection string to something like:
connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"
If you have a user "xyz" with a password of "top$secret" in your database.
Either: "xyz\ASPNET" is not a login (in sys.server_principals)
Or: "xyz\ASPNET" is set up but not mapped to a user in the database test (sys.database_principals)
I'd go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.
To test if it's set up as a login
SELECT SUSER_ID('xyz\ASPNET') -- (**not** SUSER_SID)
If NULL
CREATE LOGIN [xyz\ASPNET] FROM WINDOWS
If not NULL
USE test
GO
SELECT USER_ID('xyz\ASPNET')
If NULL
USE test
GO
CREATE USER [xyz\ASPNET] FROM LOGIN [xyz\ASPNET]
I had this problem and what solved it for me was to:
Go to the Application pools in the IIS
Right click on my project application pool
In Process Model section open Identity
Choose Custom account option
Enter your pc user name and password.
For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).
The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):
In SQL Server Management Studio, open Object Explorer and expand the folder of
the server instance in which to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter the name of a Windows user in the Login name box.
Select Windows Authentication.
Click OK.
For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.
Also you need to change the User mapping to allow access to the Database which you want to access.
Most times, it's not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.
Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).
In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine....meanwhile management studio is still downloading
This Works for me.
Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping” tab.
Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
Click OK.
Read this blog.
http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/
It also happen when you type wrong name of DB
ex : xxx-db-dev to xxx-dev-db
Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first
The Issue
The error presents itself as a message similar to this:
Cannot open database "DATABASE NAME" requested by the login. The login
failed. Login failed for user XYZ.
The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
The error can also be found as a seemingly locked database file.
The Fix
The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!
Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)
Open SQL Server Management Studio
In the "Connect to Server" window (File->Connect object explorer) enter the following:
Server type : Database Engine
Server name : (localdb)\v11.0
Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
Click "Connect"
Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
Find your database. It should be named as the full path to your database (.mdf) file
You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
This the issue! Your database has crashed essentially..
Right click on the database then select "Tasks -> Detach...".
In the detach window, select your database in the list and check the column that says "Drop Connections"
Click OK.
You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.
The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed
I tried to update the user, and it worked. See the command below.
USE ComparisonData// databaseName
EXEC sp_change_users_login #Action='update_one', #UserNamePattern='ftool',#LoginName='ftool';
Just replace user('ftool') accordingly.
I had this problem when I created a WPF .NET Core + Entity Framework Core project and then cloning it on a a new laptop.
Using:
update-database
in the package manager console simply solved it.
To open package manager console go to:
Tools-> Nuget Package Manager -> Package Manager console
I used Windows authentication to connect to local database .mdf file and
my local server was sql server 2014.
My problem solved using this connection string:
string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception.
To resolve this issue follow below steps.
Make sure the object explorer is pointed to a system database like master.
Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO
I ran into this issue when attempting to write to the default database provided in the asp.net mvc template. This was due to the fact that the database hadn't been created yet.
To create the database and make sure that it is accessible follow these steps:
Open up the Package manager console in Visual Studio
Run the command "update-database"
This will create the database an run all the necessary migrations on it.
I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.
NB: If using a windows service to host the webservice.
You have to insure that your webservice is using the right Log on account to connect to SQL Server.
Open services(I assume the windows service has been install)
Right click on the service and goto properties.
Click on "Log On" Tab
Click on "This account" radio button
Click "Browse"
Enter Pc user name in Text Field and click "Check Name" Button to the right.
Click on text in Text Field, press "OK" button
enter login password and Apply
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
If you haven't created the database in your server you will get the same login error.Make sure that the database exist before you login.
it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!
Edit: Setting the login as db owner solved the next problem, too
Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.
My apologies about bad english.
Kind regards, Ignat.
In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:
2016-10-28 10:27:10.86 Logon Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.
So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.
Even if you've set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of 'owner'.
In my case, I was running a Windows Service under "System" identity. The error was:
System.Data.SqlClient.SqlException (0x80131904):
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAME\HOSTNAME$'.
The problem is that the error is very misleading. Even after I added 'MYDOMAINNAME\HOSTNAME$' login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error.
Apparently I needed to do the same for 'NT AUTHORITY\SYSTEM' login. After I did that, I was able to login without a problem. I don't know why the error message complains about 'MYDOMAINNAME\HOSTNAME$'. I deleted that login and the corresponding user and everything still works.
When using EF Code First, make sure the database exists. You could run the update-database command first.
If none of the above solution is working.
I encountered with the same error message but my issue was completely different. I had just restore my database and the database was in restoring mode. So if your database is in rstoring mode just apply following query.
RESTORE DATABASE MyDatabase
FROM DISK = 'pathToYourDbBackup\MyDatabase.bak'
WITH REPLACE,RECOVERY
I had this happen to me when I deleted the DB and forgot to recreate it. It happens sometimes, since Database folder needs refresh.
If you didn't have any problems before and you get this error only in the package manager console, you don't need to do anything special. Just open the sql server object explorer window and connect and run the command again in the console.
I have read other questions on SO in regards to security and registry keys, nothing has helped me solve my particular use case scenario.
Here's my scenario:
What I'm Trying To Do
I want to, in code, delete a windows event log.
The Problem
When executing the function, I receive a System.ComponentModel.Win32Exception. The exception message is "Access is denied".
How I Am Doing It Currently
I am using an impersonator function that I wrote which wraps around the EventLog.Delete function, it drops me into a user context that has full access to the EventLog Registry Hive. Subsequently the logs I am interested in also have full access for this particular user.
My Question
Why do I receive a "Access Is Denied" if the user I am running under (through impersonation) has full access to the log in question? I've tested my Impersonation function and it works as expected for other code I've written. I don't get why I would get access denied for this.
In another scenario with my impersonation function it works just fine, for example if I tried to write to a file that the user context that is running the program does not have write access to, then I would not be able to write to the text file, however if I use my impersonation to drop into a user context that does have write access then it works just fine (I can write to the file). So I just don't understand why the same concept can't be applied to registry keys.
What am I missing here?
The Code
Exception Message
My Test
Where sw-test is a user I created for testing purposes, it has full access permissions to the registry we are trying to delete.
[TestMethod]
public void DeleteEventLog_ValidatedUser_DeleteLog()
{
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd"))
{
Logging logging = new Logging();
logging.DeleteEventLog("testLog");
}
}
Okay I eventually got around to figuring this out, there were two issues at play here that were causing the mentioned exception being thrown, they are as follows:
1. Visual Studio was NOT running in administrator mode.
Not running visual studio in administrator mode was one part of the problem, this seems to be associated with access tokens in the windows OS. According to a source I read, if I run a program without UAC on (which is my scenario, I have it off), then the program being run gets a copy of my access token. However if I have UAC enabled, the program gets a copy of my access token but it is a restricted access token. (see: What precisely does 'Run as administrator' do?) - To be honest this doesn't really make sense in my case, why do I have to run as admin if I have UAC off? Shouldn't visual studio have an unrestricted copy of my access token? I am in the administrator group with UAC off...
2. Not Specifying NewCredentials As a Logon32Type In Impersonation
I don't really understand it but as soon as I specified this for my impersonation everything started working perfectly, I read a blog about it, it talks about how it was introduced in the VISTA days and how it was mainly used to specify credentials to outbound network connections to servers, and was mainly used to remedy security-related issues server-side. Don't see how it correlates to interfacing with local event logs though. (see: https://blogs.msdn.microsoft.com/winsdk/2015/08/25/logonuser-logon32_logon_new_credentials-what-is-this-flag-used-for/)
Code
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd", Advapi32.Logon32Type.NewCredentials))
{
EventLog.CreateEventSource("testSource", "testLog");
EventLog.Delete("testLog");
}
Where the NewCredentials is an int 9
I've been given a task to update a C# tool that works with the JAMS scheduler tool, and I've only heard good things about JAMS in spite of my complete inability to install or get it to work at all. I haven't been able to find anything online about this problem, so I know it must be something stupid that I'm doing. (I come from a mac/unix background and everything on windows seems fairly foreign to me)
I've gone through (multiple) successful installs of the JAMS x64 demo, but when I open the Windows JAMS Client GUI, I get consistently get an error popup saying:
Unable to load specified root folder: \
Exception:System.Net.Sockets.SocketException (0x80004005): No such host is known
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at MVPSI.JAMS.Server.GetURL(String objectURL)
at MVPSI.JAMS.Server.GetRemoteObject[T](String objName)
at MVPSI.JAMS.Server.Connect()
at MVPSI.JAMS.Server.GetRemoteObject[T](String objName)
at MVPSI.JAMS.Folder.Check(Int32& folderID, String folderName, FolderAccess access, Server js)
at JAMSWin.FolderNavigatorCtl.LoadRootFolder(String folderAddress) in c:\ProductionAZ\JAMS\Release\V6.1\JAMSWin\FolderNavigatorCtl.cs:line 406
I believe this error is caused by the JAMS server service using an incorrect server name, but I've tried many combinations (I've also installed/setup JAMS dbs in both my SQL2008 database engine and SqlExpress):
(local)
(local)\SqlExpress (with various capitalizations though I don't think this matters, does it?)
(local)\SQL2008
domainName\SqlExpress
... (the list goes on. Some of them were entirely impossible and I shouldn't have tried them, such as SQLEXPRESS\JAMS, but in my panic I did try it.)
No matter what I enter as the server name, I get the same result - the popup, and then the GUI window comes up saying "Unable to connect to the JAMSServer service; No such host is known."
This is all local, so I don't think it is a connectivity problem.
Any help would be greatly, greatly appreciated.
blue - full disclosure here as I work for JAMS.
Without seeing your logs here, it's a little difficult to say for sure what could be going wrong, my best guess is you're defining the SQL Server as the Server the client is connecting to, rather than just your local machine. The Client is trying to connect to the JAMS Server which in turn is trying to talk to SQL.
There is a Red J at the upper left hand corner of the product, if you click there and then on "Servers" you can define the JAMS Server you're trying to talk to. As you mentioned this is all local, simply utilize "localhost" and you should be off to the races.
If you're still having issues, I'd recommend sending in your logs to support for review because there may be something else going on here, it's too tough to say at the moment.
Devon
I am working with an ASP.NET 2.0 application (created by my predecessor). Users log into it with AD credentials, and everything done within the app uses those credentials. I modified a page in the application that has nothing to do with event logging, and now my users get this error:
Here is the relevant code from the global.asax file:
public void LogException(Exception e)
{
string exceptionXml = RenderException(e, true);
_EventLog.WriteEntry("Exception of type " + e.GetType().FullName + " occurred.\n\n" + exceptionXml, EventLogEntryType.Error);
}
RenderException() just puts the exception XML into a flat string, removing white spaces.
I am at a loss on how to get rid of this error. I have tried re-publishing the website with an iisreset. I have tried restarting the web server (2k3 w/ iis 6.0), flushing the app pool. I have also tried modifying the permissions in the registry for the top-level event log key. Can anyone tell me how to get rid of this error? It does not happen on my computer, so it is very hard to replicate. Also, the browser used does not seem to matter. The previous version will work for the same persons getting this error.
By default the ASPNET user cannot access the existing event logs categories.
If you do want to write messages to the event log you must create your own category
Launch RegEdit
Navigate to HKEY_LOCAL_MACHINE\SYSTEM\
CurrentControlSet\Services\EventLog\
From the menu, select Edit->Permissions
Click the Add button and write ASPNET. (if ASP.NET is running under a different user id, use that id instead)
Click OK.
Select the newly added user from the list (ASP.NET Machine User by default).
Click on Full Control in the Allow column.
Click OK.
You can also check that the user, under which the applications is running, belongs to the correct group, for example IIS_WPG
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3648346f-e4f5-474b-86c7-5a86e85fa1ff.mspx?mfr=true
You appear to be calling an instance method of the EventLog class on the _EventLog instance:
_EvengLog.WriteEvent(message, ...);
But according to MSDN documentation for the EventLog class:
Any instance members are not guaranteed to be thread safe.
I suspect this is a likely source of your problem, and would recommend you use one of the static methods (which are guaranteed to be thread safe):
System.Diagnostics.EventLog.WriteEvent(source, message, ...);
Alternatively you could implement your own synchronization, but I wouldn't recommend this.
I am using the Mathematica .Net/Link platform to create a web service to format and calculate math problems. However I am unable to get it working.
I create it using this code:
_Log.IpDebug("Starting the Kernel Link");
if (string.IsNullOrEmpty(_MathLinkArguments))
_InternelKernel = MathLinkFactory.CreateKernelLink();
else
_InternelKernel = MathLinkFactory.CreateKernelLink(_MathLinkArguments);
_Log.IpDebug("Kernel Link Started");
_InternelKernel.WaitAndDiscardAnswer();
The value of _MathLinkArguments is -linkmode launch -linkname \"C:\\Program Files\\Wolfram Research\\Mathematica\\7.0\\Math.exe\".
This piece of code is called from the Application_Start method of the global.asax.cs file.
When it gets to the WaitAndDiscardAnswer() call it gives the server error:
Error code: 11. Connected MathLink program has closed the link, but there might still be data underway.
Note: The SampleCode given with the .NET/Link package (both a console app and a WinForms app) works.
Edit:
I copied the console app sample code given with Mathematica into an asp.net page and it gave me the same error the first load and then on subsequent loads it gave me:
Error code: 1. MathLink connection was lost.
Edit2:
I forgot to mention that when I have procmon and task manager open while running my app, I can tell that Math.exe starts but it immediately exits, which makes those error code make complete sense...but doesn't explain why that happened.
To allow the .Net/Link to work in Asp.net (at least in IIS 7.5) you need to enable the property loadUserProfile on the app pool for the web site.
I am not entirely sure why this is the case, but from what I found while trying to debug this, there are some things that are gotten from the user's profile. I know for a fact that the default location of the kernel is, which explains why I couldn't use it with no arguments, and so I can only assume that other things are needed as well and without the profile it couldn't determine that.
But whatever the reason is this is required, it is, or at least it is a fix if you are getting similar problems like this in your own application.
I got the same error in a .Net WinForm application.
mathKernel = new MathKernel();
mathKernel.Compute("<< XYZ`XYZGraphs`");
The error occurred on loading the package straight after instantiating the MathKernel.
To resolve it you can wait a couple of seconds and then instantiating the MathKernel works fine. During this state where there might still be data underway the following conditions are both false:
if (!MathKernel.IsConnected)
{
MathKernel.Connect();
}
if (MathKernel.IsComputing)
{
MathKernel.Abort();
}
Edit:
I've recieved the error again and this time was able to determine the problem.
Using a command line open the MathKernel.exe and view the error message: