Telerik Forums
UI for Blazor Forum
1 answer
7 views

i using Telerik upload for uloading multiple file and max upload file is 5 but time of working uplaod works well but when i remove uplaoded item it just remove from frontend but in my controller it has diffrent id and client side has diffrent id i got it when i debug the code tried multiple times but i got not clue i am giving my full razor component and controller in below 
below is my models 

public class FileMetadata
{
    public string FileId { get; set; }
    public long Size { get; set; }
    public string FileName { get; set; }
    public byte[] FileContent { get; set; }
    public Guid? ProcessId { get; set; }
    public Guid? StructureId { get; set; }
    public Guid? BillingSiteId { get; set; }
}
 public partial class Document
 {
     public Guid DocumentId { get; set; }

     public Guid InvoiceId { get; set; }

     public Guid? JobId { get; set; }

     public int JobStep { get; set; }

     private string _fileName;

     public string FileName
     {
         get { return _fileName; }
         set
         {
             _fileName = value;
             this.DocumentFormat = GetDocumentFormatByFileExtension(value);
         }
     }

     // Field is ignored in regard to DbContext load/save
     public string FileData { get; set; }

     public DateTime CreatedOn { get; set; }

     public DocumentType DocumentType { get; set; }

     public DocumentFormat DocumentFormat { get; set; }

     public DocumentSource DocumentSource { get; set; }

     public bool CanBeArchived { get; set; } 

     public List<Variable> Variables { get; set; }


     [JsonIgnore]
     public virtual Invoice Invoice { get; set; }

     [JsonIgnore]
     public virtual Job Job { get; set; }

     private static DocumentFormat GetDocumentFormatByFileExtension(string fileName)
     {
         if (string.IsNullOrEmpty(fileName)) 
             return DocumentFormat.Undefined;

         try
         {
             string fileExtension = Path.GetExtension(fileName)?.ToLower();

             return fileExtension switch
             {
                 ".pdf" => DocumentFormat.PDF,
                 ".txt" => DocumentFormat.TXT,
                 ".json" => DocumentFormat.JSON,
                 ".xml" => DocumentFormat.XML,
                 ".vars" => DocumentFormat.VARS,
                 _ => DocumentFormat.Undefined,
             };
         }
         catch
         {
             return DocumentFormat.Undefined;
         }           
     }
 }


below is my razor component code 
<style>
    /*  to show custom message for Bug 51695: [Manual upload] Invalid success text  */
    .k-file-validation-message::before {
        content: "@(isUploadedSuccess ? Resources.FileUploadMsg : "")";
        visibility: @(isUploadedSuccess ? "visible" : "hidden");
    }

    /*  to hide the predefined message when file is uploaded  */
    .k-file-validation-message {
        visibility: @(isUploadedSuccess ? "hidden" : "visible");
    }

        /* display error message for invalid file in red */
        .k-file-validation-message.k-text-error {
            color: red;
        }
</style>

<div style="width: 400px;">

    <!-- Drop Zone Section -->
    <div class="dropzone-section">

        <TelerikDropZone Id="dropzone-id"
                         DragOverClass="dropzone-over"
                         NoteText="@DropZoneHintText">
        </TelerikDropZone>

        @if (UseDropZoneOverStyles)
        {
            <style>
                .dropzone-over .k-dropzone-inner {
                    border: 2px dashed;
                }
            </style>
        }
    </div>

    <!-- Upload Section -->
    <div class="upload-section divstyling">
        <TelerikUpload DropZoneId="dropzone-id" @ref="@UploadRef" Id="uploadFile"
                       SaveUrl="@UploadSaveUrl"
                       MaxFileSize="@(16 * 1024 * 1024)"
                       Class="@UploadClass"
                       OnSuccess="@OnUploadSuccess"
                       OnRemove="@OnUploadRemove"
                       OnError="@OnUploadError"
                       Multiple="true"
                       AllowedExtensions="@AllowedFileExtensions"
                       Accept=".pdf,.xml"
                       OnSelect="@OnSelectHandler" />
    </div>

    <!-- Notification Section OnSelect="@OnSelectHandler"-->
    <div class="notification-section">
        <TelerikNotification @ref="@NotificationRef" Class="MyTelerikNotification" HorizontalPosition="NotificationHorizontalPosition.Center" />
    </div>

    <!-- Upload Button -->
    <div class="button-section d-md-flex justify-content-md-end">
        <button id="btnUpload"
                type="button"
                class="btn btn-sm btnAction btn-action-filled-blue mr-1 mt10"
                @onclick="@Upload"
                disabled="@(isUploadInProgress || !selectedFiles.Any())">
            @if (isUploadInProgress)
            {
                <span class="spinner-border spinner-border-sm mr-1"></span>
            }
            @(isUploadInProgress ? Resources.Uploading : Resources.AddAttachment)
        </button>
    </div>
</div>

<style>
    /* Drop Zone */
    .dropzone-section {
        width: 100%;
        max-width: 600px;
        text-align: center;
        margin-bottom: 20px;
    }

    /* Upload Section */
    .upload-section {
        width: 100%;
        max-width: 600px;
        margin-bottom: 20px;
    }

    /* Notification Section */
    .notification-section {
        width: 100%;
        max-width: 600px;
        margin-bottom: 20px;
    }

    /* Buttons */
    #btnUpload {
        border: 2px solid;
        border-radius: 20px;
        opacity: 1;
        margin-right: 0px;
        font-weight: bold;
        /*font-size: 0.85rem !important;*/
        padding-left: 20px !important;
        padding-right: 20px !important;
        max-width: fit-content;
    }

        #btnUpload:focus {
            outline: none !important;
            box-shadow: none !important;
        }
    /* Other Styles */
    .dropzone-over .k-dropzone-inner {
        border: 2px dashed;
    }

    .no-dropzone .k-dropzone-hint {
        display: none;
    }

    .divstyling {
        padding-bottom: 10px;
    }
     /* Error Notification caption */
  /* .MyTelerikNotification .k-notification-container .k-notification {
        width: 300px;
        height: 50px;
        font-size: 1.5em;
        text-align: center;
        align-items: center;
    }  
    .divstyling > .k-upload .k-upload-files{
        max-height : 250px; 
    }*/
</style>

and here is code behind code
using Blazored.Modal;
using Blazored.Modal.Services;
using CmpInvoicePlatform.Client.Services.Dialog;
using CmpInvoicePlatform.Client.Services.Request;
using CmpInvoicePlatform.Shared.Models;
using CmpInvoicePlatform.Shared.Resources;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Telerik.Blazor;
using Telerik.Blazor.Components;
using Telerik.Blazor.Components.Notification;

namespace CmpInvoicePlatform.Client.Pages.Invoices
{
    public partial class MutlipleAttachmentAdd : ComponentBase
    {

        [CascadingParameter]
        BlazoredModalInstance ModalInstance { get; set; }

        [Inject]
        private IRequestService RequestSvc { get; set; }
        [Inject]
        private IDialogService DialogSvc { get; set; }

        [Inject]
        private NavigationManager NavigationManager { get; set; }

        [Parameter]
        public InvoiceModelViewModel InvoiceMVM { get; set; }

        private string DropZoneHintText => UploadVisible ? Resources.ManualUploadDrop : string.Empty;

        private bool UseDropZoneOverStyles { get; set; } = true;

        private bool UploadVisible { get; set; } = true;

        private string UploadClass => $"no-dropzone {(!UploadVisible ? "k-hidden" : string.Empty)}";

        private string UploadSaveUrl => ToAbsoluteUrl("api/MultipleFileUpload/save");

        private HttpClient _httpClient;

        public List<string> AllowedFileExtensions = new List<string> { ".pdf", ".xml" };

        //mainly used to check the file uploaded is successful or not so according to it disabled the upload button
        private bool isUploadedSuccess { get; set; }
        private bool isUploadInProgress { get; set; }
        private TelerikUpload UploadRef { get; set; }

        private List<UploadFileInfo> selectedFiles = new();

        private List<FileMetadata> fileMetadataList = new();

        private static int MaxAttachmentFile = 5;

        private static string MaxFileErrorMsg = string.Format(Resources.MaxUploadedFileErrorMsg, MaxAttachmentFile);
        private string ToAbsoluteUrl(string url)
        {
            return $"{NavigationManager.BaseUri}{url}";
        }

        private TelerikNotification NotificationRef { get; set; }

        private void OnUploadSuccess(UploadSuccessEventArgs args)
        {
            isUploadedSuccess = (args.Operation == UploadOperationType.Upload) ? true : false;
        }

        private void OnUploadError(UploadErrorEventArgs e) => isUploadedSuccess = false;

        // Check if the extensions of all selected files are present in the allowed extensions list.
        private async Task OnSelectHandler(UploadSelectEventArgs e)
        {
            var currentFileUploadedCount = selectedFiles.Count + e.Files.Count();
            // Prevent selecting more than 5 files total
            if (currentFileUploadedCount > MaxAttachmentFile)
            {
                e.IsCancelled = true;
                await DialogSvc.AlertAsync(Resources.MaxFileUploadedTitle, MaxFileErrorMsg);
                return;
            }

            selectedFiles.AddRange(e.Files);

            isUploadedSuccess = e.Files.All(file =>
                AllowedFileExtensions.Contains(file.Extension) &&
                !(file.InvalidMinFileSize || file.InvalidMaxFileSize || file.InvalidExtension)
            );
        }

        private async Task Upload()
        {
            try
            {
                isUploadInProgress = true;
                var documentIds = new List<Guid>();
                // Get all files by using UploadController
                _httpClient = new HttpClient();

                using var response = await _httpClient.GetAsync(new Uri($"{NavigationManager.BaseUri}api/MultipleFileUpload/GetAllFiles"));

                if (response.IsSuccessStatusCode)
                {
                    var uploadedFiles = await response.Content.ReadFromJsonAsync<List<Document>>();

                    // Process the files list as needed
                    foreach (var file in uploadedFiles)
                    {
                        var newDocument = new Document
                        {
                            DocumentId = Guid.NewGuid(),
                            InvoiceId = InvoiceMVM.InvoiceId,
                            DocumentSource = DocumentSource.External,
                            DocumentType = DocumentType.Support,
                            FileName = file.FileName,
                            FileData = file.FileData,
                        };

                        await RequestSvc.InvoiceAttachmentAddAsync(newDocument);
                        documentIds.Add(newDocument.DocumentId);
                    }


                    await DialogSvc.AlertAsync(Resources.AddAttachment, Resources.MultipleAttachmentUploadSuccessMsg);

                    UploadRef.ClearFiles();
                    selectedFiles.Clear();
                    isUploadedSuccess = false;

                    //Return the list of uploaded document IDs to the calling component
                    await ModalInstance.CloseAsync(ModalResult.Ok(documentIds));

                }

                await _httpClient.GetAsync(ToAbsoluteUrl("api/MultipleFileUpload/CleanFiles"));

            }
            catch (Exception ex)
            {
                await DialogSvc.AlertAsync(Resources.UploadInvoice, ex.Message);
            }
            finally
            {
                isUploadInProgress = false;
            }
        }

        private async void OnUploadRemove(UploadEventArgs args)
        {
            _httpClient = new HttpClient();
            foreach (var file in args.Files)
            {
                selectedFiles.RemoveAll(f => f.Id == file.Id);

                await _httpClient.PostAsync(
                    ToAbsoluteUrl("api/MultipleFileUpload/remove"),
                    new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("fileId", file.Id)
                    }));
            }

            if (!selectedFiles.Any())
            {
                UploadRef.ClearFiles();
                await _httpClient.GetAsync(ToAbsoluteUrl("api/MultipleFileUpload/CleanFiles"));
            }
        }

    }

}

please look at the screenshots and provide appropriate solution as soon as possible[High Priority]

Thanks in Advance

    
Ivan Danchev
Telerik team
 answered on 08 Jul 2025
1 answer
182 views
In .NET 8, Microsoft will be introducing support for IAsyncEnumerable JSON deserialization (Streaming deserialization APIs). This feature allows for items in a long list to be deserialized as they are streamed to the client from a server, rather than waiting for the entire request to be completed. So it will result in a perceived performance increase. Is there any chance for Progress to look into bringing support for this feature to Telerik Data Source Responses? I can anticipate the data field in the response class makes this a challenging ask. Also, the server-side needs to be able to return yield for async items. I am interested in seeing this feature implemented so the grids in my applications that have many items will begin to be usable sooner.
1 answer
608 views

I have a relatively long running task and would like to show a Dialog box informing the user stuff is happening with a ProgressBar to show completion progress. However when the ProgressBar is in DialogContent it is not updating the UI when I update the Value of the progressbar.

If I put the progressbar in the body of the page it works as expected.

Razor Code is something like:

<TelerikDialog @bind-Visible="@DialogVisible"
               Width="500px"   
               ShowCloseButton="false"
               CloseOnOverlayClick="false">
    <DialogTitle>Updating</DialogTitle>
    <DialogContent>
        <p>Assigning stuff...</p>
         <TelerikProgressBar Value="@ProgressValue" Max="100"></TelerikProgressBar>
    </DialogContent>
</TelerikDialog>

Then code is:

@code {
	private bool DialogVisible { get; set; } = false;
	private double ProgressValue = 0;

	private async void ButtonClick()
	{
		DialogVisible = true;

		for (var i = 0; i < 20; i++)
		{
			ProgressValue = Math.Round((double)i / 20 * 100);
			StateHasChanged();
			await Task.Delay(1000);
		}
	}
}

 

Nadezhda Tacheva
Telerik team
 answered on 21 Feb 2023
1 answer
156 views
Since 4.0.0 version, the proposed CSS customization is not working with custom Saas Theme Buider again.
Progress color does't rendering.

Please update ThemeBuilder.
Nadezhda Tacheva
Telerik team
 answered on 01 Feb 2023
0 answers
220 views

Hello,

I have a scenario where I have a Telerik Notification with a Telerik progress bar embedded.  I am looking to update the progress bar of multiple instances of the notification independently based in separate threads.

Would this be possible?

Thanks,

Tony

 

Tony
Top achievements
Rank 1
 asked on 20 Dec 2022
0 answers
166 views

Hello,

I am trying to implement a progress bar while importing an excel file. The progress bar does not work, I implement the sample within my code and its not working anyway.

Here is the code :

 

@page "/administration/excel"

@inject HttpClient httpClient
@inject IJSRuntime jSRuntime

@implements IDisposable

@using System.Timers

@using XxxPathie.Libraries.Shared.Models.Tools;
@using XxxPathie.Libraries.Ui.Tools.Network;

<h3>Tools</h3>

<label for="specialites">Spécialités</label>
<InputFile id="specialites" OnChange="OnSpecialitesChange">Specialités</InputFile>
<br />
<label for="motscles">Mots clés</label>
<InputFile id="motscles" OnChange="OnMotsClesChange">Mots clés</InputFile>

<br />
<label for="principesactifs">Principes actifs</label>
<InputFile id="principesactifs" OnChange="OnPrincipesActifsChange">Principes actifs</InputFile>

<br />
<label for="preparations">Préparations</label>
<InputFile id="preparations" OnChange="OnPreparationsChange">Préparations</InputFile>

<br />
<br />

<TelerikProgressBar @ref="progressBar" Value="@progressValue" Max="progressMax"></TelerikProgressBar>

<TelerikProgressBar Value="@ProgressValue" Max="100"></TelerikProgressBar>

@code {
    TelerikProgressBar progressBar;
    Timer timer = new();
    ExcelFile progress = new();
    double progressValue = 0;
    double progressMax = 1000;
    bool refresh = false;

    public void Dispose()
    {
        StopProgress();
        Timer?.Close();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (Timer.Enabled == false)
        {

            Timer.Start();
        }
    }

    public void OnTimerElapsed(Object source, ElapsedEventArgs e)
    {
        if (ProgressValue < 100)
        {
            UpdateProgress();
        }
        else
        {
            StopProgress();
        }
    }

    public void UpdateProgress()
    {
        ProgressValue += ProgressStep;

        InvokeAsync(StateHasChanged);
    }

    public void StopProgress()
    {
        Timer?.Stop();
    }

    public const int TimerInterval = 1000;
    public const int TotalTime = 10 * TimerInterval;
    public double ProgressValue = 0;
    public int ProgressStep = 100 / (TotalTime / TimerInterval);
    public Timer Timer { get; set; } = new Timer();

    private async void OnSpecialitesChange(InputFileChangeEventArgs args)
    {
        await ManageDownload(args.File, "excel/specialites", "Spécialités.xlsx");
    }

    private async void OnMotsClesChange(InputFileChangeEventArgs args)
    {
        await ManageDownload(args.File, "excel/motscles", "Mots clés.xlsx");
    }

    private async void OnPrincipesActifsChange(InputFileChangeEventArgs args)
    {
        await ManageDownload(args.File, "excel/principesactifs", "Principes actifs.xlsx");
    }

    private async void OnPreparationsChange(InputFileChangeEventArgs args)
    {
        await ManageDownload(args.File, "excel/preparations", "Préparations.xlsx");
    }

    private async Task ManageDownload(IBrowserFile file, string url, string fileName)
    {
        byte[] bytes = new byte[file.Size];

        using (var stream = file.OpenReadStream(250 * 1024 * 1024))
        {
            await stream.ReadAsync(bytes, 0, bytes.Length);
        }

        progress = await RestClient.Instance.PostAsync<ExcelFile>(httpClient, url, bytes);

        progressValue = 0;
        progressMax = progress.MaxCount;

        refresh = !refresh;

        timer.Stop();
        timer.Interval = 200;
        timer.AutoReset = true;
        timer.Elapsed -= ProgressPlease;
        timer.Elapsed += ProgressPlease;
        timer.Start();
    }

    private void ProgressPlease(Object source, ElapsedEventArgs e)
    {
        progressValue++;
        progressMax = 1000;
    }

    private async Task ProgressReport(ExcelFile progress, string fileName)
    {
        try
        {
            for (; ; )
            {
                progress = await PoolProgress(progress, "fileName");
                progressMax = progress.MaxCount;
                progressValue = progress.DoneCount;
            }
        }
        catch (Exception exception)
        {
            var breakime = 1;
        }
    }

    private async Task<ExcelFile> PoolProgress(ExcelFile progress, string fileName)
    {
        progress = await RestClient.Instance.GetAsync<ExcelFile>(httpClient, "excel/progress/" + progress.Identifier);

        if (progress.DoneCount == progress.MaxCount && progress.bytes != null)
        {
            var href = httpClient.BaseAddress + progress.Identifier.ToString();
            await jSRuntime.InvokeAsync<object>("triggerFileDownload", fileName, href);

            throw new Exception("OK");
        }
        else if (progress.Identifier == Guid.Empty)
        {
            return progress;
        }
        else if (progress.DoneCount == progress.MaxCount)
        {
            throw new Exception("OK");
        }

        return progress;
    }
}

John
Top achievements
Rank 1
 asked on 15 Dec 2022
2 answers
1.9K+ views

Is there a way to format the color of TelerikProgressBar based off data?  

I see you can set the Class on that item, however it does not apply background-color to the fill of the bar.

 

I've found that I can modify all bars by setting the following css:

.k-progressbar .k-state-selected {

       background-color:green;
    }

 

Thanks!

Nadezhda Tacheva
Telerik team
 answered on 27 Jun 2022
2 answers
2.3K+ views

I have the following scenario:

- file download from a site;

- process records on file to store in a database.

The first take about 4 seconds and the second around a minute or a little more.

Followed the sample of ProgressBar to signal that records are being processed, however, the UI is not being updated. 

The environment is Blazor with .NET 5.04 and the latest version of UI for Blazor

Below is the Razor component where the data is handled.

Any suggestions on how to update the UI and reflect the current status?

Thanks

 

@page "/importPeers"
@using DataLoader.Models
@using DataLoader.Services
@using System.Timers
@implements IDisposable
@inject LoadDataFIService service

<h1>CVM FI Download</h1>

<p>componente para realizar o download de informações da CVM e carga no banco de dados</p>
<hr />
<br />

<div class="row">
    <div class="col-sm-8 col-md-8">
        <div class="row">
            <div class="col-sm-6 col-md-6">
                <span>
                    Mês Referência:
                    <TelerikDatePicker @bind-Value="@selectedDate"
                                       BottomView="@CalendarView.Year"
                                       Format="MMM yyyy">
                    </TelerikDatePicker>
                </span>
            </div>
            <div class="col-sm-3 col-md-3">
                <TelerikButton OnClick="@OnProcessDataClick">Processar</TelerikButton>
            </div>
        </div>
    </div>
</div>
<br />
<div class="row">
    <div class="col-sm-8 col-md-8">
        @processingAction
        <br />
        <TelerikProgressBar Indeterminate="@isIndeterminate" Value="@CurrentValue" Max="@MaxValue" />
    </div>
</div>
@currentCount importados...
<hr />




@code {
    public string processingAction { get; set; }
    public bool isIndeterminate { get; set; } = false;
    public int progressValue { get; set; } = 0;
    DateTime selectedDate { get; set; } = DateTime.Now;
    int currentCount = 0;
    public double MaxValue { get; set; } = 100;
    public double CurrentValue { get; set; } = 0;
    public double StepValue { get; set; } = 5;
    public Timer Clock { get; set; } = new Timer();

    void OnProcessDataClick()
    {
        currentCount++;
        ProcessData();

    }

    void ProcessData()
    {
        //signal progress bar for download
        processingAction = "Downloading...";
        MaxValue = 5 * 1000;                    // download should take no more than 4 seconds
        StartProgress();

        var result = service.DownloadFile(selectedDate);

        // signal end of downloading
        processingAction = "Downloaded!";
        StopProgress();

        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

        if (result)
        {
            processingAction = "Processing records...";
            MaxValue = 65 * 1000;       // data processing should last about a minute or more
            StartProgress();
            //watch.Start();

            currentCount = service.ReadCsvFile(selectedDate);

            //watch.Stop();
            processingAction = "Records processed!";
            StopProgress();
        }

        // Console.WriteLine(watch.Elapsed);
    }

    public void Dispose()
    {
        StopProgress();
        Clock?.Close();
    }

    public void StartProgress(int interval = 200)
    {
        if (Clock?.Enabled == false)
        {
            Clock.Interval = interval;
            Clock.Elapsed -= OnClockElapsedEvent;
            Clock.Elapsed += OnClockElapsedEvent;
            Clock.AutoReset = true;
            Clock.Start();
        }
    }

    public void OnClockElapsedEvent(Object source, ElapsedEventArgs e)
    {
        if (CurrentValue < MaxValue)
        {
            UpdateProgress();
        }
        else
        {
            StopProgress();
        }
    }

    public void UpdateProgress()
    {
        CurrentValue += StepValue;
        InvokeAsync(StateHasChanged);
    }

    public void StopProgress()
    {
        Clock?.Stop();
        InvokeAsync(StateHasChanged);
    }

}

Drewanz
Top achievements
Rank 1
Veteran
 answered on 16 Apr 2021
1 answer
477 views

Hi Telerik Blazor team and users,

some question regarding the width of the progress bar component:

1. Is it planned to set the width by a property, e.g. Width="100%"?

2. Currently the control width is still the same after the target device is changed by Google developer tools (attached files). Is it a bug?

 

Regards, Stefan

Marin Bratanov
Telerik team
 answered on 25 Oct 2020
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?