2020-07-17 Learned Today

 

How to fix .NET C# error: System.Security.AccessControl.PrivilegeNotHeldException: The process does not possess the ‘SeSecurityPrivilege’ privilege which is required for this operation.

 

If encountered the error “System.Security.AccessControl.PrivilegeNotHeldException: The process does not possess the ‘SeSecurityPrivilege’ privilege which is required for this operation.”, when calling GetAccesControl,

with “AccessControlSections.All”. After I changed this to “AccessControlSections.Access” the problem was resolved.

 

namespace ConsoleApp1

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine($”Start application”);

 

            DirectoryInfo dirInfo = Directory.CreateDirectory(\\SomeNetworkPath”);

            DirectorySecurity dirSecurity = dirInfo.GetAccessControl(AccessControlSections.Access);

 

            Console.WriteLine($”Wait for user to close the application”);

            Console.ReadLine();

        }

    }

<

p style=”background: #1e1e1e”>}

 

 

 

 

2020-07-16 Learned Today

 

Visual Studio Code can be used as hex editor

By installing this extension: https://marketplace.visualstudio.com/items?itemName=ms-vscode.hexeditor

 

How to play an entire folder containing *.mp3 files from OneDrive on iOS / iPhone

Yes, it is a paid app if you want to play an entire folder containing mp3 files from OneDrive, but it does the job well.

 

.NET C# FileInfo class does NOT support uri’s like file:/// or file:/

The code:

string assemblyPath = “file:///C:/Temp/ConsoleApp1/ConsoleApp1/bin/Debug/ConsoleApp1.exe”;

FileInfo assemblyPathFileInfo = new FileInfo(assemblyPath);

Will throw the error System.NotSupportedException: ‘The given path’s format is not supported.’

I encountered this problem, when I wanted to get the location of an .NET console executable, by using:

System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

 

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApp1

{

    class Program

    {

        static void Main(string[] args)

        {

            string assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            Console.WriteLine($”Exe is located at {nameof(assemblyPath)} [{assemblyPath}”);

 

            Uri assemblyPathAsUri = new Uri(assemblyPath);

            string assemblyAbsolutePath = assemblyPathAsUri.AbsolutePath;

            Console.WriteLine($”Exe is located at {nameof(assemblyAbsolutePath)} [{assemblyAbsolutePath}”);

 

            string assemblyFolder = Path.GetDirectoryName(assemblyAbsolutePath);

            Console.WriteLine($”Exe is located in {nameof(assemblyFolder)} [{assemblyFolder}”);

 

            Console.ReadLine();

        }

    }

}

<

p style=”background: #1e1e1e”>
 

 

Result:

Exe is located at assemblyPath [file:///C:/Temp/ConsoleApp1/ConsoleApp1/bin/Debug/ConsoleApp1.exe

Exe is located at assemblyAbsolutePath [C:/Temp/ConsoleApp1/ConsoleApp1/bin/Debug/ConsoleApp1.exe

Exe is located in assemblyFolder [C:\Temp\ConsoleApp1\ConsoleApp1\bin\Debug

 

 

2020-07-15 Learned Today

 

How to open an integrated Windows PowerShell terminal / command line inside Visual Studio 2019

 

View > Terminal

Or

CTRL + `

 

One of the great Visual Studio Code features, that was previously not supported in Visual Studio 2019, was opening a PowerShell command line inside Visual Studio 2019 itself.

Yes, there was the “Package manager console” but that behaved differently then a normal PowerShell command line.

But from Visual Studio 2019 16.3, we have an integrated PowerShell terminal inside Visual Studio 2019 itself.

2020-07-06 Learned Today

 

Using IIS ApplicationPoolIdentity to run git inside a PowerShell script, run by a .NET Core web application

 

I encountered the following error, when trying to execute a PowerShell script from a .NET Core web application:

ErrorStreamEvent: System.Management.Automation.RemoteException: Could not create directory ‘/c/WINDOWS/system32/config/systemprofile/.ssh’.

ErrorStreamEvent: System.Management.Automation.RemoteException: Host key verification failed.

ErrorStreamEvent: System.Management.Automation.RemoteException: fatal: Could not read from remote repository.

 

To solve this problem, I had to give the application pool identity rights on the “C:\Windows\System32\config\systemprofile” folder.

Make sure in IIS the application pool property: “Load user profile” is set to true.

 

 

What to do when “Get column information” does not work in EF 6 edmx

This is probably due to, using temp tables in your stored procedure.

Just use real tables in the stored procedure, then use “Get column information” and then remove the real tables and switch the stored procedure back to using temp tables.

 

 

What to do when EF 6 does cannot create a complex type

Sometimes, when your stored procedure ends with a select of constants for example, EF 6 edmx can’t create a complex type.

To solve this, temporarily select columns with the same type from a real table, create the complex type and revert the stored procedure back to returning constants.

 

Unable to start debugging on the web server. The remote server returned an error: (503) Server Unavailable.

Make sure your IIS application pool is started .

 

 

How to fix Chrome error NET::ERR_CERT_COMMON_NAME_INVALID

 

If you are developing a .NET Core web application with Visual Studio and when you start debugging your application on IIS https binding, you might get the chrome error:

NET::ERR_CERT_COMMON_NAME_INVALID

 

I used PowerShell to create a certificate in the local Personal store on the server, then exported this certificate to a file on the server and then imported it back into the Trusted Root CAs via MMC (to avoid browser warnings).

https://stackoverflow.com/questions/19441155/how-to-create-a-self-signed-certificate-for-a-domain-name-for-development/22282433

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

 

 

To trust the new certificate:

  • Open mmc.exe => File => Add / Remove Snap-in… => Certificates => Add => Computer account => Next => Local computer: (the computer this console is running on) => Finish => Ok
  • Go to Console Root => Certificates (Local Computer) => Personal => Certificates =>
  • Right click on the created “*.mydomain.com” certificate => All Tasks => Export… => follow the export wizard to create a .pfx file:
    • Yes, export the private key
    • Check “Include all certificates in the certification path if possible”
    • Check “Export all extended properties”
    • Check “Enable certificate privacy”
    • Click on “Next”
    • Check “Password”
    • Use a password like “1234”
    • Encryption: “AE256-SHA256”
    • Click on “Next”
    • Choose a file path, like “C:\Temp\mydomain.cert.pfx”
  • Go to Console Root => Certificates => Trusted Root Certification Authorities and import the new .pfx file

 

 

How to use the self-signed certificate in IIS

 

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

 

NOTE

I had to clear the SSL state on Windows 10 before the error in Chrome was resolved

 

 

 

Firefox

Even after installing this self-signed certificate, Firefox will not allow you to visit the site directly, without warning pages.

If you want to remove the warning page just visit the page and then click on “Advanced”

 

Click on “Accept the Risk and Continue”

 

 

Firefox will still show you a warning if you click on the “lock” symbol:

 

 

Dealing with slow “Downloading proxy settings” in Chrome

 

Just turn off “Automatically detect settings” in Windows 10

 

 

How to revert git commit but keep changes – aka undo last commit en redo last commit

 

https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-git

 

 

How to fix: SQL Server – The database principal owns a schema in the database, and cannot be dropped

 

https://dba.stackexchange.com/questions/19456/the-database-principal-owns-a-schema-in-the-database-and-cannot-be-dropped-mess

 

 

 

 

 

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.