I have recently subscribed for Azure free trial, and I'm currently trying to publish my website.
However, as I got my website published I encountered the following error:
[NullReferenceException: Object reference not set to an instance of an object.]
MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +56
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +276
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +27
System.Data.Entity.Infrastructure.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k) +32
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection) +251
System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +56
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +43
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +610
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
When I run this locally with the connection-string to my remote database it works fine, but as soon as I publish it it doesn't work.
My connection strings look like this:
<add name="DefaultConnection" connectionString="user id=****;password=****;persistsecurityinfo=False;server=**** ;database=iprospect_tools" providerName="MySql.Data.MySqlClient" />
<add name="ToolsEntities" connectionString="metadata=res://*/ToolsModel.csdl|res://*/ToolsModel.ssdl|res://*/ToolsModel.msl;provider=MySql.Data.MySqlClient;provider connection string="user id=****;password=****;persistsecurityinfo=False;server=****;database=tools"" providerName="System.Data.EntityClient" />
When I remote debug my application, this is the error evaluation:
Any idea what might be causing this error?
There is some informatin missing form your question that would make providing a consice answer easier, but here is what I would do:
Figure out where the db is being hosted
The first thing to do here is to figure out what service you are using for your MySQL database. In Azure there are at least four ways to host a MySQL database and each one might require different steps.
MySQL in App
Since you are doing a remote connection from your desktop I don't think you are using this option.
MySQL provided by ClearDB
If you are using this, then server name would be something like: us-cdbr-azure-*.cloudapp.net
MySQL provided by Microsoft
If you are using this, then server name would be something like: *.mysql.database.azure.com
MySQL hosted in an IaaS VM
If you are using this, then server name would be something like: *.cloudapp.net
If the database is not hosted in Azure, then you should check network configuration.
Create a simplest app possible to test connectivity.
Assuming your DB is hosted in Azure the next step is to reduce your dependencies in an effort to identify if the issue lies with the Db server, network config, your code, or another dependency.
string myConnectionString = "your-connectionstring-goes-here";
try{
using (var con = new MySqlConnection { ConnectionString = myConnectionString }){
con.Open();
if (!con.Ping()){
System.Diagnostics.Trace.TraceError("MySQL Ping Failed:");
}
else{
System.Diagnostics.Trace.TraceInformation("MySQL Successfull");
}
}
}
catch (Exception exep){
System.Diagnostics.Trace.TraceError("Could not connect to MySQL: " + exep.Message);
}
Note that in this example we are hard-coding the connection string into the code to bypass even web-config.
If this is working then we know connectivity to the DB is good and the app service app can reach the DB. Skip step (3) and go to step (4)
If it's not working then the we still have a bit more debugging to do. Go to step (3)
Fix network/firewall on DB server
If your DB is being hosted by Microsoft MySQL check to make sure the Firewall is allowing your app to connect to it and repeat step (2)
If your DB is being hosted in an IaaS VM make sure the ports and network are open to accepct connections and repeat step (2)
Once you get step (2) to work then try with your code again.
Debug your code
Once you get step (2) working and then that rules out connectivity issues. That means that the bug is in your code, connection string config or the way you are using Entity Framework.
Hope this helps
If the website is working locally, and database connection failing after publishing to Azure - definitely config is missing in Azure website Settings.
Check out these SO thread 1 and SO thread 2
Related
I have a web API hosted on Heroku. It serves data from a ClearDB via a Golang program. I have a C# .NET script that will need to insert data into that ClearDB. I had this idea working on my local machine, but as I moved everything over to heroku, the C# part stopped working.
I have been successful in connecting with MySQL Workbench 8.0 and with my Golang program itself. The GO program can successfully connect, query, and serve data.
I know there are many other questions like this, and most of them seem to be solved with the connection string. I have tried almost ALL of the different ways you can string up a connection string. This is what i last tried (credentials have been changed to random letters):
connectionData = #"Server = eu-cd-steel-west-01.cleardb.net; Port = 3306; Database = heroku_555555555; Uid = b7039sldk253; Pwd = e3502ldks;";
The error I am getting happens when I run this:
connection = new MySqlConnection(connectionData);
connection.Open();
Error:
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
---> System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.ThrowHelper.ThrowMoreThanOneMatchException()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at MySql.Data.Common.StreamCreator.GetTcpStream(MySqlConnectionStringBuilder settings)
at MySql.Data.Common.StreamCreator.GetStream(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at DatabaseTesting.DataBaser.connect() in C:\Users\surf.user\source\repos\DatabaseTesting\DatabaseTesting\DataBaser.cs:line 38
I understand there are SSL credentials and all sorts of stuff, but I am lead to believe that doesn't matter as I didn't have to configure anything special to connect on workbench. Is there anything extra I need to do to successfully open the ClearDB connection on C#?
I suspect you're running into this known bug in Oracle's MySQL Connector/NET: bug 97448. (I can't resolve the domain name you gave in the question, but if it resolves to more than one A record then that will trigger the bug.)
The fix is to uninstall the MySql.Data NuGet package and install MySqlConnector instead: https://www.nuget.org/packages/MySqlConnector/
This supports the same API as MySql.Data, so it should be a drop-in replacement.
I am working on a Website that was donated to our institution, right now I'm trying to decide exactly how to set up two connection strings (CS) in the Web.config file (some of the details in these connection strings were redacted by the donator).
The CS I have a question about is referenced in sessionState:
<sessionState allowCustomSqlDatabase="true" mode="SQLServer" sqlConnectionString="DevelopmentSessionState" cookieless="false" timeout="20"/>
I'm trying to determine what type of Account I should be using for the UserID in the SessionState CS. In order to get the Website functional I used the sa account, but I know this isn't a good idea - I'm looking for an account to replace sa. I have no idea if this is a user I should define in SQL Server, or if I should use a pre-existing account, or what type of access this user should have.
I am also fuzzy on the idea of why a separate connection string is needed for Session State. The Website's c# code uses the other CS explicitly to connect to the db, but the only reference to the SessionState CS is in Web.config. I have read a lot about Session State and SQLServer mode that past few days, but I haven't found any recommendations for what account to use or why a separate CS is needed for SessionState.
Thanks,
Chris
Update: This is the stack trace from the abend that happens when I substitute my UserID for sa in the Session State CS (I replaced my actual User ID with USERID):
Server Error in '/' Application.
Failed to login to session state SQL server for user 'USERID'.
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.Web.HttpException: Failed to login to session state SQL server for user 'USERID'.
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 'USERID'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876535
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1121
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +144
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +367
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
System.Web.SessionState.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo) +93
[HttpException (0x80004005): Failed to login to session state SQL server for user 'USERID'.]
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
I did finally succeed in creating a user that worked in the Session State CS.
To begin with, rather than running InstallSqlState.sql I ran aspnet_regsql.exe. The SQL file had a warning not to run it standalone and that I should instead use aspnet_regsql.exe, so I did that. I used the following options:
aspnet_regsql.exe -ssadd -sstype p -E -S servername
This created db ASPState and meant that I had to use mode="SQLServer" in in web.config.
I also had to add role 'public' to ASPState as suggested here:
http://forums.asp.net/t/969708.aspx
This post included giving 'public' permissions but did not talk about which ones would be needed, so I had to experiment with that until the CS worked. Permissions were added by right clicking on db ASPState, choosing Properties, selecting Permissions, highlighting database role 'public', then checking off permissions under the 'Grant' heading.
Finally I logged in to SQL Server Management Studio using SQL Server Authentication and created a new user S1. I only gave 'Connect' permission to S1 using the same navigation described above. S1 replaced sa in the session state connection string. Here is the web.config entry for the session state CS. Obviously I changed the pw and servername, but you can see the format I used:
<add name="DVSessionState" connectionString="Data Source=servername;User Id='S1';Password='password'"/>
The following steps describe how to run the InstallSqlState.sql and the UninstallSqlState.sql script files to configure SQL Server mode session state management.
In SQL Query Analyzer, on the File menu, click Open.
In the Open Query File dialog box, browse to the InstallSqlState.sql script file, and then click Open. By default, InstallSqlState.sql is located in one of the following folders:
system drive\WINNT\Microsoft.NET\Framework\version\
system drive\Windows\Microsoft.NET\Framework\version\
After InstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.
Before you run the UninstallSqlState.sql script file to uninstall SQL Server mode session state management configuration, you must stop the w3svc process. To do this, follow these steps:
On the Windows Start menu, click Run, type cmd, and then click OK to open a command prompt.
At the command prompt, type net stop w3svc. You receive confirmation that the w3svc process is stopped.
In SQL Query Analyzer, on the File menu, click Open.
In the Open Query File dialog box, browse to the UninstallSqlState.sql script file, and then click Open. By default, UninstallSqlState.sql is located in one of the following folders:
system drive\WINNT\Microsoft.NET\Framework\version\
system drive\Windows\Microsoft.NET\Framework\version\
After UninstallSqlState.sql opens in SQL Query Analyzer, click Execute on the Query menu to run the script.
After you uninstall SQL Server mode session state management configuration, you must restart the w3svc service. To restart the w3svc process, type net start w3svc at a command prompt.
Modify the Web.config File of Your Application
To implement ASP.NET SQL Server mode session state management, you must modify the <sessionState> element of your application's Web.config file as follows:
Set the mode attribute of the <sessionState> element to SQLServer to indicate that session state is stored in SQL Server.
Set the sqlConnectionString attribute to specify the connection string for SQL Server. For example:
sqlConnectionString="data source=MySQLServer;user id=;password="
Note: The user, <user name>, must have permissions to perform this operation on the database.
The modified <sessionState> element should appear as follows:
<sessionState
mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=<username>;password=<strongpassword>"
cookieless="false"
timeout="20"
/>
Note: Ensure that you use the correct case when you specify the <sessionState> element and the associated attribute values. This code is case sensitive.
I have created a windows service which listen to a TCP/IP port and save received data in database using Entity Framework. Most of the time it works fine but some time its throwing an exception "The underlying provider failed on open." on save data in database.
Here is my exception details:
Exception: 2/27/2014 10:31 AM:
The underlying provider failed on Open.
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at Service.DemoService.Save(String received, TcpClient client)
What is the thing behind this exception and how to resolve it?
Usually, when working with Entity Framework you'll need to enable the multiple active result sets option in your connection string by setting MultipleActiveResultSets to true as follows.
<add name="conn"
connectionString="
Data Source=.\;
Initial Catalog=TDB;
UID=admin123;
PWD=123;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
Verify that it solves your problem.
Check whether you SQL Server is running or not.
Just Open Task Manager and Goto Services, Click on Services button below and check whether SQL Server is running or not.
In my case, the issue was that the account which I was using to connect to SQL server was not added to app pool identity. Once I added the account 'domain\username' to app pool, it started working.
Change
integrated security= False ; MultipleActiveResultSets=True
in your connection string , it should be work.
I had this error but I solved it by Opening Task Manager, Go to Services and checking if my SQL Server is running or not. Your Sql server should be running.
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.
We have a web service on server #1 and a database on server #2.
Web service uses transaction scope to produce distributed transaction. Everything is correct.
And we have another database on server #3. We had some problems with this server and we reinstalled operation system and software. We configured MSDTC and tried to use web service from server #1 to communicate with database on this server.
And now after first select statement within transaction scope we get: The operation is not valid for the state of the transaction. This exception falls in every web service request if it is using transaction scope.
Server #2 and Server #3 is almost similar. The difference can be only in settings.
.NET framework 3.5 SP1 installed and SQL Server SP3 on all servers.
Full stacktrace:
System.Transactions.TransactionState.EnlistPromotableSinglePhase(InternalTransaction
tx, IPromotableSinglePhaseNotification
promotableSinglePhaseNotification, Transaction atomicTransaction) в
System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification
promotableSinglePhaseNotification) в
System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction
t в System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction t в
System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction
transaction) в
System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction
transaction) в
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) в
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) в
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory) в
System.Data.SqlClient.SqlConnection.Open() в
NHibernate.Connection.DriverConnectionProvider.GetConnection() в
NHibernate.Impl.SessionFactoryImpl.OpenConnection()
I searched this message but didn't found any appropriate solution.
So what settings should I check and what exactly should I do to fix it?
Lanfear, I have come across the same error message and I found a solution. Your situation may be different, but I hope that the following knowledge will be useful to you.
System.Transactions.Transaction.Current.TransactionInformation.Status will return the status of the current transaction.
In each case where an exception is thrown with the message The operation is not valid for the state of the transaction, when I step thru with the debugger, I see that the status is "Aborted" before the exception is thrown.
In my case, the problem was caused by nesting two transactions inside each other and mistakenly aborting both when I wanted to abort only one. Apparently, if you use the TransactionScope default constructor New TransactionScope() with two nested transactions, aborting the inner transaction aborts the outer transaction as well. The solution is to use the Constructor New TransactionScope(TransactionScopeOption.RequiresNew) Using this constructor, the inner transaction will be a new transaction and aborting it will not abort the outer transaction.
This solved my issue.
Enabling the Distributed Transaction Coordinator solved the issue for me (this was done on both machines: the one that has the web service and the one that has the database. Not sure though if it is needed for the web service).
I followed the steps described here to enable the DTC and to add an exception to the Windows Firewall: Enable Network DTC Access for Windows Server 2008