Why does this code cause an error? - asp.net

I have been looking for hours on how to connect to my local SQL database. I can't believe its been this difficult. Anyway, i think I am more on the right track with this code.
<%
Dim myConnection as System.Data.SqlClient.SqlConnection
Dim myCommand as System.Data.SqlClient.SqlCommand
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=dbtest;Integrated Security=True")
myConnection.Open()
%>
However, It still does not work. I don't know where to begin because I also get this message when the page loads:
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
I created a web.config file, and it didn't change anything. I'm so lost. Any help is appreciated!
Stack Trace: [SqlException
(0x80131904): Cannot open database
"dbtest" requested by the login. The
login failed. Login failed for user
'IIS APPPOOL\DefaultAppPool'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
+6244425 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj) +245
System.Data.SqlClient.TdsParser.Run(RunBehavior
runBehavior, SqlCommand cmdHandler,
SqlDataReader dataStream,
BulkCopySimpleResultSet
bulkCopyHandler, TdsParserStateObject
stateObj) +2811
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean
enlistOK) +53
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword,
Boolean ignoreSniOpenTimeout, Int64
timerExpire, SqlConnection
owningObject) +248
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String
host, String newPassword, Boolean
redirectedUserInstance, SqlConnection
owningObject, SqlConnectionString
connectionOptions, Int64 timerStart)
+6260362 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection
owningObject, SqlConnectionString
connectionOptions, String newPassword,
Boolean redirectedUserInstance)
+6260328 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString
connectionOptions, Object
providerInfo, String newPassword,
SqlConnection owningObject, Boolean
redirectedUserInstance) +354
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection
owningConnection) +703
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection
owningConnection, DbConnectionPool
pool, DbConnectionOptions options) +54
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject) +6261592
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject) +81
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) +1657
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) +88
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory
connectionFactory) +6265031
System.Data.SqlClient.SqlConnection.Open()
+258 ASP.index_aspx.__Render__control1(HtmlTextWriter
__w, Control parameterContainer) +71 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter
writer, ICollection children) +115
System.Web.UI.Page.Render(HtmlTextWriter
writer) +38
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +4240

It's here
Cannot open database "dbtest"
requested by the login. The login
failed. Login failed for user 'IIS
APPPOOL\DefaultAppPool'
The App Pool identity account is set up in SQL Server but is not set up in the database dbtest. You get a different error message if you could not connect to the SQL Server instance, but you are connecting for you to get this error message above.1
So, in SQL:
USE dbtest
GO
CREATE USER [IIS APPPOOL\DefaultAppPool] FROM LOGIN [IIS APPPOOL\DefaultAppPool]
Edit:
When you connect to a "database", you actually authenticate 3 times (basically)
To the Windows/domain install hosting the SQL Server Instance (out of scope here)
To the SQL Server instance, where you are a "login" set up SQL Server via CREATE LOGIN
This login maps to zero or more databases as a "user", which is what you needed to do here
In this case, you were set up in SQL Server as a login but not set up in the target database hosted within the SQL Server instance.

Put the CustomError tag and value properly, like:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
This will expose the exact issue to you.

Try to set Data Source=(local)

Have you followed all the instructions and made sure the customerErrors tag in the web.config looks like this:
<customErrors mode="Off" />
And the real error appears to be that the user ASP.Net is running as does not have permission to log in to the database.

Related

Two strings in Web.config

I have two connectionstrings in my webconfig.
like this:
<connectionStrings>
<add name="DataAccess_DynamicWebEntities" connectionString="metadata=res://*/DataAccess_DynamicWeb.csdl|res://*/DataAccess_DynamicWeb.ssdl|res://*/DataAccess_DynamicWeb.msl;provider=System.Data.SqlClient;provider connection string="data source=\SQLEXPRESS;initial catalog=Dynamicweb-Verploegen-Test_new;user id='VERPLOEGEN\Niels';password='';multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="NAV2DWservice.Properties.Settings.NAVconnectionString" connectionString="Data Source=\SQLEXPRESS;Integrated Security=SSPI;Initial catalog=Verploegen-Test;"/>
</connectionStrings>
So the above connectionstring works, but the one below doesnt work.
And yes, the datbase name is correct.
Thank you
This is the error:
System.Data.EntityException: De onderliggende provider is mislukt op Open. ---> System.Data.SqlClient.SqlException: Login failed for user 'VERPLOEGEN\Niels'.
bij System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
bij System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
bij System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
bij System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
bij System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
bij System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
bij System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
bij System.Data.SqlClient.SqlConnection.Open()
Yes, I have a login. see image
If I declare it like this:
<add name="DataAccess_DynamicWebEntities" connectionString="Data Source=DESKTOP-UON3ACI\SQLEXPRESS;initial catalog=Dynamicweb-Verploegen-Test_new;Integrated Security=SSPI;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="NAV2DWservice.Properties.Settings.NAVconnectionString" connectionString="Data Source=DESKTOP-UON3ACI\SQLEXPRESS;Integrated Security=SSPI;Initial catalog=Verploegen-Test;" />
I get this error:
System.ArgumentException: Het sleutelwoord wordt niet ondersteund: data source.
bij System.Data.EntityClient.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Hashtable synonyms)
bij System.Data.EntityClient.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms)
bij System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
bij System.Data.EntityClient.EntityConnection..ctor(String connectionString)
bij System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
Was doing the trick:
Are you sure that your credentials are correct? As your error message explicitly states that logging into the database failed :
Login failed for user 'VERPLOEGEN\Niels'
It's important to consider that this login information should actually be credentials to log into your SQL Server instance (e.g. sa would be an example of one of these), which can be created similar as seen below :
Otherwise, if you want to use the current user or a domain-level user then try adding the following to your connection string :
Integrated Security=SSPI;
or :
Integrated Security=true;
You may want to try accessing your local SQL instance and attempt to log in within the credentials that you are using to ensure they are correct.
It looks like a permission issue. The user 'VERPLOEGEN\Niels' cannot access the database.
The first connection string uses a SQL server account to login and the second connection string uses a Windows account. Even if the usernames and passwords are the same, they are different accounts to SQL Server and both need to be given permission. Also, to use both SQL Server accounts and Windows accounts, SQL Server must have been setup to use Mixed Authentication Mode.

userprincipal.findbyidentity an operations error occurred

Okay so, I have been given the responsibility to migrate a website with multiple applications to another server. That migration went well (all applications working). However, the performance of that new server was sub par (whole other story). We decided to migrate it again. This time everything is working very well-- except one application.
It worked just fine on the first and second IIS servers, but is refusing to cooperate this time around.
I've mirrored all the config settings that I could find from the working server:
windows authentication enabled: check
Impersonation disabled: check
applicationpool settings match: check
I just don't know what I'm missing; why would it work on one server, but not the other.
An operations error occurred.
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.Runtime.InteropServices.COMException: An operations error occurred.
Source Error:
Line 9: Dim myUsername As String = Right(User.Identity.Name, Len(User.Identity.Name) - InStr(User.Identity.Name, "\"))
Line 10: Dim ctx = New PrincipalContext(ContextType.Domain)
Line 11: Dim myUser = UserPrincipal.FindByIdentity(ctx, myUsername)
Line 12: hfValid.Value = "false"
Line 13: For Each gp As GroupPrincipal In myUser.GetAuthorizationGroups
Source File: D:\mghnet1\isOnCall\Default.aspx.vb Line: 11
COMException (0x80072020): An operations error occurred
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +378142
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_AdsObject() +31
System.DirectoryServices.PropertyValueCollection.PopulateList() +26
System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +49
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +150
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +1114
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +112
System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +31
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) +14
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue) +73
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) +28
_Default.Page_Load(Object sender, EventArgs e) in D:\mghnet1\isOnCall\Default.aspx.vb:11
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Version Information: Microsoft .NET Framework Version:2.0.50727.5466; ASP.NET Version:2.0.50727.5456
Please help, none of the other forum posts I've found have posted solutions that work for me.

Impersonation Issue on IIS7 - Entity Framework Trusted_Connection ASP.NET

I'm developing an ASP.NET Application that connects to a Database (on another machine). When I try to connect from my machine there are no problem, when I deploy it on the destination environment, EF returns an exception:
The underlying provider failed on Open.System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) at
My configuration is:
<authentication mode="Windows" />
<customErrors mode="Off"></customErrors>
<identity impersonate="true" />
<security>
<authentication>
<windowsAuthentication useKernelMode="false">
<extendedProtection tokenChecking="None" />
</windowsAuthentication>
</authentication>
</security>
And my connection string is:
<add name="pmgbicopEntities" connectionString="metadata=res://*/copDB.csdl|res://*/copDB.ssdl|res://*/copDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=[NAME]\devde;Initial Catalog=[NAME];Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
If I remove the database instruction the this.Page.User is my current Account (and this is right!), but when I open a new connection via EF I become "Anonymous"
I tried with impersonation like:
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try
{
ctx = winId.Impersonate();
//EF SOMETHING
}
catch (Exception exx)
{
}
finally
{
if (ctx != null)
ctx.Undo();
}
But I get the same exception "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."
I tried to change the application pool user, tried to impersonate manually but without any success.
The IIS configuration has some kerberos stuff that I tried to Enable and Disable but nothing change.
Do you have any suggestion? Do I have to enable something like "trust" between machines? For my development machine from "fake IIS" I have no problem but my user is enabled on the DB.
Thank you in advance.
What is your end goal here: pass through the user's credentials to SQL or use a predetermined account to connect to SQL?
Here are the settings I've had to configure Kerberos to work (which allows you to use the user's account permissions):
IIS Settings:
-Physical Path Credentials: Application User (pass-through authentication)
-Physical Path Credential Logon Type: Clear Text
-Application Pool ID: Domain\ServiceAccount
-Integrated Windows Authentication: Enabled
-Windows Authentication Providers: Negotiate
-useAppPoolCredentials (found in Configuration Editor): True
SPN created for the ServiceAccount:
SETSPN -L Domain\ServiceAccount
HTTP/Our.WebSiteURL.com
If you want don't want to use a domain service account replace that with Domain\MachineAccount in both the SPN and Application Pool.

An item with the same key has already been added. After switching web hosts

I'm transferring a .NET Framework 4.0 site from 1 web host to another. The site on the existing hosting seems to be working as intended. However, after transferring the site files and database to the new hosting and then fixing the web.config connection string to point to the new db, I'm getting errors when trying to access a page that pulls from the database.
I did not write the site, but it appears to be using a code-first setup.
Server Error in '/' Application.
An item with the same key has already been added.
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.ArgumentException: An item with the same key has already been added.
Source Error:
Line 130: if ((_Jobs == null))
Line 131: {
Line 132: _Jobs = base.CreateObjectSet<Job>("Jobs");
Line 133: }
Line 134: return _Jobs;
I've tried rebuilding the edmx file from the new database server after transferring the files. I know my connection string is working because I wrote a small test that connects to the database through the same connection string and it is able to retrieve data.
The only change I've made to the code base after copying it from it's working state is to the web.config's db connection string.
The only real notable difference from the old hosting versus the new hosting is that the old hosting was using SQLEXPRESS(unknown version), whereas the new hosting is using MSSQL 2008.
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +9378779
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadRelationshipTypes() +650
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() +17
System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() +25
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.Load() +4
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) +160
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) +166
System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) +316
System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection edmItemCollection) +84
System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) +151
System.Data.Objects.ObjectContext.GetTypeUsage(Type entityCLRType) +35
System.Data.Objects.ObjectContext.GetEntitySetForNameAndType(String entitySetName, Type entityCLRType, String exceptionParameterName) +33
System.Data.Objects.ObjectContext.CreateObjectSet(String entitySetName) +66
PR.PRModel.PREntities.get_Jobs() in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\App_Code\PRModel.Designer.cs:132
Careers.LoadJob() in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\Careers.aspx.cs:24
Careers.Page_Load(Object sender, EventArgs e) in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\Careers.aspx.cs:16
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Connection String:
<connectionStrings>
<add name="PREntities" connectionString="metadata=res://*/App_Code.PRModel.csdl|res://*/App_Code.PRModel.ssdl|res://*/App_Code.PRModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=myserver.com;Initial Catalog=mydatabase;Persist Security Info=True;User ID=username;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="ConnectionStringDB" connectionString="Data Source=myserver.com;Initial Catalog=mydatabase;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>

ERROR MESSAGE: The state information is invalid for this page and might be corrupted (Invalid viewstate)

I have two servers on IIS6 where load balancing is done by a load balancing hardware. When a response is provided Server 1 and the postback is handled by Server 2 it always gets an error The state information is invalid for this page and might be corrupted and underneath Invalid viewstate on almost every postback when requests are handled by alternative servers. If I turn off one of the server then it seems to be working fine.
I have checked the decryptionKey and validationKey are both exactly same on the both server deployment, and also wth enableEventValidation="false" and enableViewStateMac="false". There was no luck with all sorts of solutions available provided by Google :P
Please check the stack trace below where exception occurs at HiddenFieldPageStatePersister.Load() followed by Page.LoadPageStateFromPersistenceMedium().
[ViewStateException: Invalid viewstate.
Client IP: 192.168.5.21
Port: 60042
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
ViewState: {VIEWSTATE DATA}
[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +118
System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +13
System.Web.UI.HiddenFieldPageStatePersister.Load() +222
System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +107
System.Web.UI.Page.LoadAllState() +43
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6230
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +247
System.Web.UI.Page.ProcessRequest() +79
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +23
System.Web.UI.Page.ProcessRequest(HttpContext context) +111
OrderJourneyDefault.ProcessRequest(HttpContext context) in C:\inetpub\wwwroot\x\Default.aspx.cs:350
ASP.toj_application_orderjourney_default_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\82a64fa9\62e4fa0\App_Web_31vcm2al.0.cs:0
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +406
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76
NOTE: There's no AJAX/Javascript related things to mess up my application.
Thanks in advance.
Munim

Resources