Recent Comments



Robert Ethridge
Yesterday

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
Monday

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
Sunday

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
Saturday

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
Saturday

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
Saturday

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
Saturday

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 😢


Kerem Ispirli
September 16, 2020

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

The first thought I had was the convention of appending names of the async methods with "Async". From Microsoft docs:

**You should add "Async" as the suffix of every async method name you write.

This is the convention used in .NET to more easily differentiate synchronous and asynchronous methods.**

It could help in 2 ways:

  1. Name change of the method would draw attention to every call site during review.
  2. Method name with "Async" suffix would highlight the need for "await" keyword.

Frank3
September 16, 2020

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

Ahh, nasty. 😛 These types of conversions might warrant the treatment of those warnings as errors at compile-time!


Carl
September 16, 2020

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

I've experienced this same hell.

You could set things up so that CS4014 is an error instead of a warning and then suppress the message for the places (rare probably) where you actually don't want to await.


Rick Strahl
September 16, 2020

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

@Capewka - Implicit call site handling of await calls would also be heavy handed. I actually have a number of scenarios where I don't await async code and that's a good thing. 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.

And to be fair - as I point out in the post - the tooling does catch this inconsistency and warns. In my case I was unable to find it because of - warning overload (ie. my own fault). In most cases you'd see a fairly obvious warning message that you'd likely catch.


Alexei
September 15, 2020

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

Great post! Thank you! I agree with idea of cleaning warnings for legacy code, but sometimes it is not feasible. I think at least grouping of warnings by type and looking at what types of warnings code had would help


Bhanu Chhabra
September 15, 2020

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

Another fair warning to others reading this blog post.

Be careful with HttpClient and how it is configured to used as well as where it is being called!!!! Specially with async await.


Cepewka
September 15, 2020

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

Great post! Unfortunately, it once again shows that the async/await is like a cancer spreading throughout the codebase and if functions are not colored properly then nasty errors pop up. I wish they just implemented it using fibers + implicit await in the callsite, this is the most common scenario and now it takes so much code to do it right (await Foo().ConfigureAwait(false), most likely with .WithTimeout() or something similar).


Matthias
September 15, 2020

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

Had something like this just a while ago:

long currentUserId = _userRepository.GetCurrentUser().Id;

Forgot the await and got the Task id. 😅


Rick Strahl
September 15, 2020

re: Accepting Raw Request Body Content in ASP.NET Core API Controllers

@Mike - not unless you build it 😄...

That attribute was built specifically for Web API on full framework and the semantics and logic for that with core would be completely different as the pipeline is completely different. Should actually be easier as the APIs are a lot cleaner. But I haven't built it...

If you need raw request access using the Request Helpers is probably the best way to do this. I'm guessing the reason you ask is for porting an existing application?


Kalpesh
September 15, 2020

re: Content Injection with Response Rewriting in ASP.NET Core 3.x

I am encrypting response body but its client side I am unable to decrypt it. Below are the methods i am using.

public async Task InvokeAsync(HttpContext httpContext)
{
    httpContext.Response.Body = EncryptStream(httpContext.Response.Body);
    httpContext.Request.Body = DecryptStream(httpContext.Request.Body);
}
private static CryptoStream EncryptStream(Stream responseStream)
    {
        Aes aes = GetEncryptionAlgorithm();
        CryptoStream base64EncodedStream = new CryptoStream(responseStream, new ToBase64Transform(), CryptoStreamMode.Write);
        CryptoStream cryptoStream = new CryptoStream(base64EncodedStream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write);
        return cryptoStream;
    }
private static Stream DecryptStream(Stream cipherStream)
    {
        Aes aes = GetEncryptionAlgorithm();
        CryptoStream base64DecodedStream = new CryptoStream(cipherStream, new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces), CryptoStreamMode.Read);
        CryptoStream decryptedStream = new CryptoStream(base64DecodedStream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read);
        return decryptedStream;
    }

Mike Rickerby
September 14, 2020

re: Accepting Raw Request Body Content in ASP.NET Core API Controllers

Is there any way to do use [NakedBody] attribute with ASPNET Core 3?


Rick Strahl
September 14, 2020

re: Using the brightness() CSS Filter to generically highlight Content

@Koos - thanks for the clarification, and the example, that's quite useful!

Totally agree, on the color saturation. I guess it takes some experimenting to get it to look right for your specific themes and colors and... preferences. For example I would think the highlight should be the deeper saturated color vs. the active. Any generic solution is likely to have a few issues with some color combos and requires some customization to work across colors.


Rick Strahl
September 14, 2020

re: Excluding Files and Folders in Visual Studio Web Site Project

@Jon - For purely static content Solution folders work. VS also has a new Folder Project which is basically just a file reference. That might work for your scenario of scripts. The problem with that project type is that it's literally just a folder dump - there's no support for publishing and other project type features which still would be useful.

SDK projects already provide all the features needed if we could just do away with requiring an executable and entry point for the project that would be all that's needed.


Hes
September 14, 2020

re: ASP.NET Core WebSockets and Application Lifetime Shutdown Events

Sorry for posting this question again: How do you stop ASP.Net Core from accepting new requests when your application is shutting down and you've delayed it for a few final operation?


Koos
September 14, 2020

re: Using the brightness() CSS Filter to generically highlight Content

I love the creative use of the brightness() filter! I'd like to point out that by only changing brightness, colors can look oversaturated (for lighter variations) or dull (for darker variations). People who mix paints know: you don't create nice shades just by adding black or white.

I forked the example where I added a saturate() filter for lighter and darker (for :active) to make the colors appear more consistent with their base variants (and created a bit more contrast between the base colors and their variants).

If anyone plans to use this technique in production: keep in mind doing color contrast accessibility testing is tricky this way!


Andres
September 13, 2020

re: Using the ng-BootStrap TypeAhead Control with Dynamic Data

Thanks for the explanation. There's also an event that really helps. Check "selectItem", the documentation explains as it follows:

" /** * An event emitted right before an item is selected from the result list. * * Event payload is of type NgbTypeaheadSelectItemEvent. */"

Hope this helps.


Blair Allen
September 10, 2020

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

@Rick Strahl, in your last code example where you conditionally add the console logging provider, you could make the code more robust/easy to read by depending on an instance of IHostEnvironment or IWebHostEnvironment. e.g.:

private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _hostEnvironment;

public Startup(IConfiguration configuration, IWebHostEnvironment hostEnvironment)
{
    _configuration = configuration;
    _hostEnvironment = hostEnvironment;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(config =>
    {
        // clear out default configuration
        config.ClearProviders();

        config.AddConfiguration(_configuration.GetSection("Logging"));
        config.AddDebug();
        config.AddEventSourceLogger();
        
        if (_hostEnvironment.IsDevelopment()) 
        {
            config.AddConsole();
        }
    });

    ...
}

public void Configure(IApplicationBuilder app)
{
    if (_hostEnvironment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    ...
}

Now both Configure and ConfigureServices are depending upon the same environment helper class and the code to check the current environment is much cleaner.

Per Visual Studio template, Configure already wants an argument for IWebHostEnvironment. I removed it since an instance is now provided via dependency injection (just like IConfiguration) and did not notice any adverse side effects. The framework seemingly is happy to call Configure with just the argument for the app builder.

Question: Wouldn't you also want to move config.AddDebug(); to the conditional test for a development environment? It seems the debug provider provides logging to a debugger, which you are unlikely to do in a production environment. Am I correct, or is AddDebug() useful even in production environments?

That all aside, thank you for providing this in-depth explanation of how the framework sets up the logging providers by default and how to make production code more efficient!


Chris
September 08, 2020

re: Video Rendering Issues for WPF Windows

This is good stuff. I'm using ModernWpfUI for my WPF UI framework. I went ahead and added this option in as a setting in my application so hopefully if this edge case ever comes up it can be worked around without a future update.

As always, good stuff and thanks for the share Rick!


Rafael Machado
September 07, 2020

re: Creating Angular Synchronous and Asynchronous Validators for Template Validation

Thank you for this post!

It really helped me building a directive that checks for duplicates emails. Couldn't find how to go about on async validators. Your post made it so clear to do so.

Again thank you, and keep creating awesome content 😉


Frank
September 06, 2020

re: Web Browser Control & Specifying the IE Version

Hey Rick, Frank from Berlin here!

Stumbling through my bookmarks I read through this post (again) and found something new!

I'm using FEATURE_BROWSER_EMULATION registry keys for years but did not know about the meta tag alternative. This is very useful for cases where I have control over the content. Especially when working within the VFP IDE. I can't use the registry settings for vfp9.exe, as I'm also using vfp's environment manager and this stops working with more current emulations (at least with the settings I tried). Using the "X-UA-Compatible" mode I now can use css3+ as well as the old evironment manager.

BTW. I found that a registry key value of 0 seems to behave like "latest installed". No indepth investigation but 0 works fine for me with wwhelp.exe, hh.exe and foxhhelp9.exe as well as my application. For Foxhhelp9.exe I also set the registry key in DOS - Format (FOXHHE~1.exe). This made it work on one machine.

Regards

Frank


Michael Janulaitis
September 05, 2020

re: Debouncing and Throttling Dispatcher Events

Rick thanks for the article. I am using this to throttle a real-time log viewer and wanted my screen to immediately scroll if more than the interval has passed. In this way my users get better response when the log is slowly updating but the throttle is adhered to when the log is under load.

        public void Throttle(int interval, Action<object> action,
            object param = null,
            DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
            Dispatcher disp = null)
        {
            // kill pending timer and pending ticks
            timer?.Stop();
            timer = null;
            
            if (disp == null)
                disp = Dispatcher.CurrentDispatcher;

            var curTime = DateTime.UtcNow;

            var difference = (int)curTime.Subtract(timerStarted).TotalMilliseconds;

            // if timeout is not up yet - adjust timeout to fire 
            // with potentially new Action parameters           
            if (difference < interval)
                interval -= difference;
            else // fire immediately
                interval = 0;

            timer = new DispatcherTimer(TimeSpan.FromMilliseconds(interval), priority, (s, e) =>
            {
                if (timer == null)
                    return;

                timer?.Stop();
                timer = null;
                action.Invoke(param);
            }, disp);

            timer.Start();
            timerStarted = curTime;
        }

Rick Strahl
September 01, 2020

re: ClientIDMode in ASP.NET 4.0

@Ishant - nope. Only the id attribute is affected by this. ASP.NET needs the name to reflect the container hierarchy using that funky syntax in order to match server side controls to the POST data you send back. If you want just 'clean' naming, use a plain <input> control and explicitly read Request.Form["txtName"] - IOW, don't use the control model.


Ishant Jindal
September 01, 2020

re: ClientIDMode in ASP.NET 4.0

is there any solution to clean up 'name' property of control , like this "ctl00$content$txtName" to this "txtName" ?


Jason
September 01, 2020

re: WPF Window Closing Errors

Nice job.

Might be worth also adding that same IsClosing logic to ShutdownApplication() in order to prevent the shutdown logic from potentially running twice if e.g. the user tries to close the main window again while a dialog is shown.


Rick Strahl
August 25, 2020

re: Strongly Typed Configuration Settings in ASP.NET Core

@Costas - sure you can do that. You just use multiple configuration objects. I do this all the time in most of my applications. Rather than have one large configuration object I have several specific ones and I load up each one with what's described here. I can then either collect them all into my own object which can be stored in DI, or you just reference/load them individually.


Kostas
August 25, 2020

re: Strongly Typed Configuration Settings in ASP.NET Core

How about mapping complex types. E.g. I would like a way to map a single connection string name to the actual connection string defined to a different configuration section.

class LoggingSettings {
  public ConnectionString {get; private set; } // Map a connection string name to the actual connection string name+value pair here.
}

class ConnectionString {
   public Name { get; private set; }
   public ConnectionStringValue { get; private set; }
}

JSON:

...
"LoggingSettings" : {
   "ConnectionString": "LoggingConnectionString"
},
"ConnectionStrings" : {
   "LoggingConnectionString": "Data Source=..."
},
...

I wish MS made things more flexible and provided examples on complex setups...


Roger
August 24, 2020

re: Displaying Nested Child Objects in the Windows Forms Designer Property Grid

Hi Rick, I discovered that the child properties need this directive and then the parent is notified and updates.

[NotifyParentProperty(true)]

Thanks again.


Roger
August 24, 2020

re: Displaying Nested Child Objects in the Windows Forms Designer Property Grid

Hi Rick, Thank you for your article. Very well presented. One issue is the parent property only updates when it either gets focus, looses focus or one of the child properties are Reset but unfortunately it does not update when any of it's child properties are changed. Only if focus is set back to the parent does it get updated. Do you know why? Please find the following code based on your example. Thank you.

    public class rrrDataGridView : DataGridView
    {
        [Category("_Custom"), Description("Object property."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public AUser TheUser { get; set; } = new AUser();
        
        [TypeConverter(typeof(AUserConverter))]
        public class AUser
        {
            public AUser() { }

            private string m_FName = "Joe";
            [DefaultValue("John")]
            public string FName { get { return m_FName; } set { m_FName = value; } }

            private string m_LName = "Shmo";
            [DefaultValue("Doe")]
            public string LName { get { return m_LName; } set { m_LName = value; } }

            public override string ToString()
            {
                return (m_FName + " " + m_LName);
            }
        }

        public class AUserConverter : TypeConverter
        {
            public override bool GetPropertiesSupported(ITypeDescriptorContext context)
            {
                return true;
            }

            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                return TypeDescriptor.GetProperties(typeof(AUser));
            }
        }
    }

Roger
August 24, 2020

re: Displaying Nested Child Objects in the Windows Forms Designer Property Grid

Hi Rick, Thank you for your article. Very well presented. One issue is the parent property only updates when it either gets focus, looses focus or one of the child properties are Reset but unfortunately it does not update when any of it's child properties are changed. Only if focus is set back to the parent does it get updated. Do you know why? Please find the following code based on your example. Thank you.

    public class rrrDataGridView : DataGridView
    {
        [Category("_Custom"), Description("Object property."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public AUser TheUser { get; set; } = new AUser();
        
        [TypeConverter(typeof(AUserConverter))]
        public class AUser
        {
            public AUser() { }

            private string m_FName = "Joe";
            [DefaultValue("John")]
            public string FName { get { return m_FName; } set { m_FName = value; } }

            private string m_LName = "Shmo";
            [DefaultValue("Doe")]
            public string LName { get { return m_LName; } set { m_LName = value; } }

            public override string ToString()
            {
                return (m_FName + " " + m_LName);
            }
        }

        public class AUserConverter : TypeConverter
        {
            public override bool GetPropertiesSupported(ITypeDescriptorContext context)
            {
                return true;
            }

            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                return TypeDescriptor.GetProperties(typeof(AUser));
            }
        }
    }

Ronnie
August 24, 2020

re: Accepting Raw Request Body Content in ASP.NET Core API Controllers

You should try setting the AllowEmptyInputInBodyModelBinding on MvcOptions which allows a default (null for reference types) to be deserialised:

`csharp services.AddOptions<MvcOptions>().Configure( o => o.AllowEmptyInputInBodyModelBinding = true ); `


Rick Strahl
August 20, 2020

re: Live Reloading Server And Client Side ASP.NET Core Apps with BrowserSync

@Clarence - images and non-text content are just bypassed by this middleware so shouldn't have any effect on them. I suspect though that perhaps authentication is causing issues with access to the images. Also turn off the middleware and run with it off and see if you end up with the same issue.


Clarence
August 20, 2020

re: Live Reloading Server And Client Side ASP.NET Core Apps with BrowserSync

It works, but it can't find my images I placed under wwwroot. Says "Access Denied" I'm a long time .Net developer (over 20 years) and Core has been the biggest overhaul since .Net arrived in 2000. Such a radical change seems unnecessary except to keep up with Angular, Grunt & that mishmash of web development overkill. But rant aside does this sound problem familiar?


Ronald Kroon
August 17, 2020

re: Content Injection with Response Rewriting in ASP.NET Core 3.x

According to this announcement wrapping the response stream with StreamResponseBodyFeature will happen automatically when assigning the HttpResponse.Body.


Rick Strahl
August 14, 2020

re: FireFox, Windows Security and Kestrel on ASP.NET Core

@ziggy - how are you setting up the HTTP call? The client has to be able to support the Windows auth on the client.

For data APIs (ie. outside of a browser) Windows Auth is a terrible idea.


Ziggy
August 14, 2020

re: FireFox, Windows Security and Kestrel on ASP.NET Core

Great, but did you managed to consume your api from another api (client-server to host-server scenario)? I've asp net core 3.1 web API with "Negotiate" authentication and it's hosted as windows service under Kestrel only (corp environment 😃). Authentication and authorization works as expected consuming API from any Browser or Fiddler - they pick up current network credentials from my dev laptop and handshake succeeds. But when I try to consume it from another asp net core 3.1 web API - I get 401. Tried many different things (impersonation, different http handler settings and etc.) which I found on Internet - but nothing helped...


Chen
August 13, 2020

re: Auto Selecting Cultures for Localization in ASP.NET

Hi, What is your advice when your site use a lot with date times and support also Thai language that use ThaiBuddhistCalendar (543 years difference). On one hand I want to be local to any culture by browser language (include difference between dot and comma on decimal numbers) on other hand I don't want to check the calendar type in any place in the code.

Thank you,


Perustaja
August 12, 2020

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

Thanks Steven, this was causing mine to not work. Interestingly, the routing attributes work still prior to that call, I may not know enough but that sounds a bit odd.

I'm using it for a global 404 redirect.


Rick
August 09, 2020

re: Using .NET Core Tools to Create Reusable and Shareable Tools & Apps

@Marcus - Maybe the Nuget team just needed a kick in the ass with a post like this??? 😃


Marcus Turewicz
August 09, 2020

Robin
August 09, 2020

re: Deleting Problem Folders and Files on Windows: Could not find this Item Error

You've made an old man very happy!

[That's rather sad as it was just 800 kb or so in one stray file but the little b was had been annoying me for days 😃 ]


Sachin Singh
August 09, 2020

re: GZip/Deflate Compression in ASP.NET MVC

It only works for html , what should i do to compress css and javacript. Google page insights checks everything so i am getting "F" grade for Gzip compression.


Rick Strahl
August 08, 2020

re: Handling SPA Fallback Paths in a Generic ASP.NET Core Server

@Mike - yes it has to be at the end because it's the handler of last resort. So basically it has to fire if nothing else has fired.