Rick Strahl
November 22, 2022

### re: Avoid WebDeploy Locking Errors to IIS with Shadow Copy for ASP.NET Core Apps

I'm so disappointed nobody bothered to post a hysterical, "right click deploy is evil" rant. 😂

Mirality
November 22, 2022

### re: Referencing a Local Private NuGet Package in your Solution

The nuget.config works for non-SDK projects too -- I've used that for years. The direct project property requires the SDK project.

One downside of this sort of thing (which is why publishing a feed is preferred) is that it requires committing binary packages to your source control, which is generally frowned on -- especially if you're releasing updates frequently. It also means you can end up with multiple copies of these dependency packages strewn around multiple repositories, and it becomes less obvious when something is outdated since it no longer has a central feed that's up to date (so every copy will think it's the latest).

For in-house dev I've used a shared folder as nuget feed combined with nuget.config -- but of course that will only work for people who have access to that shared folder. There's also quite a few private feed servers around for wider usage.

Robert Schnitzer
November 22, 2022

### re: Combining Bearer Token and Cookie Authentication in ASP.NET

I'm looking at implementing a similar dual token/cookie authorization, but for OIDC; i.e. rather rather than have my own authorize endpoint, the token or cookie originates in an external OIDC provider. It seems pretty straightforward, at least in theory, to dynamically choose token or cookie from each request as in your example, and then to also tie into the OIDC middleware. Any wisdom or gotchas on this approach that you can pass to me would be greatly appreciated. Thanks!

Thusitha H
November 22, 2022

### re: LINQ to SQL and Transactions

One downside of TransactionScope is that we cannot assign that to a specific data context. It usually tries to scope all the contexts with all the different connection strings. This makes things escalated to DTC. DTC is not running in Azure app services, and that was a huge problem for us. We had to resort to the old Transaction way of things.

Vince
November 13, 2022

### re: ASP.NET Core In Process Hosting on IIS with ASP.NET Core

@Vince - good question. I haven't checked with 7.0 but with 6.0 - raw throughput processing with the IIS module under heavy load was roughly 50% faster than using Kestrel for me in local testing.

I think anytime you have to make an extra http call/hop to pass request data on you're going to lose some performance in the transport layer, so I'm not surprised at all to see this. You're basically doubling the overhead of connection management as you are doing it in two places effective (ie. IIS Proxy and then again with Kestrel).

All that said - in terms of real per request performance for typical application hits I think the overhead of all of this is negliable anyway for all but the most high performance types of services where request overhead is a significant part of every request - not likely in most typical business applications. So you can use either and likely see very little - if any - impact in performance. You do end up with extra processes and some slight system behavior differences due to the different hosting processes.

Vince
November 12, 2022

### re: ASP.NET Core In Process Hosting on IIS with ASP.NET Core

It's 2022 now and .NET 7 just got released. I'm hearing about all the improvements in Kestrel. Is InProcess (IIS + IISHttpServer) still more performant than OutOfProcess (IIS + Kestrel)? Or is the IIS reverse proxy just too much of a bottleneck to make OutOfProcess worth it?

Martin K
November 10, 2022

### re: Avoid WebDeploy Locking Errors to IIS with Shadow Copy for ASP.NET Core Apps

Hi, sorry i didn't, it was a bit TL;DR

My point was, that try the app_offline approach first until it fails and then proceed with the shadow copy.

In my case, I use local IIS for debugging and it was driving me crazy that IIS would lock the files and make it impossible to Build the website. Having the Pre-Build script was enough though.

Rick Strahl
November 10, 2022

### re: Avoid WebDeploy Locking Errors to IIS with Shadow Copy for ASP.NET Core Apps

@Martin - did you actually read the post?

WebDeploy has built-in support for AppOffline.html but it will not always work to unload the application. It is not reliable to unload running application, as there can be operations that are still processing longer than the timeout allows.

Nor is this any simpler even if it did work- because you now have to copy the file using some other mechanism outside of WebDeploy. The whole point of WebDeploy is to automate the process of publishing so you don't have to go through many steps to update the server binaries.

Martin K.
November 10, 2022

### re: Avoid WebDeploy Locking Errors to IIS with Shadow Copy for ASP.NET Core Apps

Hi Rick.

I ran into this issue of locked files when developing a WebAPI in .NET6.

I was adviced to look into Shadow Copy - but managed to find a much simpler solution:

Simply by leveraging the App_Offline.htm functionality of IIS.

In the root of my project i have the file ready, then in the Pre-Build Script i simply copy it to the destination like this:

copy "$$(ProjectDir)App_Offline.htm" "$$(TargetDir)"

This has proven for me to be enough to fix the issue of locked files. The App_Offline.htm shuts down the App Pool and the file is automatically removed when overwriting the files in Publish phase.

Daniel
November 08, 2022

### re: Automating IIS Feature Installation with Powershell

Hi,

2 Years late but anyway.

as I needed it to create a template here is the PS to get a list of "enabled" Features 😃

Get-WindowsOptionalFeature -Online | Where-Object { \$_.State -ne "Disabled" } | Select FeatureName | Format-Table


Sam
November 08, 2022

### re: Async and Async Void Event Handling in WPF

Have you looked at Task.Yield()? https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.yield?view=net-6.0 TLDR; it forces the runtime to execute asynchronously when awaited/called, so maybe this might be a little "cleaner" than "await Task.Delay(1)"... that's kinda splitting hairs over a millisecond delay.

Also, i don't see any (Task).ConfigureAwait(false).
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.configureawait?view=net-6.0 TLDR; like many/most UI frameworks, WPF has it's own SynchronizationContext... don't quote me on this, but i'm 98.732197% sure that .NET (the artist formerly known as .NET Core) dropped the need to call .ConfigureAwait(false) to prevent Task from auto-synching back to the UI thread, however .Net Framework (the behemoth we've loved for the last 20 yrs) will do you that favor in sneaky/particular contexts (WPF/WinForms/various testing AppDomains/etc.) - IMHO, it's the most annoying "feature" in the history of .NET - you basically need to always add .ConfigureAwait(false) if you don't want the runtime doing that favor for you.

Also wanted to say "Thanks" for your posts through the years! They have helped me out tremendously for a long time.

Mikhail Kalatchev
November 06, 2022

### re: Fighting WebView2 Visibility on Initialization

Thanks a lot, Rick! My case is with two WebView2 in a TabControl. First (selected by default) is initialized, second - never. Your post confirmed to me that Visibility is the problem. Switching a Visibility is a solution, but I think MS have to add callback for initializing. Or kind of default options. The problem is that default userDataFolder is not accessible when the app is installed per computer and user is a restricted one.

Best regards, Mikhail.

Rick Strahl
November 06, 2022

### re: Referencing a Local Private NuGet Package in your Solution

@Esty - yes it works with .NET Framework, but only if you use an SDK style project. You can target net472, net48 etc. and with those projects it works.

There might be some way to make this work with old projects too but probably requires some custom MSBuild tasks.

Esty
November 05, 2022

### re: Referencing a Local Private NuGet Package in your Solution

thank you! exactly what i was looking for -local nuget.config in local solution root folder! just one question please: will it work in .net framework too?

November 01, 2022

### re: Fix automatic re-routing of http:// to https:// on localhost in Web Browsers

I have also had some success in using a secure tunneling software like ngrok while in development to access my local site over https. Here's an example blog post https://adamtheautomator.com/ngrok/

Felipe
November 01, 2022

### re: Connection Failures with Microsoft.Data.SqlClient 4 and later

Just got hit by this one while migrating a project from System.Data.SqlClient to Microsoft.Data.SqlClient. I'm fine with the change to the default but that error message could be a lot better. Instead of throwing a certificate exception, SqlClient should be aware that since the server returned to certificate and the connection string expects encryption, that the mismatch is the issue, not the (non-existent) remote certificate.

Keith W.
October 28, 2022

### re: ASP.NET MVC HttpVerbs.Delete/Put Routes not firing

I faced the same problem for days trying to figure out why a new Web API 2.0 with Get, Post, and Puts would not do my Put calls and returned 404s for those. Wish I had found this post sooner. Thanks for posting. I added the ExtensionlessUrlHandler-Integrated-4.0 handler to web.config and it worked immediately. Great job and thanks for posting such valuable info. I really enjoy your site. Always great info on it. Thanks

Rich
October 27, 2022

Jay
October 27, 2022

### re: Keeping Content Out of the Publish Folder for WebDeploy

Another option would be to set the Build Action to None on the items you don't wish published. Unfortunately, you can't set it on a directory, but you can multiselect the individual items in the directory and set the Build Action on them all at once.

Rick Strahl
October 25, 2022

### re: Runtime C# Code Compilation Revisited for Roslyn

@Wolfgang - I guess it depends on what you need to do and what assemblies you need to have loaded. In all of my scenarios I'm using it for scripting purposes so any assemblies needed are already loaded and I can assign them from the loaded assembly list plus whatever is explicitly specified. The big issue in .NET Core is to know what assemblies are needed due to the extremely atomized nature of the 'runtime' assemblies compared to full framework.

If you want to be sure the runtime refs are probably safer but it should be easily testable to work with references manually added - it either works or it doesn't.

Wolfgang
October 25, 2022

### re: Runtime C# Code Compilation Revisited for Roslyn

@Rick about "They are not available on a non-dev machine": When using the project property PreserveCompilationContext or PreserveCompilationReferences, this works when using dotnet publish: the "refs" subdir is then added to the publish dir and must be copied to the target machines. "Only" 10 MB and 200 files.

In our real app, I ran into strange compilation errors as reported in the linked Github issue, so I finally found out about the reference assemblies.

Yogabagaba
October 25, 2022

Robert
October 18, 2022

### re: Windows Authentication with HttpClient

I have a Maui app that is using httpclient and it works great on Windows and iOS but the android client keeps failing with 401 error. I have tried using the AndroidHandler and everything else I can find with no success. I heard that .NET Core 6 has this issue and .NET Core 7 was supposed to fix it. However after using the Preview version it still fails. I have verified that I have all of the Android Permissions for this task as well. I am using NTLM authentication. Any advise will be greatly appreciated.

Rick Strahl
October 15, 2022

### re: Runtime C# Code Compilation Revisited for Roslyn

@Wolfgang, yes that's by design if you don't specify the reference assemblies and use the default imports. The reference assemblies add a large disk footprint because it has to be present at runtime for dynamic compilation to work, and some of us don't want to add that our applications. They are not available on a non-dev machine.

There are different ways to specify the assembly list, and using the reference assemblies is one of them. There's an entire section in the post above on this topic 😄

Matthew Abbott
October 11, 2022

### re: Work around localhost unsecured HTTPS access for Development Sites in Edge

I tend to avoid localhost if possible, and prefer a local.domain.com approach (inline with test.domain.com, staging.domain.com, www.domain.com, etc.

To that end, I created my own Certificate Authority (CA) using OpenSSL and have a powershell script for easily generating and installing certificates on my development box.

Wolfgang
October 11, 2022

### re: Runtime C# Code Compilation Revisited for Roslyn

Really great article - helped me a lot!

But I think this line of code might cause trouble:

var rtPath = Path.GetDirectoryName(typeof(object).Assembly.Location)...


This picks a runtime assembly from "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.9". For compilation, it seems to be better to use the "Reference Assemblies" found e.g. at. "C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\6.0.9\ref\net6.0".

For the same reasons, you should also not add a reference to "System.Private.CorLib.dll" 😉

By adding this line to the project file, Visual Studios copies the reference assemblies to the bin\Debug\net6.0-windows\refs subdirectory and you could load from there:

    <PreserveCompilationContext>True</PreserveCompilationContext>


Doozy Tools
October 07, 2022

### re: Linq to SQL DataContext Lifetime Management

Seeing this post again after 14 years as I came across my comment in 2009 in this article. Look like world is moved far from here but concepts are still same with new terminology. We are still working with .NET and our recent online free tool site Doozy Tools is still using LINQ and DataContext. We are more reliant on JavaScript which is now able to process PDF files without uploading it.

Rick Strahl
September 23, 2022

### re: Work around localhost unsecured HTTPS access for Development Sites in Edge

@Thomas - That seems unnecessary since the app can respond on first hit with an HSTS header and redirect. I get the immediate redirect is one extra step for potential attack vector, but there will always be at least 1 first request against the site anyway, so that risk is always there regardless of the caching.

Agreed though - I think the only place where this is really an issue these days is for a local dev site. So it sure would make sense for HSTS perhaps to be more lenient on local machine IP addresses (or even just localhost).

David
September 23, 2022

### re: Keeping Content Out of the Publish Folder for WebDeploy

Rick, thank you so much! I crashed my website after I published it by using webpublisher cause App_Data folder was overwriten. I only used this tag '<ExcludeApp_Data>true</ExcludeApp_Data>'. I have no idea why this bug is not fixing by the team. Using App_Data is not realy special. Very crazy bug!

Thomas Levesque
September 22, 2022

### re: Work around localhost unsecured HTTPS access for Development Sites in Edge

HSTS headers should not be cached and certainly not beyond the scope of the active session

Actually, this is kind of the point of HSTS... It ensures the website is always accessed via HTTPS after the first visit (or even for the first visit thanks to HSTS Preload list). But maybe there should be an exception for locahost, since it's typically used for development purposes...

Lance
September 22, 2022

### re: Gotcha: Entity Framework gets slow in long Iteration Loops

Just implemented this change to create the context inside my for loop... shaved hours off the processing time. I'm iterating ~24k times. My best estimate is I went from 6+ hours to 8 minutes. Now I'm wondering if I should iterate some number of times in a single context before recreating it. In other works, instead of 1 context to 1 iteration... do 1 context to 50 iterations for example. Is there even more speed to squeeze out of this? 😃 Anyone tried tuning like this?

Thanks for the post!

Rick Strahl
September 22, 2022

### re: Work around localhost unsecured HTTPS access for Development Sites in Edge

@Thom - great tip - I have to try this with WinAcme... that would be a great and relatively easy way to create a local development certificate in general.

Thom
September 22, 2022

### re: Work around localhost unsecured HTTPS access for Development Sites in Edge

Another workaround using LetsEncrypt that doesn't involve tunneling to your local site, as long as you have access to the DNS for a site: let's say you're developing for a public site named www.whatever.com. Create a local development site with the URL development.whatever.com. Then use LetsEncrypt verification method of looking up a specific TXT record for the subdomain. When LetsEncrypt prompts you to add the specific txt string to the TXT record for the site's DNS, do so. It'll then add the SSL cert to your local site without ever having to allow external access to the site. I use https://www.win-acme.com/ to do this, but I suspect other methods might also support this.

Rick Strahl
September 11, 2022

### re: Referencing a Local Private NuGet Package in your Solution

@bitbonk - it'll be checked in and pulls down with the Repo. This could be a private repo, so not broad exposure. But even for a public repo in some cases I want to distribute a binary as part of my project, but not necessarily have it as a general use library that other would use.

I realize people could still do that with the repo scenario but much less likely than if it was published or available in source code.

bitbonk
September 11, 2022

### re: Referencing a Local Private NuGet Package in your Solution

If you reference a library that is not public in a public project, how is anyone who pulls down the public project repo going to be able to build it? They won’t have access that private library and the project therefore won’t build.

Chris
August 31, 2022

### re: Capturing Performance Counter Data for a Process by Process Id

Even after years, this article helped me alot. Too bad there is still no convenient possibility to get the process cpu usage for a specific pid (except uwp). Thanks!

August 31, 2022

### re: Mapping Multiple Static File Folders in ASP.NET Core

Excellent tip as always.

Frank
August 29, 2022

### re: Async and Async Void Event Handling in WPF

Lol, I was searching for exactly this but for "MAUI" and it came up with this article as the time of publication is listed as Maui time.

Lee
August 12, 2022

### re: Back to Basics: Custom HTTP Response Header Manipulation in ASP.NET Core

This is excellent. I've been having the same problem in trying to manipulate the response headers. I used this technique of the custom middleware shown here. It adds headers no problem but it wasn't removing them. I did post the issue on github but maybe here is better 😃

Jake Coyne
August 09, 2022

### re: Windows Authentication with HttpClient

@Rick - thank you it was entirely my mistake in assuming that it was looking for NTLM (based on the domain credentials). Your answer led me down the right path, thank you so much!

Rick Strahl
August 09, 2022

### re: Windows Authentication with HttpClient

@Jake - you probably have to check a request that works and compare that indeed the server works with Windows authentication. You should hook up an HTTP proxy (like Fiddler) and see what gets sent - you should see the Negotiate header being sent to the server. Whether the server uses that correctly is another story, but that's what checking with some other mechanism verifies whether the UID and Password are valid and Windows Auth is actually what hte server is looking for. The server should be responding with a 401 along with the supported protocols in the headers.

Rick Strahl
August 09, 2022

### re: JavaScript Debugging in a Web Browser Control with Visual Studio

@Johnx - yup, but that dialog is very noisy and whether the debugger pops up depends on configuration and security settings - it's very unreliable and annoying if you forget to turn it off. Best not to muck with that one I think.

Jake Coyne
August 09, 2022

### re: Windows Authentication with HttpClient

Rick, Thank you for this, your writings are very helpful. I am wondering if you can offer some advice on why it might still be failing. If I access my API endpoint via a web browser it will ask for my credentials and if I provide my network credentials return the expected JSON. However, when I try this code:

Uri uri = new Uri("MY URL");
CredentialCache credentialsCache = new CredentialCache { { uri, "Negotiate", new NetworkCredential("USER", "PASS", "DOMAIN") } }; //Have also tried ("DOMAIN\\USER", "PASS") format
HttpClientHandler handler = new HttpClientHandler { Credentials = credentialsCache, PreAuthenticate = true };
HttpClient httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };
var response = await httpClient.GetAsync(uri);


I get a 401 Unauthorized every time. I have tried using NTLM instead of Negotiate, with and without PreAuthenticate and always the 401 response. Unfortunately, the service I am calling is a third party I don't have much control over and I am currently out of ideas.

Johnx
August 08, 2022

### re: JavaScript Debugging in a Web Browser Control with Visual Studio

There is another IE flag in the options above that also help, it covered by bottom of red box and defaulted off. You can 'enable' the option to be 'notified of every script error' ( lots of popups). Tells you file/line#/errormsg. By default you can't jump into the debugger, unless attached, but this will popop with hints and correct line #'s. So helpful.

Henke
August 04, 2022

### re: Using WSL to Launch Several Bash Commands from an Application

32 bit applications do not look in System32
– Do you mean 64 bit applications do not look in System32?

Marc W
August 02, 2022

### re: Combining Bearer Token and Cookie Authentication in ASP.NET

@Steve Hunt, you saved my day. I have mixed mode in core 6. after jwt my Identity mvc login stopped to work. This line resumed to work with jwt for api an cookie for asp/mvc

return IdentityConstants.ApplicationScheme;


Bryant
July 29, 2022

### re: VSIX Installer Extension Manifest and Visual Studio Version Numbers

Hi Rick,

I agree about the PITA nature of VSIX. I'm running into a targetversion issue that led me here. I'm curious if you have experience with it.

I am updating an existing item templates VSIX project. The item templates make use of the WizardExtention. Those templates can only refer to a single version of VS. I need to have a set of item templates for VS2019 and a set for VS2022 because of the required difference in the WizardExtension values. I have attempted to get that to happen using the TargetVersion setting on the Assets tab in the Extension Manifest editor. What I am expecting is that if I set an asset to v17 or above, v16 won't be able to see it. And that isn't happening whether I use the UI or the XML document.

In the VSIX manifest schema description it says "TargetVersion - the version range to which the given asset applies. Used for shipping multiple versions of assets to different versions of Visual Studio." so I think I'm in the right place.

Are you familiar with the settings or do you have any other ideas?

Thanks

Firegarden
July 25, 2022

### re: IDbCommand and generic Parameters

Hi Rick, Have you considered the option of just making your own objects out of the interfaces?

Thank you, Rob

public class DbDataParameter : DataParameter, IDbDataParameter
{
public byte Precision { get; set; }
public byte Scale { get; set; }
public int Size { get; set; }
}


Rick Strahl
July 24, 2022

### re: .NET Core 3.0 SDK Projects: Controlling Output Folders and Content

@Cathei - yeah, it'd be nice if <projectReference> worked but unfortunately it doesn't. Setting <private>false</private> has no effect and still pulls in all dependencies of the referenced project, unlike the DLL reference.

Noe
July 22, 2022

### re: Prettifying a JSON String in .NET

This is exactly what I was looking for to simply print Azure SDK responses. Thanks!