Wednesday, June 7, 2023

Call Power BI API from .net Core API with Delegated Permissions

 If you want to consume Power BI API from .net Core API there are multiple ways of doing it. 

1. Call with Delegated Permission. 

2. Call with Service Principle. 

Certain endpoints cannot be called with Service Principle. Like you want to get the list of reports that caller user has access too. In this case, you'll need to use Delegated Permission. 

In order to achieve this in ASP.NET Core API,  you need to do the following 


1. Register an App in Azure. 

2. Go to API Permissions and select the Delegated Permissions for Power BI Service. 

3. In your API, you need to inject the following. 


3. Pay attention to the method "GetAccessTokenForUserAsync" used to get the delegated access and the ClaimPrincipal is passed in the method. 

4. This will give you the token which you can use to call the Power BI API. 




Thursday, May 4, 2023

Some Useful features - Microsot Devleoper World!!

 Here are some of the new and exciting features in Microsoft Dev World.

Some of them are available in preview. 

EF Core Power Tool - To generate DB Context

 Nice tool with a lots of customization to generate the DB Schema. 

EF Core Power Tools 

There are lot of material available on how to get started and it is very straight forward to start using it. 

Best thing I like about this and why I used it to customize the name of the Class which is being generated. If you have multiple table with the same name but in the different schema, by default the class name are appended with 1,2. 

For example,

If you have two tables, 

Local.Customer
Master.Customer

Then default EF core will generate the class name as Customer & Customer1. Not that intuitive. 

With EF Core Power Tools, You can customize the class name generation. 

Create a new file with the name "efpt.renaming.json" and put it inside the same folder as your "efpt.config.json".





    







You can also customize the columns inside a table. 

* If you are renaming multiple tables from a single schema, add all of them in the same Tables array. 

 I would try to create a small video some time and share the link.

Until next Cheers!


 

 


Tuesday, January 25, 2022

Tips for faster angular Development

  • Use Host Module Replacement
    • ng serve --hmr  
  • Open browser automatically
    • ng serve --hmr -o
  • Have multiple terminal Open in VS Code.

Thursday, January 20, 2022

Angular Error - Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime

Mostly this happens when there is conflict in the npm version installed vs the version which is your project using.

Best way worked for me is to uninstall node-saas and install saas. 

Commands to follow


1. npm uninstall node-sass

2. npm install sass

Thanks!



Wednesday, September 8, 2021

Administer Port Exclusion

 There might be instances when you cannot use a port. You end up getting the error that port is in use. However, no process using that port. 

That could be because those ports might be reseverd. you can check it using the following command

netsh int ip show excludedportrange protocol=tcp

If you see your port there, you can clear those reservation using the following command

net stop winnat

Tuesday, September 7, 2021

Docker Desktop - Error message when trying to switch to windows container

 Exception:

System.ServiceProcess.TimeoutException:
Time out has expired and the operation has not been completed.
at System.ServiceProcess.ServiceController.WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout)
at Docker.Backend.Processes.WindowsDockerDaemon.TryToStartService(Settings settings, String args, Dictionary`2 env) in C:\workspaces\master-merge\src\github.com\docker\pinata\win\src\Docker.Backend\Processes\WindowsDockerDaemon.cs:line 208
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.b__0(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()


Solution:

Remove the readonly flag of the following file. 

C:\ProgramData\Docker\panic.log

Don't know the connection but it works :)


Thursday, August 12, 2021

Change URL of Git Repo

 To change the URL of Git Repo from one to another is


run 

git remote -v

to see existing URL from within your repo folder.

run 

git remote set-url origin {newURL}


Done!

You can run git remote -v again to make sure that update is successful.




Wednesday, June 23, 2021

Change Detection Strategy - Angular

 Each of the angular component uses Default change detection policy by default. UI keep checking for the change continuously. Which many times affect the performance of the component and overall product. 

There is a way you can control this by setting the Change Detection for your component. 


How to find out the effect Change detection is putting on your control.

Override ngAfterViewChanged event on your component and use code similar to below. 

  ngAfterViewChecked(){
    this._ngZone.runOutsideAngular(() => {
      if(this.divElement.nativeElement)
      {
      this.divElement.nativeElement.classList.add('highlight')
      setTimeout(() => {
        this.divElement.nativeElement.classList.remove('highlight')
      }, 1500)
    }
    })

  }


Inject "private _ngZone : NgZone" to your constructor. 

divElement is the Element in your html. 

and highlight-css , change the background color of the div with css. 

You will see how many times the event fires. 


Changing the Default Change Detection:

- You can change the default change detection by setting the changeDetection to OnPush in your Component declaration. 

Ref:

https://medium.com/ngconf/simplified-angular-change-detection-e74809ff804d

https://pankajparkar.github.io/demystifying-change-detection/#/default-strategy

Wednesday, June 2, 2021

Increase the number of files visible in Azure KUDU

 Problem: Kudu console doesnt show more than 400 files. 

Open kudu ,

go to console and run following command

window.localStorage['maxViewItems'] = 1000

refresh the page.


Wednesday, April 14, 2021

Docker Default Network Connectivity

*Make sure to set "bridge":"none" in "C:\ProgramData\Docker\config\daemon.json".

And Stop and Start Docker service using Stop-Service Docker and Start-Service Docker. 


Create a docker network using 

docker network create -d "transparent" tnet

make sure it got created

docker network ls

test it by running a sample container

docker run -it --network=tlan mcr.microsoft.com/windows/nanoserver:1903

You will end up on command prompt of the docker. 

run ipconfig and see if it is assigned proper ip by DHCP. 

and run the ping command to validate the internet connectivity.

Monday, March 8, 2021

Running prod Angular on Dev Machine

 Build your app using the prod flag. 

NG_BUILD_MANGLE=false node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng build --prod --aot


*NG_BUILD_MANGLE is used for performance troubleshooting. 

once done, go to dist directory and run npm i -g serve (if not already installed)

and then run serve -s. this will start the http server. 


Better you do performance troubleshooting in incognito mode where no chrome extension is loaded. I assumed you are using chome for performance troubleshooting :)

Wednesday, March 3, 2021

Showing network mapped drive in SQL Restore Database

 EXEC sp_configure 'show advanced options', 1;

GO

RECONFIGURE;

GO


EXEC sp_configure 'xp_cmdshell',1

GO

RECONFIGURE

GO


EXEC XP_CMDSHELL 'net use H: \\192.172.0.141\Downloads /User:username password '


You need /User if your shared drive requires authentication. Once this is done, You should be able to see H drive whle restoring the database. 


Tuesday, December 1, 2020

Set Azure App Servie Settings from Azure DevOps Pipeline

 There are instances where you need to set certain values in your Azure App Service Configuration Application Settings. You can do that through your release pipeline in Azure DevOps. 

There is a task available "Azure App Service Settings Task".

Add that task to your pipeline. Select the Azure Subscription, App Service Name, Resource Group and any slot if applicable. 

You need to set the value in the App Settings section. you need to provide the array as below. 

[
{
 "name": "himalkey1",
  "value": "himalvalueabcd",
  "slotSetting": false
},
{
 "name": "himalkey3",
  "value": "$(Variable1)",
   "slotSetting": false
}
]

In the example above, himalkey1 setting will be assigned the hard coded value. While himalkey3 will be assigned the value of Variable1. Variable1 is defined in the variable group.

Similarly, you can also set General settings and Connnection string for the Azure App. 


Sunday, July 26, 2020

A strongly-named assembly is required.

There are instances when you are try to use a nuget package in  your project and you end up with the error "A strongly-named assembly is required.". 

This is because you have given strong name to your assembly however the nuget package isn't strongly-named. Some of the nuget package release the strong-named versioned but not all. 

If you are hit with this road block, you can add a nuget package "StrongNamer". This nuget package will take care of signing the other assemblies. 

Saturday, July 25, 2020

Build Version Number in Azure DevOps

We migrated from TFS to Azure DevOps and hit with the road block to start the versioning from the same number where it left off in TFS.
Say TFS Last build number is : 1.0.0.91
then I want the next number in Azure to start with 1.0.0.92.

Here is how i cracked it.

Create a variable say V4 and set it's value to $[counter(92)].
and then you can use $(V4) in build version number. This variable is maintained per pipeline. and increment automatically any time a build is made.

There is another issue that you want to reset the 4th build number any time first 3 number changes. So you want your 4th Number relative to the first 3 version numbers.
For example,
your current number is 1.0.0.92
and you increment third number,
1.0.1.X, you don't want your X to be 93 next. you want it to start from 0. and same rule applies anytime you change other build number

Here is how you can change it.
Create 4 variables in build pipeline.
V1 => 1
V2 => 0
V3 => 0
V4 => $[counter(format('{0}.{1}.{2}',variables['V1'],variables['V2'],variables['V3']),0)]

Here V4 is defined as related to V1, V2 and V3. The value of the counter (V4) will be maintained per value of V1, V2 & V3 per pipeline. any time the the value of any V1, V2 & V3 changes, V4 will reset the counter to zero.

This will fix your problem of managing the build number for your builds.


Monday, May 25, 2020

Code Coverage for Azure DevOps



  1. In your Visual Studio solution, add a unit test project (end of name with Tests).
  2. Reference the Nuget package coverlet.msbuild which will be used as an extension of the dotnet test command used later.
dotnet test --configuration Release /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=./TestResults/Coverage/

reportgenerator -reports:.\TestResults\Coverage\coverage.cobertura.xml -targetdir:.\CodeCoverage -reporttypes:HtmlInline_AzurePipelines

  1. In Azure DevOps Pipeline Build, add a task .NET Core to perform unit tests and collect data on code coverage (via coverlet). This task will generate a coverage.cobertura.xml file in your test project folder, in Cobertura format which is supported by Azure DevOps.
    • Commande : Test
    • Path to projet(s) : **/*[Tt]ests/*.csproj
    • Arguments : --configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutput=./TestResults/Coverage/ /p:CoverletOutputFormat=cobertura
    • Publish test results and code coverage : checked
  2. Via the Marketplace, add the extension[ReportGenerator] (https://marketplace.visualstudio.com/items?itemName=Palmmedia.reportgenerator) (from Palmmedia) and this task in your Pipeline:
    • Reports : **/coverage.cobertura.xml
    • Target directory : CoverageReport
    • Report types: HtmlInline_AzurePipelines;Cobertura
    This task will generate an HTML report of the coverage code (supported by Azure), in the /CoverageReport folder.
  3. Add a task Publish code coverage results to publish the HTML report in a Coverage tab of the Build Summary.
    • Code coverage tool : Cobertura
    • Summary file : **/coverage.cobertura.xml
    • Report dyrectory : CoverageReport

Exclude Any assembly:
reportgenerator -assemblyfilters:-BuildLibrary -reports:.\TestResults\Coverage\coverage.cobertura.xml -targetdir:.\CodeCoverage -reporttypes:HtmlInline_AzurePipelines

+ to include and - to exclude and Name of the assembly without extension.
File Filter:

reportgenerator -filefilters:-*Reference.cs* -reports:.\TestResults\Coverage\coverage.cobertura.xml -targetdir:.\CodeCoverage -reporttypes:HtmlInline_AzurePipelines

Ref:

Azure DevOps and the Code Coverage


Wednesday, May 6, 2020

How to set ArrAffinity cookie SameSite attribute to None for Azure App Service with web.config


<system.webServer>
  <rewrite>
    <outboundRules>
      <rule name="Add SameSite Cookie Flag to ArrAffinity cookie" enabled="true">
        <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" />
        <!--pattern="ARRAffinity=.*\/;.*"-->
        <conditions>
          <!-- <add input="{R:0}" pattern="SameSite=(Lax|Strict|None)" ignoreCase="true" negate="true" /> -->
          <add input="{R:0}" pattern="ARRAffinity=(.*)" ignoreCase="true" negate="true" />
          <add input="{HTTP_USER_AGENT}" pattern="Macintosh; Intel Mac OS X 10_14.+Version/.*Safari" ignoreCase="true" negate="true" />
          <add input="{HTTP_USER_AGENT}" pattern="CPU iPhone OS 12" ignoreCase="true" negate="true" />
          <add input="{HTTP_USER_AGENT}" pattern="iPad; CPU OS 12" ignoreCase="true" negate="true" />
        </conditions>
        <action type="Rewrite" value="{HTTP_COOKIE};Path=/;HttpOnly;SameSite=None;secure" />
      </rule>
    </outboundRules>
  </rewrite>
</system.webServer>



Credit to Clover Zhang @Microsoft. 

Thursday, April 30, 2020

If you get internet not available while running powershell script

You may get error like
WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.
WARNING: Unable to download the list of available providers. Check your internet connection.
PackageManagement\Get-PackageProvider : Unable to find package provider 'NuGet'. It may not be imported yet. Try 
'Get-PackageProvider -ListAvailable'.

At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:7415 char:30


Open Powershell in admin mode and run following command.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Tuesday, April 21, 2020

JSON Variable Substitution in Azure DevOps

for the JSON file with Array,

{
"City"[
{
"Name": "Sydney"
},
"Name": " Melbourne"
]
}

If you want to replace say Sydney with Perth, you need to create the variable Name as

City.0.Name

To access Melbourne,
City.1.Name

Arrays should be accessed using index and should go with . (dot) in the variable name.

I'm using File Transform Task in Azure DevOps.

ref:
JSON variable substitution example