Download Logo

Blazor WASM on GitHub Pages

Deployment Steps Create Blazor Webassembly Project using cli or using Visual Studio CLI Source Link Create .github Folder Inside .github Folder create another Folder workflows Inside workflows create file dotnet.yaml Code below for above process 1 2 3 4 5 6 7 8 dotnet new blazorwasm -o BlazorGitHubPagesDemo cd .\BlazorGitHubPagesDemo\ code . mkdir .github cd .\.github\ mkdir workflows cd .\workflows\ echo "" > "dotnet.yaml" Open The created yaml File And Paste The Below Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 name: DeployBlazorWebAssembly on: push: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x - name: Publish .NET Core Project run: dotnet publish BlazorGitHubPagesDemo.csproj -c Release -o release --nologo - name: Change base-tag in index.html from / to BlazorGitHubPagesDemo run: sed -i 's/<base href="\/" \/>/<base href="\/BlazorGitHubPagesDemo\/" \/>/g' release/wwwroot/index.html - name: copy index.html to 404.html run: cp release/wwwroot/index.html release/wwwroot/404.html # (Allow files and folders starting with an underscore) - name: Add .nojekyll file run: touch release/wwwroot/.nojekyll - name: Commit wwwroot to GitHub Pages uses: JamesIves/github-pages-deploy-action@3.7.1 with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} BRANCH: gh-pages FOLDER: release/wwwroot Change in above Code Based On Project On Line number 16 Change Dotnet version appropriate to you project Version ...

July 12, 2024 · 3 min · 491 words · PrashantUnity
Download Logo

Giscus in Blazor

Giscus Script Configuration Be sure To Change Parameter value Based on you Generation from here https://giscus.app/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <script src="https://giscus.app/client.js" data-repo="PrashantUnity/GettingStarted" data-repo-id="R_kgDOKzC5Hw" data-category="General" data-category-id="DIC_kwDOKzC5H84CdPDh" data-mapping="specific" data-term=" GettingStarted Discussions" data-strict="0" data-reactions-enabled="1" data-emit-metadata="0" data-input-position="top" data-theme="light" data-lang="en" data-loading="lazy" crossorigin="anonymous" async> </script> Above Code is Coverted to be usable in Blazor 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 @using Microsoft.AspNetCore.Components @if (Script != null) { <div> @Script </div> } @code { #region Parameter // change only commented section [Parameter] public string InputPosition { get; set; } = "top"; [Parameter] public string Term { get; set; } = "GettingStarted Discussions"; // name anything it will create one one discussion based on name [Parameter] public string Repo { get; set; } = "PrashantUnity/GettingStarted"; // your repository name [Parameter] public string RepoId { get; set; } = "R_kgDOKzC5Hw"; // this is generated by giscus website only one time creation required for one repo #endregion public string Category { get; set; } = "General"; public string CategoryId { get; set; } = "DIC_kwDOKzC5H84CdPDh"; // this is generateeed by giscus website only one time creation required for one repo public string Mapping { get; set; } = "specific"; public bool ReactionsEnabled { get; set; } = true; public string Theme { get; set; } = "light"; public string Language { get; set; } = "en"; public string Loading { get; set; } = "lazy"; public string EmitMetadata { get; set; } = "0"; public string Strict { get; set; } = "0"; private RenderFragment Script { get; set; } protected override void OnParametersSet() { Script = new RenderFragment(b => { b.OpenElement(0, "script"); b.AddMultipleAttributes(1, new List<KeyValuePair<string, object>>() { new KeyValuePair<string, object>("src", "https://giscus.app/client.js"), new KeyValuePair<string, object>("data-repo", Repo), new KeyValuePair<string, object>("data-repo-id", RepoId), new KeyValuePair<string, object>("data-category", Category), new KeyValuePair<string, object>("data-category-id", CategoryId), new KeyValuePair<string, object>("data-mapping", Mapping), new KeyValuePair<string, object>("data-term", Term), new KeyValuePair<string, object>("data-strict", Strict), new KeyValuePair<string, object>("data-reactions-enabled", ReactionsEnabled ? "1" : "0"), new KeyValuePair<string, object>("data-emit-metadata", EmitMetadata), new KeyValuePair<string, object>("data-input-position", InputPosition), new KeyValuePair<string, object>("data-theme", Theme), new KeyValuePair<string, object>("data-lang", Language), new KeyValuePair<string, object>("data-loading", Loading), new KeyValuePair<string, object>("crossorigin", "anonymous"), new KeyValuePair<string, object>("async", true), }); b.CloseElement(); }); } } Uses 1 <GiscusIntegration />

July 12, 2024 · 2 min · 417 words · PrashantUnity
Download Logo

Blazor snippets

String Interpolation 1 <img Class="@($"hello{variable}")" Width="64px" Height="64px" /> Get Dotnet Version Name using in Project 1 string version = Environment.Version.ToString(); Upload File Code for Uploading Images 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @page "/" <InputFile multiple OnChange="@HandleFileInput" /> @code { List<string> _items = new(); async Task HandleFileInput(InputFileChangeEventArgs e) { foreach (var item in e.GetMultipleFiles()) { using var stream = item.OpenReadStream(); using var ms = new MemoryStream(); await stream.CopyToAsync(ms); _items.Add($"data:{item.ContentType};base64,{Convert.ToBase64String(ms.ToArray())}"); } } } Convert Image As base64 string and then Display in Browser 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @using System.IO <MudFileUpload T="IBrowserFile" FilesChanged="UploadFiles"> <ButtonTemplate> <MudFab HtmlTag="label" Color="Color.Secondary" Icon="@Icons.Material.Filled.Image" Label="Load picture" for="@context.Id" /> </ButtonTemplate> </MudFileUpload> @if(ImageUri!="") { <MudImage Src="@ImageUri" Width="400" Height="400" /> } @code { string ImageUri=""; private async Task UploadFiles(IBrowserFile file) { var image = await file.RequestImageFileAsync("image/png", 600, 600); using Stream imageStream = image.OpenReadStream(1024 * 1024 * 10); using MemoryStream ms = new(); //copy imageStream to Memory stream await imageStream.CopyToAsync(ms); //convert stream to base64 ImageUri = $"data:image/png;base64,{Convert.ToBase64String(ms.ToArray())}"; } } Call Javascript Function 1 2 3 window.blazorKeyPressed = function() { }; 1 2 3 4 5 [Inject] protected IJSRuntime JSRuntime { get; set; } = null!; async Task CallJavascript() { await JSRuntime.InvokeVoidAsync("blazorKeyPressed"); } Call C# Code From JavaScript 1 2 3 4 5 window.blazorKeyPressed = function(dotnetHelper) { document.addEventListener('keyup', function(event) { dotnetHelper.invokeMethodAsync('OnArrowKeyPressed', event.key); }); }; 1 2 3 4 5 6 7 8 [Inject] protected IJSRuntime JSRuntime { get; set; } = null!; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await JSRuntime.InvokeVoidAsync("blazorKeyPressed", DotNetObjectReference.Create(this)); } } Code Which will be Called by Js 1 2 3 4 5 [JSInvokable] public void OnArrowKeyPressed(string key) { } Download Image using Base64 string 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 window.downloadImage = (base64Image, fileName) => { const byteCharacters = atob(base64Image); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray]); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); }; Download Div as Image 1 2 3 4 5 6 7 8 9 10 window.generateImage = function (id) { html2canvas(document.getElementById(id)).then(function (canvas) { var image = canvas.toDataURL('image/png'); var a = document.createElement('a'); a.href = image; a.download = 'generated_image.png'; a.click(); }); } Using Image URI 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 window.downloadImageUrl = (imageUrl, fileName) => { fetch(imageUrl) .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // Set the file name a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); }) .catch(error => console.error('Error downloading image:', error)); }; Code To Invoke All Above Three Methods/Approach 1 2 3 4 5 6 7 8 9 10 11 12 byte[] ConvertSKBitmapToByteArray(SKBitmap bitmap, SKEncodedImageFormat format) { using (var image = SKImage.FromBitmap(bitmap)) using (var data = image.Encode(format, 100)) { return data.ToArray(); } } var arr = bmp.Bytes;// ConvertSKBitmapToByteArray(bmp, SKEncodedImageFormat.Png); await JSRuntime.InvokeVoidAsync("downloadImage", Convert.ToBase64String(arr), "image.png"); await JSRuntime.InvokeVoidAsync("downloadImageUrl", $"https://picsum.photos/200/300", "image.png"); await JSRuntime.InvokeVoidAsync("generateImage", IDOfImageToDownload); // element as canvass as image

July 12, 2024 · 3 min · 553 words · PrashantUnity
Download Logo

SkiaSharp + Blazor WASM

Implementation Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 @page "/" @using SkiaSharp @using SkiaSharp.Views.Blazor <button @onclick="ButtonClicked">Redraw Image</button> <SKCanvasView @ref="canvasReference" OnPaintSurface="@OnPaintSurface" style="@($"height: {1920}px; width: {1080}px;")" IgnorePixelScaling=true /> @code { SKCanvasView canvasReference; void ButtonClicked() { canvasReference.Invalidate(); } private void OnPaintSurface(SKPaintSurfaceEventArgs e) { var canvas = e.Surface.Canvas; canvas.Clear(SKColor.Parse("#003366")); int width = 300; int height = 300; int step = 12; SKBitmap bmp = new(width, height); Random rand = new(0); SKPaint paintR = new() { Color = SKColors.White.WithAlpha(100), IsAntialias = true }; for (var i = 0; i < width; i = i + step) { for (var j = 0; j < height; j = j + step) { paintR.StrokeWidth = rand.Next(1, 6); Draw(i, j, step, step, paintR, canvas); } } } void Draw(int x, int y, int width, int height, SKPaint paint, SKCanvas canvas) { Random random = new Random(); paint.Color = listOfColor[random.Next(0, listOfColor.Count)]; var prob = random.Next(0, 10); if (prob < 5) { SKPoint pointOne = new(x, y); SKPoint pointTwo = new(x + width, y + height); //paint.StrokeWidth = rand.Next(1, 10); canvas.DrawLine(pointOne, pointTwo, paint); //canvas.DrawCircle(pointOne, random.Next(1, 6), paint); } else { SKPoint pointOne = new(x + width, y); SKPoint pointTwo = new(x, y + height); //paint.StrokeWidth = rand.Next(1, 10); canvas.DrawLine(pointOne, pointTwo, paint); } } List<SKColor> listOfColor = new List<SKColor> { SKColor.Parse("#EEF5FF"), SKColor.Parse("#B4D4FF"), SKColor.Parse("#86B6F6"), SKColor.Parse("#176B87"), SKColor.Parse("#00A9FF"), SKColor.Parse("#89CFF3"), SKColor.Parse("#A0E9FF"), SKColor.Parse("#CDF5FD"), SKColor.Parse("#FF90BC"), SKColor.Parse("#FFC0D9"), SKColor.Parse("#F9F9E0"), SKColor.Parse("#8ACDD7"), SKColor.Parse("#F2AFEF"), SKColor.Parse("#C499F3"), SKColor.Parse("#33186B"), }; }

July 12, 2024 · 2 min · 304 words · PrashantUnity