Keyword not supported: 'port' - NpgSql - asp.net-mvc

I have the following problem with the azure web app:
When publishing, the following error occurs:
Keyword not supported: 'port'.
at System.Data.SqlClient.SqlConnectionStringBuilder.GetIndex(String keyword)
at System.Data.SqlClient.SqlConnectionStringBuilder.set_Item(String keyword, Object value)
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnectionStringBuilder..ctor(String connectionString)
at Microsoft.Web.Deployment.ConnectionStringMatcher.RemoveExtraSlashFromDataSourceName(String connectionString)
at Microsoft.Web.Deployment.ConnectionStringMatcher.GetStandardConnectionString(String userConnectionString, Boolean isSqlCE)
at Microsoft.Web.Deployment.SqlInfo.GetBuilder(String connectionString, String errorMessageFormat)
appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=xxxxx;Database=xxxxx;Port=5432;User Id=test;Password=xxxxx;Ssl Mode=Require;",
"ProviderName": "Npgsql"
},
Startup.cs:
services.AddDbContext<Context>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

Is your PostgreSQL server created in Azure?
According to the error message, the port parameter should not appear in the connection string.
If it is created in azure, your DefaultConnection should be like the following string.
Server=jasonp2testsql.postgres.database.azure.com;Database={your_database};Port=5432;User Id=jasonp2#jasonp2testsql;Password={your_password};Ssl Mode=Require;
You also can refer to this post.
C# SqlConnection Exception: Keyword not Supported 'Port'
And the offical document is useful to you.

Related

SSL connection to the postgresql ASP.NET

I am trying to connect to a postgresql database through SSL. In the appsetting.json file, my connection string is
"DefaultConnection": "Sslmode=Require;Sslrootcert=rootCA.crt;Sslcert=postgres_client.crt;Sslkey=postgres_client.key;Server=xxx.xxx.xxx.xx;Database=my_database;Username=my_username"
When I run the api, I get the error message as followed
System.ArgumentException: Keyword not supported: sslrootcert (Parameter 'keyword')
at Npgsql.NpgsqlConnectionStringBuilder.GetProperty(String keyword)
at Npgsql.NpgsqlConnectionStringBuilder.set_Item(String keyword, Object value)
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at Npgsql.NpgsqlConnectionStringBuilder..ctor(String connectionString)
at Npgsql.NpgsqlConnection.GetPoolAndSettings()
at Npgsql.NpgsqlConnection.set_ConnectionString(String value)
at Npgsql.NpgsqlConnection..ctor(String connectionString)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
By the way, I am able to connect to my database in the terminal with
psql "sslmode=verify-ca sslrootcert=/rootCA.crt sslcert=postgres_client.crt sslkey=postgres_client.key hostaddr=xxx.xxx.xxx.xx port=xxxx user=my_username dbname=my_database"
So, is my asp.net connection string wrong, or the rootCA.crtfile is not set properly? Thanks in advance for any advice:))

Trying to use Azure Pod Identity fails a number of times, before finally succeeding

Intro: I'm trying to get Azure Pod Identity to work in our cluster to read secrets from a KeyVault, and am mostly succeeding (so far so good). For the time being, we have two keyvaults, two AzureIdentity's, two AzureIdentityBinding's and two Pods using each their keyvault.
While testing, both pods are equal - only difference being their aadpodidbinding and an environment variable indicating what keyvault to use. At startup, the pod connects to the KeyVault, reads two values and prints them with Console.WriteLine. If the connection fails, the pod will crash and k8s will restart it.
The problem: One pod might startup being able to read from the keyvault immediately, while the other will crash and restart for - what seems to be - rather consistently 5 times before being able to get an access token.
When it fails, the following Exception is thrown:
Unhandled Exception: Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/******************. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/******************. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. MSI ResponseCode: Forbidden, Response: no AzureAssignedIdentity found for pod:default/kv-test-be
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/******************. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Environment variable LOCALAPPDATA not set.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/******************. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. No such file or directory
at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(String authority, String resource, String scope)
at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.<get_KeyVaultTokenCallback>b__8_0(String authority, String resource, String scope)
at Microsoft.Azure.KeyVault.KeyVaultCredential.PostAuthenticate(HttpResponseMessage response)
at Microsoft.Azure.KeyVault.KeyVaultCredential.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(String vaultBaseUrl, Nullable`1 maxresults, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, String vaultBaseUrl, Nullable`1 maxresults, CancellationToken cancellationToken)
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at KeyvaultTest.Program.Main(String[] args) in /app/src/Program.cs:line 16
The behaviour is similar when using FlexVolume (which eventually one group of our pods will use in production), but I find it easier to relate to the error with two equal pods.
While waiting for the pod to succeed, I'm seeing both "binding removed" and "binding applied" messages in mic's log.
My questions:
Is this behaviour "as intendend" and perhaps documented somewhere?
Is there a setting I can apply to make the "remove - apply" cycle faster?
Is there anything else that can be done to improve the time between pod creation and the identity binding being applied? Is this issue perhaps related to https://github.com/Azure/aad-pod-identity/issues/145
Sourcecode:
Program.cs
using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace KeyvaultTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Keyvault read");
var configuration = new ConfigurationBuilder()
.AddAzureKeyVault()
.Build();
var test1 = configuration.GetValue<string>("jtest");
Console.WriteLine(test1);
var test2 = configuration.GetValue<string>("jtest:jtest");
Console.WriteLine(test2);
Console.WriteLine("Finished Keyvault read");
}
}
}
KeyVaultConfiguration.cs.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;
namespace KeyvaultTest
{
public static class KeyVaultConfiguration
{
public static IConfigurationBuilder AddAzureKeyVault(this IConfigurationBuilder builder)
{
var builtConfig = builder.Build();
var keyVaultName = Environment.GetEnvironmentVariable("KV_NAME");
if (string.IsNullOrWhiteSpace(keyVaultName))
{
throw new Exception("KV_NAME is not defined");
}
Console.WriteLine($"Using KV_NAME = {keyVaultName}");
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(
$"https://{keyVaultName}.vault.azure.net/",
keyVaultClient,
new DefaultKeyVaultSecretManager());
return builder;
}
}
}
Any help, hints or ideas are much appreciated.
Note: I've posted this same question to the Issue board on of the project's github page https://github.com/Azure/aad-pod-identity/issues/181
We were facing the same issue. We overcame this issue by upgrading AAD Pod Identity. Our version was 1.5 and upgrading this one to 1.7 resolved our issue.
Before that, we had also upgraded the packages (Microsoft.Azure.Services.AppAuthentication & Azure.Security.KeyVault.Secrets) that our applications were using to the latest versions but it wasn't enough.

Connection string not working in ASP.NET Core

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=ABC; Trusted_Connection=True; MultipleActiveResultSets=true"}
I am working with ASP.NET Core MVC. I have this connection string in my appsettings.json file but it doesn't seem to work. While running "dotnet ef database update" from cmd, I am getting this error keyword not supported: 'server.'. What's wrong with it?
Apologies! In my ConfigureServices method in Startup.cs, I was using SQLite database provider
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")))
I changed it to the following, and it worked with my connection string.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
The connection string should start of with Data Source=.
In Visual Studio if you open the SQL Server Object Explorer and click on the database you are wanting to connect to. The connection string will be displayed in the Properties window. The connections string should look something like this for localDb
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=Fals

Keyword not supported : 'host' error when migration ef on POSTGRESQL

Currently I am doing database migration using MVC6 on .netcore 2.0. here is the link that I am following, to migrate POSTGRESQL : https://damienbod.com/2016/01/11/asp-net-5-with-postgresql-and-entity-framework-7/
in my appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DataAccessPostgreSqlProvider": "User ID=ids;Password=****;Host=127.0.0.1;Port=5432;Database=IDS;Pooling=true;"
}
}
I start migrate using the following command:
dotnet ef migrations add testPG
it is successful and no error at all but when I tried to run the following command on command prompt, the error is coming out.
dotnet ef database update
here is the error what I saw on cmd.
can somebody pls enlighten me to this?
Edited full stacktrace is here :
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\Richard\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
System.ArgumentException: Keyword not supported: 'hostaddr'.
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 Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
at Microsoft.EntityFrameworkCore.Internal.RelationalLoggerExtensions.MigrateUsingConnection(IDiagnosticsLogger`1 diagnostics, IMigrator migrator, IRelationalConnection connection)
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)
Keyword not supported: 'hostaddr'.
Thanks You
Frog
Make sure that the class which implements IDesignTimeDbContextFactory contains the correct DB definition for PostgreSQL. Pay attention to this line builder.UseNpgsql(connectionString); here:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<DomainModelPostgreSqlContext>
{
public DomainModelPostgreSqlContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<DomainModelPostgreSqlContext>();
var connectionString = configuration.GetConnectionString("DataAccessPostgreSqlProvider");
builder.UseNpgsql(connectionString);
return new DomainModelPostgreSqlContext(builder.Options);
}
}
Are you sure ,you are not using SQL Server connection (using (IDbConnection pgcon = new SqlConnection(con))) instead of PostgresSQL connection( using (IDbConnection pgcon = new NpgsqlConnection(con)))in your code?It happened to me before.
I had this same issue. After searching all over with no luck, I figured it out. The keyword "host" is in your connection string. You should replace this with server.
For example:
Host=127.0.0.1 should be Server=127.0.0.1

Why does XDocument.Load throw exception when ELMAH is enabled?

I have the following code that retrieves a link to the latest post from the blog subsite:
XDocument doc = XDocument.Load("http://www.mysite.com/blog/syndication.axd");
XElement node = doc.Descendants("item").FirstOrDefault();
string text = node.Element("title").Value;
string uri = node.Element("link").Value;
The code always worked fine. This week I added ELMAH.MVC via NuGet as a Package Reference. As soon as I deploy the web.config file with the added ELMAH sections, I get the following error:
System.Web.HttpException (0x80004005): Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
If I put the old web.config file back, the error goes away.
Any idea why adding ELMAH would cause XDocument.Load to fail?
You need to look at your ASP.Net site and find the server-side error.

Resources