Download Logo

Java interview prep

Collections Framework Deep Dive 1️⃣ Why does HashMap allow one null key but Hashtable doesn’t? Short Answer: HashMap was designed for modern multi-threaded applications with null-safe design; Hashtable predates this and was optimized for thread-safety by rejecting nulls outright. Detailed Explanation: Hashtable uses the hashCode() method on every key. If you pass null, it throws a NullPointerException immediately—no comparison, no storage. This is intentional: it forces you to know your data upfront. ...

November 12, 2025 · 38 min · 7889 words · Aayush Bhardwaj
Download Logo

JSON to tree in C#

Handling Dynamic JSON with Variable Property Names Here is one way you can solve it 😁. Since json can have name and Several children so we can create Tree like node 1 2 3 4 5 public class JsonNode { public string Name {get;set;} public List<JsonNode> Child {get;set;} = []; } Below code generate tree using Recursion 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 using System; using System.Collections.Generic; using System.Text.Json; public static JsonNode BuildTree(JsonElement element, string nodeName) { var node = new JsonNode { Name = nodeName }; if (element.ValueKind == JsonValueKind.Object) { foreach (var property in element.EnumerateObject()) { node.Child.Add(BuildTree(property.Value, property.Name)); } } else if (element.ValueKind == JsonValueKind.Array) { int index = 0; foreach (var item in element.EnumerateArray()) { node.Child.Add(BuildTree(item, $"[{index}]") ); index++; } } else { node.Child.Add(new JsonNode { Name = element.ToString() }); } return node; } Here we we have sample code to initialize/ use the above code ...

February 24, 2025 · 2 min · 240 words · PrashantUnity
Download Logo

Learn C# — links

C# Learning Resources for Beginners Welcome to this comprehensive guide of C# programming resources! Whether you’re interested in game development, web applications, or general software development, these carefully curated resources will help you start your C# journey. This guide is organized by topic, from basic setup to advanced concepts, making it easy to find exactly what you need at each stage of your learning process. Official Documentation Start your C# journey with Microsoft’s official documentation - the authoritative source for everything C#. The documentation includes: ...

October 19, 2025 · 4 min · 685 words · PrashantUnity
Download Logo

Classes in C# (Ch. 11)

Class A class represents a blueprint of an object. Currently, we know some basic data types: For representing numbers, we use types like int, long, byte, decimal, etc. For representing words, we use string or arrays of characters (char[]). For storing collections of numbers, we use arrays (int[], float[], etc.). However, what about storing complex objects like Person, Planet, etc.? For example, a Person object might have properties like Name (a string), Age (an integer), and methods like IsCoding(). classDiagram class Person{ +Name +Age +IsCoding() } From the diagram above, we see that a class named Person encapsulates a contextual representation driven by developers. It defines properties and behaviors specific to a person, allowing us to model and work with such complex entities in code. ...

June 24, 2024 · 6 min · 1173 words · PrashantUnity
Download Logo

Org chart with Tailwind

Organizational Chart A simple Organizational chart using tailwind css 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modern Organizational Chart</title> <script src="https://cdn.tailwindcss.com"></script> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"> <style> :root { --color-blue: #6366f1; --color-teal: #2dd4bf; --color-orange: #fb923c; --color-pink: #f472b6; --color-sky: #38bdf8; --color-gray: #9ca3af; --color-indigo: #818cf8; } html, body { height: 100%; margin: 0; overflow: hidden; /* Prevents scrollbars on the body */ } body { font-family: 'Inter', sans-serif; background-color: #f1f5f9; color: #1e293b; display: flex; flex-direction: column; } .page-wrapper { /* New class for the main container div */ display: flex; flex-direction: column; flex-grow: 1; /* Allow this wrapper to grow and fill space */ min-height: 0; /* Fix for flexbox overflow issue in some browsers */ } .org-chart { display: flex; overflow: hidden; cursor: grab; user-select: none; background-color: #f8fafc; border-radius: 0.5rem; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); flex-grow: 1; /* Make the chart container fill available vertical space */ } .org-chart ul { padding-top: 30px; position: relative; display: flex; justify-content: center; } .org-chart > ul { transform-origin: 0 0; transition: transform 0.2s ease-out; } .org-chart li { text-align: center; list-style-type: none; position: relative; padding: 30px 10px 0 10px; transition: all 0.5s; } /* --- New Node Styling --- */ .node-wrapper { position: relative; display: inline-block; } .node-card { padding: 1rem 1.5rem; background-color: white; border-radius: 8px; display: inline-block; min-width: 160px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border-top: 4px solid; border-color: var(--node-color, var(--color-gray)); transition: all 0.3s ease; } .node-image { width: 64px; height: 64px; border-radius: 50%; border: 4px solid; border-color: var(--node-color, var(--color-gray)); background-color: white; position: absolute; top: 0; left: 50%; transform: translate(-50%, -50%); z-index: 1; } /* --- New Connecting Lines --- */ /* Vertical line coming DOWN from parent node */ .node-wrapper::after { content: ''; position: absolute; bottom: -30px; /* should match li top padding */ left: 50%; transform: translateX(-50%); width: 2px; height: 30px; background-color: #94a3b8; } /* Hide the downward line if node has no children or is collapsed */ .node-wrapper.no-children::after, li.collapsed .node-wrapper::after { display: none; } /* Vertical line going UP from child node */ .org-chart li::before { content: ''; position: absolute; top: 0; left: 50%; transform: translateX(-50%); width: 2px; height: 30px; background-color: #94a3b8; } /* Horizontal line connecting all children */ .org-chart li::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 2px; background-color: #94a3b8; } /* Remove lines for the root node */ .org-chart > ul > li::before, .org-chart > ul > li::after { display: none; } /* Adjust horizontal line for first and last child */ .org-chart li:first-child::after { left: 50%; width: 50%; } .org-chart li:last-child::after { width: 50%; } .org-chart li:only-child::after { display: none; } /* --- Collapsible styles --- */ .org-chart li > ul { display: flex; } .org-chart li.collapsed > ul { display: none; } .toggle-btn { position: absolute; bottom: -10px; left: 50%; transform: translateX(-50%); width: 20px; height: 20px; background-color: white; color: #475569; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: bold; cursor: pointer; border: 1px solid #cbd5e1; user-select: none; transition: all 0.3s ease; z-index: 10; } .toggle-btn:hover { background-color: #f1f5f9; transform: translateX(-50%) scale(1.1); } /* --- Advisory Node --- */ .advisory-node { position: absolute; top: 50%; left: 100%; transform: translateY(-50%); padding-left: 50px; } .advisory-connector { content: ''; position: absolute; top: 50%; left: 100%; width: 50px; height: 2px; background: #94a3b8; } .root-node-wrapper { position: relative; } </style> </head> <body class="bg-gray-100"> <main id="chart-container" class="org-chart"> <!-- Chart will be generated here by JavaScript --> </main> <script> const orgData = { name: 'Mr. Anderson', role: 'Director', color: 'var(--color-blue)', imageUrl: 'https://placehold.co/100x100/6366f1/ffffff?text=MA', advisory: { name: 'Advisory Committee', role: 'Guidance & Oversight', color: 'var(--color-gray)', imageUrl: 'https://placehold.co/100x100/9ca3af/ffffff?text=AC' }, children: [ { name: 'Mr. Robert', role: 'Deputy Director', color: 'var(--color-teal)', imageUrl: 'https://placehold.co/100x100/2dd4bf/ffffff?text=MR', children: [ { name: 'Head of Education', role: 'Team Lead', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=HE', children: [ { name: 'Lectures Team', role: 'Content Delivery', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=LT', children: [ { name: 'John Doe', role: 'Lecturer', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=JD'}, { name: 'Jane Smith', role: 'Lecturer', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=JS'} ]}, { name: 'Student Coordinators', role: 'Support', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=SC', children: [ { name: 'Peter Jones', role: 'Coordinator', color: 'var(--color-orange)', imageUrl: 'https://placehold.co/100x100/fb923c/ffffff?text=PJ'} ]} ] }, { name: 'Mark Davis', role: 'Senior Manager', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=MD', children: [ { name: 'Accounting', role: 'Finance', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=A', children: [ { name: 'Alice Williams', role: 'Accountant', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=AW' } ]}, { name: 'Operational Staff', role: 'Execution', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=OS', children: [ { name: 'Bob Brown', role: 'Operator', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=BB' }, { name: 'Charlie Green', role: 'Operator', color: 'var(--color-pink)', imageUrl: 'https://placehold.co/100x100/f472b6/ffffff?text=CG' } ]} ] }, { name: 'Technicians', role: 'Technical Support', color: 'var(--color-sky)', imageUrl: 'https://placehold.co/100x100/38bdf8/ffffff?text=T', children: [ { name: 'Maintenance Staff', role: 'Infrastructure', color: 'var(--color-sky)', imageUrl: 'https://placehold.co/100x100/38bdf8/ffffff?text=MS', children: [ { name: 'David White', role: 'Technician', color: 'var(--color-sky)', imageUrl: 'https://placehold.co/100x100/38bdf8/ffffff?text=DW' } ]}, { name: 'IT Support', role: 'Helpdesk', color: 'var(--color-sky)', imageUrl: 'https://placehold.co/100x100/38bdf8/ffffff?text=IT' } ] }, { name: 'Sarah Miller', role: 'HR Manager', color: 'var(--color-indigo)', imageUrl: 'https://placehold.co/100x100/818cf8/ffffff?text=SM', children: [ { name: 'Recruitment', role: 'Talent Acquisition', color: 'var(--color-indigo)', imageUrl: 'https://placehold.co/100x100/818cf8/ffffff?text=R' }, { name: 'Employee Relations', role: 'Internal Affairs', color: 'var(--color-indigo)', imageUrl: 'https://placehold.co/100x100/818cf8/ffffff?text=ER' } ] } ] }, ] }; function createNode(person) { const li = document.createElement('li'); const wrapper = document.createElement('div'); wrapper.className = 'node-wrapper'; if (!person.children || person.children.length === 0) { wrapper.classList.add('no-children'); } const img = document.createElement('img'); img.src = person.imageUrl; img.alt = `Profile picture of ${person.name}`; img.className = 'node-image object-cover'; img.style.borderColor = person.color; const nodeDiv = document.createElement('div'); nodeDiv.className = 'node-card'; nodeDiv.style.borderColor = person.color; const nameDiv = document.createElement('div'); nameDiv.className = 'font-bold text-slate-700 text-md pt-6'; nameDiv.textContent = person.name; const roleDiv = document.createElement('div'); roleDiv.className = 'text-sm text-slate-500'; roleDiv.textContent = person.role; nodeDiv.appendChild(nameDiv); nodeDiv.appendChild(roleDiv); wrapper.appendChild(img); wrapper.appendChild(nodeDiv); if (person.children && person.children.length > 0) { const toggleBtn = document.createElement('span'); toggleBtn.className = 'toggle-btn'; toggleBtn.textContent = '−'; wrapper.appendChild(toggleBtn); toggleBtn.addEventListener('click', (e) => { e.stopPropagation(); const parentLi = e.target.closest('li'); parentLi.classList.toggle('collapsed'); e.target.textContent = parentLi.classList.contains('collapsed') ? '+' : '−'; }); } li.appendChild(wrapper); return li; } function createAdvisoryNode(person, parentWrapper) { const advisoryWrapper = document.createElement('div'); advisoryWrapper.className = 'advisory-node'; const nodeLi = createNode(person); // remove connector pseudo elements from this special node nodeLi.style.padding = 0; nodeLi.querySelector('.node-wrapper').classList.add('no-children'); advisoryWrapper.appendChild(nodeLi); parentWrapper.appendChild(advisoryWrapper); const connector = document.createElement('div'); connector.className = 'advisory-connector'; parentWrapper.appendChild(connector); } function buildChart(person, parentElement, level = 0) { const node = createNode(person); parentElement.appendChild(node); // Add a wrapper for the root node to position advisory node correctly if(level === 0) { const rootWrapper = node.querySelector('.node-wrapper'); rootWrapper.classList.add('root-node-wrapper'); if(person.advisory) { createAdvisoryNode(person.advisory, rootWrapper); } } if (level >= 1) { node.classList.add('collapsed'); const toggleBtn = node.querySelector('.toggle-btn'); if (toggleBtn) toggleBtn.textContent = '+'; } if (person.children && person.children.length > 0) { const childUl = document.createElement('ul'); node.appendChild(childUl); person.children.forEach(child => buildChart(child, childUl, level + 1)); } } const chartContainer = document.getElementById('chart-container'); const rootUl = document.createElement('ul'); chartContainer.appendChild(rootUl); buildChart(orgData, rootUl); // --- Pan and Zoom Logic --- const chart = chartContainer.querySelector('ul'); let scale = 1; let panning = false; let pointX = 0; let pointY = 0; let start = { x: 0, y: 0 }; function setTransform() { chart.style.transform = `translate(${pointX}px, ${pointY}px) scale(${scale})`; } window.addEventListener('load', () => { const containerWidth = chartContainer.offsetWidth; const chartWidth = chart.offsetWidth; pointX = (containerWidth - chartWidth) / 2; pointY = 50; // Add some initial top padding setTransform(); }); chartContainer.onmousedown = function (e) { if (e.target.closest('.toggle-btn, .node-card a')) return; e.preventDefault(); panning = true; start = { x: e.clientX - pointX, y: e.clientY - pointY }; chartContainer.style.cursor = 'grabbing'; }; chartContainer.onmouseup = function () { panning = false; chartContainer.style.cursor = 'grab'; }; chartContainer.onmouseleave = function () { panning = false; chartContainer.style.cursor = 'grab'; }; chartContainer.onmousemove = function (e) { if (!panning) return; e.preventDefault(); pointX = e.clientX - start.x; pointY = e.clientY - start.y; setTransform(); }; chartContainer.onwheel = function (e) { e.preventDefault(); const xs = (e.clientX - pointX) / scale; const ys = (e.clientY - pointY) / scale; const delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY); (delta > 0) ? (scale *= 1.1) : (scale /= 1.1); scale = Math.max(0.3, Math.min(scale, 2)); // Clamp scale pointX = e.clientX - xs * scale; pointY = e.clientY - ys * scale; setTransform(); }; </script> </body> </html>

Google Sheets Integration

Sheets CRUD service

Overview The GenericGoogleSheetsService is a powerful .NET service that provides a complete CRUD (Create, Read, Update, Delete) interface for Google Sheets integration. This service eliminates the need to write boilerplate code for each entity type by using generic programming and reflection to automatically map between your C# objects and Google Sheets rows. Link to GitHub Repository: GenericGoogleSheetsService on GitHub Key Features Generic Type Support: Works with any class that implements IEntityWithId and has a parameterless constructor Automatic Type Mapping: Uses reflection to map property names to Google Sheets columns Complete CRUD Operations: Create, Read, Update, and Delete operations with async support Flexible Authentication: Supports both JSON credentials and service account file paths List Property Support: Handles List<string> properties with custom delimiters Error Handling: Graceful error handling with detailed logging Multiple Sheet Support: Can work with different sheets within the same spreadsheet Use Cases Data Synchronization: Keep your application data synchronized with Google Sheets Reporting: Export application data to Google Sheets for analysis Configuration Management: Store application configuration in Google Sheets Data Backup: Use Google Sheets as a backup storage solution Collaborative Data Entry: Allow multiple users to edit data through Google Sheets Prerequisites Before implementing this service, ensure you have: ...

Download Logo

Lists to Excel

Creating Excel File from List With Different Sheet With Naming nuget package used OpenXML 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 public static MemoryStream WriteMultipleListsToExcel_OpenXml(params (string sheetName, IEnumerable<object> list)[] sections) { var memoryStream = new MemoryStream(); using (var spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook)) { var workbookPart = spreadsheetDocument.AddWorkbookPart(); workbookPart.Workbook = new Workbook(); var workbookProps = new WorkbookProperties() { DefaultThemeVersion = 124226 }; // Ensure workbook properties workbookPart.Workbook.AppendChild(workbookProps); var sheets = workbookPart.Workbook.AppendChild(new Sheets()); uint sheetId = 1; foreach (var (sheetName, list) in sections) { var worksheetPart = workbookPart.AddNewPart<WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData()); var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = sheetId++, Name = sheetName }; sheets.Append(sheet); var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); var type = list.GetType().GetGenericArguments()[0]; var properties = type.GetProperties(); // Add header row var headerRow = new Row(); foreach (var prop in properties) { headerRow.Append(CreateTextCell(prop.Name)); } sheetData.Append(headerRow); // Add data rows foreach (var item in list) { var dataRow = new Row(); foreach (var prop in properties) { var value = prop.GetValue(item)?.ToString() ?? string.Empty; dataRow.Append(CreateTextCell(value)); } sheetData.Append(dataRow); } worksheetPart.Worksheet.Save(); } workbookPart.Workbook.Save(); } memoryStream.Position = 0; return memoryStream; } private static Cell CreateTextCell(string value) { return new Cell { CellValue = new CellValue(value), DataType = CellValues.String }; } Use of Above Function lets Suppose we have Below Class ...

Download Logo

Tables in Polyglot

Setup Polyglot Notebook Environment Import nuget package 1 #r "nuget: Microsoft.Data.Analysis" Import namespace 1 2 3 using System; using System.Collections.Generic; using Microsoft.Data.Analysis; Create class 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class RedirectEntry { public string WebsiteUrl { get; set; } public string RedirectUrl { get; set; } public string Status => IsValid ? "✅" : "❌"; public bool IsValid { get; set; } } var data = new List<RedirectEntry> { new RedirectEntry { WebsiteUrl = "https://codefrydev.in/Updates", RedirectUrl = "https://codefrydev.in/", IsValid = true }, }; Create Generic Function for any type of list injection 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 DataFrame ShowTable<T>(List<T> items) { var properties = typeof(T).GetProperties(); List<DataFrameColumn> columns = new(); foreach (string header in properties.Select(p => p.Name)) { columns.Add(new StringDataFrameColumn(header, new List<string>())); // Read as string } foreach(var item in items) { for (int i = 0; i < properties.Length; i++) { var values = properties.Select(p => p.GetValue(item)?.ToString() ?? "").ToList(); ((StringDataFrameColumn)columns[i]).Append(values[i]); } } return new DataFrame(columns); } Simply call the function in next cell without any commas or stuff 1 ShowTable(data)

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