IIS SQL Server configuration - c#

I have a C# ASP.net project which was developed using Visual studio for web 2013 and SQL Server express 2012.
I used a database connection line as follows:
SqlConnection objConnection = new SqlConnection("Data Source=.\\MYDB;Initial Catalog=MYDB;Integrated Security=true");
objConnection.Open();
This worked fine when in developer mode in Visual Studio - but now I have deployed to IIS which runs under user IIS_IUSRS(Andy-PC\IIS_IUSRS).
When I visit my pages they then throw the following error:
Server Error in '/' Application.
Cannot open database "MYDB" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\MYDB'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot open database "MYDB" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\MYDB'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Cannot open database "MYDB" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\MYDB'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
System.Data.SqlClien
Its pretty self explanatory - my connection string with integrated security=true is not successfully working as the current logged in user is not IIS_IUSRS.
Can somebody please help to show what I should alter the connection string to in order to create the connection when connecting as this new IIS user?

You need to change the user that your application pool is running as.
Go to Advance Setting for the Application Pool and change the Identity to a user that can access your sql server.

Actually you can use that connection string, just grant permissions to IIS APPPOOL\MYDB in your SQL server and database.

Using an explicit account for the site may make managing security easier in the long run, e.g. placing a connection string in the Web.config file for your ASP .NET project like:
<add name="SiteDB"
connectionString="Data Source=HostName\SQLServerInstance; Initial Catalog=MyDB; User Id=MyFirstWebsite; Password=secret"
providerName="System.Data.SqlClient"/>
Then using ConfigurationManager to get the connection string.
When there are several sites on the server this will make it clear which database this site should be using and, if several of the sites share the database, you can have them use different credentials so that they can have different access restrictions.

Related

"Can not find server or is not available" on test server but not while debugging

I keep getting an error when trying to access the database from a web site it returns an error that it can't find the server or it's inaccessible.
Now I did a search and I found many possible reasons - I turned on named pipes and also did what this link suggested (i.e. set the IP addresses to "enabled") yet I'm still getting the error.
Error SqlException: System.Data.SqlClient.SqlException (0x80131904):
Error An error has occurred with the network or the occurrence when
connecting to SQL Server. Can not find server or is not available.
Verify that the instance name is correct and that the configuration of
SQL Server allow remote connections. (provider: Named Pipes Provider,
error: 40 - Could not open a connection to SQL Server) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
I also downloaded this little app and I copy/pasted the connection string from the web.config used in IIS for this site and the app is able to connect and query the same database being targeted by the web site.
And, as the title says, this error is utterly missing when I debug it in VS2010. What could be causing this error when launching from the server?
Edit: the connection string includes a user name and password (it's not Windows Authentication).
Most likely a security issue. If using windows authentication then make sure the thread pool that the web application is running as has sufficient DB access\privileges.
The issue is that the web.config references another config file
<appSettings file="config/dev.config">
and so the connection string in web.config is ignored over the one in dev.config - an error to have it in both (the one on the test server was created by someone else and worked on static pages - it only failed when the website had to query the database), that's why the version in Visual Studio was running fine.

Login failed for user 'NT AUTHORITY\SYSTEM'. Reason: Failed to open the explicitly specified database

I have an application that access a database frequently for a number of functions. It was running fine for several days. I received a System.Data.SqlClient.SqlException exception this morning. The application wasn't doing anything out of the regular when this happened. Any Ideas on what caused this or how to prevent it in the future?
Windows Event Log
NT AUTHORITY\SYSTEM
Reason: Failed to open the explicitly specified database.
[CLIENT: <local machine>]
Exception Stack Trace
System.Data.SqlClient.SqlException (0x80131904):
Cannot open database ""MyDB"" requested by the login. The login failed.
Login failed for user 'NT AUTHORITY\SYSTEM'.
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at ***.SubmitContextChanges(DataContext dataContext, Int32 counter) in c:\Work\***.cs:line 332
Windows event right after
Attempting to load library 'xpstar.dll' into memory.
This is an informational message only. No user action is required.
This message means that it did contact the server, but could not open the database specified in the connection string (named in the exception message).
Things to check:
That the database exists on the SQL server and that it is online.
That the user has access to the specified database.
That the default database for the login is correct and that the user has access to it.
That the connection string hasn't been altered.
It turns out that one of our tables was getting too large and not flushed often enough. That the wright to database method was timing out and our retry method threw the error.
xpstar.dll did not load out of the blue. This dll hosts the extended stored procedures used by the management tools. The fact that it loaded when the incident occurred means that there was management tool activity on the server. Which leaves open many avenues on how somebody might have messed up your database, even momentarily.
Next step is to check the administrative default trace and see if you can find any activity around the time of the incident.

Publish remote server [Win32Exception (0x80004005)]

I'm wondering if my connection string is wrong because when I publish this on a server it doesn't work, otherwise when I test it on debug mode it works.
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-app-20130122205025;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-app-20130122205025.mdf"
providerName="System.Data.SqlClient" />
<add name="SiteSourceContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=SiteSourceContext-20130125171153; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|SiteSourceContext-20130125171153.mdf"
providerName="System.Data.SqlClient" />
Can someone help out? Im relatively new and trying to learn, so I dont know what Im doing but this is the error I get:
[Win32Exception (0x80004005): The specified file is not found]
[SqlException (0x80131904): A network-related error or instance-specific occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (Provider: SQL Network Interfaces, error: 52 - Could not locate installation of a runtime database locally. Verify that SQL Server Express is installed and the runtime functionality of local database is enabled.) ]
System.Data.SqlClient.SqlInternalConnection.OnError (SqlException exception, Boolean breakConnection, Action `1 wrapCloseInAction) 6675286
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning (TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 688
Verify that SQL Server Express is installed and the runtime functionality of local database is enabled.
Try Changing This :
Data Source=(LocalDb)\v11.0
To This :
Data Source=.\v11.0
Or This :
Data Source=.\SQLExpress
Keep in mind that using Data Source=(LocalDB)\v11.0 limits the credentials to the user that created/owns the database. If you are publishing this as an ASP.NET service, your code will be running under a different user; likely NETWORK SERVICE.
Further, it looks like the connection string is specifying a file that probably only exists in your development environment, not on the server you are publishing to. You'll need to install SQLExpress on that server and set up the connection string to access that. I wouldn't use Data Source=(LocalDB)\v11.0;; instead I'd use Data Source=localhost\SQLEXPRESS; or Data Source=.\SQLEXPRESS to maintain consistency between your development environment and deployment.
Probably, the instance name of SQL server installed in your development computer and server have different names. So you need to change the connection string. If you have installed SQL Server, if not you need to install it.
Other possibility is, the instance of the SQL Server might not be running. You can go to Windows Services from control panel and check if SQL Server service you stored your database started or not. There might be multiple services, if you have multiple instances of SQL Server. Make sure that you are using the connection string for the correct instance.
Also, in your database, you should give access priority to related IIS user (e.g. IIS APPPOOL\DefaultAppPool), if you decide to use Windows Authentication. Or you can use SQL Server authentication.
In a nutshell, I believe that you have problem with referring to SQL Server Instance. When you solve it, if you do not try to access to DB with valid credentials, you will have a authentication problem.

IIS to SQL Server logging in with username that doesn't exist

i am having no problem at all compiling/debugging my web app, but when i try to run it from my IIS server i get this error:
Server Error in '/' Application.
Login failed for user 'MLABS\STUDENT-006$'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'MLABS\STUDENT-006$'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Login failed for user 'MLABS\STUDENT-006$'.]
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +578
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +88
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6275911
System.Data.SqlClient.SqlConnection.Open() +258
RadarGraphInsertDLL.LOMDLL.Get_Last_Lom() in c:\users\agordon\documents\visual studio 2008\projects\lomdb\enterdata\radargraphdll\radargraphinsertdll\lomdll.cs:212
EnterData.DataEntry.LOMForm.Page_Load(Object sender, EventArgs e) in C:\Users\agordon\Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\LOMForm.aspx.cs:20
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428
Version Information: Microsoft .NET Framework Version:2.0.50727.5448; ASP.NET Version:2.0.50727.5420
STUDENT-006 is my computer name it is not my username! i do not understand why it is trying to login with my computer name.
when the application is run, it immediately should pull data from the database. i have windows authentication enabled and it works without a problem when i run from dubugger, but when i try to compile i get the above error
what am i doing wrong?
MLABS\STUDENT-006$ is the username that the IIS application pool is running as. You either change the application pool user in IIS,
Open IIS Manager. For information about opening IIS Manager, see Open IIS Manager (IIS 7).
In the Connections pane, expand the server node and click Application Pools.
On the Application Pools page, select the application pool for which you want to specify an identity, and then click Advanced
Settings in the Actions pane.
For the Identity property, click the ... button to open the Application Pool Identity dialog box.
If you want to use a built-in account, select the Built-in account option and select an account from the list.
If you want to use a custom identity, select the Custom account option and click Set to open the Set Credentials dialog box. Then type
the custom account name in the User name text box, type a password in
the Password text box, retype the password in the Confirm password
text box, and then click OK.
Click OK to dismiss the Application Pool Identity dialog box.
or you can impersonate in web.config.
<configuration>
<system.web>
<identity impersonate="true"/>
</system.web>
</configuration>
MLABS\STUDENT-006$ is the account that the local "NETWORK SERVICE" account looks like when connecting to other machines and how the server is registered in Active Directory.
This is what the Application Pool in IIS running under, so this connects to SQL Server.
I'd suggest using a domain account especially for this

ASP.NET MVC: problem connecting to a database

I am using this guide:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-7
Like instructed, I entered to ASP.NET Web Application Administrator, but when I enter the security tab:
There is a problem with your selected
data store. This can be caused by an
invalid server name or credentials, or
by insufficient permission. It can
also be caused by the role manager
feature not being enabled. Click the
button below to be redirected to a
page where you can choose a new data
store.
The following message may help in
diagnosing the problem: Unable to
connect to SQL Server database.
I did clicked the button below, but it didn't help at all.
So far I did exactly (I think..) like the guide said I should.
I have a terrible feeling that the answer is obvious.
Edit 1:
BTW, When I open the full solution from the guide and try to open the ASP.NET Web Application Administrator, the following error shows up:
There is a problem with your selected
data store. This can be caused by an
invalid server name or credentials, or
by insufficient permission. It can
also be caused by the role manager
feature not being enabled. Click the
button below to be redirected to a
page where you can choose a new data
store.
The following message may help in
diagnosing the problem: A
network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: SQL Network
Interfaces, error: 26 - Error Locating
Server/Instance Specified)
Edit 2:
Connection String:
<connectionStrings>
<add name="MusicStoreEntities"
connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
Do you have SQL server express installed and do you have the database in app_data?

Categories