Two strings in Web.config - asp.net

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.

Related

Timeout period elapsed prior to obtaining a connection from the pool

I am getting following error after hosting the application:
Error Page : http://********.in/Presentation Layer/NewQuotation.aspx
Error Message : Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
StackTrace : at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.GetNewOpenConnection()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.GetOpenConnection(Boolean disposeInnerConnection)
at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteReader(DbCommand command)
at DataLayer.Quotation_DL.insertQuoteproduct(QuotationProductCombination _objQP) in F:\gayathri reddy\Enq Quote\06-01-2015\DataLayer\Quotation_DL.cs:line 430
at BusinessLayer.Quotation_BL.insertQuoteproduct(QuotationProductCombination _objQpc) in F:\gayathri reddy\Enq Quote\06-01-2015\BusinessLayer\Quotation_BL.cs:line 88
at EngQuote.Presentation_Layer.NewQuotation.Quotationsave(Int32 status, String oper) in F:\gayathri reddy\Enq Quote\06-01-2015\EngQuote\Presentation Layer\NewQuotation.aspx.cs:line 3711
But while running the code in local Visual Studio 2010 there is no issues, when i host it in server or local machine IIS or Shared hosting server on that time only we are facing this issue
I have tried following all these steps but have not got any improvement
1).Opened and closed the connection in every DL function
2).Increased the command time out in this way
DbCommand cmd = db.GetStoredProcCommand("Procedurename");
cmd.CommandTimeout = int.MaxValue;
SqlDataReader sdata = (SqlDataReader)db.ExecuteReader(cmd);
3). Increased connection time out in web config
4). Increased executionTimeout in web config
5). Increased shutdown time out
6). Changed debug=false
but no use,connection time out problem still exists for long processes
Please suggest any solution other than above options
Expecting a good solution for this issue from u peoples
thanks in advance....
I guess connection between IIS and SQL Server was too slow to serve a connection. Just make sure the max connection limit is not reached. You can confirm by executing below select statement.
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
You can try increasing pool size in connection string. But this will have some downside. Below is the sample connection string with increased pool size.
server=localhost;database=dbname;uid=username;pwd=paswrd;Max Pool Size=200;

Object reference not set to an instance of an object GetDomains call on startup [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
*Note : This is not a null reference duplicate question. It was not so apparent what was causing it and needed deeper investigation.
My site was working fine on my local dev box and then I decided to convert Umbraco 6 from using a embedded database (SDF) to full SQL database (MDF). The database conversion went well using WebMatrix but now after changing the web config to use full SQL the site gets the below error when I run it. I have read through a few help articles online for this but nothing seems to solve my issue. Any ideas? (SQL rights, cache maybe, did I miss a config setting?
I did this basically http://carlosmartinezt.com/2014/03/umbraco-migrate-from-sql-ce-to-sql-server/
Here is my web.config
<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</DbProviderFactories>
</system.data>
<system.net>
<mailSettings>
<smtp>
<network host="127.0.0.1" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
<connectionStrings>
<add connectionString="Data Source=KBURMARK;Initial Catalog=Umbraco;Integrated Security=True" name="Umbraco" providerName="System.Data.SqlClient" />
<!-- Important: If you're upgrading Umbraco, do not clear the connection string / provider name during your web.config merge. -->
</connectionStrings>
Here is the error I am getting
[NullReferenceException: Object reference not set to an instance of an object.]
umbraco.cms.businesslogic.web.Domain.<GetDomains>b__0() +122
Umbraco.Core.Cache.<>c__DisplayClass1`1.<GetCacheItem>b__0() +41
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, CacheDependency dependency) +246
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +159
Umbraco.Core.Cache.CacheProviderExtensions.GetCacheItem(IRuntimeCacheProvider provider, String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +219
Umbraco.Core.CacheHelper.GetCacheItem(String cacheKey, TimeSpan timeout, Func`1 getCacheItem) +339
umbraco.cms.businesslogic.web.Domain.GetDomains(Boolean includeWildcards) +243
Umbraco.Web.Routing.DomainHelper.GetAllDomains(Boolean includeWildcards) +40
Umbraco.Web.Routing.PublishedContentRequestEngine.FindDomain() +365
Umbraco.Web.Routing.PublishedContentRequestEngine.PrepareRequest() +59
Umbraco.Web.Routing.PublishedContentRequest.Prepare() +36
Umbraco.Web.UmbracoModule.ProcessRequest(HttpContextBase httpContext) +738
Umbraco.Web.UmbracoModule.<Init>b__7(Object sender, EventArgs e) +132
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I solved this issue the same way. Set the connection string name="umbracoDbDSN"

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.

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

Why does this code cause an error?

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.

Resources