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
Download Logo

Firestore CRUD

Overview Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. It is a NoSQL document database that lets you easily store, sync, and query data for your applications at a global scale. In this guide, we’ll walk through how to implement a complete CRUD (Create, Read, Update, Delete) solution for Firestore in .NET with built-in schema validation and type conversion support. ...

November 15, 2025 · 17 min · 3471 words · PrashantUnity
Download Logo

.NET assemblies

Assembly Overview Assembly is unit of deployment like EXE or a DLL When you create a code and build the solution, then the .NET Framework convert your code into Intermediate Language and that is placed inside the assembly(dll), which you can find inside bin folder Assembly: A compiled code library in .NET that contains types, resources, and metadata. Types of Assemblies: Executable (EXE) and Library (DLL). Components: Manifest, metadata, IL code, and resources. ...

August 3, 2024 · 1 min · 89 words · PrashantUnity
Download Logo

Abstract class Q&A

Abstract Class Interview Questions Can an abstract class have non-abstract methods? Yes, see the example below Method hiding principle (use of New keyword) 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 public abstract class Animal { public abstract void MakeSound(); public void Eat() { Console.WriteLine("Eating..."); } public void IsAlive() { Console.WriteLine("Yes"); } public virtual void Sleep() { Console.WriteLine("Sleeping..."); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks."); } public void Bark() { Console.WriteLine("Barking..."); } public new void IsAlive() { Console.WriteLine("NO"); } public override void Sleep() { Console.WriteLine("The dog barks Sleeping."); } } class Program { static void Main(string[] args) { // Create an instance of the Dog class Dog myDog = new Dog(); // Call methods from the abstract class (Animal) myDog.Eat(); // Output: Eating... myDog.Sleep(); // Output: The dog barks Sleeping. } }

August 3, 2024 · 1 min · 182 words · PrashantUnity
Download Logo

Access modifiers

Class Accessibility Matrix Diagram What is Default accessibility of class Internal Difference between Internal and Protected Internal Look above image for clarification 1. Public Accessibility: The class is accessible from any other class or assembly. Usage: When you want the class to be widely accessible. 1 2 3 4 5 // Public class can be accessed from anywhere public class PublicClass { public string Name { get; set; } } 2. Internal Accessibility: The class is accessible only within the same assembly (project). Usage: When you want to limit access to within the assembly, which is useful for encapsulation. 1 2 3 4 5 // Internal class can only be accessed within the same assembly internal class InternalClass { public string Name { get; set; } } 3. Protected Accessibility: The class itself cannot be protected, but its members can be. A class can be derived from a base class with protected members. Usage: When you want to allow access to members only in derived classes. 1 2 3 4 5 6 7 8 9 10 11 12 13 public class BaseClass { protected string Name { get; set; } } public class DerivedClass : BaseClass { public void PrintName() { // Accessing protected member from the base class Console.WriteLine(Name); } } 4. Private Accessibility: A class itself cannot be private, but its members can be. Private members are only accessible within the same class. Usage: When you want to restrict access to the class members to only within the class itself. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class MyClass { private string Name { get; set; } public void SetName(string name) { Name = name; } public string GetName() { return Name; } } 5. Protected Internal Accessibility: The class or member is accessible within the same assembly and also to derived classes in other assemblies. Usage: Useful for situations where you want to expose class members to derived classes or within the assembly. 1 2 3 4 public class MyClass { protected internal string Name { get; set; } } 6. Private Protected Accessibility: The class or member is accessible within the same class or in derived classes that are in the same assembly. Usage: A more restrictive version of protected internal, useful for fine-grained access control. 1 2 3 4 public class MyClass { private protected string Name { get; set; } }

August 3, 2024 · 2 min · 405 words · PrashantUnity
Download Logo

ActionResult types

What is the difference between ‘ViewResult’ and ‘ActionResult’? In ASP.NET MVC, both ViewResult and ActionResult are classes that represent the result of an action method. The primary difference between them lies in their level of abstraction. ActionResult: ActionResult is the base class for all action results in ASP.NET MVC. It provides a high level of abstraction, allowing action methods to return various types of results, such as ViewResult, RedirectResult, JsonResult, etc. ...

August 3, 2024 · 2 min · 251 words · PrashantUnity
Download Logo

ADO.NET Q&A

1. What is ADO.NET? ADO.NET (ActiveX Data Objects) is a data access technology in the .NET framework used to interact with data sources, such as databases. It provides a set of classes for connecting to databases, executing commands (queries, updates), and retrieving results into datasets or data readers. 2. Differentiate between DataSet and DataReader DataSet: It’s an in-memory cache of data retrieved from the database. It can hold multiple DataTables, relationships, and constraints. It is disconnected, meaning it doesn’t need an active connection to the database once data is loaded. DataReader: It provides a read-only, forward-only stream of data from the database. It’s faster and uses less memory compared to DataSet but is less flexible as it doesn’t store data locally. 3. Explain the steps to connect to a database using ADO.NET To connect to a database using ADO.NET: ...

August 3, 2024 · 3 min · 437 words · PrashantUnity
Download Logo

App settings in .NET

Reading Configuration from appsettings.json 1 2 3 4 5 var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); var val =config["randomString"]; Binding Configuration to Static Classes 1 2 3 4 5 6 7 8 9 10 11 12 13 public static class RandomClass { public const string hello = "hello"; public static readonly string bello = "90"; static RandomClass() { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); bello = configuration["MySettings:Bello"]; } } 1. Add appsettings.json to Your Project Ensure you have an appsettings.json file in the root of your project. It might look something like this: ...

August 3, 2024 · 3 min · 434 words · PrashantUnity
Download Logo

ASP.NET Core middleware

How does middleware differ from HTTP modules in ASP.NET? Middleware in ASP.NET Core is a more flexible and lightweight approach compared to HTTP modules in traditional ASP.NET. Middleware can be added or removed easily in the application’s startup configuration. It allows for better control over the request pipeline and can be organized into a pipeline of components, whereas HTTP modules are more tightly coupled and don’t offer the same level of flexibility. ...

August 3, 2024 · 2 min · 414 words · PrashantUnity