2020-07-03 Learned Today

 

Depending on the right PowerShell NuGet package in your .NET project

https://devblogs.microsoft.com/powershell/depending-on-the-right-powershell-nuget-package-in-your-net-project/

So for running PowerShell from within a .NET Core application it is best to use the PowerShell SDK package.

 

How easily map properties from one type to another in .NET Core

https://www.c-sharpcorner.com/article/mapping-similar-objects-in-asp-net-core-2-0/

 

How to run a .NET Core web application under IIS

 

Make sure you give, your application pool rights to the application folder.

IIS AppPool\<<MyApplicationPoolName>>>

Note you can’t browse for this account, because it is not a “real” windows account.

You must put it in the textarea: “Enter the object name to select (examples):

Then click on “Check Names”

 

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1

 

If you get the error below, when running a .NET Core application under IIS, make sure you have called “UseIISIntegration”, inside de Program.cs:

 

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Hosting;

 

namespace MyDotNetAppUnderIIS

{

    public class Program

    {

        public static void Main(string[] args)

        {

            CreateHostBuilder(args).Build().Run();

        }

 

        public static IHostBuilder CreateHostBuilder(string[] args) =>

            Host.CreateDefaultBuilder(args)

                .ConfigureWebHostDefaults(webBuilder =>

                {

                    webBuilder

                    .UseIISIntegration()

                    .UseStartup<Startup>();

                });

    }

}

 

 

 

HTTP Error 403.14 – Forbidden

The Web server is configured to not list the contents of this directory.

 

Fix https certificate error, when running an Angular .NET Core 3.1 application within IIS

If you run an Angular .NET Core 3.1 application within IIS, make sure you enable the correct HSTS settings:

  • HSTS Enabled = True
  • Redirect Http to Https: True

 

 

 

2020-07-02 Learned Today

 

How to map a network drive with PowerShell

Note: The driveName does NOT have to be a letter it can be multiple characters, like DataDrive instead of Z.

param (

    [String$driveName = “Z”,

    [String$networkPath = “\\Localhost\c$”

)

 

$drive = “$($driveName):”

$driveExists = Test-Path “$($drive)”

If ($driveExists -eq $False) {

    Write-Output “Map network drive $($drive) started”

    New-PSDrive -Name $driveName -Root “$($networkPath)” -PSProvider FileSystem -Scope Global -Persist:$true

else {

    Write-Output “Network drive $($drive) exists”

}

 

 

Install a NPM package globally for all users on a Windows machine

 

https://stackoverflow.com/questions/38570209/making-global-npm-packages-available-to-all-users-on-windows-2012-server

 

 

Write-Host vs Write-Output vs Write-Information

If you want to log information form a PowerShell script and you want to ouput it to the default output stream, but also to the “Information” output stream, you can use Write-Host, instead of Write-Output or Write-Information

I use Write-Host, when the script was executed by a .NET Core application, to see the progress of the PowerShell script during execution.

 

Execute a PowerShell script with PowerShell 7

When you want to execute a PowerShell script with the PowerShell 7 executable, you can use a link in the same folder as the script without setting the “Start in” property.

Just put this in the target: “C:\Program Files\PowerShell\7\pwsh.exe” -NoExit “.\my-script.ps1”

Now you can easily share the *.lnk file.

 

 

2020-06-30 Learned Today

 

Fixing: Container cannot be copied onto existing leaf item

Strange behaviour, when copying all files and subfolders to a non-existing folder with PowerShell.

I made a mistake and tried to accidentally copy all files and folder to a non-existing folder with PowerShell, by executing:

Copy-Item -Path “C:\FilesAndFolderToBeCopied\*” -Destination “C:\MyNonExistingFolder” -Force -Recurse

Some files were copied, but then the error was thrown “Container cannot be copied onto existing leaf item”.

By creating the destination folder before copying, this error was resolved.

 

Fix: ReferenceError: primordials is not defined

Upgrade to NPM >= 12 and Gulp >= 4.0

 

How to overwrite PublishProfile => FolderProfile.pubxml => PublishUrl during a dotnet build or dotnet publish

To overwrite the PublishUrl during a publish of a .NET Core Web Application use the -o parameter:

dotnet build “C:\PathTo\MyApplication.csproj” /p:DeployOnBuild=true /p:PublishProfile=”Properties\PublishProfiles\FolderProfile.pubxml” -c Release -o “C:\Temp\MyApplication”

 

But we decided to NOT use the FolderProfile.pubxml anymore and just pass the parameter on the commandline:

dotnet publish “C:\PathTo\MyApplication.csproj” -c Release -f “netcoreapp2.2” -o “C:\Temp\MyApplication” -r “win-x64” –self-contained true | Write-Output

 

We decided to NOT use the FolderProfile.pubxml in .NET 2.2, because we observed some problems, when overwriting the publishUrl with “-o”, it would still use the “publishUrl” from the FolderProfile.pubxml.

When passing only the commands on the commandline, this problem was resolved.

2020-06-29 Learned Today

 

How to fix: Could not run the “GenerateResource” task because MSBuild could not create or connect to a task host with runtime “CLR4” and architecture “x86”

 

C:\Program Files\dotnet\sdk\3.1.301\Microsoft.Common.CurrentVersion.targets(3032,5):

error MSB4216: Could not run the “GenerateResource” task because MSBuild could not create or connect to a task host with runtime “CLR4” and architecture “x86”.

Please ensure that (1) the requested runtime and/or architecture are available on the machine, and (2) that the required executable “C:\Program Files\dotnet\sdk\3.1.301\MSBuild.exe” exists and can be run. [C:\…….csproj]

C:\Program Files\dotnet\sdk\3.1.301\Microsoft.Common.CurrentVersion.targets(3054,7): error MSB4028: The “GenerateResource” task’s outputs could not be retrieved from the “FilesWritten” parameter. Object does not match target type. [C:\……csproj]

……. -> C:.…..dll

 

I was using dotnet build, to build a solution that contained not only .NET Core applications.

To fix the problem I added the specific project I wanted to build to the dotnet build command: dotnet build “path to the csproj file”.

2020-06-26 Learned Today

    

Always disable network cache in Chrome, when developing

 

I had strange behaviour of the Chrome debugger in the Chrome developer tools.

Turned out I changed some TypeScript refreshed the page, but somehow the “Disable cache” checkbox was unchecked.

After checking this checkbox and refreshing the page, the strange behaviour was resolved.

How to resolve git merge conflicts after a git stash pop

 

https://stackoverflow.com/questions/7751555/how-to-resolve-git-stash-conflict-without-commit

 

 

2020-06-25 Learned Today

 

INSERT and DELETE statements inside an EF SaveChanges are executed sequentially

 

I wondered if DELETE and INSERT statements inside an EF SaveChanges might conflict with each other.

By conflicting I mean, when I delete a specific record in a table and after that insert the exact same table, could de insert statement be executed before the delete statement in one SaveChanges, but luckily this is not the case.

 

How to add a data dash attribute to an Html.CheckBoxFor

 

@Html.CheckBoxFor(model => car.Color, new { @data_owner = “Some owner name”, })

 

How to disable an input element by using JQuery

 

https://learn.jquery.com/using-jquery-core/faq/how-do-i-disable-enable-a-form-element/

2020-06-24 Learned Today

 

Setup PowerShell remoting

To setup a PowerShell remoting session from a Windows 10 laptop to a Windows 2008 R2 machine in an other domain, I used the following steps from:

https://4sysops.com/wiki/enable-powershell-remoting/ and added some steps for my specific situation.

 

(for this guide, all PowerShell consoles should be run in “Administrator” mode)

 

Windows 2008 R2 machine

Before I could install PowerShell 7 on a Windows 2008 R2 SP1 machine, I had to install:

WMF 4.0

I didn’t install WMF 5.1 yet, because it threw an error (may be this is fixed after WMF 4.0 installation, but I did not check yet)

https://docs.microsoft.com/nl-nl/powershell/scripting/windows-powershell/wmf/overview?view=powershell-7

 

Step 1 Install PowerShell

Install PowerShell 7.0.2

On installation check the box “Enable PowerShell remoting”

 

Step 2 Enable PowerShell remoting

On the Windows 2008 R2 machine I executed the following command inside the “out of the box PowerShell” and in the PowerShell 7 console:

Enable-PSRemoting -Force

 

Step 3 Enable the WinRM Service

Computer Configuration > Policies > Administrative Templates > Windows Components > Windows Remote Management (WinRM) > WinRM Service > Allow remote server management through WinRM

You have to enable this policy and set the IPv4/IPv6 filters to all (*).

 

Step 4 Check the Windows Remote Management Service

In the services.msc I checked it the “Windows Remote Management service” was running and startup mode was set to Automatic.

 

Step 5 Allow Windows Remote Management in the Firewall

Navigate to the following folder in the Group Policy Management Console (GPMC), right-click Inbound Rules, and click New Rule.

Computer Configuration > Policies > Windows Settings > Security Settings > Windows Firewall with Advanced Security

In the Predefined field, select Windows Remote Management and then follow the wizard to add the new firewall rule.

 

Step 6 Allow inbound remote administration exception (I believe this is only needed, when you also want to use psexec)

In the group policy management editor:

Computer Configuration > Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile.

You must enable “Allow inbound remote administration exception.

Run gpupdate /force

 

Windows 10 laptop

 

Step 1 Install PowerShell

Install PowerShell 7.0.2

On installation check the box “Enable PowerShell remoting”

 

Step 2 Enable PowerShell remoting

I executed the following command inside the “out of the box PowerShell” and in the PowerShell 7 console:

Enable-PSRemoting -Force

 

Testing

To test the PowerShell remoting, between the Windows 10 laptop en Windows 2008 R2 SP1 server, I used:

Enter-PSSession -ComputerName 11.201.209.42 -Credential MyOtherDomain\SomeDomainAdminAccount

 

 

You can use an IP address, instead of a computer name, when using PowerShell remoting

If you want to connect to a remote server by using PowerShell remoting

Enter-PSSession -ComputerName 11.201.209.42 -Credential MyOtherDomain\SomeDomainAdminAccount

 

How to automatically add unstaged files including new files to a git commit

The git commit commando does not allow you to automatically stage new files and add them to the commit.

If you want to automatically stage files that have been modified and deleted or should be added, before you commit, then you should use 2 commands:

git add . ;git commit -a

Just make sure your .gitignore file is up to date.

 

How to squash commits rewriting the commit message

https://stackoverflow.com/questions/2563632/how-can-i-merge-two-commits-into-one-if-i-already-started-rebase

You can use

 

 

 

 

 

2020-06-22 Learned Today

 

PowerShell – .NET Core C# – Why is my PowerShell.Create() – Streams.Information.DataAdded not working

I work with PowerShell on daily basis for more then 10 years and today I’m proud to announce that I made a real beginner mistake .

If you execute a PowerShell script from .NET Core C# bij using the “using (PowerShell ps = PowerShell.Create())” syntax.

You can “stream” the events written to Error, Warning and Information streams from the executed PowerShell script, by attaching delegates, like:

 

string scriptContent = await File.ReadAllTextAsync(@”C:\Temp\Test.ps1″);

 

            using (PowerShell ps = PowerShell.Create())

            {

                // Subscribe to events from some of the streams.

                ps.Streams.Error.DataAdded += ErrorDataAdded;

                ps.Streams.Warning.DataAdded += WarningDataAdded;

                ps.Streams.Information.DataAdded += InformationDataAdded;

                ps.Streams.Debug.DataAdded += DebugDataAdded;

                ps.Streams.Verbose.DataAdded += VerboseDataAdded;

 

                // Set execution policy to unrestricted

                string initScript = “Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy”// The second command to know the ExecutionPolicy level after it has been set.

                ps.AddScript(initScript);

                
 

                // Specify the script code to run.

                ps.AddScript(scriptContent);

 

                // Add parameters to the script.

                ps.AddParameter(“someParamter1”@”Some value for Parameter1″);

 

                // Execute the script and await the result.

                PSDataCollection<PSObjectpipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);

 

                // Print the resulting pipeline objects to the console (this is the standard output stream).

                foreach (var item in pipelineObjects)

                {

                    Console.WriteLine(item.BaseObject.ToString());

                }

            }

 

If you use “Write-Output” in your PowerShell script it will end up in the “standard output stream” and will only be available in the C# code above after the script has executed.

If you use “Write-Information” in your PowerShell script it will end up in the “Information output stream” which will fire during the execution of the script in the C# code above.

So, if you want to see progress information during the execution of your PowerShell script use “Write-Information” and not “Write-output”.

 

private void DebugDataAdded(object senderDataAddedEventArgs e)

        {

            PSDataCollection<DebugRecordstreamObjectsReceived = sender as PSDataCollection<DebugRecord>;

            DebugRecord currentStreamRecord = streamObjectsReceived[e.Index];

            Console.WriteLine($”DebugStreamEvent: {currentStreamRecord.Message}”);

        }

 

        private void ErrorDataAdded(object senderDataAddedEventArgs e)

        {

            PSDataCollection<ErrorRecordstreamObjectsReceived = sender as PSDataCollection<ErrorRecord>;

            ErrorRecord currentStreamRecord = streamObjectsReceived[e.Index];

            Console.WriteLine($”ErrorStreamEvent: {currentStreamRecord.Exception}”);

        }

 

        private void InformationDataAdded(object senderDataAddedEventArgs e)

        {

            PSDataCollection<InformationRecordstreamObjectsReceived = sender as PSDataCollection<InformationRecord>;

            InformationRecord currentStreamRecord = streamObjectsReceived[e.Index];

            Console.WriteLine($”InfoStreamEvent: {currentStreamRecord.MessageData}”);

        }

 

        private void VerboseDataAdded(object senderDataAddedEventArgs e)

        {

            PSDataCollection<VerboseRecordstreamObjectsReceived = sender as PSDataCollection<VerboseRecord>;

            VerboseRecord currentStreamRecord = streamObjectsReceived[e.Index];

            Console.WriteLine($”VerboseStreamEvent: {currentStreamRecord.Message}”);

        }

 

        private void WarningDataAdded(object senderDataAddedEventArgs e)

        {

            PSDataCollection<WarningRecordstreamObjectsReceived = sender as PSDataCollection<WarningRecord>;

            WarningRecord currentStreamRecord = streamObjectsReceived[e.Index];

            Console.WriteLine($”WarningStreamEvent: {currentStreamRecord.Message}”);

        }

 

 

 

How to add parameters to a PowerShell script and call it from .NET Core

If you need to run a PowerShell script from .NET Core and this script accepts parameters, then you can call it like:

.NET Core C#

string scriptContent = await File.ReadAllTextAsync(@”C:\Temp\Test.ps1″);

 

            using (PowerShell ps = PowerShell.Create())

            {

                // Subscribe to events from some of the streams.

                ps.Streams.Error.DataAdded += ErrorDataAdded;

                ps.Streams.Warning.DataAdded += WarningDataAdded;

                ps.Streams.Information.DataAdded += InformationDataAdded;

                ps.Streams.Debug.DataAdded += DebugDataAdded;

                ps.Streams.Verbose.DataAdded += VerboseDataAdded;

 

                // Set execution policy to unrestricted

                string initScript = “Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy”// The second command to know the ExecutionPolicy level after it has been set.

                ps.AddScript(initScript);

                
 

                // Specify the script code to run.

                ps.AddScript(scriptContent);

 

                // Add parameters to the script.

                ps.AddParameter(“someParamter1”@”Some value for Parameter1″);

 

                // Execute the script and await the result.

                PSDataCollection<PSObjectpipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);

 

                // Print the resulting pipeline objects to the console (this is the standard output stream).

                foreach (var item in pipelineObjects)

                {

                    Console.WriteLine(item.BaseObject.ToString());

                }

            }

 

PowerShell script (“C:\Temp\Test.ps1”)

param ($someParameter1 = “Some default value for this parameter)

 

Write-Information “Script called with $($someParameter1)”

 

 

 

How to redirect dotnet build output to the information stream of the calling PowerShell script

If you execute a PowerShell script from .NET Core and this script contains a call to “dotnet build” you probably want to capture the progress of the dotnet build process.

You can do this by redirecting / piping the output of the dotnet build process to the Write-Information cmd-let:

dotnet build /p:DeployOnBuild=true /p:PublishProfile=FolderProfile | Write-Information

 

 

How to fix Windows 10 Explorer error – Failed to enumerate objects in the container. Access is denied.

Changing the owner of the folder to the account I was signed in with, solved my problem. Even though the Windows 10 Explorer told me I was the owner of the folder.

https://recoverit.wondershare.com/partition-tips/failed-to-enumerate-objects-in-the-container.html

After that I was able to add permissions for the IIS_IUSERS account to that folder.

This was necessary to allow an IIS application pool access to the files in the folder.

 

How to fix overflow issues with css flex layout

It turns out that min-height is important for correctly scrolling flexboxes:

See https://moduscreate.com/blog/how-to-fix-overflow-issues-in-css-flex-layouts/

Set min-height: 0; on flex child element that should overflow.

 

Use NgNonBindable if you want to blog about Angular code

 

https://ngrefs.com/latest/templates/ngnonbindable

 

 

2020-06-17 Learned Today

 

FaviconsWebpackPlugin – Generating all favicon images during development build (ng build)

When using ng build, the FaviconsWebpackPlugin will only generate one favicon file, based on the given “png” or “svg”.

In production build, it will generate all kinds of “shortcut” images.

 

 

As stated in the documentation (https://github.com/jantimon/favicons-webpack-plugin),

by default, the ng build, uses the devMode setting and by default this is set to “light”.

So if you want to generate all de images during development build, use: devMode: ‘webapp’

 

mode: ‘webapp’, // optional can be ‘webapp’ or ‘light’ – ‘webapp’ by default

devMode: ‘webapp’, // optional can be ‘webapp’ or ‘light’ – ‘light’ by default

 

Custom webpack configuration

If you want to use the FaviconsWebpackPlugin with Angular 9, you need a custom webpack configuration.

More information can be found at: https://www.npmjs.com/package/@angular-builders/custom-webpack#Custom-webpack-dev-server

 

Angular 9 – HtmlWebpackPlugin – Title not generated in the Index.html

If you want to set a custom title during the ng build process, you can use the HtmlWebpackPlugin

https://github.com/jantimon/html-webpack-plugin#options

 

NOTE: You will also need to place the following <%= htmlWebpackPlugin.options.title %> inside the index.html

 


 

 

Custom webpack configuration file:

const HtmlWebpackPlugin = require(‘html-webpack-plugin’)

 

module.exports = {

    plugins: [

        new HtmlWebpackPlugin({

          filename: ‘index.html’,

          template: ‘./src/index.html’,

          title: ‘Some custom title’

        })

      ],

};

 

 

How to generate an Angular spike application at the PowerShell command line, by using a specific local Angular cli version

I wanted to generate an Angular spike application by using a specific local Angular cli version and not the globally installed Angular cli version and I also wanted to only use PowerShell.

To this, I used this script:

 

    $rootFolder = “C:\Spike”

    $appName = “MyGeneratedAngularSpike1”

    $angularCliVersion = “9.1.7”

 

    Write-Output “Create rootfolder $($rootFolder)”

    $folderExists = Test-Path “$($rootFolder)”

    If ($folderExists -eq $False) {

        mkdir “$($rootFolder)”

        Set-Location $rootFolder

 

        Write-Output “Generate package.json, so we can use a specific ng cli version locally”

        npm init –yes

 

        Write-Output “Add ng as npm script, so we can use a specific local version of the angular cli, when executing npm run ng build”

        $packageJsonPath = “$($rootFolder)/package.json”

        $json = Get-Content “$($packageJsonPath)” | ConvertFrom-Json

        $json.scripts | Add-Member -Name “ng” -value “ng” -MemberType NoteProperty

        $json | ConvertTo-Json | set-content “$($packageJsonPath)”

 

        Write-Output “Install a specific version of the Angular CLI”

        npm install “@angular/cli@$($angularCliVersion)” -D

    }

 

    Set-Location $rootFolder

 

    Write-Output “Generate Angular application $($appName)”

    npm run ng new “$($appName)”

 

    Set-Location “$($appName)”

    npm run ng serve — –open=true

<

p style=”background: #1e1e1e”>
 

 

The package.json in the folder “C:\Spike” is created with npm init and updated with “ConvertFrom-Json” and “ConvertTo-Json” cmd-lets.

It is only created to we can run a specific local version of the Angular CLI

The folder “C:\Spike\MyGeneratedAngularSpike1” contains the generated Angular 9 application.