Unable to cast object of type 'Glimpse.Ado.AlternateType.GlimpseDbConnection' to type 'System.Data.SqlClient.SqlConnection' - entity-framework

I am getting an "System.InvalidCastException occurred" exception where I am using the EF 6 asynchronous functionality.
The message is: Unable to cast object of type 'Glimpse.Ado.AlternateType.GlimpseDbConnection' to type 'System.Data.SqlClient.SqlConnection'.
This application was upgraded from MVC4 to MVC5 and is using the .Net Framework 4.5 for the first time.
I am aware this has been raised as an issue before; https://github.com/Glimpse/Glimpse/issues/540 but I tried getting the latest version of Glimpse and I still got the same problem.
I am wondering if I failed to uninstall Glimpse properly, either the latest version or the one I used previously.
The code where the exception happened is;
public static async Task<IList<Company>> GetCompaniesAsync()
{
using (var db = new SherryGreenGroupContext())
{
return await db.Companies
.Include("AddressLines")
.Where(x => x.EndOfBusinessDate == null)
.OrderBy(x => x.CompanyName).ToListAsync();
}
}
The exception is;
System.InvalidCastException occurred
HResult=-2147467262
Message=Unable to cast object of type 'Glimpse.Ado.AlternateType.GlimpseDbConnection' to type 'System.Data.SqlClient.SqlConnection'.
Source=System.Data
StackTrace:
at System.Data.SqlClient.SqlCommand.set_DbConnection(DbConnection value)
InnerException:

You should check you don't have Glimpse EF5 installed. That fixed it for me.
If you dont' then just uninstall all Glimpse packages. Clean your solution and reinstall Glimpse.

Related

Upgrade to EF Core 7 get Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: ''.'

I upgrade Ef core 6 to 7 and get this error at Database.EnsureCreated();
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
Database.EnsureCreated();
if (Database.GetPendingMigrations().Any())
{
Database.Migrate();
}
}
The database is created but I get this error. I fear if some migrations are ended with an error and are not complete. and I want these codes always be here and not commented after first run. What is this error and how to correct it?
Edits:
I deleted all content of the Migrations folder and the Sqlite Db and created an Initial migration, But when I want to apply this migration I get the same error.
I get this error after Updating Database by a Migration or at the line:
if (Database.GetPendingMigrations().Any()):
SQLite provider.
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'main' on server 'C:\Users\...\Documents\Developer\WinForms Blazor2_2022_Book_Secure_Active\WinFormsBlazor\bin\Debug\net7.0-windows\AppData\AppDB.db'.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: ''.
I created a AppData\AppDB.db in root project folder and set this db to Copy always then in the Onconfiguring in the DbContext:
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite($"Data Source={Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))}\\AppData\\AppDB.db"
, options =>
{
options.UseNetTopologySuite();
});
}
I have no main Database, I don't understand why I have this setup worked in EF Core 6 for a year but after updating to 7 it is not working! any ideas to solve this problem?
Looks like you're hitting issue #29584. It will hopefully be fixed in version 7.0.3.
For now, you can work around it by manually updating the SQLitePCLRaw dependency:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite" Version="7.0.2" />
<!-- Manually updated to fix NetTopologySuite issues -->
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.4" />
</ItemGroup>
I find the problem was using x => { x.UseNetTopologySuite(); } in the UseSqlite function when adding the ef core context, When UseNetTopologySuite() is there, Any access to the database give error: SQLite Error 1: ''. and if I remove UseNetTopologySuite() I get another error: sqlite error 1: 'no such function: initspatialmetadata'..
In Ef core 6.0.12 there is no problem and I can use Spatial Point type without any problems, even after migrating that includes a point type, several tables and views related to geometry are created automatically with Ef core 6.
I had to forget using Spatial types in EF Core 7 so that I can upgrade my EF core version.

How to gracefully handle a postgres restart in npgsql?

I have a ASP.NET Core application with npgsql that is setup to retry when a database connection fails:
services.AddDbContext<DatabaseContext>(
opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
(options) =>
{
options.EnableRetryOnFailure(10);
})
);
However, when i restart the database during a request, it will first throw an exception
Exception thrown: 'Npgsql.PostgresException' in System.Private.CoreLib.dll: '57P01: terminating connection due to administrator command'
That propogates into my code and causes an exception without any retries.
Looking into the documentation for npgsql it seems like some exceptions are marked as IsTransient, and that means they will be retried, but this one is not. I assume there's a reason for that, but I'd still like to be able to restart the postgres database without interrupting requests by simply having them retry after a while. I could create try catches around all the requests and check for this particular exception, but that seems like a clunky solution.
How do I handle this situation gracefully?
npgsql package used:
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.10" />
Managed to find an answer myself, you can add the error code in the EnableRetryOnFailure
services.AddDbContext<DatabaseContext>(
opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
(options) =>
{
options.EnableRetryOnFailure(10, TimeSpan.FromSeconds(30), new string[] { "57P01" });
})
);
Now the only question that remains is if that is a good idea or not.

Karate to Java call errors out with TypeError post upgrading from 0.9.6 to 1.0.1 [duplicate]

This question already has answers here:
Karate Custom Serialiser for Java Return Value
(2 answers)
Closed 1 year ago.
My tests were written with karate 0.9.6 and now I am in the process of fixing some of the failed tests after upgrade to 1.0.1.
Calling a Java function using obtained api response raises an error.
Sample call in karate: obj.matchName(apiResponse, rName)
Sample Java method:
public String matchName(JSONObject apiResp, String name) throws Exception {
try { }
catch (Exception e) { }
finally { }
}
Error received:
obj.matchName(apiResponse, rName)
<<<<
org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (matchName) on Utilities#a1b7549 failed due to: Cannot convert ''(language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'net.minidev.json.JSONObject': Unsupported target type. - .:program(Unnamed:1)
This used to work well before the upgrade, could you please let me know how to handle this change with upgrade?
TIA
NT
Karate never supported JSONObject, if it used to work - you were just lucky - so please read the docs: https://github.com/intuit/karate#calling-java
So use a Map, List or String as parameter types.
If you are still stuck, follow the process - and note that old versions are not supported - as of now, the latest is 1.1.0: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

VS2017 + ReactJS + use of entity framework throws and error on migration

I've started a new React+Redux project in VS2017 (.net core 2.0). Default template comes without database use, so I just added use of entity framework manually. It compiles well but when I try to add a migration using command
dotnet ef migrations add "Initial"
I'm getting the next error:
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\sibvic\AppData\Local\Temp\iu25u5dg.r0n:83:19)
at __webpack_require__ (C:\Users\sibvic\AppData\Local\Temp\iu25u5dg.r0n:20:30)
at createWebpackDevServer (C:\Users\sibvic\AppData\Local\Temp\iu25u5dg.r0n:62:26)
at C:\Users\sibvic\AppData\Local\Temp\ftqvg4wq.l1l:114:19
at IncomingMessage.<anonymous> (C:\Users\sibvic\AppData\Local\Temp\ftqvg4wq.l1l:133:38)
at emitNone (events.js:86:13)
Current directory is: C:\projects\test\bin\Debug\netcoreapp2.0
)
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
It looks like this features is too new. Not much information I can find. And can't figure out what's wrong by myself (at least yet, rubber duck method doesn't work either).
Any idea how to fix it?
I had the same issue during migration from dotnet core 1.1 to 2.0.
I had to update implementation of my Program class to following:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
I know that this is not about React+Redux, but maybe it can help you.

TFS Server plugin fails after upgrade from TFS2012 to TFS2015 RC

We have just upgraded one of our servers from TFS2012.2 to TFS2015RC. Everything went "smooth", but we are encountering an issue:
A while ago we wrote a server side plugin for TFS, which listens to the WorkitemChangedEvent. It implements the ISubscriber interface. The following piece of code was working fine before the update:
void ITfsService.UpdateState(int workItemId, string newState)
{
var wi = store.GetWorkItem(workItemId);
wi.State = newState;
wi.Save();
}
After the update, and after recompiling against the TFS2015 dlls, the following error occured:
Failed to process notification: TF237124: Work Item is not ready to save.
Note that none of the workitemtypes has changed, it is the same data.
I tried getting more information out of the error by calling Validate() before saving, this is the output:
Status: InvalidListValue
State: "Resolved, To Be Reviewed"
WIT: Task
Id: 5842
Field: State
However, the state "Resolved, To Be Reviewed" does exists in the list of available states. In the GUI it is perfectly possible to change the state of the item to "Resolved, To Be Reviewed":
What is causing the Save() to fail?
Finally found the cause of this:
Apparently, the Validate() call validates against the whole ProcessConfiguration.xml. Because in TFS2012 there were both AgileProcessConfiguration and CommonProcessConfiguration, there were underlying problems with the workitem states.
After resolving those issues in the correct ProcessConfiguration file, the plugin was working again (and, TFS could also upgrade the Backlog\IterationPlanning features.)