SQL Server connection string in Appsettings.json + .net Core 3.1 - sql-server

I'm trying to setup and connect to my remote development SQL Server (SQL 2017) in appsettings.json within .NET Core 3.1, I have tried the following approaches yet without any success.
"ConnectionStrings": {
//"DefaultConnection1": "DATA SOURCE=[servername];UID=[username];PWD=[password];DATABASE=[databasename]",
//"DefaultConnection2": "Data Source=[servername]; Initial Catalog=[databasename];User ID=[username];Password=[password]",
//"DefaultConnection3": "DataSource=[servername];Initial Catalog=[databasename];User Id=[username];password=[password]",
"DefaultConnection4": "Server=[servername];Database=[databasename];User Id=[username];password=[password];Trusted_Connection=False;MultipleActiveResultSets=true;"
},
Error of DefaultConnection1:
ArgumentException: Keyword not supported: 'uid'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword))
Error of DefaultConnection2:
ArgumentException: Keyword not supported: 'initial catalog'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Error of DefaultConnection3:
ArgumentException: Keyword not supported: 'initial catalog'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Error of DefaultConnection4:
ArgumentException: Keyword not supported: 'server'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Any ideas, pointers or help is much appreciated.

thanks for your help and advice, i might have just found the solution and am able to connection the SQL database successfully now, the problem was as following:
The following package was installed on the solution:
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder
in Startup.cs the following line was used in the ConfigureServices(IServiceCollection services):
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlLite(Configuration.GetConnectionString("DefaultConnection")));
However after research i found out that i should rather use the following line:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Which was not accessible due the following package missing:
Microsoft.EntityFrameworkCore.SqlServer
After installing this package via package Manager using the following command:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
I was able to access the SQL server using the following connection string:
"ConnectionStrings": {
"DefaultConnection": "Server=[servername];Database=[databasename];Persist Security Info=True;User ID=[username];Password=[password];MultipleActiveResultSets=True;"
},
For safety, as Christian pointed out, I removed also the other connectionstring references.

Probably it's just because you're not supposed to put comments (//) in JSON as JSON is a data format and doesn't support comments. So try actually removing the lines starting with // from your config.

Your setup in appsettings.json is fine.
Suppose the model in your cs file is mytestModel.
Here is the code to read the connection string:
public class mytestModel : PageModel
{
public string connectstring = "";
private IConfiguration MyConfiguration;
public mytestModel (IConfiguration _configuration)
{
MyConfiguration = _configuration;
}
public void OnGet()
{
connectstring = this.MyConfiguration.GetConnectionString("DefaultConnection4");
}
}
It should be noted that the type of model (eg. PageModel) does not matter. The name of the model is what matters.

Related

How to use Hangfire in ASP.NET Core with Azure database and Active Directory Password authentication

We're trying our first use of Hangfire (v1.7.19) in an ASP.NET Core WebApi application (.NET 5). Previously they've all been old school ASP.NET, and have worked without issue.
Hangfire packages used (per the Hangfire documentation) are Hangfire.Core, Hangfire.SqlServer and Hangfire.AspNetCore. We've also tried to just use the combined Hangfire package, but are having the same results.
Lifting directly from the code on that documentation page, in ConfigureServices we add
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(connectionString), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
which, at runtime, gives
System.ArgumentException
HResult=0x80070057
Message=Keyword not supported: 'authentication'.
Source=System.Data.SqlClient
StackTrace:
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
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)
at Hangfire.SqlServer.SqlServerStorage.<.ctor>b__6_0()
at Hangfire.SqlServer.SqlServerStorage.CreateAndOpenConnection()
at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](DbConnection dedicatedConnection, Func`2 func)
at Hangfire.SqlServer.SqlServerStorage.UseConnection(DbConnection dedicatedConnection, Action`1 action)
at Hangfire.SqlServer.SqlServerStorage.Initialize()
at Hangfire.SqlServer.SqlServerStorage..ctor(String nameOrConnectionString, SqlServerStorageOptions options)
at Hangfire.SqlServer.SqlServerStorage..ctor(String nameOrConnectionString)
at Hangfire.SqlServerStorageExtensions.UseSqlServerStorage(IGlobalConfiguration configuration, String nameOrConnectionString)
The value of connectionString is
Initial Catalog=XXX;Data Source=YYY;Authentication=Active Directory Password;UID=ZZZ;PWD=PPP"
This works fine with local SqlServer and LocalDb, but not with AzureDB. The connection string is exactly the one we're also using for EntityFrameworkCore 5 (in fact, the value is assigned from context.Database.GetConnectionString()).
I've read where there were issues with AzureDB and .NET Core, but those were resolved quite some time ago. Looking through the Hangfire.SqlServer package dependencies, I see where it uses System.Data.SqlClient, and current documentation for AzureDB use all refer to Microsoft.Data.SqlClient, which makes me think that the enhancements to support Active Directory Password authentication weren't made in System.Data.SqlClient but only in the newer Microsoft.Data.SqlClient package. If that's the case, I can put in a request that Hangfire replace its SqlClient package, but want to get confirmation before I do that.
Any ideas if this is indeed the case? Is there something we can do in the meantime to fix this instead?
Thanks in advance.
Hangfire IO GitHub Issue 1827
Pointers from Sergey Odinokov
As early as 1.7.8 there has been support to use an overload of UseSqlServerStorage that accepts a Func<DbConnection> instead of a connection string where you can use a connection factory to provide the newer Microsoft.Data.SqlClient.SqlConnection which supports the Authentication keyword.
Here is the related source code
You can use this like
services.AddHangfire(config => config
// other options you listed above removed for brevity
.UseSqlServerStorage(
() => new Microsoft.Data.SqlClient.SqlConnection(<connection_string>)
, new SqlServerStorageOptions() {...}
)
);

Symfony 3.3 Doctrine Fixtures Load skipping SQL views

I'm trying to use SQL views with Doctrine.
Everything works fine so far, but I have a problem when running a basic fixtures load (with no options). I get the following error messages.
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'DELETE FROM gp_items':
SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]View or function 'gp_items' is not updatable
because the modification affects multiple base tables.
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]View or function 'gp_items' is not updatable
because the modification affects multiple base tables.
[PDOException]
SQLSTATE[42000]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]View or function 'gp_items' is not updatable
because the modification affects multiple base tables.
I looked at the code that loads the fixtures from the bundle ("doctrine/doctrine-fixtures-bundle": "^2.3") and I think I have to alter something to the ORMPurger (Doctrine\Common\DataFixtures\Purger) but I'm not sure how to go about that.
So I would like to know how to override a function in that specific class.
Cheers!
Ok,
So I decided to fork the DoctrineFixturesBundle and use my own version of it in my project.
https://github.com/jbonnier/DoctrineFixturesBundle
In order for composer to use it, I modified my composer.json file adding the following code before the last closing bracket.
,
"repositories": [
{
"type": "vcs",
"url": "https://github.com/jbonnier/DoctrineFixturesBundle"
}
]
I also change my require-dev statement to use my personnal branch.
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "dev-jbonnier",
...
}
EDIT:
Additional explanation.
I'm currently working with version v2.4.1 of the bundle.
Here's the change I made to it.
File : Command/LoadDataFixturesDoctrineCommand.php
Changed line 113
from
$purger = new ORMPurger($em);
to
$purger = new ORMPurger($em, $this->listViews($input->getOption('em')));
Add function to class after line 136
/**
* Return an array with all views names in the database.
*
* #return array
*/
protected function listViews($entityManager)
{
$em = $this->getContainer()->get('doctrine')->getManager($entityManager);
$conn = $em->getConnection();
$sm = $conn->getSchemaManager();
$views = $sm->listViews();
$rst = array();
foreach ($views as $view)
{
array_push($rst, $view->getName());
}
return $rst;
}
I had a similar problem. I was lazy so I did the workaround to load our fixtures this way.
I you find a clean solution I'm interested
bin/console -e=test doctrine:database:drop --if-exists --force
bin/console -e=test doctrine:database:create --if-not-exists --no-interaction
bin/console -e=test doctrine:migrations:migrate --no-interaction
bin/console -e=test doctrine:fixtures:load --append --no-interaction

Database name containd dot in jdbc url spring boot

Dear all I am in the unfortunate sitution to connect to an sqlserver 2005 databae that was provided to me and contains o dot (.)
I have setup a configuration for spring boot like
#Configuration
public class CustomConfig {
#Bean
#Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("myuname")
.password("mypass")
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3.5;")
.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.build();
}
}
And of course I get an exception stating com.microsoft.sqlserver.jdbc.SQLServerException: Database '5' does not exist. Make sure that the name is entered correctly.
I have tried in vain the following
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName={REALLY_BAD_NAME_V3.5};")
that gives the same error and
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3{.}5;")
And gives a malformed url exception after reading these instructions.
Any ideas?

com.microsoft.jdbc.sqlserver.SQLServerDriver not found

adapter.js file:
var procedure1Statement = WL.Server.createSQLStatement("select [sname] from [TestDb].[dbo].[studentinfo]");
function procedure1() {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : []
});
}
adapter.xml file:
<dataSourceDefinition>
<driverClass>com.microsoft.sqlserver.jdbc.SQLServerDriver</driverClass>
<url>jdbc:sqlserver://localhost;databaseName=TestDb</url>
<user>user</user>
<password>pass</password>
</dataSourceDefinition>
getting error like this:
{
"errors": [
"Runtime: java.lang.ClassNotFoundException: Class com.microsoft.jdbc.sqlserver.SQLServerDriver not found in Worklight platform or project \/HelloWorld"
],
Read the error. Your error is that the driver is missing.
Make sure you have placed the jdbc driver in your-project\server\lib
Then make sure you are correctly pointing to the database in the XML file: IBM Worklight 6.1 - Failed connecting to MS SQL using SQL adapter

How to use MSSQL DSN as URL in DataSource.groovy

I have been trying this code in DataSource.groovy but its showing an error of "No suitable driver"
dataSource
{
pooled = true
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
String url="jdbc:microsoft:sqlserver:DSNname";
}
I have already included two jdbc SQLserver drivers sqljdbc, sqljdbc4 (*.jar files).
I also tried this code but went futile.
DataSource
{
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
//url="jdbc:sqlserver://localhost:1433;database=DBNAME" its working
url="jdbc:odbc:myDSN"
username="sa"
password=""
}
Thanks a ton in advance.

Resources