Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cast Error when using DistributedCache #744

Closed
monsieurberry opened this issue Aug 13, 2019 · 7 comments
Closed

Cast Error when using DistributedCache #744

monsieurberry opened this issue Aug 13, 2019 · 7 comments
Assignees
Milestone

Comments

@monsieurberry
Copy link

monsieurberry commented Aug 13, 2019

Hi!

I'm just testing out the DistributedCache with SQL Server. I've created a Cache DB and table with ...

dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache

... and wired everything up in my Startup.cs by adding ...

services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration["DistCache_ConnectionString"];
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
services.AddPiranhaDistributedCache();

.. to ConfigureServices(), and ...

App.CacheLevel = Piranha.Cache.CacheLevel.Full;

to Configure().

When I first load up my site everything works perfectly. I check my cache table and everything is in there, so I know writing to the cache works and all is (hopefully) configured OK.

When I refresh my page (now getting from the cache) I get the following error...

An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[Piranha.Services.SiteService+SiteMapping]' to type 'System.String'.
Piranha.Cache.DistributedCache.Deserialize(byte[] bytes) in DistributedCache.cs, line 128

I've tried debugging and a few different options, however I'm a bit lost - was hoping I could try and figure out what was going wrong but no luck unfortunately.

I also tried out the same on 6.1.0 but I got the same error.

If you need anymore info please let me know.

Thanks!

@monsieurberry
Copy link
Author

monsieurberry commented Aug 13, 2019

Managed to fix the issue with the following changes to Deserialize in DistributedCache.

A bit of a hack, but hopefully gives you guys an idea of where the problem is :-)

///


/// Deserializes the byte array to an object.
///

/// The byte array
/// The object type
/// The deserialized object
private T Deserialize(byte[] bytes)
{
if (bytes == null)
{
return default(T);
}
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream(bytes))
{
var obj = formatter.Deserialize(stream);
if (!(obj.GetType() == typeof(string)) && IsSerializable(obj.GetType()))
{
return (T)obj;
}
else
{
// First lets decode the byte array into a string
var json = (string)obj;
// Next deserialize the json into an object
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
return JsonConvert.DeserializeObject(json, settings);
}
}
}

@tidyui
Copy link
Member

tidyui commented Aug 14, 2019

Thanks for investigating the issue further! We'll take a look at it.

Regards

@monsieurberry
Copy link
Author

monsieurberry commented Aug 14, 2019

Thank you, Håkan!

I think I may have found a better solution for you.

It seems as if the SiteMapping is cached as a List object, but when it's retrieved from the cache in SiteService, it specifies IList...

I was able to solve the issue by changing IList<SiteMapping> to List<SiteMapping> in GetByHostnameAsync.

Hope this helps :-)

@tidyui tidyui modified the milestones: Version 7.0.3, Version 7.0 SR 3 Sep 3, 2019
@nahojd
Copy link

nahojd commented Apr 15, 2020

I get (more or less) the same error when I try to use RedisCache (from Microsoft.Extensions.Caching.StackExchangeRedis) or even the default Distributed Memory Cache (services.AddDistributedMemoryCache), which is just an in-memory implementation.

Specifically, I get

An exception of type 'System.InvalidCastException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Unable to cast object of type 'System.Collections.Generic.List`1[Piranha.Models.PostType]' to type 'System.String'.'
   at Piranha.Cache.DistributedCache.Deserialize[T](Byte[] bytes)
   at Piranha.Cache.DistributedCache.Get[T](String key)
   at Piranha.Services.PostTypeService.<GetTypes>d__8.MoveNext()

or sometimes in PageTypeService.GetTypes instead.

When i use RedisCache I can see that the data has been written to Redis, but it can't retrieve it.

Has anyone got DistributedCache working? I'm using the latest Piranha version (8.1.0).

@tidyui
Copy link
Member

tidyui commented Apr 15, 2020

I will see if I can replicate the error on the version/v8.1 branch.

@tidyui
Copy link
Member

tidyui commented Apr 15, 2020

So I have looked into the problem and apparently how models are loaded have changed a bit since the distributed cache was written. Also, unfortunately we don't run any integration tests on distributed cache, only on memory cache which I will look into, otherwise we would've caught the problem earlier.

For those of you that need distributed caching while we try to resolve the issue, I've created a gist that contains an alternate distributed cache that doesn't use binary formatting, instead it serializes objects using Newtonsoft.Json. This will not be as fast as using a binary formatter, but it's a good intermediate solution while waiting for the official fix.

https://gist.github.com/tidyui/95c441293af55f9eb906ba756ae398e5

Best regards

@nahojd
Copy link

nahojd commented Apr 17, 2020

@tidyui Thanks, I'll try that until this is sorted out! 👍

@tidyui tidyui added this to the Version 8.3 milestone Jun 2, 2020
@tidyui tidyui self-assigned this Jun 2, 2020
@tidyui tidyui closed this as completed in b0fe2c1 Jun 2, 2020
@tidyui tidyui changed the title Cast Error when using SQL Server DistributedCache Cast Error when using DistributedCache Jun 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants