In Power Bi, there is challenge to get page details when changing the pages. In Angular/JavaScript, powerBI client provides event handling to manage this. For this page changes, we have "pageChanged" event. Below sample code will help us to get events on page changes, so that you can capture bookmark if needed on previous page names etc.,
Important codings & concepts in web & window applications using microsoft technologies.
Friday, July 21, 2023
How to get previous page details in page change event on embedded PowerBI report
Thursday, March 9, 2023
Regex - To find word startswith __ and endswith __ but does not contain __
Regex to match words start with double underscore (__) and endswith double underscore (__), but should not contains double underscore (__)
Pattern: /\_\_[^_\n]{1}.*?([^_\n]+)\_\_/g
This will match __somekey__ , __some_key__, but not __some__key__, insted it will match __some__
Friday, January 13, 2023
How to cancel any running task by wait for sometime in C#
Problem Statement: In some real time scenario, you may need to cancel some long running tasks in certain time interval and then proceed.
Here in below example, i am calling some infinite time method and am not sure when it will be completed. So i am making 30 seconds maximum to wait and cancelling it.
RunSomeTestJob();
string RunSomeTestJob()
{
string result = "";
//loop your logic
try
{
Console.WriteLine("Running Job Started " + DateTime.Now.ToString());
// Create CancellationTokenSource.
var source = new CancellationTokenSource();
// ... Get Token from source.
var token = source.Token;
var someTask = Task.Run(() =>
{
result =
infinteJobWork(token);
}, token);
someTask.Wait(30 *
1000);
//someTask.Dispose();
source.Cancel();
}
catch (Exception ex)
{
//suppress error and proceed
//log somewhere
}
Console.Write("Running Job Completed " + result + DateTime.Now.ToString());
Console.Read();
//proceed with next steps
return result;
}
string
infinteJobWork(CancellationToken token)
{
//Short running Job - Fixed timing
//for (int i = 0; i < 3; i++)
{
//Long running Job - Indefinite time
while (true)
{
//TODO: make some api call or some work to external api
Console.WriteLine("Running Job : " + DateTime.Now.ToString());
Thread.Sleep(5 *
1000);
// See if we are canceled from our CancellationTokenSource.
if
(token.IsCancellationRequested)
{
Console.WriteLine("Job cancelled");
return "Job cancelled";
}
}
}
//return "Job done";
}
Wednesday, July 6, 2022
Export Website as PDF - Using Headless browser
There are many way we can download website html in C# and export it as PDF or however we wanted. But most of these ways not having option to render complete JavaSript and render the page fully.
Option 1:
Simply use WebClient and export website into html then to PDF
using (WebClient client = new WebClient())
{
byte[] websiteData = client.DownloadData("somewebsiteurl");
File.WriteAllBytes(“savepath”, websiteData);
//do further steps to convert html to pdf
}
Option 2:
Use Headless browser with Puppetter to export as PDF from URL, here you can add more wait handlers to render the JavaScript
Ref:
https://developer.chrome.com/docs/puppeteer/
https://www.puppeteersharp.com/
Using JS:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'example.png' });
await browser.close();
})();
Using C#:
using var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(
new LaunchOptions { Headless = true });
await using var page = await browser.NewPageAsync();
await page.GoToAsync("http://www.google.com");
await page.ScreenshotAsync(outputFile);
Note: we can also use installed browsers for exporting website as below
Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
Args = "{ "--disable-features=site-per-process", "--disable-web-security" }",
ExecutablePath = “any chromimum browser exe path”
});
Wednesday, June 22, 2022
Angular Ng Build out of memory issue
If you come accross issue with Angular ng build in prod mode for out of memory issue, like below
Command: ng build --prod
Include command with "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/", you can increase the size however wanted. This will solve the issue, we can also update this size in environment variables of system.
Command: node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod
Monday, April 25, 2022
JSON Path to use in Angular Projects
How to use JSON Path to query any JSON object.
For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON
this.obj ={
id: 1,
"name": "balaji"
}
For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/
this.objData = {
data: [
{
"id": 1,
"name": "Balajiprasad",
"age": 18,
"address": {
"state": "TN",
"country": "India"
}
},
{
"id": 2,
"name": "prasad",
"age": 28,
"address": {
"state": "Tx",
"country": "US"
}
}
]}
In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath
Steps to use,
1. Add "json-path" in package.json file under dependencies
"dependencies": {
"jsonpath": "1.1.1"
}
2. Add reference of "json-path" directly in component. No need to specify in App.module
import * as jp from 'jsonpath'
3. Use the JSON path in code , need to use $.. (double dots)
let state = jp.query(this.objData, '$..data[0].address.state')
Tuesday, April 12, 2022
Excel - Find sum of all digits to single digit
In excel, use below formula to get sum of all digits into single digit (For ex: 3268 -> Total 1). This is useful to findout vehicle number's total.
Formula: =IF(MOD(A1,9)=0,"9",MOD(A1,9))
Wednesday, December 15, 2021
AI Based PDF OCR using Microsoft Azure Form Recognizer
In real world, we will have many PDF files to read the content and prefill the forms in web application. To automatically read this PDF and predict the values, Microsoft offering cognitive service called Form Recognizer. Using this service, we can pass our PDF file and get the extracted OCR values as JSON back with bounding box coordinates.
Ref: https://azure.microsoft.com/en-in/services/form-recognizer/#features
We can use some custom libraries to highlight the bounding box coordinates in UI over the image. For this we can convert PDF into images and display it in UI as well.
For ex:
https://www.w3schools.com/tags/tag_map.asp
Sample JSON extracted: Highlighted sample bounding box coordinates.
{"status":"succeeded","createdDateTime":"2021-02-23T05:09:00Z","lastUpdatedDateTime":"2021-02-23T05:09:11Z","analyzeResult":{"version":"2.1.0","readResults":[{"page":1,"angle":0,"width":1700,"height":2200,"unit":"pixel","lines":[{"text":"CONTOSO LTD.","boundingBox":[114,134,466,134,466,175,115,175],"words":[{"text":"CONTOSO","boundingBox":[115,135,333,134,333,176,115,176],"confidence":0.994},{"text":"LTD.","boundingBox":[357,134,465,134,465,176,358,176],"confidence":0.994}],"appearance":{"style":{"name":"other","confidence":0.878}}},{"text":"INVOICE","boundingBox":[1410,114,1601,115,1601,155,1410,155],"words":[{"text":"INVOICE","boundingBox":[1411,115,1593,115,1592,156,1411,155],"confidence":0.995}],"appearance":{"style":{"name":"other","confidence":0.878}}},.......}
Monday, September 13, 2021
Browser - Change Current Geo Location
In order to test different Geo Location in browser, we have option to change location in browser. Follow below steps,
Browsers used: Chrome, IE Edge
- Go to Developer Tools (Click F12)
- Click ... Settings Icon -> More Tools -> Sensors
- Now in Sensors Window, Change the location as needed. You can also manage for new locations.
Monday, August 24, 2020
SQL - Modify Array of JSON
How to copy one array of JSON object into another array of JSON in SQL. Take this below sample copy array of empIds from one JSON into another JSON
DECLARE @pArrayOfIntEmps nvarchar(max)='{ "empIds": [' + '1,2'+'] }'
--JSON_Query will return array value from json whereas JSON_VALUE return object value from json
--select
JSON_QUERY(@pArrayOfIntEmps,'$.empIds')
DECLARE @info NVARCHAR(max)='{"id":1,"abc":false,"empIds":[3,4]
}'
SET @info= JSON_MODIFY(ISNULL(@info,'{}'),'$.empIds,JSON_QUERY(@pArrayOfIntEmps,'$.empIds'))
select @info
--Output {"id":1,"abc":false,"empIds":[1,2]
}, this empIds will be replaced by array of int