Git Product home page Git Product logo

blazorfilereader's People

Contributors

catlan avatar cwinland avatar douglasdwyer avatar grishat avatar markjerz avatar pfeurean avatar tewr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blazorfilereader's Issues

How to read multiple files without drag-n-drop?

Try this code but FileReader see only last file
`
<input type="file" multiple @ref=inputElement />
<button @OnClick="Add" class="btn btn-primary">read
<button @OnClick="ReadFile" class="btn btn-primary">read
@code
{
ElementReference inputElement;
IFileReaderRef fileReaderReference;

public async Task AddToList()
{ 
    fileReaderReference = fileReaderService.CreateReference(inputElement);
}

public async Task ReadFile()
{
....
    foreach (var file in await fileReaderReference.EnumerateFilesAsync())
    {
        ....
     }
}

}
`

Source control question

Adding your package results in

image

but the files are actually located

image

so I get this message, and I can't add them to source control

image

I can ignore the warning obviously.

Improved error handling

Some of the recent framework issues have shown that the error management could be improved.

  • callbacks should be changed from void to promises to bubble exceptions happening in the framework
  • js exceptions could be returned to .NET with full call stack, just not the message

Easier setup for WASM

WASM Setup currently requires some clunky copy-paste implementation of an obscure plumbing interface. Could be fixed by providing another micro-nuget-package.

Drag & drop

@catlan : Thank you for your PR. I'm having trouble firing the drop event using your example. The browser default event is fired (file opens in browser when dropped on element, as if ev.preventDefault() is never called)

Do you have a full example on how to use the code you provided to share?

I tried with preview7.

Regards

Unable to reset the file picker

Hi
I am new to html
I use this file picker and it works good but i need some way to reset/clear it.
I have global save button where i save difrent propertys on a object where i also save the file to azureblob. the problem is that the control keep the file refrens så on very save i add a new version of the same file to the azureblob storage.

Improvement of Memory Usage

Is there any way to improve the memory usage when you need all the bytes into memory? I loaded all the bytes into memory using the "CreateMemoryStreamAsync" and then doing a .ToArray() to convert the bytes into a Base64, so that I can upload this string up to my S3 Bucket.

However, even tho it does work, these are the horrific stats:

An image with the size of 5 MB, increased the memory usage of the application by 50 MB.

This happens everytime you select an image, it keeps increasing it (ofcourse with different stats than 50 MB, depending on the file size). I even tried setting the string to the "SecureString" so it could be disposable, but even that didn't clear the memory afterwards.

So simply, any way to improve the memory usage, or clear the memory usage after not needing it anymore?

Manual inclusion of Js for interop needed

Currently (since 0.8.0 in server-side, for both projec types in 0.9.0), the js interop file must be added manually on the index page.

Apparently static content serving from blazorlib is a feature that no longer exists - "a known limitation with the Razor Components template in Preview 2" . This bug is what I'm experiencing, and like it says it's being tracked in issue dotnet/aspnetcore/issues/6349 .

ReadFileInfoAsync Fails SSB

Describe the bug
When calling ReadFileInfoAsync using Server Side Blazor Preview 8. You get "An exception occurred executing JS interop: The JSON value could not be converted to Blazor.FileReader.FileInfo. Path: $ | LineNumber: 0 | BytePositionInLine: 104.. See InnerException for more details."

Seems like JS is pulling info, but server.blazor.js errors.

To Reproduce
Steps to reproduce the behavior:

  1. Call - var fileInfo = await file.ReadFileInfoAsync();
  2. Click on - catch error

Expected behavior
It returns fileinfo

Screenshots

Project type
Server-side

Environment

  • Browser chrome
  • Version of Blazor.FileReader ( _14.19226
  • Version of .net sdk 3 preview 8

Additional context
Stacktrace

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Microsoft.JSInterop.JSRuntimeBase.<InvokeWithDefaultCancellation>d__131.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Blazor.FileReader.FileReaderJsInterop.<GetFileInfoFromElement>d__15.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Blazor.FileReader.FileReference.d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VisualBlazor.Pages.Qutes.View.d__96.MoveNext() in E:\VisualApprovals\VAPortal3\Pages\Qutes\View.razor:line 948

DragNDrop SSB Race Condition

  • Server side blazor
  • Similar code to the dragndrop example
  • Getting the following error randomly on refresh (about 30%-50% of the time):
      Unhandled exception rendering component: Could not find 'FileReaderComponent' in 'window'.
Error: Could not find 'FileReaderComponent' in 'window'.

The error occurs on: RegisterDropEventsAsync(); :

       protected override async Task OnAfterRenderAsync()
        {
            labelFilesReference = fileReaderService.CreateReference(labelElement);
            await labelFilesReference.RegisterDropEventsAsync();
        }

I do have InitializeOnFirstCall enabled, but I also tried this as well:

       protected override async Task OnAfterRenderAsync()
        {
            await fileReaderService.EnsureInitializedAsync();
            labelFilesReference = fileReaderService.CreateReference(labelElement);
            await labelFilesReference.RegisterDropEventsAsync();
        }

... and still received the error (same frequency). Adding Task.Delay did not help.

Retrying when it fails fixes the issue, which I think is probably evidence that there is a race condition here (which could mean the problem can only be replicated at very low latency e.g. local development).

This works:

        protected override async Task OnAfterRenderAsync()
        {
            labelFilesReference = fileReaderService.CreateReference(labelElement);
            try
            {
                await labelFilesReference.RegisterDropEventsAsync();
            }
            catch (JSException ex)
            when (ex.Message.Contains("Could not find 'FileReaderComponent' in 'window'"))
            {
                // failed race condition, just try again
                await labelFilesReference.RegisterDropEventsAsync();
            }
        }

Input reference Clear Method

As discussed in #35 . This could be a useful method to have while still having a slim API. This method should be on IFileReaderRef. IMO a better API than to use bind, also considering that bind currently crashes in Ms Edge

Base64 stream API

A lower-level api should be created, which exposes the base64-encoded string returned by the FileReader.

The use-case is when the byte-stream once the data has arrived to clr-land is just raw data passed on to something else that requires base64-encoding, such as a cloud service.

Current process is either a) file -> byte[] -> base64 (wasm with shared buffer option) or worse b)file -> base64 -> byte[] -> base64 (for server-side or wasm without shared buffer option).

The process should rather be just file -> base64, the first two steps of process b.

Fatal error in IL Linker - prev. 9

Hi there.

I'm using this library to upload relatively small images on client side Blazor. After updating to prev 9 at compile time I get
Unhandled Exception: Mono.Linker.MarkException: Error processing method: 'System.Void Blazored.Typeahead.BlazoredTypeaheadBase1/d__63::MoveNext()' in assembly: 'Blazored.Typeahead.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Threading.Tasks.Task1<!!0> Microsoft.JSInterop.IJSRuntime::InvokeAsync(System.String,System.Object[]) this error.
(In prev. 8 everything worked fine)
Please let me know if you have encountered something similar or know where to look for a solution.
Thank you

The full error message:

Processing embedded resource linker descriptor: System.Text.Json.xml
Processing embedded resource linker descriptor: System.Text.Encodings.Web.xml
Processing embedded resource linker descriptor: mscorlib.xml
Duplicate preserve in resource mscorlib.xml in mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e of System.Threading.WasmRuntime (All). Duplicate uses (All)
Duplicate preserve in resource System.Text.Encodings.Web.xml in System.Text.Encodings.Web, Version=4.0.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Text.Encodings.Web.TextEncoder (Nothing). Duplicate uses (Nothing)
Duplicate preserve in resource System.Text.Encodings.Web.xml in System.Text.Encodings.Web, Version=4.0.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Buffers.OperationStatus System.Text.Encodings.Web.TextEncoder::EncodeUtf8Shim(System.Text.Encodings.Web.TextEncoder,System.ReadOnlySpan1<System.Byte>,System.Span1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
Duplicate preserve in resource System.Text.Encodings.Web.xml in System.Text.Encodings.Web, Version=4.0.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Int32 System.Text.Encodings.Web.TextEncoder::FindFirstCharacterToEncodeUtf8Shim(System.Text.Encodings.Web.TextEncoder,System.ReadOnlySpan1<System.Byte>) Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Text.Json.JsonPropertyInfoNullable2 (Nothing). Duplicate uses (Nothing)
Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Void System.Text.Json.JsonPropertyInfoNullable2::.ctor() Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Text.Json.Serialization.JsonPropertyInfoNotNullableContravariant4 (Nothing). Duplicate uses (Nothing)
Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Void System.Text.Json.Serialization.JsonPropertyInfoNotNullableContravariant4::.ctor() Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Text.Json.Serialization.Converters.JsonConverterEnum1 (Nothing). Duplicate uses (Nothing)
Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Void System.Text.Json.Serialization.Converters.JsonConverterEnum1::.ctor(System.Text.Json.Serialization.Converters.EnumConverterOptions) Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Void System.Text.Json.Serialization.Converters.JsonConverterEnum1::.ctor(System.Text.Json.Serialization.Converters.EnumConverterOptions,System.Text.Json.JsonNamingPolicy)
Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Text.Json.Serialization.Converters.JsonKeyValuePairConverter2 (Nothing). Duplicate uses (Nothing) Duplicate preserve in resource System.Text.Json.xml in System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 of System.Void System.Text.Json.Serialization.Converters.JsonKeyValuePairConverter2::.ctor()
Type System.Reflection.Assembly has no fields to preserve
Type Mono.ValueTuple has no fields to preserve
Fatal error in IL Linker

Unhandled Exception: Mono.Linker.MarkException: Error processing method: 'System.Void Blazored.Typeahead.BlazoredTypeaheadBase1/<HandleFocus>d__63::MoveNext()' in assembly: 'Blazored.Typeahead.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Threading.Tasks.Task1<!!0> Microsoft.JSInterop.IJSRuntime::InvokeAsync(System.String,System.Object[])
at Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
at Mono.Linker.Steps.MarkStep.Process()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
at Mono.Linker.Pipeline.Process(LinkContext context)
at Mono.Linker.Driver.Run(ILogger customLogger)
at Mono.Linker.Driver.Execute(String[] args, ILogger customLogger)
at Mono.Linker.Driver.Main(String[] args)

EPPlusCommon.razor issue

you have

<th @rowspan="cell.Rowspan" @colspan="cell.Colspan">@cell.Value</th>

should be

<th rowspan="@cell.Rowspan" colspan="@cell.Colspan">@cell.Value</th>

Also the code will link fine for the server side demo.

Progress callback

Not a bug - a request. Can we have notification of progress during the upload?

I have code like this:

            try
            {
                using (var stream = await file.CreateMemoryStreamAsync(4096))
                {
                    if (Workbook != null)
                    {
                        Workbook.Dispose();
                    }

                    Workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
                    ....
                }
            }
            catch (Exception ex)
            {
                Output += ex.Message;
            }

If would useful for larger file to be notified of progress. Maybe an event on IFileReference or a callback in CreateMemoryStreamAsync.

[Bug] tsconfig.json is being packed

As of version 0.12.19167 of tewr.blazor.filereader. When referencing Nuget package, the tsconfig.json is visible in the consuming project.

image

End to end tests

Some basic end to end tests as in blazor would save a bunch of time as debugging is a pain.

Excel demo page

The demo source doesn't contain the Excel import page contained in the live demo. Is this because you hit the same issue that I did when referencing EPPlus (and some other packages) where the linker fails because the parameter list is too long?

Streaming a file to cloud storage

This is almost certainly not an actual bug, and instead will likely just illustrate my lack of understanding of streams in .Net. I'm trying to use the azure SDK to stream file contents to blob storage without loading it all into memory first. The azure SDK has the following signature:

public class BlobClient : BlobBaseClient{
    Task<Response<BlobContentInfo>> UploadAsync(Stream content);`
}

So the idea here is you can just give it a stream, and it will upload it for you. So perhaps something like this:

using (Stream stream = await file.OpenReadAsync()) {
	await blobClient.UploadAsync(stream);
}

However this fails due to the restriction to async-only reads and a NotSupportedException is raised in FileReaderJsInterop as the azure blob client attempts to call Read on the underlying stream.

  • Does it make sense to allow/implement Read when running on the server side?
  • Or Are there any workarounds available to enable this kind of scenario? Perhaps some kind of wrapper stream?

Also just wanted to extend a warm thank you for the work on this package, it's a lot of work creating a great file upload experience and this package takes care of so much heavy lifting!

Save to IFileReference

Can i write data directly to IFileReference? I want to resize image in browser, save data and then send data to API controller.
Something like this:

using (var stream = await file.CreateMemoryStreamAsync())
{
using (Image image = Image.Load(stream))
{
image.Mutate(x => x.Resize(image));
image.SaveAsJpeg(stream);
}
// save back to IFileReference
await stream.WriteAsync(file);
}

I use client-blazor RC1

Some Questions: WASM vs Server Side

Hi Guys,

I'm a noob in this subject. I have two questions:

  1. What is the different between WASM and Server Side?
  2. Does the loading. Net Assembly actually executes on the client browser, if yes, if we add a MethodInfo .Invoke after loading the assembly, will it be executed in the Web Browser Context?

Also when loading a .net library in my VS in "Blazor.FileReader.Wasm.Demo", it shows the following error:

[IFileInfo.Name: Blazor.FileReader.dll
IFileInfo.Size: 38912
IFileInfo.Type: application/x-msdownload
IFileInfo.LastModifiedDate: 05/07/2019 04:21:15
Reading file...Done reading file Blazor.FileReader.dll
.Loading assembly...
Assembly loaded.
Loading assembly contents...
Public Types:
Assembly loading of types failed: System.Reflection.ReflectionTypeLoadException: Exception of type 'System.Reflection.ReflectionTypeLoadException' was thrown.
Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.](url)

Using Visual Studio Preview. All the project settings are as your GitHub, nothing changed.
.Net core version 3.0.0-preview4-19216-03.

Any help is appreciated.

Btw very nice project, good work!

Question: additive Drag+Drop possible?

Hi,

I'd like to fake the popular "dropzone.js" with BlazorFileReader.
Main motivation is, that dropzone.js can collect multiple drag+drops and start the upload afterwards.
Unfortunately, BlazorFileReader's DragDrop-Demo clears the droplist before every dropevent-handling. I'm a simple man, so I removed FileList.Clear() in RefreshFileList()) ;-) - was fine on the first look.
But on the second, I realized that the FileInfo-Contents changed but IFileReference.ReadFileInfoAsync() returned the same stream twice. :-(
What has to be done to mimic "dropzone.js"'s behavior?

Thanks for help!
Sascha

Build improvements

The build experience should be improved, as theres a few manual steps involved with the current state of things

  • Minified javascript option
  • DRY experience for interop reference (.NET first?). Assembly name, method calls.

A gulp script could be used to achieve this.

Tewr.Blazor.FileReader leaks js files into project

When adding Tewr.Blazor.FileReader 0.10.19116 to a Blazor Client Side project it leaks the "content" folder into the project.

image

Repro Steps:

  1. Create Blazor project

  2. Add "Tewr.Blazor.FileReader" 0.10.19116 Nuget package

Blazor 0.8.0 breaks FileReader

Hi All

Should be a simple referencing fix, but Blazor 0.8.0 has moved the ElementRef to Microsoft.AspNetCore.Components from Microsoft.AspNetCore.Blazor

Server-side projects has a max buffer-size of 2895 bytes

Since 3.0.0 preview 4, Server-side blazor Json Serialization fails with a not very descriptive exception if the signalR message is too large (over 2895), and when set lower, sporadically:

after this function call:

this.CallMethod("ReadFileMarshalledAsyncCallback", { callBackId, data });

which calls

this.dotNet.invokeMethodAsync(this.assemblyName, name, params);

we get this:


Uncaught (in promise) Error: System.Runtime.Serialization.SerializationException: Invalid JSON string
   at SimpleJson.SimpleJson.DeserializeObject(String json)
   at SimpleJson.SimpleJson.DeserializeObject(String json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
   at SimpleJson.SimpleJson.DeserializeObject[T](String json)
   at Microsoft.JSInterop.DotNetDispatcher.InvokeSynchronously(String assemblyName, String methodIdentifier, Object targetInstance, String argsJson)
   at Microsoft.JSInterop.DotNetDispatcher.BeginInvoke(String callId, String assemblyName, String methodIdentifier, Int64 dotNetObjectId, String argsJson)
    at endInvokeDotNetFromJS (blazor.server.js:8)
    at blazor.server.js:8
    at new Promise (<anonymous>)
    at e.beginInvokeJSFromDotNet (blazor.server.js:8)
    at blazor.server.js:1
    at Array.forEach (<anonymous>)
    at e.invokeClientMethod (blazor.server.js:1)
    at e.processIncomingData (blazor.server.js:1)
    at e.connection.onreceive (blazor.server.js:1)
    at WebSocket.i.onmessage (blazor.server.js:1)
endInvokeDotNetFromJS @ blazor.server.js:8
(anonymous) @ blazor.server.js:8
beginInvokeJSFromDotNet @ blazor.server.js:8
(anonymous) @ blazor.server.js:1
e.invokeClientMethod @ blazor.server.js:1
e.processIncomingData @ blazor.server.js:1
connection.onreceive @ blazor.server.js:1
i.onmessage @ blazor.server.js:1

Not really clear if this is happening on the server or on the client, but I suspect the client as the task on the server never resolves.

Seems that with an even lower buffer size, like 2000, it never happens.

Anything over 3000, it happens all the time. Fun stuff!

Uploading file > 30MB on Server-Side Blazor causes "Request body too large"

Describe the bug
Uploading a file > 30MB results in

Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer: Error: Unexpected exception in "IISHttpContext.ReadBody".

Microsoft.AspNetCore.Server.IIS.BadHttpRequestException: Request body too large.
   at Microsoft.AspNetCore.Server.IIS.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadBody()

(the error actually happens at about 21.3MB of the file transferred).

To Reproduce
Steps to reproduce the behavior:

  1. New server-side project on preview 7 and filereader 0.13.19207
  2. Use example async method with stream reading
  3. Upload file > 30MB

Project type
Server-side

Environment

  • Browser: chrome and edge
  • Version of Blazor.FileReader: 0.13.19207
  • Version of .net sdk: 3.0.0-preview7-27912-14

Additional context
I've tried increasing the signalr message size, but I don't think that's the issue here. IIS is complaining that the request body is too big.. I'm not sure why it would be. Below is my code:

<input type="file" @ref="inputTypeFileElement" />
<button type="button" @onclick=ReadFile>Read file</button>

@code {
    private ElementRef inputTypeFileElement;

    public async Task ReadFile()
    {
        foreach (var file in await fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync())
        {
            var buffer = new byte[16384];
            int read = 0;
            using (Stream stream = await file.OpenReadAsync())
            {
                using (var fileStream = new FileStream("incomingFile.bin", FileMode.Create, FileAccess.Write))
                {
                    while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await fileStream.WriteAsync(buffer, 0, read);
                    }
                }
            }
        }
    }
}

[WASM] Reintroduce shared memory buffer

Up until preview6, the blazor filereader Wasm library used unmarshalled calls to communicate the file chunks from js to .net. This is no longer the case due to a breaking change in blazor(mono?) that broke the implementation. Might be something as simple as a name change in the API, have not investigated thoroughly.

Main motivation of reintroducing this thing is speed (~30% faster) and general memory / cpu usage (not really benchmarked though current marshaled memory usage should at minimum the be 2.4 * buffer size compared to unmarshalled)

First issue is how to re-implement the method.
The original implementation passed a reference to a byte array to js in the first call. Current implementations doing about the same thing (ex http message handler in blazor) rather have a call originating from js to allocate and get a reference to that array, which could be considered being the reference implementation.

Second issue, how to enable usage of the method..
As there is still no WASM target for libraries, an initialization option has to be added that enables referencing MonoWebAssemblyJSRuntime.InvokeUnmarshalled<...>. I'm a little bit unhappy about making end-users do that this as it makes setup quite complex. Might be possible with a simple boolean option but that would cost a lot in reflection instead.

Loading time (CSB).

Describe the bug
When i try to read a csv file of 40.000kb (360.000 lines) i takes a really long time (couple minutes)

im using:
new StreamReader(await _fileReference.OpenReadAsync()

I tried reading by line:
var line = await reader.ReadLineAsync();

or reading by file
var text = await reader.ReadToEndAsync(); This took 4.03 minutes for 40927219 chars.

My computers does start using more memory but nothing extreme.

Unable to use file read with server-side preview6

Describe the bug
Can't use the file reader component with server side Blazor. The signalr connection fails. On the backend side, the code just hangs when attempting to read from the stream at await stream.ReadAsync
Due to other dependencies with the project, I'm unable to use net 3.0 preview7 at this time.

To Reproduce
Steps to reproduce the behavior:
Pretty much using the suggested code to reproduce this.

public async Task<string> GetImagePathAsync()
{
    foreach (var file in await FileService.CreateReference(FileElement).EnumerateFilesAsync())
    {
        var fileInfo = await file.ReadFileInfoAsync();
        using var stream = await file.OpenReadAsync();
        var imageData = new byte[stream.Length];
        await stream.ReadAsync(imageData, 0, (int)stream.Length);

        using var imageStream = new MemoryStream(imageData);
        return await Client.UploadImageAsync(imageStream, fileInfo.Name, fileInfo.Type);
    }
    return null;
}

Project type
Server-side

Environment

  • Browser: Safari, Firefox and Chrome
  • Version of Blazor.FileReader - 0.12.19186
  • Version of .net sdk - 3.0.100-preview6-012264

Regression?

Updating to latest version

image

The error message is back

image

image

Blazor Server running in docker container cant access static web assets

Describe the bug
Building an blazor app server-side with FileReader works without any problem. When deploying as docker container, startup fails as it wants to access "/root/.nuget/packages/tewr.blazor.filereader/0.15.0.19248/staticwebassets" during first run, which is not mounted as a volume.

Error message

Unhandled exception. System.IO.DirectoryNotFoundException: /root/.nuget/packages/tewr.blazor.filereader/0.15.0.19248/staticwebassets/
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsFileProvider..ctor(String pathPrefix, String contentRoot)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__2_0(ContentRootMapping cr)
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.OfTypeIterator[TResult](IEnumerable source)+MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
   at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass8_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
   at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()

Project type
Server-side

Environment

  • Visual Studio Preview 16.3
  • Blazor.FileReader Preview 9 / 0.15.0.19248
  • .net core 3 preview 9

What might be a solution to avoid this error and to avoid mounting as a volume as this is not available on client environments? Should I include the static assets directly in the source folder?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.