I am using Webmatrix.data's Database entity to create a database connection, however it doesnt like my connection string. I am running it from MVC ASP.net.
Ive tried changing it to server / database, but still errors the same. Where am I going wrong?
using (var db = Database.OpenConnectionString(#"Data Source=MY-HP\Serv;Initial Catalog=MyDBSQL;User ID=sa;Password=password"))
{
var items = db.Query("SELECT * FROM TaskPriority");
}
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalog'.
check here: Database.OpenConnectionString Method (String, String)
try to specify the provider name as second parameter, from the MSDN example:
var connectionString = "Data Source=.\\SQLExpress;Initial Catalog=SmallBakery;Integrated Security=True";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
ARRRRHHHHHH!!!!!
This is the second time I've run into this, grrrh - wasted hours on it.
Error:
The server encountered an error processing the request. The exception message is 'Keyword not supported: 'initial catalog;MyDatabase;data source'.'. See server logs for more details. The exception stack trace is:
Stacktrace:
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable
parsetable, String connectionString, Boolean buildChain, Hashtable
synonyms, Boolean firstKey) at
System.Data.Common.DbConnectionOptions..ctor(String connectionString,
Hashtable synonyms, Boolean useOdbcRules) at
System.Data.SqlClient.SqlConnectionString..ctor(String
connectionString) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String
connectionString, DbConnectionOptions previous) at
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey
key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions&
userConnectionOptions) at
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey
key) at
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString,
SqlCredential credential)
This was my faulty connection string:
<add name="Production" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog;MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
Looks good right? WRONG
Eventually I spotted the semi-colon here:
Initial Catalog;MyDatabase
To correct it, I used an equal sign:
Initial Catalog=MyDatabase
The correct connection string:
<add name="ConnString" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog=MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
You can use the below code
Config file :
<connectionStrings>
<add name="con" connectionString="Data Source=ServerName;Initial Catalog=master;Integrated Security=SSPI;" providerName="System.Data.SqlClient"></add>
</connectionStrings>
cshtmlfile :
var db = Database.Open("con");
var selecteddata = db.Query("select * from movie");
I ran into the error in one of the IdentityServer quickstarts.
Had to replace
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
With
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Using
Microsoft.EntityFrameworkCore.SqlServer
Because obviously my DB was a Microsoft SQL Server and not SQLite.
For me I was getting this error because I was using a templated solution. Unbeknownst to me the template only installed support for sqlite. I had to install Microsoft.EntityFrameworkCore.SqlServer and change the calls in my code from UseSqlite to UseSqlServer.
You need to check your connection string.
I received the error because I had db(instead of 'Database') in my connection string.
"DevConnection": "server=DEL1-XX-XXXX;db=DonationDb;user=sa;password=XXXX"
Updating the above connection string(db to Database) should solve the problem. Below is the working connection string.
"DevConnection":"server=DEL1-XX-XXXX;Database=DonationDb;user=sa;password=QwerXXXX"
I suggest:
You can check your connection string format clearly especialy " and ". In my case this is:
You may try generate db by EF again.
Related
Is there any suggestion for PostgreSQL to add type Nvarchar?
This is the error that I am getting:
Npgsql.PostgresException (0x80004005): 42704: type "nvarchar" does not exist
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception data:
Severity: ERROR
SqlState: 42704
MessageText: type "nvarchar" does not exist
Position: 94
File: d:\pginstaller_13.auto\postgres.windows-x64\src\backend\parser\parse_type.c
Line: 274
Routine: typenameType
42704: type "nvarchar" does not exist
Thank you.
"National" string data types are a vestige from the dim and distant past when people still used single-byte encodings like ISO 8859-1 or Windows-1252.
Nowadays we store data using UNICODE encodings, in the case of PostgreSQL, UTF-8. Since you can store any character that way, there is no need for a special data type.
This error occured to me when my last migration (which the update-database command uses) was not for a PostgreSQL connection.
You can try this:
create a new migration with add-migration <name>
clear the database with update-database 0
apply the newly created migration on the database with update-database
In my case, first I was using SQL Server as DB and changed to PostgreSQL. Old migrations were caused the problem type "nvarchar" does not exist. Deleted old migrations and created new migration, updated everything worked fine.
So i get the error that i should call WebSecurity.InitializeDatabaseConnection
before i call any function of the webSecurity Class
So i created _AppStart.cshtml and placed this code in it :
#using System.Configuration;
#{
string connString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
WebSecurity.InitializeDatabaseConnection(connString, "users", "id", "email", autoCreateTables: true);
}
and in Web.Config i got
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
<connectionStrings>
<add name="conString" providerName="System.Data.SqlClient"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False"/>
</connectionStrings>
now i get this error from the InitializeDatabaseConncection method :
Connection string "Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False" was not found.
whats the problem ?
WebSecurity.InitializeDatabaseConnection is not asking you for a connection string. It's asking you for the name of the connection string. It will then retrieve the connection string form the configuration file for you.
WebSecurity.InitializeDatabaseConnection("conString", "users", "id", "email", autoCreateTables: true);
When you have a question about why a method is not behaving as expected, read the documentation! It states for that parameter:
The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.
I am using VS 2008 .NET 3.5 & have a SQL Server database file in App_Data. When I click on "Test Connection" of database it succeeds. When I try to connect it through code, it fails. After trying to find & solve the problem reading so many sites, I think I am confused with the connection string.
My code is :
string sql = "select count(*) from LoginDB where loginUserName = #userName and loginPassword = #password";
string conStr = ConfigurationManager.ConnectionStrings["VinciConnectionString"].ConnectionString;
statusLbl.Text += "\n Conn Str = " + conStr;
conn = new SqlConnection(conStr);
statusLbl.Text += "\n Executed Conn : " + conn.ToString();
SqlCommand cmd = new SqlCommand(sql, conn);
statusLbl.Text += "\nconn DB = " + conn.Database;
In the output I get :
Conn Str = server=localhost;database=VincitoreDB.mdf;uid=VTSONY\Vikram10;Password=000;
Executed Conn : System.Data.SqlClient.SqlConnection
conn DB = VincitoreDB.mdf
SQL = System.Data.SqlClient.SqlCommand
The error message that I get here is :
A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
The DB "Modify Properties"-"Advanced" tab shows this :
Original connection string was :
<connectionStrings>
<add name="VinciConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VincitoreDB.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
After trial & error, right now it's :
<connectionStrings>
<add name="VinciConnectionString"
connectionString="server=localhost;database=VincitoreDB.mdf;uid=VTSONY\Vikram10;Password=000;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Can anyone please help me figure out what & why am not able to connect to the database? Have spend lots of hrs trying to figure out reading lots of forums, but no success. If this the problem of connection string or something else?
Please help me out. Any help is highly appreciated.
Thanks
Enable in your Sql Server Configuration manager under SQL Server Networki configuration > Protocols fro SQLExpress > TCP IP - Enabled after this restart the computer or the service.
In connection string provide your computers name for example: MY-PC\SQLEXPRESS
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.
I'm getting the following exception when I try to start nservicebus.host.exe with service account credentials:
Database was not configured through Database method.
System.Data.SQLite.SQLiteException: Unable to open the database file
at System.Data.SQLite.SQLite3.Open(String strFilename, SQLiteOpenFlagsEnum flags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection() in :line 0
at NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() in :line 0
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) in :line 0
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) in :line 0
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) in :line 0
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in D:\dev\fluent-nhibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs:line 93
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in D:\dev\fluent-nhibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs:line 100
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.Build(IDictionary^2 nhibernateProperties, Boolean updateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\Internal\SessionFactoryBuilder.cs:line 48
--- End of inner exception stack trace ---
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.Build(IDictionary^2 nhibernateProperties, Boolean updateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\Internal\SessionFactoryBuilder.cs:line 55
at NServiceBus.ConfigureNHibernateSagaPersister.NHibernateSagaPersister(Configure config, IDictionary^2 nhibernateProperties, Boolean autoUpdateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\ConfigureNHibernateSagaPersister.cs:line 80
at Ibfx.BackOffice.Services.NewAccounts.NewAccountsEndpoint.Init() in C:\Dev\TFS\Omega\Src\Svcs\NewAccounts\Src\Service\NewAccountsEndpoint.cs:line 67
at NServiceBus.Host.Internal.GenericHost.Start() in c:\Dev\DotNet\NServiceBus\src\host\NServiceBus.Host\Internal\GenericHost.cs:line 56
Everything works fine if I run the host using my own account, but if I run the host as a service with domain credentials or use those same credentials with the RunAs command I get the above exception. What are the permissions I need to configure so the service will work?
Here's my config:
var configure = NServiceBus.Configure.With()
.Log4Net<Log4NetLoggerAdapter>(a => { })
.UnityBuilder(container)
.XmlSerializer()
.RijndaelEncryptionService()
.MsmqTransport()
.IsTransactional(false)
.PurgeOnStartup(false)
.MsmqSubscriptionStorage();
configure.Configurer.ConfigureComponent<MsmqSubscriptionStorage>(
ComponentCallModelEnum.None).ConfigureProperty(p => p.DontUseExternalTransaction
, true
);
IBus bus = configure.UnicastBus()
.ImpersonateSender(true)
.LoadMessageHandlers()
.Sagas()
.NHibernateSagaPersister()
.CreateBus()
.Start();
And I have a NServiceBus.Host.exe.config file with the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
</configuration>
What happens when you temporarily give EVERYONE and ANONYMOUS LOGON Full Control over the directory specified? If that solves the exception, it's definitely a security issue. Are you using |DataDirectory| in your connection string? Are you sure the process is actually looking at the directory that you think it's looking at?
Following that, I would try using the SQLite in memory connection string settings to see if it's able to at least create a database and use it:
":memory:;Version=3;New=True;Pooling=True;Max Pool Size=1;"
The above string uses in-memory SQLite but keeps a single connection open so that the tables and data continue to exist until the process exits.
Another strategy that I would use is to change the saga persister to another SQL flavor, such as MS SQL to see if that solves it.