Replace absolute paths with relative paths in TypeScript files

Just some small Power Shell script to replace absolute paths with relative paths in TypeScript.
I needed this because inside an Angular Library NPM package we where using tsconfig ‘path mapping’,
but this caused some issues when using this library inside an angular application.

The script will changes TypeScript code like:

import { UserRouteAccessService } from 'folder-3/folder-4/folder-5/folder-6/shared/auth/user-route-access-service';

into

import { UserRouteAccessService } from '../shared/auth/user-route-access-service';

function changeAbsolutePathsToRelativePaths { $rootFolder = "C:\Dev\folder-1\folder-2\folder-3\folder-4\folder-5\folder-6" Set-Location $rootFolder $find = "'folder-3/folder-4/folder-5/folder-6/" # Files in the root folder should use "./" $replaceWithForRoot = "./" processFolder -folder $rootFolder -find $find -replaceWith $replaceWithForRoot } function processFolder { param($folder, $find, $replaceWith) $files = [System.IO.Directory]::GetFiles($folder) foreach ($file in $files) { replaceTextInFile -file $file -find $find -replaceWith $replaceWith } # Files in sub folders should use "../" if($replaceWith -eq "./") { $replaceWith = "" } $replaceWith = $replaceWith + "../" $subFolders = [System.IO.Directory]::GetDirectories($folder) foreach ($subFolder in $subFolders) { processFolder -folder $subFolder -find $find -replaceWith $replaceWith } } function replaceTextInFile { param($file, $find, $replaceWith) $text = [System.IO.File]::ReadAllText($file) $newText = $text.Replace($find, "'" + $replaceWith) if ($text -ne $newText) { Write-Host "Replace $find with $replaceWith in $file" [System.IO.File]::WriteAllText($file, $newText) } } changeAbsolutePathsToRelativePaths

How to use an Azure DevOps NuGet feed in Visual Studio Code and Visual Studio

If you want to use NuGet or npm packages from an Azure DevOps pipeline in Visual Studio Code, you can following these steps:

Prerequisites

You must first install the “Microsoft Azure Artifacts Credential Provider”.

https://github.com/Microsoft/artifacts-credprovider

On a Windows machine I installed it by:
– creating a file: C:\Temp\installcredprovider.ps1″.
– copying the code from “https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1” to it
– executed the file in a PowerShell prompt:

Set-Location "C:\Temp"
.\installcredprovider.ps1

Project

Add the feed to NuGet configuration

Add feed to your NuGet configuration by executing:

nuget.exe sources Add -Name “spike-feed” -Source “https://roelvanlisdonk.pkgs.visualstudio.com/_packaging/spike-feed/nuget/v3/index.json”

NOTE: use the exact line as found under > Artifacts > Connect to feed button:
In mine case: nuget.exe sources Add -Name “spike-feed” -Source “https://roelvanlisdonk.pkgs.visualstudio.com/_packaging/spike-feed/nuget/v3/index.json”

The name should really be the name of the feed, not some custom name.

Feed

Run dotnet restore once with –interactive to authenticate against the Azure DevOps feed

We have to execute dotnet restore with –interactive once, to authenticate against the Azure DevOps feed.

dotnet restore --interactive

After that you can use dotnet restore without manual authentication.
Now if you open the .NET Core solution in Visual Studio it will also work and you don’t have to do anything.

Angular – Test error – No base href set

When running a ng test with Angular v6.2.9 cli, I was getting the error:

Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.

This was fixed by adding the RouterTestingModule tot the TestBed TestingModule:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { RouterTestingModule } from '@angular/router/testing';

describe('AppComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
        declarations: [],
        imports: [
        AppModule,
        RouterTestingModule
        ]
    }).compileComponents();
}));

it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
    });
});

Change linked service / dataset connection string in an Azure Data Factory with PowerShell after deployment

When you connect an Azure Data Factory to GIT it will create json files per linked service, but the json file will contain some part of the connection string. If you want to change the connection string after deployment, you can use the following script.


# This script assumes the linked service json files can be found in the folder .\linkedService, relative to the location of this script.

param (
    [Parameter(Mandatory=$True)]
    [string]
    $ResourceGroupName,

    [Parameter(Mandatory=$True)]
    [string]
    $DataFactoryName,

    [Parameter(Mandatory=$True)]
    [string]
    $Find,

    [Parameter(Mandatory=$True)]
    [string]
    $Replace
)

$root = $PSScriptRoot
$scriptName = $MyInvocation.MyCommand.Name
Write-Host "$scriptName - start"

Write-Host "Get all linked service json file names"
$linkedServicesPath = "$root\linkedService"
$names = Get-ChildItem -Path "$linkedServicesPath" -Name

Write-Host "Loop file names"
foreach ($name in $names)
{
    Write-Host "Find the text [$Find] and replace with [$Replace] in the file [$path]."
    $path = [System.IO.Path]::Combine($linkedServicesPath, $name)
    (Get-Content -Path "$path" -Raw).Replace("$Find", "$Replace") | Set-Content -Path "$path"

    $linkedServiceName = [System.IO.Path]::GetFileNameWithoutExtension($name)
    Write-Host "Update the linked service [$linkedServiceName] on ResourceGroupName [$ResourceGroupName] in DataFactoryName [$DataFactoryName] by using File [$path] on Azure.."
    Set-AzureRmDataFactoryV2LinkedService -ResourceGroupName "$ResourceGroupName" -DataFactoryName "$DataFactoryName" -Name "$linkedServiceName" -File "$path"
}

Write-Host "$scriptName - end"

Example linked service json file:
Note: The sql server database connections, that I use, use MSI for authentication.

{
	"name": "MySqlDb1LinkedService",
	"type": "Microsoft.DataFactory/factories/linkedservices",
	"properties": {
		"type": "AzureSqlDatabase",
		"typeProperties": {
			"connectionString": "Integrated Security=False;Encrypt=True;Connection Timeout=30;Data Source=my-sql-server-v1.database.windows.net;Initial Catalog=MySqlDb1"
		}
	}
}

Select views that don’t reference other views in SQL Server

 

 

— Select views that don’t reference other views.

select

        s.[name]

,       v.[name]

from    sys.views v

join    sys.schemas s on v.schema_id = s.schema_id

where   v.object_id not
in (

    select distinct

                r.referenced_id

    from        sys.dm_sql_referenced_entities (s.[name] + ‘.’ + v.[name], ‘OBJECT’) r

    join        sys.objects o on r.referenced_id = o.object_id

    where       o.[type] = ‘V’

)

order by    s.[name], v.[name]

 

 

Select views that reference other views in SQL Server

 

— Select views that reference other views.

select distinct

            s.[name]

,           v.[name]

,           r.referenced_schema_name

,           r.referenced_entity_name

from        sys.views v

join        sys.schemas s on v.schema_id = s.schema_id

cross
apply sys.dm_sql_referenced_entities (s.[name] + ‘.’ + v.[name], ‘OBJECT’) r

join        sys.objects o on r.referenced_id = o.object_id

where       o.[type] = ‘V’

order by    s.[name], v.[name]

How to pass arguments to program, when debugging in Visual Studio Code

Found my answer at: https://github.com/Microsoft/vscode/issues/2167

You have to pass the arguments as individual string elements:

“args”: [


“–test”, “buildOutput/JavaScript1.js”,


“–env”, “devtest-chrome-win8”

]

My program needed a parameter -d and a parameter -s, so I changed the args to:

“args”: [


“-d”, “some value for d”,


“-s”, “some value for s”

]

And those parameters where picked up by the McMaster.Extensions.CommandLineUtils, that I used in the program.

Visual Studio Code – Multiple MSBuild project files found in ‘…’. Specify which to use with the –project option.

When developing, I like to have my tests in the same folder as the code and make the build process excluded test code for a production build (<Compile Remove=”**\*Test.cs” />).
So I created a .NET Core command line application in Visual Studio Code (my.command.line.csproj) and placed a test project file inside the samen folder (my.command.line.test.csproj).

my.command.line.csproj



<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>

<OutputType>Exe</OutputType>

<TargetFramework>netcoreapp2.2</TargetFramework>

</PropertyGroup>

<ItemGroup>

 <Compile Remove="**\*Test.cs" />


</ItemGroup>

</Project>

my.command.line.test.csproj


<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>

<TargetFramework>netcoreapp2.2</TargetFramework>

<IsPackable>false</IsPackable>

<GenerateProgramFile>false</GenerateProgramFile>

</PropertyGroup>

<ItemGroup>

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />

<PackageReference Include="MSTest.TestAdapter" Version="1.3.2" />

<PackageReference Include="MSTest.TestFramework" Version="1.3.2" />

</ItemGroup>

</Project>

Then I executed dotnet test

This will throw the following error:
Program.cs(10,27): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

This can be fixed by adding: <GenerateProgramFile>false</GenerateProgramFile> to a PropertyGroup inside the my.command.line.test.csproj.

Then when you execute dotnet test again, you will get the error:

MSBUILD : error MSB1011: Specify which project or solution file to use because this folder contains more than one project or solution file.

To fix it, execute:
dotnet test “my.command.line.test.csproj”

When you execute dotnet watch test, you will first get the error

Multiple MSBuild project files found in ‘C:\Dev\’. Specify which to use with the –project option.

You might want to fix it like: dotnet watch –project “my.command.line.test.csproj” test, but then the watcher will start watching but you will get the error:

MSBUILD : error MSB1011: Specify which project or solution file to use because this folder contains more than one project or solution file.

watch : Exited with error code 1

watch : Waiting for a file to change before restarting dotnet…

To fix this, execute dotnet watch –project “my.command.line.test.csproj” test “my.command.line.test.csproj”

Now your tests will be executed and the tests will be re-executed, when any of the files change.

How to fix: No IntelliSense for .NET Core C# files in VSCode

When using the C# 1.17.1 Visual Studio Code extension, I didn’t get correct IntelliSense for C# files.

There was a problem with Omnisharp. It outputted the error found below.

I also had Visual Studio Community 2017 installed and the Visual Studio Build Tools.

After uninstalling the Visual Studio Build Tools. Visual Studio Code asked me to install necessary build tools, after clicking “Yes” to install, the problem was fixed.

 

Error

Omnisharp error in VSCode: Could not load SDK Resolver. A manifest file exists, but the path to the SDK Resolver DLL file could not be found.

 

 

Starting OmniSharp server at 1/14/2019, 7:44:48 AM

Target: c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test

 

OmniSharp server started.

Path: C:\Users\roelv\.vscode\extensions\ms-vscode.csharp-1.17.1\.omnisharp\1.32.8\OmniSharp.exe

PID: 17140

 

[info]: OmniSharp.Stdio.Host

Starting OmniSharp on Windows 6.2.9200.0 (x64)

[info]: OmniSharp.Services.DotNetCliService

DotNetPath set to dotnet

[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator

Located 3 MSBuild instance(s)

1: Visual Studio Build Tools 2017 15.9.28307.280 – “C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin”

2: Visual Studio Community 2017 15.9.28307.280 – “C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin”

3: StandAlone 15.0 – “C:\Users\roelv\.vscode\extensions\ms-vscode.csharp-1.17.1\.omnisharp\1.32.8\msbuild\15.0\Bin”

[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator

Registered MSBuild instance: Visual Studio Build Tools 2017 15.9.28307.280 – “C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin”

[info]: OmniSharp.Cake.CakeProjectSystem

Detecting Cake files in ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test’.

[info]: OmniSharp.Cake.CakeProjectSystem

Could not find any Cake files

[info]: OmniSharp.WorkspaceInitializer

Project system ‘OmniSharp.DotNet.DotNetProjectSystem’ is disabled in the configuration.

[info]: OmniSharp.MSBuild.ProjectSystem

No solution files found in ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test’

[info]: OmniSharp.MSBuild.ProjectManager

Queue project update for ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj’

[info]: OmniSharp.Script.ScriptProjectSystem

Detecting CSX files in ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test’.

[info]: OmniSharp.Script.ScriptProjectSystem

Could not find any CSX files

[info]: OmniSharp.WorkspaceInitializer

Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpWorkspaceOptionsProvider

[info]: OmniSharp.WorkspaceInitializer

Configuration finished.

[info]: OmniSharp.Stdio.Host

Omnisharp server running using Stdio at location ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test’ on host 10684.

[info]: OmniSharp.MSBuild.ProjectManager

Loading project: c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj

[warn]: OmniSharp.MSBuild.ProjectManager

Failed to load project file ‘c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj’.

c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj(1,1)

Microsoft.Build.Exceptions.InvalidProjectFileException: Could not load SDK Resolver. A manifest file exists, but the path to the SDK Resolver DLL file could not be found. Manifest file path ‘C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\SdkResolvers\Microsoft.Build.NuGetSdkResolver\Microsoft.Build.NuGetSdkResolver.xml’. SDK resolver path: C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\CommonExtensions\Microsoft\NuGet\Microsoft.Build.NuGetSdkResolver.dll c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj

at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)

at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.TryAddAssemblyFromManifest(String pathToManifest, String manifestFolder, List`1 assembliesList, ElementLocation location)

at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.FindPotentialSdkResolvers(String rootFolder, ElementLocation location)

at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolvers(LoggingContext loggingContext, ElementLocation location)

at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.Initialize(LoggingContext loggingContext, ElementLocation location)

at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive)

at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.<>c__DisplayClass3_0.<ResolveSdk>b__0(String key)

at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)

at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive)

at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult, Boolean throwOnFileNotExistsError)

at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)

at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)

at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)

at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(ILoggingService loggingService, BuildEventContext buildEventContext)

at Microsoft.Build.Evaluation.Project.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)

at Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)

at Microsoft.Build.Evaluation.Project.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)

at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)

at Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)

at OmniSharp.MSBuild.ProjectLoader.EvaluateProjectFileCore(String filePath)

at OmniSharp.MSBuild.ProjectLoader.BuildProject(String filePath)

at OmniSharp.MSBuild.ProjectFile.ProjectFileInfo.Load(String filePath, ProjectLoader loader)

at OmniSharp.MSBuild.ProjectManager.LoadOrReloadProject(String projectFilePath, Func`1 loader)

 

[fail]: OmniSharp.MSBuild.ProjectManager

Attemped to update project that is not loaded: c:\Dev\GitHub\roelvanlisdonk\dev\c#\core\test\core.test.csproj