Recent Comments



Ben
November 17, 2020

re: Fixing Visual Studio Intellisense Errors

Just in case someone faces intellisense issues after migrating a project to VS2019 or after a VS update. See here.

Analyze > Build and Suppress Active Issues is a very helpful thing πŸ˜‰


Paul
November 12, 2020

re: Web Browser Control & Specifying the IE Version

Hi Rick,

Hello from Canada.

WOW! Thanks for this. In one of our VFP9 products we use a third party HTML control to display maps. We have struggled with this problem for years (IE compatibility mode warnings).Your suggested solution solved all our issues. Finally! Thanks so much!


Alois Kraus
November 12, 2020

re: A .NET Color Console Helper

This is a great class! I have added two things.

  1. Some people use custom background colors which make custom colors unreadable
         /// <summary>
        /// For guys who do not like the color scheme make it possible to turn it off
        /// </summary>
        public static bool EnableColor
        {
            get; set;
        } = true;

and then in the various places added the check:

        public static void WriteLine(string text, ConsoleColor? color = null)
        {
            if (color.HasValue && EnableColor)
  1. When pressing Ctrl-C/Break switch back to the initial color (most of the time) to prevent cluttering up the console output after our program has exited
      /// <summary>
       /// Default color 
       /// </summary>
       static readonly System.ConsoleColor InitialForeColor = System.Console.ForegroundColor;

       static ColorConsole()
       {
           CtrlCHandler.Instance.Register(Console_CancelKeyPress);
       }

       private static void Console_CancelKeyPress()
       {
           EnableColor = false; // other threads might still be printing after we have reset the console color
           Console.ForegroundColor = InitialForeColor;
       }

Luke O'Brien
November 12, 2020

re: Adding Additional Mime Mappings to the Static File Provider

Thanks Rick, this is really helpful and provided the solution to my problem, actually I read your blog quite a lot and I have found many solutions to problems I come accross on your blog!
I am using Blazor, I have a UI project and a Api project, I am publishing my UI project to the wwwroot of another "Publish" project and serving the Blazor dlls as static files.

One knew puzzle. I noticed that the new .Net 5 is generating .br and .gz files.
How do we check the accept-encoding header and return the .gz version of the file if it exists?
I tried the following but the file.context is read only:

            app.UseStaticFiles(new StaticFileOptions
            {
                // add the mimemappings
                ContentTypeProvider = extensionProvider,
                OnPrepareResponse = content =>
                {
                    if (content.Context.Request.Headers.ContainsKey("accept-encoding") &&
                        content.Context.Request.Headers["accept-encoding"].Contains("gzip"))
                    {
                        var path = content.File.PhysicalPath;
                        path += ".gz";
                        if (File.Exists(path))
                        {
                            content.File = new FileInfo(path);
                        }

                    }
                }
            });

Rick Strahl
November 06, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

@William - CSS changes will not immediately show - you need to hard reload the page once before CSS changes show in Chromium browsers. Due to the cache logic in Chromium (and other browsers too I think). After the one hard refresh, CSS changes will show up as you make them... weird behavior but apparently this is by design.


William
November 06, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

Update to previous comment:

I change my folder to monitor from

"FolderToMonitor": "~/../"

to

"FolderToMonitor": "~/.."

I also restarted my browser due to any update so one of the two fixed it.


CB
November 02, 2020

re: Dealing with Anti-Virus False Positives

When you got your signature certificate, what personal information did you provide? I would like to use my company information only, and not my personal information.


Annie
November 02, 2020

re: HttpWebRequest and GZip Http Responses

Hi Rick,

Can I use it in my WCF service the client need the response to be gzip encoded and should I place the HttpCompression code after each response (multiple scenarios for failure and success) or just one time before creating the response and sending it.

response = new Basic_Response { code = "0", message = "Auth Failed", data= null, success= true };

                HttpResponse Response = HttpContext.Current.Response;
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
                if (AcceptEncoding.Contains("gzip"))
                {
                    Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, 
                 System.IO.Compression.CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "gzip");
                }

Chris Marisic
October 30, 2020

re: Use Powershell to bind SSL Certificates to an IIS Host Header Site

Following up to Dave's answer, this can be one-lined and not require any variables at all:

(Get-WebBinding -Name "My Api" -Port 443 -Protocol "https" -HostHeader "api.my.com")
.AddSslCertificate("SSL_THUMBPRINT_HERE", "my")

The last parameter "my" will resolve to the certificate store for the local computer for the Personal\Certificates folder [typical webserver SSL installation location]. You can grab the thumbprint value by inspecting the certificate in a browser, certmanager snapin, or alternatively you can use other commands on this post/comments to get the cert via powershell and access the thumbprint as a property of it.


Daniel Rose
October 29, 2020

re: Static Constructor Failures and Declaration Order

I saw that almost immediately, but the reason being that I got burned by something similar before.

If you use WPF's DependencyPropertyKey, it needs to be initialized before the corresponding DependencyProperty. ReSharper used to rearrange that, which caused similar errors during runtime (IIRC I filed a bug for that).


Rick Strahl
October 28, 2020

re: Creating Custom .NET Project Types with .NET CLI Project Templates

@Ignat - not that I know of, and frankly I think that would be a terrible idea as that would be an invitation for malicious code to execute.

Since they are delivered as NuGet packages, you're limited to the NuGet operation which AFAIK doesn't include code execution of any kind.

If you need templates that execute code you likely need to build for Visual Studio and use a VSIX.


Ignat Andrei
October 28, 2020

re: Creating Custom .NET Project Types with .NET CLI Project Templates

Just asking : could we run custom code in our template after dotnet new is doing his job ?


Laurens
October 23, 2020

re: Flexbox Containers, PRE tags and managing Overflow

Found your post through https://drailing.net/2018/04/css-quicky-fixing-flexbox-width-with-pre-tags/.

I stumbled upon the breakout problem of pre inside a parent which was itself part of a display: grid rendering using auto in grid-template-columns. Applying min-width: 0 to the parent solved the issue. So it seems the solution and underlying implementations relate to flexbox as well as to grid layouts - in Chrome at least.


WizX20
October 22, 2020

re: ASP.NET Core IIS InProcess Hosting Issue in .NET Core 3.1

For anyone running into this exception after changing DEBUG settings in the project properties. have a look at issue 16805

In short

  • Close the application and VS
  • Go to the solution root and delete the entire .vs folder
  • Done

Rick
October 21, 2020

re: Mirror your iOS Device Screen on Windows with the free 5KPlayer

@Kimon - I'm pretty sure that Bonjour is required in order to sync through iTunes. I can't be 100% sure because I may have had a pre-store version of iTunes installed, but I didn't install anything special to make either iTunes sync or 5k player work.

You should check and see whether the service is installed and perhaps not enabled or started.


Kimon
October 21, 2020

re: Mirror your iOS Device Screen on Windows with the free 5KPlayer

Installing iTunes from the Windows store does not install Bonjour. Bonjour SDK and Bonjour Print Services also don't install the Bonjour necessary for this product. I have an email into the company - let's see what they come up with.


Rick Strahl
October 21, 2020

re: Mirror your iOS Device Screen on Windows with the free 5KPlayer

I guess you'll need to install iTunes from the Windows store.


Kimon
October 21, 2020

re: Mirror your iOS Device Screen on Windows with the free 5KPlayer

Unfortunately, the screen mirroring won't work unless you have Bonjour on your Windows machine. I haven't found a way to download Bonjour since iTunes is now a Windows app. Ideas?


Rick Strahl
October 21, 2020

re: Publishing and Running ASP.NET Core Applications with IIS

@Chris - that's not right. I have built a couple of applications that use Windows Authentication running IIS, IIS Express and the local Kestrel server. The apps are SPA style apps and are using APIs for data retrieval on separate sites set with CORS. It works fine.

Getting Windows Authentication working is another story - that's a pain in the ass especially in Kestrel, but you can find more info on that in a couple of related posts (and another here).


Chris
October 21, 2020

re: Publishing and Running ASP.NET Core Applications with IIS

Great article Rick.

You say "There should be very few reasons for you to run IIS during development" which I understand based on you reasoning however it appears that AJAX requests are all but impossible with .Net Core when you have Windows Authentication enabled due to the fact that CORS OPTIONS pre-flight requests do not have the necessary authentication token to allow the request to actually reach the Kestrel server and therefore the .Net Core website.

The only suggested solution to this is to use the IIS CORS Module but this then requires you to run the site through IIS. I've not yet managed to successfully run a project through IIS and make use of the CORS Module so my only options are to constantly publish and test or make do without AJAX. It's almost as if the Kestrel server is implementing just enough functionality to block the OPTIONS requests but not enough functionality to get around this as you would be able to in a live environment.

I'd love to know if you have an alternative solution to this.


Joel Lucsy
October 20, 2020

re: Window Activation Headaches in WPF

I've implemented a program that uses a separate process as a viewer. The key to allowing the first process to set focus to the second process is by using the AllowSetForegroundWindow with the process id of the first process from the second process. Its sortof a security feature with opt-in semantics. Look up the docs for AllowSetForegroundWindow for details on how this works.


Rick Strahl
October 18, 2020

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

@Marty - are those the 27" screens? Yeah no doubt 27" is too small for that high a resolution. And a 5k display almost certainly has to run some sort of scaling - even on a 40" screen I'd expect that. I'm not sure I see the point for a PC screen to have ultra-high compressed pixel counts.

To me the key is whatever resolution I can run at 100%! Anything else is just a waste of pixels IMHO. For 4k I think the sweet spot would be 34/35" but very few screens come in that size. 32" is just little too small...


Martin Glynn
October 18, 2020

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

I got 2 LG UltraFine 5K Display with a new Mac Pro 2019 - I wouldn't recommend them for writing code - I have to run them at 150% and then I have to sit closer to the screen. For keyboards, I love my Kinesis .


Sean
October 18, 2020

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

I have a similar setup, but without both a Logitech mouse AND keyboard, their software doesn't fit my needs. I found a fork of Synergy that works better than Synergy (in my experience at least) and is free. If interested, it's called Barrier (https://github.com/debauchee/barrier). Thanks for the article, I always like reading about other setups. πŸ˜ƒ


Jun Ramoneda
October 16, 2020

Daniel Lesage
October 16, 2020

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

For anyone with multiple Windows computers and without those Logitech devices, there's always "Mouse Without Borders" from Microsoft Garage. I've been using it for a few months now across one desktop and three laptops.


Andrew
October 14, 2020

re: A HighlightJs Copy Code Badge Component

Hi Rick, I have the latest from NPM. It was actually a bit more complicated - because line numbers javascript creates a table, so I needed to loop through all rows.

Code changed to this:

        // select the <code> tag and grab text
        var $code = $origCode.querySelector("pre>code");
        var text = "";
        var rows = $code.getElementsByTagName("tr");
        if (rows && rows.length > 0) { // using lineNumbersBlock
          for (var i = 0, row; row = rows[i]; i++) {
            text += row.textContent + "\n";
          }
        }
        else {
          text = $code.textContent || $code.innerText;
        }

Rick Strahl
October 14, 2020

re: A HighlightJs Copy Code Badge Component

@Andrew - hmmm... I thought that was fixed a while back in the repo. This code may not be completely up to day. Maybe check source or use from NPM.


Andrew
October 14, 2020

re: A HighlightJs Copy Code Badge Component

Thanks for this, hooked it up pretty easily to angular app. Question though - when copying I never get line breaks. Looks like its related to another plugin highlightjs-line-numbers.js Fix was/is to revert $code.innerText, which has markup fine.

Is there a way to optionally choose which value you take? I could'nt see it, so have just hacked the JS for now.


Federico Rossi
October 13, 2020

re: Custom Message Formatting in WCF to add all Namespaces to the SOAP Envelope

Amazing job Rick, thanks for the explanation. I have a doubt, is there any way to ignore or skip null values when serializing? thanks


Rick Strahl
October 13, 2020

re: Window Activation Headaches in WPF

@Thomas - no, haven't figured this out, but I suspect it has to do how Windows intercepts and implements the 'focus-stealing protection'. How that works is a mystery, but if anybody figures it out, please leave a comment.

I hunted around for an explanation but I came up blank. The StackOverflow link in the post, has some additional links including one from Raymond Chen which mentions potential lockups for repeated calls to AttachThreadInput().


Thomas Levesque
October 13, 2020

re: Window Activation Headaches in WPF

That's good to know, thanks! I ran into similar issues before.

And sure enough: On my dev machine which worked fine before, the thread Ids were the same. But on the slow machine, the thread Ids were different

Did you figure out the reason for this difference?


Ashley
October 09, 2020

re: Back to Basics: Non-Navigating Links for JavaScript Handling

This article is so, so wrong. No, the links in this case would NOT "do the right thing" for a screen reader or person navigating via keyboard. You're advocating using a link because you're lazy and don't want to style a button to look like a link, but semantically it's wrong and you're making it very hard for keyboard or screen-reader users to use your page. Accessibility is important and this is one of the top links that came up when searching for how to handle a link where the href isn't immediately known.


Sandeep Parmar
October 08, 2020

re: Don't let ASP.NET Core Console Logging Slow your App down

Hello,

I have dotnet core 2.2 where I am facing similar issue with console logging. I have multi threaded console application where I have configure logging as below but somehow I am not able to turn off the logging. I tried different options. As I have long running process as time goes I see many threads and memory increase in task manager.

"Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
    },
    "Console": {
      "LogLevel": {
        "Default": "None"
      }
    }
  }

 services.AddLogging(b =>
            {
                b.ClearProviders();
                //b.AddConfiguration(s_configuration.GetSection("Logging"));
                //b.AddFilter((category, level) => true);
                //b.AddConsole(options => options.IncludeScopes = false);
            });

Rick Strahl
October 06, 2020

re: Creating Custom .NET Project Types with dotnet new Project Templates

@Kathleen - thanks for the ref about Templates in VS. I've updated the post to reflect that support.


Cathei
October 06, 2020

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

Hi, Rick. So what I’m trying to say is you don’t have to convert <ProjectReference> to <Reference> manually for <Private> metadata. You can’t use <IncludeAssets> like you posted, but you can directly use <Private>. So,

<Reference Include="$(SolutionDir)MarkdownMonster\bin\$(Configuration)\$(TargetFramework)\MarkdownMonster.exe">
    <Private>false</Private>
</Reference>

Above setting is equivalent to:

<ProjectReference Include="$(SolutionDir)MarkdownMonster\MarkdownMonster.csproj">
    <Private>false</Private>
</ProjectReference>

Simpler!


Kathleen Dollard
October 06, 2020

re: Creating a dotnet new Project Template

Great article!!!

We also hate that VSIX makes template installation so hard, so we're fixing that!

Visual Studio 2019 16.8, currently in preview, has a feature flag (Tools/Options/Preview Features) named "Show all .NET Core templates in the New Project Dialog". Check that and you should find your template in Visual Studio.

We'd like feedback on this, and we know this may result in a lot of templates! You can filter with the search (at the top) and the three combo boxes. Let us know what you're interested in searching/filtering on.

You can find more about .NET CLI templates appearing in Visual Studio in this blog post.


Lachlan B
October 04, 2020

re: Back to Basics: Rewriting a URL in ASP.NET Core

Just to be pedantic. The rewrite middleware only contains an option for redirecting non www traffic to a www address, not the other way around. Which is annoying because who uses www anymore? πŸ˜ƒ Looks like it might be done in dotnet 5 though - https://github.com/dotnet/aspnetcore/issues/12978


Rick Strahl
October 02, 2020

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

@Cathei - that's what I'm already doing with the project reference in the sample project code I show above? What are you referring to exactly?


Cathei
October 02, 2020

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

Actually, to mark your project reference private you can just write <Private>False</Private> inside of <ProjectReference> item. According to Microsoft Documentation, <ProjectReference> item will be transformed to <Reference>, thus any valid metadata for <Reference> may be valid.


Aditya Gupta
September 30, 2020

re: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

I really owe you Rick, you have saved me, is struggled for almost 2 days and was manually setting the values from model but got stuck in case of dropdowns and other controls. Finally came across your blog and it helped me understand what might be going wrong. Thanks a ton!


Robert Ethridge
September 22, 2020

re: WPF Rendering DUCE.Channel Crashes due to Image Loading

Thanks much, Rick! We spent hours trying to figure this out. A bad logo brought the system to it's knees.


Ndaba
September 21, 2020

re: Using Angular's Live Reload Web Server to Refresh Pages on a Phone

Thanks. This works, but fails for websockets connections for live updates testing on mobile device. I have tried the --disable-host-check option, but it does not seem to get around the issues as websocket for live updates will not connect as it tries to use http://localhost:4200 . Do you know how to connect?


Rick Strahl
September 20, 2020

re: Serving ASP.NET Core Web Content from External Folders

@Joe - you need to add the file provider explicitly to the Service collection via services.AddSingleton(myFileProvider) probably. But... this might not be that good of a solution because there may be other IFileProvider instances in use elsewhere and already be in the DI container (not sure - you need to look at the services collection to see).

Another way to do this might be to store the file provider you're using somewhere that's scoped to the application (or your component). A static property or on some App or Config type object. The provider won't change so that's a simple solution.


Joe Lin
September 19, 2020

re: Serving ASP.NET Core Web Content from External Folders

Thank you! Your articles are some of the most informative out there.

I was able to apply your idea, supply a StaticFileOptions to app.UseStaticFiles(), and reference files from other folders in my HTML markup.

However, I also need to inject IFileProvider into a controller (inheriting from ControllerBase). But the following doesn't work:

public MiscController(IFileProvider fileProvider)

When I run my application, I get a runtime exception:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.FileProviders.IFileProvider' while attempting to activate ... MiscController

How can I configure an IFileProvider service in ConfigureServices(), when the file provider is created in Configure()? I had hoped app.UseStaticFiles() would magically make my PhysicalFileProvider available for dependency injection.


Rick Strahl
September 19, 2020

re: Don't get burned by missing await Calls for Async Code in ASP.NET Core Middleware

@PilotBob - That depends on what the process is doing and how it handles the operation.

await is just returns a task. If you assign a task and move on, it behaves as any other separate thread (or local depending on whether the task is already complete) would. An exception on a separate non-awaited async thread is likely to fail silently unless it's a critical system error.

I think the recommended way to signify that is to use code like this:

var _ = WriteOutputAsync();

This avoids the compiler warning, plus gives a visual signal that you are explicitly ignoring the result of a call and forget operation.

It should be very rare that this is done - async is usually there for a reason, but there are times when code can go on without waiting for completion.


Tariq Hameed
September 19, 2020

re: Resetting Entity Framework Migrations to a clean Slate

Hi Rick,

A great help. appreciate you. in my case i had role-authentications and lot of migrations. I commented both up scripts from CreateIdentitySchema and migration-Initial and than update-database. works fine now with only one migration. thanks alot.


PilotBob
September 19, 2020

re: Don't get burned by missing await Calls for Async Code in ASP.NET Core Middleware

For example, in that same bit of middleware there's some Web Socket handling that is async and runs on a background thread, and that code can safely execute without an await while in other locations that same method can and should use an await.

I thought using asyc without await for this type of thing was a code smell. Async isn't the same as multi-threaded. If an exception occurs in the non-awaited task it could crash the process.

Or have things changed?


Rick Strahl
September 16, 2020

re: Don't get burned by missing await Calls for Async Code in ASP.NET Core Middleware

@Kereem - yup, usually I agree with that. In this case because it was legacy code that was converted that didn't happen because the code was essentially upgraded. Could have happened but didn't in the melee that was going on while working the Async cascade πŸ˜„

Also frankly I'm not sure anymore whether I actually left the original code to explicitly not be awaited because it worked perfectly fine without it and there is quite a bit cleanup code that happens post Write that actually benefits from running in parallel. It worked reliably in 2.x - started failing only in 3.x which is essentially a time bomb and was definitely a bad idea (if that what the thinking was on my part). Good example of code debt, collected in kind 😒