Entity Framework Generator For Postgres - postgresql

I found a nice article in http://www.loresoft.com/Generate-ASP-NET-Web-API. I've read and test it with the SQL Server database with success. Now, I want to change the database engine into PostgreSQL, I've migrated the database from SQL Server into PostgreSQL.
But, When I am executing:
efg generate -c ""Host=localhost;Username=admin;Database=dbTest;Password=admin;Persist Security Info=True""
The console showing me:
17:18:04 W Option file not found: generation.yml
17:18:04 I Using default options
17:18:04 D Creating database model factory for: SqlServer
17:18:04 I Loading database model ...
17:18:04 F Host terminated unexpectedly
System.ArgumentException: Keyword not supported: 'host'.
at Microsoft.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
at Microsoft.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at Microsoft.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions options)
at EntityFrameworkCore.Generator.CodeGenerator.GetDatabaseModel(IDatabaseModelFactory factory) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 371
at EntityFrameworkCore.Generator.CodeGenerator.Generate(GeneratorOptions options) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator.Core\CodeGenerator.cs:line 40
at EntityFrameworkCore.Generator.GenerateCommand.OnExecute(CommandLineApplication application) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\GenerateCommand.cs:line 76
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.Invoke(MethodInfo method, Object instance, Object[] arguments)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.OnExecute(ConventionContext context, CancellationToken cancellationToken)
at McMaster.Extensions.CommandLineUtils.Conventions.ExecuteMethodConvention.<>c__DisplayClass0_0.<<Apply>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.ExecuteAsync(String[] args, CancellationToken cancellationToken)
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at EntityFrameworkCore.Generator.Program.Main(String[] args) in C:\projects\entityframeworkcore-generator\src\EntityFrameworkCore.Generator\Program.cs:line 50
I think I was missing some dependencies package. But, I am not sure what is it.
Thank you very much

I've found the solution, and decide to post it here because It may help other people in the future.
Actually, efg command will use SqlServer provider if we not mentioning any "provider" parameter. So, I've revised my command into:
efg generate -c "Host=localhost;Username=admin;Database=dbTest;Password=admin;Persist Security Info=True" -p PostgreSQL

Related

Database Migration is getting failed due to NLOG.config in Visual Studio 2022 Mac

I started programming with Visual Studio 2022 in Mac M1. I am developing an application with .net core 6 and initially I used to develop in Windows. I copied my project and started to work in VS 2022 Mac. While doing the DB Migration (Using dotnet CLI) I am getting error and it's getting failed due to NLog.config. I am using NLog for the logging functionality.
DataAccess layer and WepAPI are separate project in a solution.DBContextClass and migration scripts are present in DataAccess Layer and the connection string is present in WebAPI.
Error while doing the db migration:
Time Elapsed 00:00:01.65 Build succeeded. dotnet exec --depsfile
/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/bin/Debug/net6.0/MyCoreApplicationWebAPI.deps.json
--additionalprobingpath /Users/MASKED/.nuget/packages --runtimeconfig /Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/bin/Debug/net6.0/MyCoreApplicationWebAPI.runtimeconfig.json
/Users/MASKED/.dotnet/tools/.store/dotnet-ef/6.0.7/dotnet-ef/6.0.7/tools/net6.0/any/tools/netcoreapp2.0/any/ef.dll
database update -c ApplicationDbContext --assembly
/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/bin/Debug/net6.0/MyCoreApplication.DataAccess.dll
--project /Users/MASKED/Projects/MyCoreApplication/MyCoreApplication.DataAccess/MyCoreApplication.DataAccess.csproj
--startup-assembly /Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/bin/Debug/net6.0/MyCoreApplicationWebAPI.dll
--startup-project /Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/MyCoreApplicationWebAPI.csproj
--project-dir /Users/MASKED/Projects/MyCoreApplication/MyCoreApplication.DataAccess/
--root-namespace MyCoreApplication.DataAccess --language C# --framework net6.0 --nullable --working-dir /Users/MASKED/Projects/MyCoreApplication/MyCoreApplication.DataAccess
--verbose Using assembly 'MyCoreApplication.DataAccess'. Using startup assembly 'MyCoreApplicationWebAPI'. Using application base
'/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/bin/Debug/net6.0'.
Using working directory
'/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI'.
Using root namespace 'MyCoreApplication.DataAccess'. Using project
directory
'/Users/MASKED/Projects/MyCoreApplication/MyCoreApplication.DataAccess/'.
Remaining arguments: . Finding DbContext classes... Finding
IDesignTimeDbContextFactory implementations... Finding application
service provider in assembly 'MyCoreApplicationWebAPI'... Finding
Microsoft.Extensions.Hosting service provider... Using environment
'Development'. NLog.NLogConfigurationException: Exception when loading
configuration
/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/nlog.config
---> System.Xml.XmlException: Root element is missing. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at
System.Xml.XmlTextReaderImpl.ParseDocumentContent() at
System.Xml.XmlTextReaderImpl.Read() at
System.Xml.XmlReader.MoveToContent() at
NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader,
String fileName, Boolean ignoreErrors) --- End of inner exception
stack trace --- at
NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader,
String fileName, Boolean ignoreErrors) at
NLog.Config.XmlLoggingConfiguration..ctor(XmlReader reader, String
fileName, LogFactory logFactory) at
NLog.Config.LoggingConfigurationFileLoader.LoadXmlLoggingConfiguration(XmlReader
xmlReader, String configFile, LogFactory logFactory) at
NLog.Config.LoggingConfigurationFileLoader.LoadXmlLoggingConfigurationFile(LogFactory
logFactory, String configFile) at
NLog.Config.LoggingConfigurationFileLoader.TryLoadLoggingConfiguration(LogFactory
logFactory, String configFile, LoggingConfiguration& config) at
NLog.Config.LoggingConfigurationFileLoader.Load(LogFactory logFactory,
String filename) at
NLog.Config.LoggingConfigurationWatchableFileLoader.Load(LogFactory
logFactory, String filename) at
NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional)
at NLog.LogFactory.LoadConfiguration(String configFile) at
NLog.LogManager.LoadConfiguration(String configFile) at
Program.$(String[] args) in
/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/Program.cs:line
25
--- End of stack trace from previous location --- at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.CreateHost()
at
Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass10_0.b__0(String[]
args) at
Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass13_0.b__3(String[]
args) at
Microsoft.EntityFrameworkCore.Design.Internal.AppServiceProviderFactory.CreateFromHosting(String[]
args)
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error:
Exception when loading configuration
/Users/MASKED/Projects/MyCoreApplication/MyCoreApplicationWebAPI/nlog.config
No application service provider was found. Finding DbContext classes
in the project... Found DbContext 'ApplicationDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to
create an object of type 'ApplicationDbContext'. For the different
patterns supported at design time, see
https://go.microsoft.com/fwlink/?linkid=851728 --->
System.InvalidOperationException: Unable to resolve service for type
'Microsoft.EntityFrameworkCore.DbContextOptions1[MyCoreApplication.DataAccess.Data.ApplicationDbContext]' while attempting to activate 'MyCoreApplication.DataAccess.Data.ApplicationDbContext'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13() --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13() at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1
factory) at
Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String
contextType) 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)
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see
https://go.microsoft.com/fwlink/?linkid=851728

Squidex Within an Azure App Service: MongoDb connection failed to connect to database Squidex

I'm new to Squidex and MongoDB and I'm trying to set up Squidex within an Azure App Service following this guide:
https://docs.squidex.io/01-getting-started/installation/install-azure
I've completed the setup without issues and I'm able to connect to my MongoDb instance locally, without issue using the user I've configured as an administrator within my Squidex Mongo Database.
However, my App Service fails to start with the following error:
2021-02-18T00:45:27.806844798Z Unhandled exception. Squidex.Hosting.Configuration.ConfigurationException: MongoDb connection failed to connect to database Squidex.
2021-02-18T00:45:27.806899798Z
2021-02-18T00:45:27.806905498Z ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.
2021-02-18T00:45:27.806910099Z ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
2021-02-18T00:45:27.806914099Z at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
2021-02-18T00:45:27.806918499Z at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ExecuteAsync(IConnection connection, CancellationToken cancellationToken)
2021-02-18T00:45:27.806931099Z at MongoDB.Driver.Core.Authentication.SaslAuthenticator.AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
2021-02-18T00:45:27.806935599Z --- End of inner exception stack trace ---
2021-02-18T00:45:27.806948099Z at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
2021-02-18T00:45:27.806952999Z at MongoDB.Driver.Core.Servers.Server.GetChannelAsync(CancellationToken cancellationToken)
2021-02-18T00:45:27.806956899Z at MongoDB.Driver.Core.Operations.CreateIndexesOperation.ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken)
2021-02-18T00:45:27.806960799Z at MongoDB.Driver.OperationExecutor.ExecuteWriteOperationAsync[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)
2021-02-18T00:45:27.806964699Z at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperationAsync[TResult](IClientSessionHandle session, IWriteOperation`1 operation, CancellationToken cancellationToken)
2021-02-18T00:45:27.806970799Z at MongoDB.Driver.MongoCollectionImpl`1.MongoIndexManager.CreateManyAsync(IClientSessionHandle session, IEnumerable`1 models, CreateManyIndexesOptions options, CancellationToken cancellationToken)
2021-02-18T00:45:27.806974799Z at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
2021-02-18T00:45:27.806978699Z at Squidex.Infrastructure.MongoDb.MongoRepositoryBase`1.InitializeAsync(CancellationToken ct) in /src/src/Squidex.Infrastructure.MongoDb/MongoDb/MongoRepositoryBase.cs:line 113
2021-02-18T00:45:27.806984099Z --- End of inner exception stack trace ---
2021-02-18T00:45:27.806987899Z at Squidex.Infrastructure.MongoDb.MongoRepositoryBase`1.InitializeAsync(CancellationToken ct) in /src/src/Squidex.Infrastructure.MongoDb/MongoDb/MongoRepositoryBase.cs:line 119
2021-02-18T00:45:27.806991899Z at Squidex.Hosting.InitializerHost.StartAsync(CancellationToken cancellationToken)
2021-02-18T00:45:27.806995599Z at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
2021-02-18T00:45:27.806999399Z at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
2021-02-18T00:45:27.807003099Z at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
2021-02-18T00:45:27.807006899Z at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
2021-02-18T00:45:27.807930204Z at Squidex.Program.Main(String[] args) in /src/src/Squidex/Program.cs:line 22
I'm using a connection string similar to this within the EVENTSTORE__MONGODB__CONFIGURATION and STORE__MONGODB__CONFIGURATION application settings in my App Service:
mongodb://[USER_NAME]:[PASSWORD]#[MONGO_IP]:27017
I was able to resolve the issue, Squidex requires the connection string include the authSource as well. If you encounter this issue, add ?authSource=[DatabaseName] to your connection string. In my case, this is what was required:
mongodb://[USER_NAME]:[PASSWORD]#[MONGO_IP]:27017?authSource=Squidex

Unexpected exception chain after updating EF 6.x

I updated from EF6.2 to EF6.4 and I encountered this exception chain:
[VerificationException: Operation could destabilize the runtime.]
System.Data.Entity.Core.Metadata.Edm.FacetDescription.Validate(String declaringTypeName) +70
System.Data.Entity.Core.Metadata.Edm.FacetDescription..ctor(String facetName, EdmType facetType, Nullable`1 minValue, Nullable`1 maxValue, Object defaultValue, Boolean isConstant, String declaringTypeName) +103
System.Data.Entity.Core.SchemaObjectModel.FacetDescriptionElement.CreateAndValidateFacetDescription(String declaringTypeName) +115
System.Data.Entity.Core.SchemaObjectModel.TypeElement.ResolveTopLevelNames() +119
System.Data.Entity.Core.SchemaObjectModel.Schema.ResolveTopLevelNames() +206
System.Data.Entity.Core.SchemaObjectModel.Schema.Resolve() +16
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection) +554
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, DbProviderManifest providerManifest, IList`1& schemaCollection) +156
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.LoadProviderManifest(XmlReader xmlReader, String location, Boolean checkForSystemNamespace, Schema& schema) +151
System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest.Load(XmlReader reader) +75
System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest..ctor(XmlReader reader) +116
System.Data.Entity.SqlServer.SqlProviderManifest..ctor(String manifestToken) +37
System.Data.Entity.SqlServer.<>c.<GetDbProviderManifest>b__29_0(String s) +25
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +65
System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifest(String versionHint) +125
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken) +55
[ProviderIncompatibleException: The provider did not return a ProviderManifest instance.]
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken) +187
System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +119
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +43
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +159
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +124
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +678
System.Data.Entity.Internal.InternalContext.Initialize() +20
Website.Db.Context..ctor(DbConnection Connection) in Context.vb:15
Website._Default.GetNewsItems() in Default.aspx.vb:13
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +92
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +191
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
lambda_method(Closure , MethodInfo , Object , Object[] ) +39
System.Web.UI.WebControls.ModelDataSourceView.InvokeMethod(ModelDataSourceMethod method, Boolean isAsyncMethod) +326
System.Web.UI.WebControls.ModelDataSourceView.InvokeMethod(ModelDataSourceMethod method) +7
System.Web.UI.WebControls.ModelDataSourceView.GetSelectMethodResult(DataSourceSelectArguments arguments) +68
System.Web.UI.WebControls.ModelDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +14
System.Web.UI.WebControls.Repeater.GetData() +233
System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +207
System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +62
System.Web.UI.WebControls.Repeater.DataBind() +131
System.Web.UI.WebControls.Repeater.EnsureDataBound() +114
System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +16
System.Web.UI.Control.PreRenderRecursiveInternal() +166
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4722
Here's line 15 of Context.vb:
Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))
A pretty straightforward database call, I'd say.
However, when I bumped back down to EF6.2, the error stopped.
I'm finding plenty of references to the individual exceptions here on SO, but nothing I've found so far quite fits the context of the combination of the three taken together with what the code is doing (general database access).
Do I need to alter my DAL code somehow in order to accommodate the EF6.4 update? Were there some breaking changes?
--EDIT--
Running locally under an explicit setting of Medium Trust, I get a different chain:
[PolicyException: Execution permission cannot be acquired.]
System.Security.CodeAccessSecurityEngine.TryResolveGrantSet(Evidence evidence, PermissionSet& grantSet) +14092083
System.Security.CodeAccessSecurityEngine.ResolveGrantSet(Evidence evidence, Int32& specialFlags, Boolean checkExecutionPermission) +60
[FileLoadException: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416)]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +232
System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) +176
System.Reflection.Assembly.LoadFrom(String assemblyFile) +53
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.GetRuntimeAssemblyFromSetupConfiguration(Assembly& runtime) +27
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.LoadRuntime() +26
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.PreApplicationStart() +45
[InvalidOperationException: The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +919
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +169
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +172
System.Web.Compilation.BuildManager.ExecutePreAppStart() +172
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +854
[HttpException (0x80004005): The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724
This occurs under both EF6.2 and EF6.4.
If this is occurring on your remote deployment and not your local development environment after upgrading the EF version then I would suspect there is an issue with the deployment process.
Check the web.config in the deployed build to ensure that there are no EF-related runtime version dependency version overrides. (EntityFramework.dll and EntityFramework.SqlServer.dll)
Check the EntityFramework.dll assembly version between the deployed file on the remote server and your working local instance.
Copy the deployment from the remote server into a local folder, point IIS at it and then hook VS up running your project using Attach to Process on w3wp.exe. Set a breakpoint somewhere in the code and check that it remains a "hot" hit-able breakpoint and not an inactive one stating something along the lines of "The breakpoint will not currently be hit. The source line does not match..." This would indicate that the deployed code does not reflect a current, complete rebuild of what you are running in VS.
If you are using an automated build:
Check that dependency DLLs are not being checked in and that the build machine is actively resolving NuGet packages properly.
Check your references for EF, both before you upgrade the EF version (Source control revert all changes, use what was last built and deployed) Under the project explorer under References, select EntityFramework and check the path listed. It should be pointing to:
{Your solution folder}\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll
If it is pointing to anything like a \bin\debug etc. folder, remove the reference and repair to point at the NuGet package.
If NuGet packages folder is checked in, make sure this folder is complete and up to date in source control. When checking in nuget folders (as opposed to package version locking) I find this needs to be done from Explorer / TFS as normal VS checkins won't include them in pending changes. (unlike /bin folder changes if you accommodate them.) package folder updates can be skipped when initial checkins were made but then things like .ignore files are added/updated causing newer .dll files not to be updated.
Check for any stale or mismatched project files (.csproj/.vbproj) in your local environment vs. what is in source control. Often these can get flagged at some point as "Excluded Files" resulting in the automated build using out of date references.
Have a check through these and see if that identifies anything.

Database from AlwaysOn availability group restored as normal database

I have a problem with a normal SQL database restored from a DB set in AlwaysOn high availability group in SQL Server 2017.
I restored a copy of production db to a different server, to be used as QA test database, with a different name also - MyDB_demo
The problem is, the QA app copy (same code as production with new development enhancements) get an error at some point.
Even if my conn str points to MyDB_demo, I get the following error
[SqlException (0x80131904): The target database ('MyDB') is in an availability group and is currently accessible for connections when the application intent is set to read only. For more information about application intent, see SQL Server Books Online.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +2444190
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +5775712
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2127
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +139
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +136
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +88
MyApp.SqlHelper.ExecuteDataset(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) +163
MyApp.PermitFunctions.GetSystemMessages(String sp, Int32 iPermitID, Int32 iAppID, SqlConnection cn) +219
MyApp.Municipality.LoadSystemMessage() +3869
MyApp.Municipality.Page_Load(Object sender, EventArgs e) +101
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
Is there any reference in the newly restored DB (named now MyDB_demo) that stores the original name of production DB and why is it trying to access it?
Any suggestion is appreciated.
EDIT
Actually, the server used to restore MyDB_demo is one of the secondary nodes for AlwasyOn availability group; it also contains a RO copy of production database, MyDB.
So the server has:
RO copy of production DB (MyDB)
normal, stand-alone db restored for QA - MyDB_demo
Hence, I understand the error message - it would makes sense if I tried to access directly the secondary, RO copy of production db from connection string.
But I do not: the connection string (which I double-checked) is trying to connect to QA db, MyDB_demo.
Here is some additional info:
the error is thrown in SQLHelper class, the helper class from MS to work with SQL Server, in the ExecuteDataset function
the error is thrown ONLY on one stored procedure - lot of other stored procedures and also direct SQL statements run just fine
I inspected the stored procedure, thinking it might contains accidentally a hardcoded reference to DB name - it doesn't
and the strange part - I run the stored procedure with the same parameters as called from the app in SSMS - and it run just fine - no error
So it looks somehow the connection string MIGHT be altered (!!!) is some way by the NET application itself, and only for this stored procedure?
Anyone ever encountered something like this?
Thank you
Due to the strange (read: stupid) situation that the culprit SP fails only when called from within app, but runs ok when tried in SSMS, I tried a "stupid" approach: I inspected its code, commented out two fields that were set with sub-selects like select top 1 from ..... where.... (actually I replaced theit values with dummy ones) and I changed an Order By field that was initially specified like "InspectionType" Desc, which I removed quotation marks from.
Doing this, the SP suddenly started to work ok even when called from the app.
Then I reverted all changes to original (added quoted back and put back the sub-selects) and the SP continued to work ok.
So ... problem solved.
Stupid approach for stupid problem (!?!?!)
In any case, if anyone has a better idea or explanation of what might have happened, I'd be glad to hear it
EDIT
I think I understand the fix.
By editing and saving the stored procedure, its query plan was recompiled.
So the original error might have been caused by the old query plan.
But why did it referenced the database name? Is the actual database name referenced in query plans? This looks a little odd to me.
And another question (open):
Does the SQL Server optimizer detect if a DB runs in high-availability mode, and when optimizing the queries, does it decide if a query is read-only mode and automatically redirects it toward a read-only node? Even if the ApplicationIntent readonly parameter is not present in connection string?
Because it was not in this case, even in production - we just implemented AlwaysOn functionality and are in the process of updating app to take advantage of R/O nodes.
Any comments are appreciated

How to fix “The ConnectionString property has not been initialized” in nopCommerce

I'm trying to integrate nopCommerce into a third party system but am hitting a problem when I try to access any nopCommerce pages. Because I'm integrating with a third party system I've had to merge web.configs and copy all files over. I have a standalone install of nopCommerce aswell and that is running fine.
Any help would be greatly appreciated.
The error I am getting is as follows:
The ConnectionString property has not been initialized.
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.InvalidOperationException: The ConnectionString property has not been initialized.
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:
[InvalidOperationException: The ConnectionString property has not been initialized.]
System.Data.SqlClient.SqlConnection.PermissionDemand() +5038498
System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
System.Data.SqlClient.SqlConnection.Open() +125
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +52
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +161
System.Data.EntityClient.EntityConnection.Open() +98
System.Data.Objects.ObjectContext.EnsureConnection() +81
System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) +46
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) +151
System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func`2 keySelector) +90
NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings.SettingManager.GetAllSettings() +542
NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings.SettingManager.GetSettingByName(String name) +121
NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings.SettingManager.GetSettingValue(String name) +49
NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings.SettingManager.GetSettingValueBoolean(String name, Boolean defaultValue) +54
NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings.SettingManager.GetSettingValueBoolean(String name) +41
NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.CustomerManager.get_UsernamesEnabled() +45
NopSolutions.NopCommerce.Web.Administration.LoginPage.ApplyLocalization() +108
NopSolutions.NopCommerce.Web.Administration.LoginPage.Page_Load(Object sender, EventArgs e) +40
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
NopSolutions.NopCommerce.Web.BaseNopAdministrationPage.OnLoad(EventArgs e) +44
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
You need to have a valid connection string.
After you pass the database installation phase (when you fill in the database settings) nop commerce is keeping the database information in a file that is not within the project, you can find it within the App_Data folder in the Presentation\Nop.Web\App_Data\ named Settings.txt, update it if you need and run the application again.
You need to have a valid connection string for the NopCommerce database in web.config, and you need to ensure that it gets read.
At Application_Start in global.asax NopCommerce reads in the connection string and injects it into the business logic DLL. If that doesn't happen, the data access layer (in the business logic DLL) won't be able to open a connection and you'll get the error you just posted. I suggest check web.config and global.asax; if both look good put a breakpoint in Application_Start.
The connection string is not held in the web.config file in nopcommerce... it is in the ConnectionStrings.config file. You might want to check for that file and copy it over if it is not there or put your connection string in there if the file is there and the string is not.