Recent Comments



Rick Strahl
Wednesday

re: Prettifying a JSON String in .NET

@Serhan - neither of these are valid JSON. Comments aren't officially supported in JSON and most parsers will just ignore the comments. Many others will outright fail on comments. Duplicate keys are also not valid for JavaScript/JSON and are consolidated into a single value. How would you even reference these duplicate keys?

Garbage in Garbage out.


Rick Strahl
Wednesday

re: Fixing Windows Control Focus on Toolbar and Menu Controls

@Dalibor - still a problem on WPF as you can see in the examples unless you do direct to source binding with UpdateSourceTrigger=PropertyChanged.

The issue really isn't framework specific - this is a Windows issue in that menu and toolbar controls don't change focus which is generally what you want, but that requires mitigation if databinding frameworks rely on the focus change to update the data source.


Dalibor Carapic
Tuesday

re: Fixing Windows Control Focus on Toolbar and Menu Controls

I was under the impression that WPF did not have this issue. AFAIK in Windows Forms the binding update was normally done through Validation events and the buttons had CausesValidation=true which would force revalidation/rebinding.

P.S. Your captcha is discriminating against people who do not know math /s


Alex
Tuesday

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

Just bumped into this problem after migrating from System.Data.SqlClient to Microsoft.Data.SqlClient. Thanks Rick!


Matthew
January 19, 2022

re: Prettifying a JSON String in .NET

I've been assigned to a project involving a lot of JSON and I keep coming back to this. Thanks!


Serhan
January 12, 2022

re: Prettifying a JSON String in .NET

Hey Rick.

Data integrity is crucial for debugging scenarios and unfortunately this method causes data loss in some cases.

Test your solution with the following two JSON.

/*Json.NET respects me!*/{"foo":"bar"}
{"p":"1","p":"2","p":"3"}

I would stick with less-fancy but more reliable JsonTextWriter.WriteToken(JsonReader).


Narbeh Minassian
January 12, 2022

re: Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application

Rick,

I ran into this issue when implementing some automation/simulation that requires a claims principal for a background process. Let's say you want to programmatically authenticate and call a protected controller/action. The automation invokes the SignIn method and then immediately calls RenderAction() to invoke an action that requires authorization. Since SignIn() appears to just create and return an auth cookie, we have no other subsequent request that would send that auth cookie to be handled and a Principal to be created.

Of course you could argue that if it's a single request, you don't need to even call the SignIn() method and just opt to create a new Claims Principal but if we could use the same authentication method as a regular human user then it prevents me from creating a separate process for the automation. By just creating the ClaimsPrincipal during the sign in makes the method more versatile.

It took me a few hours to figure out why my automation was returning a 401 and redirecting to the login page. I can't imagine them leaving this out intentionally but who knows. There may be a case where the auth cookie to be created is intentionally set to be expired and we can't assume the request is authenticated after SignIn() so it could pose a security risk. Great article by the way, I learned a lot about OWIN authentication.


Ritchie Whytock
January 12, 2022

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

Awesome, many thanks for this - just hit the same issue migrating from Core 3.1 to .Net 6 where upgraded the Microsoft.Data.SqlClient package at the same time!


Rick Strahl
January 10, 2022

re: Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application

@Narbeh - I suppose that makes sense and is easy enough to do, although I find it doubtful that you'd need the Principal to check if you're in a the middle of a login operation.

What's your use case where that's necessary?


Narbeh Minassian
January 09, 2022

re: Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application

There is a bug in the SignIn() method where it fails to set the Claims Principal and Claims Identity for the current request. You need to manually set it in case the authentication request itself also needs to access authorized actions/controllers. Luckily we can easily set the User principal:

var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

AuthenticationManager.SignIn(new AuthenticationProperties()
{
    AllowRefresh = true,
    IsPersistent = isPersistent,
    ExpiresUtc = DateTime.UtcNow.AddDays(7)
}, identity);

/* This ensures the current request is authroized in case your app needs to access authorized actions/controllers */
AuthenticationManager.User = new ClaimsPrincipal(identity);

Matt
January 07, 2022

re: Fixing Visual Studio Intellisense Errors

So we had this issue recently in VS 2019, with an older project. It wasn't just IntelliSense showing errors that weren't really there, we also had an issue where we couldn't navigate to certain references in the project. The issue was in the project file. We had multiple references to different Microsoft.Net.Compilers & Microsoft.CodeDom.Providers.DotNetCompilerPlatform versions. After cleaning these up...everything was gravy. Hope this helps someone.


Alan Farkas
January 06, 2022

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

Thanks again Rick for your continued sharing of excellent tips and helpful advice. Luckily I found your post relatively quickly, so I only spent about a half hour on this.


Richard Tallent
January 06, 2022

re: Handling HTML5 Client Route Fallbacks in ASP.NET Core

One caveat to the app.Run() method: if your route ends with a dotted string (e.g. "/foo/bar.baz"), the route will be handled (and 404'd) by the static file handler (assuming of course you are also using UseStaticFiles), since the URL "looks like" it should be a file. Periods are fine in "folder" portions of the path (e.g., "/foo.bar/baz").


Johan
January 05, 2022

re: Prettifying a JSON String in .NET

Hi Rick, just made great use of this pretty printer, excellent/thanks.

You still surf Kanaha Lowers? Remember you from when I lived in Kula back in the nineties /Aloha from Goteborg, Sweden ๐Ÿ˜ƒ


Iuliu Sandu
January 05, 2022

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

Thanks Rick! I spend a few days debugging this and I could not find any related resources on the web.


Michele
December 31, 2021

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

Thank you Rick, very insightful post. Just a question: if you switch from inprocess to outofprocess, where is the setting that specify in which port kestrel runs the app? Is it automatically picked by Kestrel? In visual studio you have launchsettings.json where you specify the port. Happy new year by the way#


Harvey Berman
December 23, 2021

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

I'm new to ASP.NET Core, and am not a professional programmer. I struggled for 2 days trying to figure out how to rewrite URL's using the endpoint routing system in ASP.NET Core. Never got it to do what I wanted it to do. Then, I found your clear, easy-to-understand explanation. Just what I needed. I am very happy to send a donation your way. Many thanks.


Rick Strahl
December 23, 2021

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

@Randy - I like it. Nice and simple. The Rewrite middleware will do this for you as well though albeit with a little more cryptic syntax ๐Ÿ˜„


David De Sloovere
December 16, 2021

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

Thanks Rick! I just bumped into this issue. Knew I had seen this blogpost and just had to find it. Took me 2 minutes to 'fix' it. Using this option also works for like, as another reader pointed out. TrustServerCertificate=true;


Ed
December 15, 2021

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

Great article, I will be buying the Logitech MK850 Multi-Device Wireless keyboard and mice, just tired of having multiple keyboard and mice on my desk. I wish there was some software or hardware that allow me to do the same for my ultra-wide monitor to display both my Windows and MAC onto one wide screen side by side, I do not want to go out and buy those PBP ultra-wide monitors.


httpb
December 15, 2021

re: A HighlightJs Copy Code Badge Component

@Rick Strahl, The reason $code.textContent does not work is that it contains no newlines at all, probably due to $code containing a HTML table (generated by line numbering plugin) with each line of highlighted code wrapped inside atr tag.

It seems the $code.innerText detects the layout and inserts newline characters after closing tr tags. I'm using the Windows system, so not sure if other platforms behave the same or not.


Rick Strahl
December 13, 2021

re: A HighlightJs Copy Code Badge Component

@httpb - not sure that what you describe matches what I see. Using .innerText will potentially not fix up the text at all, while .textContent does on browsers that support it. For IE (which is less of an issue nowadays then it was when this post was written), .innerText does a better job. I think the issue you might be seeing is that the linebreaks come back as \n instead of \r\n on Windows which may screw things up for some legacy editors that expect \r\n. If you add in the \r\n you may screw up non-windows platforms though, so... there's no solution that works for everything I think. .textContent IMHO is the most universal choice especially for developer types that are likely to use source code snippets.


httpb
December 13, 2021

re: A HighlightJs Copy Code Badge Component

Hi,

Thanks for the Copy Badge component. I use it on my tech blog and I can't imagine not having it. Recently, I wrote an article about how to add Highlight.js to WordPress where I also mention 3 plugins that improve the highlighting.js library and one of them is the Badge component.

I also had the issue with newlines due to highlightjs-line-numbers.js plugin putting the highlighted code inside a HTML table and my solution was to modify the var text = $code.textContent || $code.innerText; line to var text = $code.innerText; inside the Copy Badge component.


Adin
December 12, 2021

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

I'm going to add "Encrypt=False" to all my connection strings in all my projects, since by the time I upgrade them I'll probably forget that I read this here and go nuts trying to figure it out ๐Ÿ˜ฏ

Cheers


Beth
December 12, 2021

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

Regarding the multiple monitors, can you set it up that when you use the Logitech devices to switch between the MAC and PC that both monitors are used for the computer selection? In other words, when I am using the PC, I want both monitors to be active for the PC and when I switch to the MAC, I want both monitors to be active for the MAC so I always have dual monitor capability when working from either machine. In reading the post, it seems that you have one monitor per device and you are using the Logitech devices to switch between the MAC and PC but you only have one monitor active/connected to the each the MAC and PC.


Rick Strahl
December 10, 2021

re: Windows Authentication with HttpClient

Thanks Matt - but the password was changed to protect the guilty ๐Ÿ˜„ Not a real password or account name for that matter.


Matt
December 10, 2021

re: Windows Authentication with HttpClient

Not sure if you wanted your password shown in there - this is probably redundant but in case you use that password elsewhere I thought I'd mention it!


Benk
December 10, 2021

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

This is windows only , its because console has a giant lock on it to prevent multi threaded garbling of the messages serilogs console is even worse.


David W Elyk
December 09, 2021

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

In regards to Daniel's point about expecting breaking changes in major version updates.

The Connection strings in my Apps haven't changed in 20 years, this is the first occurrence of a "Breaking Change" going back to .Net Framework 1.0

It's kind of a big thing, thanks for pointing it out Rick!


kapsiR
December 09, 2021

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

I appreciate this change - secure defaults are the way to go!
There are so many issues and breaches out there just because insecure defaults!

I your case:

  1. Always read release notes for a major version (there are breaking changes all the time) ๐Ÿ˜‰
  2. I'd recommend using TrustServerCertificate=true; instead of disabling the encryption by default

Rick Strahl
December 08, 2021

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

@Mark - sure but then again, when do you ever not copy the crazy connection string from Azure directly out of the portal? It's not like they can't put the flag in there. Nobody in their right mind would type that connection string manually.


Mark
December 08, 2021

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

Of course, encryption is on by default for Azure SQL Server, and that's what Microsoft really want you to use these days...


daniel
December 08, 2021

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

this change is documented in Breaking Changes section in the release notes:

https://github.com/dotnet/SqlClient/blob/main/release-notes/4.0/4.0.0.md

you've always to expect breaking changes when switching major number of a package/library or product.


John
December 07, 2021

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

O M G - thanks for the heads up! imho that is going to cause no end of tickets for them


Celso
December 07, 2021

re: Set-Cookie Headers getting stripped in ASP.NET HttpHandlers

Rick,

Almost 2022 and I'm still experiencing the same issue here. But thanks to you I was able to pinpoint the source of it. One has to remove the WebDAV modules and handlers in order to get rid of this bug. Hope it helps as much as your post has helped me.


Emilio
December 02, 2021

re: Configuring ASP.NET and IIS Request Length for POST Data

5 years later, this blog post is still saving the day. Thanks, Rick!


Ron Clabo
December 01, 2021

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

This is a really great article Rick. I've admired and appreciated many of your articles over the years and just came across this one anew when thinking of switching from OutOfProcess hosting to InProcess. I really appreciate your thoroughness and especially the benchmarks provided here. Thanks!


Ralph
November 29, 2021

re: Windows Authentication with HttpClient

The documentation:

The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos. Classes that implement the ICredentials interface, such as the CredentialCache class, return NetworkCredential objects.


Rick Strahl
November 28, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

@alex - not sure what you mean. This works:

async Task InitializeAsync()
{
    // must create a data folder if running out of a secured folder that can't write like Program Files
    var browserFolder = Path.Combine(wsApp.Configuration.CommonFolder, 
                                     wsApp.Constants.WebViewEnvironmentFolderName);
    var options = new CoreWebView2EnvironmentOptions("--disable-web-security");
    var env = await CoreWebView2Environment.CreateAsync(
        userDataFolder: browserFolder, options: options
    );
    await WebBrowser.EnsureCoreWebView2Async(env);

The environment error means you're probably not setting up a custom folder for your environment and it's going to some existing environment that's not compatible. IOW, make sure you explicitly create an environment folder for your app.


alex
November 23, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

This stuff dont work. I mean i was able to load content froms static file. But issue is changing environment throw error

System.ArgumentException: 'WebView2 was already initialized with a different CoreWebView2Environment. Check to see if the Source property was already set or EnsureCoreWebView2Async was previously called with different values.'

Only option is null. await webView.EnsureCoreWebView2Async(null);

i want to change environment options var op = new CoreWebView2EnvironmentOptions("--disable-web-security");

Basically try to do testing locally without running separate server.


Chuck Dee
November 23, 2021

re: Accepting Raw Request Body Content with ASP.NET Web API

I added the following:

        if (type == typeof(Stream))
        {
            return actionContext.Request.Content
            .ReadAsStreamAsync()
            .ContinueWith((task) =>
            {
                SetValue(actionContext, task.Result);
            });
        }

This works, but there's an annoying instance where sometimes it does not- the stream is zero bytes when I get here. It seems to be based on web server configuration, but I can't figure out what it could be. Any ideas on what I might be missing?


Rick Strahl
November 17, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

@Ben - no I perfectly understood what you asked. The NetFX version and Core versions are different.

Similar functionality, different implementation for obvious reasons in that NetFX doesn't have middleware or default DI to inject with. You can use the Westwind.Web.Markdown package perfectly fine with classic MVC on NetFX, but it's a different library from the .NET Core Westwind.AspnetCore.Markdown package. IOW, you have to choose depending on your platform.


Ben McIntyre
November 17, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

Sorry, we're going around in circles - I should have been more specific at the outset. To serve .md files in Asp Net Core/Std MVC, I believe I need to do

      services.AddMarkdown(config =>
        {
            config.AddMarkdownProcessingFolder("/posts/", "~/Views/Shared/_MarkdownTemplate.cshtml");
        });

and

       app.UseMarkdown();

This does not appear to be supported in the .Web package, but the .DotNetCore package doesn't appear to support Full Fwk 4, so I presume my only option is to change to an updated Net Core framework and then use the .DotNetCore version.
Or, of course, just use the static methods as a workaround and not serve .md files.


Rick Strahl
November 16, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

@Ben - uh, and that matters how? This extension uses statics and controls, neither of which makes sense for DI and either of which can be used from anywhere.

If you're a stickler for everything has to go through DI, then you have to go elsewhere - namely write your own.


Ben McIntyre
November 15, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

@Rick sure, there's no requirement for DI, but I am using DI, and the .Web versions seems not to support it...


Rick Strahl
November 15, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

@Ben - not sure what you mean. WestWind.Web.Markdown has a net40 target for full framework. There is no DI requirement, nor does it need .NET Standard.


Ben McIntyre
November 15, 2021

re: Creating a generic Markdown Page Handler using ASP.NET Core Middleware

Hi Rick!
Long time fan and owner of Markdown Monster, just one question. I'm stuck in a project running .NET 4.6.2 as NetCore Standard 2, so it's got to use WestWind.Web.Markdown (rather than AspNetCore.Markdown), but because it's Net Standard it still uses the service injection model of Net Core.
I don't think this case is covered in either package for serving markdown directly - I'll just have to upgrade to NetCore 3 or Net(core)5. Just checking there's no workaround.


James White
November 09, 2021

re: Back to Basics: Add an ASP.NET Runtime Information Startup Banner

I really like this idea and have incorporated it into my applications as an extension method for IWebHostBuilder/IHostBuilder. Adding the product/file version is also helpful when youโ€™re tracking bug fixes and such. Thanks!


Randy Burden
November 09, 2021

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

Thanks. I used your redirect example to come up with the following:

private void HandleRedirects(IApplicationBuilder app)
{
    // Old Url, New Url
    var redirects = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        {"/Reports/BatchReport", "/Reports/BatchDetailReport" }
    };

    app.Use(async (context, next) =>
    {
        if (redirects.TryGetValue(context.Request.Path, out var redirectUrl))
        {
            context.Response.Redirect(redirectUrl);
            return;
        }

        await next();
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    HandleRedirects(app);

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    // ...
}

Jรถrg
November 08, 2021

re: Discovering new C# String Pattern Matching Features

sol, I even like to write it as
`csharp "New".Equals(parameter) `
pretty close to spoken langauge