Receiving weird host can't be null error with ef core - ef-core-3.1

I have recently installed the EF Core 3.1.6 on a home project using postgresql.
I have the connection string, and can add migrations easily with the Package Manager Console. If I run my application the Database.Migrate() will migrate the migrations easily. However if I attempt to update the database via the Package Manager Console with an 'update-database' I receive this error:
System.ArgumentException: Host can't be null
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnection.Open()
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
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.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Host can't be null
I do not know what is happening, if I am missing a nuget package, etc. Any possible help and explanation for what is happening would be greatly appreciated.

I Solved it. It had to do with the way I was building the connection string on runtime and not buildtime.

You should export your env variables first from terminal like this:
export $(grep -v '^#' ./dev.env | xargs)
{dev.env} -> change it to your env file

Check your connection string in your startup class you may have different connection string name with the config of the database in the startup when you are using appsetting.json
Startup configuration
appsetting.json

You should set ConnectionStrings in program.cs|startup.cs.
Add this into the program.cs (.net7)
builder.Services.Configure<ConnectionStrings>(
builder.Configuration.GetSection(nameof(ConnectionStrings))
);
or startup.cs (.net6):
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

add bellow lines in Program.cs file
builder.Services.AddDbContext<ApplicationDBContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IDataAccessProvider, DataAccessProvider>();
and bellow connection string in appsettings.json
  "ConnectionStrings": {
    "DefaultConnection": "User ID=postgres;Password=******;Host=127.0.0.1;Port=****;Database=at;"
  },   "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"

Related

FirebirdSql Data Client I/O error during "CreateFile (open)" operation for file

One of our clients is getting this error very randomly. Once or twice a week. It has only been happening for the last month or so.
Error message:
I/O error during "CreateFile (open)" operation for file "ttt"
Error while trying to open file
Stack trace:
at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.CreateNewConnection(FbConnectionString connectionString, FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.CreateNewConnectionIfPossibleImpl(FbConnectionString connectionString, FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.GetConnection(FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Get(FbConnectionString connectionString, FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnection.Open()
at TTT.DALFirebird.FbSocket.ExecuteScalar(CommandType commandType, String commandText, String connectionString, FbParameter[] parameters)
at TTT.LibGlobal.Data.FirebirdHelper.TestConnection(String connectionString)
------
Error message:
I/O error during "CreateFile (open)" operation for file "ttt"
Error while trying to open file
Stack trace:
at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ProcessResponse(IResponse response)
at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadResponse()
at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadGenericResponse()
at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.Attach(DatabaseParameterBuffer dpb, String dataSource, Int32 port, String database)
at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
The database is hosted on a dedicated PC with Windows 8.1.
Firebird version: 3.0.7.33374 (x64)
Firebird Sql Data Client version: 4.6.1.0
I checked the security settings for the database file and gave full control for the system and users. Not sure what else it could be as the 3050 port is open and there's no issue with users connecting 99% of the time. Is a particular test their I.T. can run to diagnose?
The connection string for the desktop application is:
dialect=3;initial catalog=<Database Alias>;data source=<IP ADDRESS>;user id=<User>;password=<Password>;character set=ISO8859_1;pooling=True;connection lifetime=30;server type=Default;port number=3050
Please let me know if you require any further information.
They are trying to connect to database "ttt". This database (or alias) is not found so they get the error. As the developer of the application you should know what "TTT" object in the call stack may be and how connection string is formed.

Unable to run .net core app Azure Durable Functions v3 in docker

I am trying to implement a docker-compose.yml file to build a container for a .net core Azure Durable Function v3. The following code snippet is from the environment file i.e. .env:
AzureWebJobsStorage=MyConnectionString
AzureWebJobsDashboard=MyConnectionString
AzureWebJobsStorageQueue=MyAnotherConnectionString
This is how a part of the docker-compose file looks like:
local.mydurablefunction:
image: ${DOCKER_REGISTRY-}myfunction
build:
context: .
dockerfile: src/MyFunction/Dockerfile
ports:
- 34080:34080
environment:
- AzureWebJobsStorageQueue
- AzureWebJobsDashboard
- AzureWebJobsStorageQueue
When running docker-compose up I get the following error message:
fail: Host.Startup[515] A host error has occurred during startup
operation 'd8e39085-bed2-4f30-b80b-37d2fe1b286d'.
System.InvalidOperationException: Unable to find an Azure Storage
connection string to use for this binding. at
Microsoft.Azure.WebJobs.Extensions.DurableTask.AzureStorageDurabilityProviderFactory.GetAzureStorageOrchestrationServiceSettings(String
connectionName, String taskHub
This is how the function looks like:
[FunctionName("MyTrigger")]
public async Task RunAsync(
[QueueTrigger("queuename", Connection = "")] string metadataPayload,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log,
CancellationToken cancellationToken)
{
}
Somewhere in the function's body, we are calling a durable task which looks like the following code snippet:
[FunctionName("Orchestrator")]
public async Task RunOrchestratorAsync(
[OrchestrationTrigger] IDurableOrchestrationContext context,
[DurableClient] IDurableOrchestrationClient orchestrationClient,
ILogger log)
{
}
And this is the service dependency definition:
{
"dependencies": {
"storage1": {
"type": "storage",
"connectionId": "AzureWebJobsStorageQueue"
}
}
}
What is the solution for this problem or what may be missing in this configuration? Could it be due to not being able to copy the environment variables to the container?

Azure Devops Pipeline Environment Resource Agent installation issue

I have been trying to add an environment resource to our pipeline in azure devops but every time i install it with the powershell script they provide it asks me for tags. If i don't want to input tags it errors. If i choose to put in tags it errors. Either way it starts over every time and it will never successfully install. Anyone know if this is something on my end or on their end? I looked through the diagnostic file and the exceptions it is logging look like it's something that i can't fix but i have been having issues with this for over a week and thinking it was something that Microsoft would realize and patch. Now i'm wondering if there is something else i can do?
[2020-05-22 13:01:48Z ERR VisualStudioServices] POST request to https://DEVOPS_URL/24cca667-60da-4ba2-a323-4e05c46f3309/_apis/pipelines/environments/3/providers/virtualmachines failed. HTTP Status: InternalServerError, AFD Ref: Ref A: 56C7161B437D41698EBBDE7ACBF4CAA2 Ref B: ATAEDGE0918 Ref C: 2020-05-22T13:01:48Z
[2020-05-22 13:01:48Z INFO CommandSettings] Flag 'unattended': 'False'
[2020-05-22 13:01:48Z ERR Terminal] WRITE ERROR (exception):
[2020-05-22 13:01:48Z ERR Terminal] Microsoft.VisualStudio.Services.WebApi.VssServiceResponseException: TF400898: An Internal Error Occurred. Activity Id: acb8a36a-e602-4988-b3f7-8fbeecd729e0.
---> System.NullReferenceException: TF400898: An Internal Error Occurred. Activity Id: acb8a36a-e602-4988-b3f7-8fbeecd729e0.
--- End of inner exception stack trace ---
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.HandleResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.SendAsync(HttpRequestMessage message, HttpCompletionOption completionOption, Object userState, CancellationToken cancellationToken)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.SendAsync[T](HttpRequestMessage message, Object userState, CancellationToken cancellationToken)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.SendAsync[T](HttpMethod method, IEnumerable1 additionalHeaders, Guid locationId, Object routeValues, ApiResourceVersion version, HttpContent content, IEnumerable1 queryParameters, Object userState, CancellationToken cancellationToken)
at Microsoft.VisualStudio.Services.Agent.Listener.Configuration.EnvironmentVMResourceConfigProvider.AddAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
at Microsoft.VisualStudio.Services.Agent.Listener.Configuration.ConfigurationManager.ConfigureAsync(CommandSettings command)
I was experiencing a similar error "Failed to add virtual machine resource. Linked environment pool is null."
Answer from Kevin Ross here: https://developercommunity.visualstudio.com/t/addition-of-resource-to-environment-fails-for-user/1048111
I resolved my error by following the below steps:
Get the deployment pool ID from the environment URL
Find the deployment pool settings in the organization settings and navigate to the correct pool based on ID from step 1
From the deployment pool settings, go to security and add the required user to administrator role or whatever role is required

Mobile Services (.Net backend) using incorrect connection string

I am struggling to make the .Net backend of Mobile Services use the correct connectionString. When I publish the service I select the correct connection string for "MS_TableConnectionString". If I check the web.config on the server (via FTP) I see what I would expect:
web.config on server:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:[ServerAddress].database.windows.net,1433;Initial Catalog=[MyMobileService_db];Integrated Security=False;User ID=[correctUserName];Password=[CorrectPassword];Connect Timeout=30;Encrypt=True" providerName="System.Data.SqlClient" />
In my context it is configured to use a connection string called MS_TableConnectionString:
private const string connectionStringName = "Name=MS_TableConnectionString";
public MyMobileServiceContext() : base(connectionStringName)
{
Schema = "MyMobileService";
}
To see what connection string is actually being used I added this to an example controller:
Example Client Code:
public class ExampleController : ApiController
{
MyMobileServiceContext context;
public ApiServices ApiServices { get; set; }
public ExampleController()
{
context = new MyMobileServiceContext();
}
public async Task<IHttpActionResult> PostExample(ExampleItem item)
{
ApiServices.Log.Warn("ConnectionString: " + context.Database.Connection.ConnectionString);
...
}
And when I look at the Log Entry on Mobile Services I see a different UserName and Password:
[2014-04-15T12:26:33.1410580Z] Level=Warn, Kind=Trace, Category='PostExampleItem', Id=00000000-0000-0000-0000-000000000000, Message='ConnectionString: Data Source=[SameServerAddress].database.windows.net;Initial Catalog=[SameDatabaseName];User ID=[DifferentUserName];Password=[DifferentPassword];Asynchronous Processing=True;TrustServerCertificate=False;'
The different username and password are the same as I see in the original .PublishSettings file that I downloaded under the name of SQLServerDBConnectionString but I have no idea where this is stored on the server?
Because of the different username and password I see the following exception in the log:
[2014-04-15T13:18:11.2007511Z] Level=Error, Kind=Trace, Category='App.Request', Id=d7ec6d25-f3b7-4e88-9024-217be40ae77f, Exception=System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: Cannot open database "master" requested by the login. The login failed.
Login failed for user '[DifferentUserName]'.
This session has been assigned a tracing ID of '[GUID]'. Provide this tracing ID to customer support when you need assistance.
Any help would be much appreciated as at the moment I am having to hard code the whole connection string in the constructor of the Context to make it work.
Thanks
F
UPDATE: 15th April 2014 15:23
I deleted all my publisher profiles and created a copy of the original .PublishSettings file. From this I deleted all but one profile. I then deleted the SQLDBConnectionString attribute to confirm that it is not because I was sending this that was causing the problem. The result was no change, it is still using the DifferentUserName and Password so it must be reading it from the server somewhere.
We have a hole at the moment in that we pick up the connection string from the portal yet don't expose the ability to set or modify connection strings there.
The work-around is to set an application setting in the portal and then use that in your code using the ApiServices class, something like this (in your controller)
string connectionString = this.Services.Settings["YourConnectionStringAsAppSetting"];
I know it is confusing... we'll make it easier to access and modify the connection strings.
Henrik

How do I set an ADO.NET Entity Framework connection string via the Windows Azure (Preview) Management Portal?

In the Windows Azure (Preview) Management Portal you can change the configuration options for web sites (see http://www.windowsazure.com/en-us/manage/services/web-sites/how-to-configure-websites/#howtochangeconfig).
I currently set the connection string for my ADO.NET Entity Framework connection via Web.Release.Config, but I want to set it via the Management Portal, but no matter what I use, I always end up with the following error:
The specified named connection is either not found in the
configuration, not intended to be used with the EntityClient provider,
or not valid.
It does work for regular connection strings, ie without the metadata key defining metadata and mapping information (csdl, ssdl, msl).
Here's what I do:
I go to https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/[MY-STAGING-SITE-NAME]/configure
Under "connection strings" I have a key named "ApplicationServices" that looks like this:
Server=tcp:xxxxx.database.windows.net,1433;Database=xxxxx;User
ID=xxxxx#xxxxx;Password=xxxxx;Trusted_Connection=False;Encrypt=True;Connection
Timeout=30;
This one works.
I have another key for the Entity Framework connection. Let's call that one FooBarContext. It looks like this:
metadata=res:///Models.FooBarContext.csdl|res:///Models.FooBarContext.ssdl|res://*/Models.FooBarContext.msl;provider=System.Data.SqlClient;provider
connection
string="Server=tcp:fooserver.database.windows.net,1433;Database=foobar;User
ID=myname#fooserver;Password=xxxxxxxxxx;Trusted_Connection=False;Encrypt=True;Connection
Timeout=30;"
This one causes the error described above. It is copied from the working value in Web.Release.Config, with the " replaced by a ".
I have tried other variations: with the " untouched, with metadata appended at the end, but to no avail. I have reproduced the problem with a second website.
The solution for my problem was selecting "Custom" instead of "SQL Azure" from the "SQL Azure / SQL Server / MySQL / Custom" selector for the Entity Framework connection string, even though the database does run on SQL Azure.
[Edit] From a popular comment by #matthew-steeples below:
I would add to this for anyone else having the same issue is that
sometimes the config file will have " instead of ", and the Azure
Websites needs those to be changed to "
Replace
"
with
"
In the connection string.
Not only did I have to use double quotes (or single quotes) instead of " (and select Custom for the type) but I also had to make sure there was a dummy value in my transform config. I was replacing the entire connectionStrings node, but decided to keep that and add this:
<add xdt:Transform="Replace" xdt:Locator="Match(name)" name="FooBarEntities" connectionString="temp" providerName="System.Data.EntityClient" />
Without this, I was getting the following error:
The connection string 'FooBarEntities' in the application's configuration file does not contain the required providerName attribute.
Beside answers above, there are 2 very important things:
You should remove "name=" from "name=connectionString"
in constructor:
public MyEntities(string connectionString)
: base($"name={connectionString}")
{
}
You should leave "duplicate" of connection string in app.config, but
replace connection string with dummy text, correct connection string
will be loaded from Azure. That's needed for providerName part.
Please read:
https://mohitgoyal.co/2017/07/05/update-connection-string-for-entity-framework-in-azure-web-app-settings/comment-page-1/
I had the same problem. I solved, putting in the web.config this connectionstring:
<add name="eManagerTurModelConnection" connectionString="metadata=res://*/ORM.eManagerFinanceModel.csdl|res://*/ORM.eManagerFinanceModel.ssdl|res://*/ORM.eManagerFinanceModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<server>.database.windows.net;Initial Catalog=eManagerTur;Integrated Security=False;User ID=<user>;Password=<Password>;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And after I removed the connectionstring of my website, worked, because it was not getting the connection string that I added in my web.config.
English bad... =)