cloudcrate / blazorstorage Goto Github PK
View Code? Open in Web Editor NEWA library for Blazor local and session storage support.
License: MIT License
A library for Blazor local and session storage support.
License: MIT License
Would be nice if you returned IServiceCollection
here instead of void
Old:
public static class ServiceCollectionExtensions
{
public static void AddStorage(this IServiceCollection col)
{
col.TryAddScoped<LocalStorage>();
col.TryAddScoped<SessionStorage>();
}
}
New:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddStorage(this IServiceCollection col)
{
col.TryAddScoped<LocalStorage>();
col.TryAddScoped<SessionStorage>();
return col;
}
}
The OldValue and NewValue of StorageEventArgs are in reverse order.
For some reason I can't get this to work. I'm using Blazor 3.2prev1.
I added .AddStorage() to the services.
I added <script src="_content/Cloudcrate.AspNetCore.Blazor.Browser.Storage/Storage.js"></script>
after the blazor.webassembly.js script.
I removed any other code that might reference to LocalStorage.
As soon as I try to render a component, I get a JSException: String contains invalid character.
Any idea what I might have done wrong here?
The library is not working 3.0.0-preview5-19227-01.
Common use-case is to synchronize information between multiple tabs of the same app (like last selected top level feature within an app).
https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-event
Let me know if you want that feature introduced,
Thanks
Thanks for this package! Might it be possible to upgrade the nuget package from preview9 to rc1?
Hi,
I'm getting a null reference exception when i use this code:
await Storage.SetItemAsync("Token", "bla");
var token = await Storage.GetItemAsync("Token");
any ideas?
NullReferenceException: Object reference not set to an instance of an object.
Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(long asyncHandle, string identifier, string argsJson)
Microsoft.JSInterop.JSRuntime.InvokeAsync(string identifier, CancellationToken cancellationToken, object[] args)
Cloudcrate.AspNetCore.Blazor.Browser.Storage.StorageBase+JsRuntimeAccessBase.InvokeAsync(string identifier, IEnumerable args, CancellationToken cancellationToken)
Cloudcrate.AspNetCore.Blazor.Browser.Storage.StorageBase.JsRuntimeInvokeAsync(string identifier, IEnumerable args, CancellationToken cancellationToken)
Cloudcrate.AspNetCore.Blazor.Browser.Storage.StorageBase.SetItemAsync(string key, string data, CancellationToken cancellationToken)
System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
ProductionPlannerFrontEnd.Shared.MainLayout.RefreshHeader() in MainLayout.razor
+
await Storage.SetItemAsync("Token", "bla");
ProductionPlannerFrontEnd.Shared.MainLayout.OnInitializedAsync() in MainLayout.razor
+
await RefreshHeader();
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange oldTree, ArrayRange newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessPendingRender()
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11+<b__11_0>d.MoveNext()
Microsoft.AspNetCore.Mvc.ViewFeatures.RazorComponents.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperComponentExtensions.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperComponentExtensions.RenderComponentAsync(IHtmlHelper htmlHelper, RenderMode renderMode, object parameters)
ProductionPlannerFrontEnd.Pages.Pages_index.b__8_1() in index.cshtml
+
@(await Html.RenderComponentAsync
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
ProductionPlannerFrontEnd.Pages.Pages_index.ExecuteAsync()
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Hello thanks for your work.
I encounter the error in server side app ```
Error: Microsoft.JSInterop.JSException: Could not find 'Cloudcrate_AspNetCore_Blazor_Browser_Storage_LocalStorage' in 'window'.
Error: Could not find 'Cloudcrate_AspNetCore_Blazor_Browser_Storage_LocalStorage' in 'window'.
Thanks
Any plans or thoughts about adding support for more secure storage of the key/value pairs? Obviously you shouldn't be storing anything ultra secure on browsers local storage but there are things that could be done to help limit abuse via dev tools.
I was thinking at a minimum maybe optionally being able to store the values base64 encoded or perhaps providing support for a full encryption module?
Hi,
in Blazor Preview 9 the signature of the method to call client side javascript has changed, so we get an error when we try to access the local storage.
The paramters to the javascript call over JsRuntimeInvokeAsync have to be an object array now and it returns a ValueTask instead of Task
Carl
Hello
I get this error when trying to use this package
Any idea?
I'm using v3.0.0 in blazor webassembly client
Just included
services.AddStorage();
in startup.cs
And
`<script src="_framework/blazor.server.js"></script>
in index.html
When I invoke the Key(i)
or KeyAsync(i)
method, I get an exception:
TypeError: key is not a function
at Object.Key (https://localhost:44329/_content/Cloudcrate.AspNetCore.Blazor.Browser.Storage/Storage.js:21:24)
at Object.invokeJSFromDotNet (https://localhost:44329/_framework/blazor.webassembly.js:1:9737)
at _mono_wasm_invoke_js_marshalled (https://localhost:44329/_framework/wasm/dotnet.3.2.0.js:1:171433)
at do_icall (<anonymous>:wasm-function[6049]:0x10f8b1)
at do_icall_wrapper (<anonymous>:wasm-function[1896]:0x50b6a)
at interp_exec_method (<anonymous>:wasm-function[1120]:0x2588e)
at interp_runtime_invoke (<anonymous>:wasm-function[5655]:0xf7391)
at mono_jit_runtime_invoke (<anonymous>:wasm-function[5109]:0xddb3d)
at do_runtime_invoke (<anonymous>:wasm-function[1410]:0x3ba85)
at mono_runtime_try_invoke (<anonymous>:wasm-function[418]:0xcfdb)
I checked in the debugger and and found that the key
was indeed not a function but a string with the value "instantiateWasm"
If I have the following code:
@foreach (var item in ToDoItems)
{
<li>@item.Name</li>
}
@functions {
List<ToDoItem> ToDoItems = new List<ToDoItem>();
protected override void OnInit()
{
ToDoItems = Storage.GetItem<List<ToDoItem>>("SomeKey");
}
}
And there is no Local Storage set at SomeKey, then ToDoItems will be set to null, because here if there is no key found it is using default(T) and IEnumerables default to null and my foreach will bomb with a Null Ref Exception. So I have to do something to null check against this such as:
protected override void OnInit()
{
var existingItems = Storage.GetItem<List<ToDoItem>>(storageKey);
if (existingItems != null)
ToDoItems = existingItems;
}
It would be cool if BlazorStorage would default to an empty collection if T is an IEnumerable
. Happy to send a PR if you think it's worth doing, or if you want to implement yourself, that's perfectly fine too. Was thinking something like
bool isNullOrEmpty = string.IsNullOrEmpty(json);
if (isNullOrEmpty)
{
if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
{
return new T();
}
return default(T);
}
return Json.Deserialize<T>(json);
If you don't think this is worth doing, no big deal, the null check isn't the end of the world, it just wasn't what I was expecting.
Also just FYI I'll be demoing your library at KCDC on Friday. Great work!
Thanks.
'IWebAssemblyHostBuilder' exists in both 'Microsoft.AspNetCore.Blazor.Browser, Version=0.5.1.0, Culture=neutral, PublicKeyToken=null' and 'Microsoft.AspNetCore.Blazor, Version=0.8.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
'BlazorWebAssemblyHost' exists in both 'Microsoft.AspNetCore.Blazor.Browser, Version=0.5.1.0, Culture=neutral, PublicKeyToken=null' and 'Microsoft.AspNetCore.Blazor, Version=0.8.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
Hi, I just saw this issue IdentityModel/oidc-client-js#631 where they are trying to have some sort of persistence when local and session storage are not available (e.g. chrome incognito mode). Do you think we should provide this kind of fallback?
Hello :)
there is a problem with Storage and Session when running the web app
here it is:
Uncaught (in promise) Error: System.InvalidOperationException: Cannot provide a value for property 'Session' on type 'Aaqar.Client.Pages.Index'. There is no registered service of type 'Cloudcrate.AspNetCore.Blazor.Browser.Storage.SessionStorage'.
at Microsoft.AspNetCore.Blazor.Components.ComponentFactory+<>c__DisplayClass6_0.<CreateInitializer>b__2 (:50690/Microsoft.AspNetCore.Blazor.Components.IComponent instance) <0x1c2d920 + 0x000c4> in <5fb27225b9c7403e87df81958625363e>:0
at (:50690/wrapper delegate-invoke) System.Action`1[Microsoft.AspNetCore.Blazor.Components.IComponent].invoke_void_T(Microsoft.AspNetCore.Blazor.Components.IComponent)
at Microsoft.AspNetCore.Blazor.Components.ComponentFactory.PerformPropertyInjection
...
Edit: Reduced stacktrace
Not compatible with 0.5 version of blazor. Have a nice day :)
When attempting to use this package with a server-side rendered Blazor application, the page fails to render when the package tries to cast the RemoteJSRuntime
instead of the client one (I assume).
Stack Trace:
System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime' to type 'Microsoft.JSInterop.IJSInProcessRuntime'.
at Cloudcrate.AspNetCore.Blazor.Browser.Storage.StorageBase..ctor(IJSRuntime jsRuntime)
at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.AspNetCore.Components.ComponentFactory.<>c__DisplayClass6_0.<CreateInitializer>b__2(IComponent instance)
at Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IComponent instance)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(Type componentType)
at Microsoft.AspNetCore.Components.Rendering.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame& frame, Int32 parentComponentId)
Edit: Reduced stacktrace
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.