Recent Comments



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!


Adin
August 31, 2022

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) };
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.GetAsync(uri);
string json = await response.Content.ReadAsStringAsync();

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!


Slobodan Gajinovic
July 22, 2022

re: SmtpClient and Locked File Attachments

Hello folks!

I have found the same problem, but using wwSMTP class… How could I release locks from attachment files, after the message had been sent, but from VFP application? Workarounds presented here are not applicable to VFP code.

I couldn’t find at wwSMTP code any reference to message object (neither to attachments objects), where could I make an explicit dispose() call. Calling loSmtp.dispose() doesn’t release lock from recently added attachments. The locks remain active untill application quit (or I didn’t find workaround solution).

Simple code example:

DO wwSmtp && load libraries
LOCAL loSMTP as wwSmtp
loSmtp = CREATEOBJECT("wwSmtp")
loSmtp.nMailMode = 0  
loSmtp.cMailServer = "smtp.office365.com:587"  
loSmtp.cSenderEmail = "Test_sender@MyCompany.com"
loSmtp.cSenderName = "Test sender"
loSmtp.cUsername = "Test_sender@MyCompany.com"
loSmtp.cPassword = "********"
loSmtp.lUseSsl = .T.
loSmtp.cSubject = "Test1"
loSmtp.cContentType = "text/html"
loSmtp.cMessage = "Test1"
lcAttachmentFile = "Test1.PDF"
loSmtp.AddAttachment(lcAttachmentFile)
loSmtp.ntIMEOUT = 30
loSmtp.Connect()
loSmtp.SendMessage("Test_Receiver@gmail.com")
loSmtp.Close()
losmtp.dispose  && this doesn't release lock from file Test1.PDF
losmtp = null
RELEASE loSmtp

*!* At this moment, file which had been attached to email message ("Test1.PDF") 
*!* remains locked (untill application quit) and it cannot be deleted or moved out.

* (...)
 
QUIT 


Rick Strahl
July 19, 2022

re: Fighting WebView2 Visibility on Initialization

@John - yeah this kind of hackery often works for things in WPF in general. I have similar things that i do during startup basically moving the window offscreen, making it visible, letting all the base config happen then snap it into the actual window position when it's ready, which is much crisper than the wiggly natural initialization.

This trick of temporarily making the WebView visible though appears to be too fast to actually have a visual impact. I think the DispatcherPriority.Render is enough to trigger whatever UI events the control needs to get past the visibility block.

Unfortunately I played around with this in the many tabs scenario of Markdown Monster and there I couldn't get this to work because these phantom activations are essentially async and I can't control the order so they end up stepping on each other and end up activating the wrong tabs. But the trick definitely is a good one if you have a single control that is hidden and needs to immediately initialize.

It might also help with pre-loading content so it doesn't slow load into the browser.


John Schroedl
July 19, 2022

re: Fighting WebView2 Visibility on Initialization

Interesting finding. Thanks for posting this we have plans to use the virtualhostname feature soon and this could head off some trouble.

This reminds me of an ugly hack I needed to perform where you could visibly see the WPF data binding of a list occurring. When the window was made visible, you'd see the old content which re-bound and then showed the new content. My only workaround (with help from Rob Relyea) was to make the list initially "invisible" with Opacity = 0 and then set to 1 to truly show it. That allowed the initial binding to happen out of sight.


Kalai
July 19, 2022

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

I want to call the angular component from the MVC controller. when I am calling the MVC controller from there to redirect angular registration page any idea


Rick Strahl
July 18, 2022

re: Fighting WebView2 Visibility on Initialization

@Dalibor - No I don't regret using the WebView despite all the issues I've run into and have worked around 😄. The truth is that other controls have other issues. I've used CEF Sharp before and had a completely different set of issues with that. As I did with the old WebBrowser control.

At the end of the day, integrating a browser that is essentially an external OS/native component is tricky and you'll end up with issues around the integration.


Edwin
July 18, 2022

re: WebView and Modal Dialogs in WPF Async Code

I'm experiencing a similar issue with WebView2 (1.0.1245.22), but only when the debugger is attached. After enabling 'native code debugging' the debugger breaks when this issue occurs, as shows the following message:

Running a message loop synchronously in an event handler in Webview can cause reentrancy issue. Please refer to https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/threading-model#re-entrancy for more information about threading model in WebView2 and how to enable native code debugging for this scenario.
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in MyApp.exe.

So this seems to be a check/warning that is deliberately added. I guess your issue is the same.


David
July 16, 2022

re: Fighting WebView2 Visibility on Initialization

I really love the fact that you document your investigation (including dead ends that you went down!) because that helps me realize that I’m not the only one who gets stuck trying to work around crazy limitations like this. Please keep up the great work on your blog - it helps us all learn not only what the end result is, but also all the troubleshooting techniques along the way.


Michael Gallo
July 16, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

What a fantastic article! I came across it while converting our C# scripting from Mono to Roslyn, and it was a big help.

I do have one issue though, and I was wondering whether you've perhaps encountered it as well: Despite adding a reference to the executing assembly, I get a System.IO.FileNotFoundException in System.RuntimeMethodHandle.InvokeMethod saying that the executing assembly could not be found (even though the path is correct).

I suspect it's because we have a native host, loading a managed dll from an external path, which is then doing the compilation etc., but I'm not sure. If I don't add the reference, everything works, but obviously the Roslyn-compiled code can't call methods in the executing assembly.


Dalibor Čarapić
July 16, 2022

re: Fighting WebView2 Visibility on Initialization

Do you regret using webview2 and not using CEF or something else?


Rick Strahl
July 14, 2022

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

@Miguel - Visual Studio uses a custom version of MSBuild that behaves differently than the version that's used in dotnet build from the command line. Other than what's in this post I don't know of another solution...


Miguel
July 14, 2022

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

Hi Rick,

I run into this problem some time ago an this post helped me sort out the output of a project using a similar plugin architecture when we moved to .net core.

This is all working fine when we build from Visual Studio which uses MSBuild.

We are now moving to containers and using multi stage builds in docker where we use dotnet build MySolution.sln to do the actual building.

For some reason dotnet build even on windows produces a different output to what MSBuild used to so we are again getting some extra files in the output folder. This also happens if you we use Rider as it uses dotnet build under the hood.

Do you have any pointers as to how to fix this again on dotnet build?

Thanks!


DaveG
July 14, 2022

re: Fixing Visual Studio Intellisense Errors

Just updated VS2022 and had this problem. Code compiled fine but lots of intellisense issues. Deleting the .vs folder cleared it up. Saved me a few hours poking around to figure it out myself....


Jim
June 30, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

Wow Rick, you are an animal with the content! Well done.


Howard
June 28, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

MVC views are a somewhat complicated way to render HTML strings. I used to use RazorEngine for this in old ASP.NET.

When we upgraded to Blazor/.NET 6 I looked for a Razor Component-based system and couldn't find one, so wrote my own: https://github.com/conficient/BlazorTemplater


Thomas Ardal
June 25, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Rick Ahh, you're right. I copied your method signature to make the code similar to your example. Don't think I can change the comment, though.


Rick Strahl
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Thomas - your static method won't be able to see the RazorViewEngine so you'd have to pass it into that method.

@Soundar - yeah lots of people commenting in regards to standalone solutions which is great, but that's not what this post is about. It's specifically meant for the scenario where you can use what's already provided in the application without additional dependencies.


Soundar
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

This looks great. But, for people looking for out of the box solution, they can try https://github.com/soundaranbu/RazorTemplating.

The major advantage is that it works outside of the MVC context. This means, they can use it in console applications as well.


Thomas Ardal
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

This is pretty much what I'm doing to render an invoice from a Razor view and then convert the HTML to a PDF file. I found that it's easier to just inject the IRazorViewEngine where I need it like this:

public MyController(IRazorViewEngine razorViewEngine)
{
    this.razorViewEngine = razorViewEngine;
}

public static async Task<string> RenderViewToStringAsync(
    string viewName, object model,
    ControllerContext controllerContext,
    bool isPartial = false)
{
    var actionContext = controllerContext as ActionContext;
    
    using (var sw = new StringWriter())
    {
        var viewResult = razorViewEngine.FindView(actionContext, viewName, !isPartial);
        ...
    }
}

Rick Strahl
June 23, 2022

re: Windows Authentication with HttpClient

@Waleed - For HttpClient you can use UseDefaultCredentials on the HttpClientHandler (or SocketHandler). Another way is to use CredentialCache.DefaultNetworkCredentials - haven't tried the latter however.


Waleed
June 23, 2022

re: Windows Authentication with HttpClient

Thanks for excellent post, this is exactly what I was looking for. The only issue that does not work for me is the credentials, is there a way to use current user windows credentials, the web service I am calling is running on IIS accepting windows authentication for internal web service


Rick Strahl
June 22, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Tobias - I haven't tried this, but you still end up with dependency on the ServiceProvider that's been populated by the ASP.NET startup in order to work. I think without those dependencies many things likely won't work - especially the path and view folder resolutions.


Tobias Bartsch
June 22, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

I used a similar approach to render my email templates but without an active http request. I just create my own ActionContext like this. I don't know if it works in all circumstances, but it was perfectly adequate for my needs.

    private ActionContext GetActionContext()
    {
        var httpContext = new DefaultHttpContext();
        httpContext.RequestServices = _serviceProvider;

        var currentUri = new Uri("htpps://myDomain.tdl"); // Here you have to set your url if you want to use links in your email
        httpContext.Request.Scheme = currentUri.Scheme;
        httpContext.Request.Host = HostString.FromUriComponent(currentUri);
        
        return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    }

Rick Strahl
June 21, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Joe - I hear you and I agree. It's possible to do outside of ASP.NET in say a desktop app, but you then still end up pulling in the ASP.NET libraries to make it happen. And getting a ControllerContext that works as expected is a pain. There are a couple of projects out there that do this, but they don't look very solid.

I had a library for full framework, but there too it was a royal pain in the ass to get it to work and there are lots of limitations running outside of ASP.NET there too. I would love to do this for Core again, but I can't justify the work for that. I've resigned myself to use custom C# scripting using Handlebars like syntax in a small library instead:

and there are other libraries like Fluid (Liquid template language) that also uses a handlebars like syntax, but without the C# language structures.


Rick Strahl
June 21, 2022

re: .NET WebRequest.PreAuthenticate – not quite what it sounds like

@Kumar - no, this is a client specific thing. The server will do what it must to authenticate - Challenge on no auth header, and accept the header if provided.

The client is who has to decide how to initially send the data to the server.


Joe Enos
June 21, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

I just wish it was easier to do it outside the context of a web request. There are times when I want to build HTML somewhere else, and have to use Mustache or Handlebars.

I've seen some people try to implement it, but there always seem to be disclaimers that it may or may not always work for whatever reasons.

It would have been awesome if Microsoft would have made Razor a standalone templating engine, and then plugged it into ASP.NET.


Kumar
June 21, 2022

re: .NET WebRequest.PreAuthenticate – not quite what it sounds like

Is there a way to enable preemptive authentication at the server, OS, or app.config level? We have a .NET 2.0 C# application running on Server 2016 POSTing to a Linux box running the recipient's web service. But opening up our code to add the header is not an option. We see a 100->401->100->200 sequence for every transmission. I proposed leaving it the way it is for the marginal security benefit. But we need to be prepared if our customer wants to reduce server load & network traffic in the future. Thank you so much for allowing me to address this issue in an informed way with our customer's IT staff!