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.
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 new to PostgreSQL and I would like to use it with Identity Server 4.
I am using next NuGet packages: IdentityServer4, IdentityServer4.EntityFramework and Npgsql.EntityFrameworkCore.PostgreSQL
I am trying to make migration for Identity Server tables on PostgreSQL. I am modifying ConfigureServices in Startup.cs with:
string connectionString = "Server=192.168.1.108; Port=5432; Database=postgres; User Id=postgres;Password=mysecretpassword";
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseNpgsql(connectionString, action=>
{
action.MigrationsAssembly(migrationsAssembly);
});
});
When I run Add-Migration command, I can see that VS prepares all migration information for me (I can see all the tables that I need), but when I run Update-Database command I get some weird error:
Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.1.4-rtm-31024 initialized 'ConfigurationDbContext' using provider
'Npgsql.EntityFrameworkCore.PostgreSQL' with options:
MigrationsAssembly=MangEx.Users System.TimeoutException: The
operation has timed out. at
Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout) in
C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 703 at
Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async,
CancellationToken cancellationToken) in
C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 555 at
Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async,
CancellationToken cancellationToken) in
C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 414 at
Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<g__OpenLong|0>d.MoveNext()
in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 270
--- End of stack trace from previous location where exception was thrown --- at Npgsql.NpgsqlConnection.Open() in
C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 153 at
Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
in
C:\projects\EFCore.PG\src\EFCore.PG\Storage\Internal\NpgsqlDatabaseCreator.cs:line
216 at
Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
at
Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String
targetMigration) at
Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
targetMigration, String contextType) at
Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
at
Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
action) The operation has timed out.
I am running PostgreSQL via Docker and it is active container, plus I am running pgAdmin4 as a Docker container and it is seeing PostgreSQL container.
I am probably missing something trivial, but as I said I am totally new to PostgreSQL so I can't pinpoint the cause of this error.
I would appreciate any leads.
It was my mistake. I have runned docker image of PostgreSQL without opening the port to outside world. When I runned that image with -p 5432:5432, I have managed to migrate Identity Server tables to the database.
I'm using
- ASP.NET, C#, .NET 4.5.2
- Oracle.ManagedDataAccess
- Oracle.ManagedDataAccess.EntityFramework
- Oracle.DataAccess
- Server running Windows Server 2008 SP2.
My website uses Oracle.DataAccess in most parts (e.g. login, search data). I'm migrating some parts to Oracle.ManagedDataAccess (e.g. insert Permit data). The website work perfectly in both my computer and server. However, when it works about 3-4 days it will show error ORA-12154 from Oracle.ManagedDataAccess parts but Oracle.DataAccess parts still work correctly. I can login or search data but I can't insert Permit data.
My current solution is recycling Application Pool every 3-4 days and it will work again. Please suggest me. Thank you.
Here is some of exception.
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> Oracle.ManagedDataAccess.Client.OracleException: ORA-12154: TNS:could not resolve the connect identifier specified ---> OracleInternal.Network.NetworkException: ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, String instanceName)
at OracleInternal.Network.OracleCommunication.DoConnect(String tnsDescriptor)
at OracleInternal.Network.OracleCommunication.Connect(String tnsDescriptor, Boolean doNAHandshake, String IName)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, CriteriaCtx criteriaCtx, String instanceName)
--- End of inner exception stack trace ---
at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, CriteriaCtx criteriaCtx, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, CriteriaCtx criteriaCtx, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, CriteriaCtx criteriaCtx)
at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
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
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.