Recent Comments



Brian
Friday

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

Thank you, thank you, thank you. I've tried a dozen different methods and none worked until this.


kapsiR
Wednesday

Bob Baldwin
May 19, 2020

re: Passing multiple POST parameters to Web API Controller Methods

Hi Rick,

I know this is an old post, but I'm seeing the same thing that Engin is. This is an otherwise excellent post, but it currently is listing JavaScript code when you meant to list dynamic based C# Web API controller code. I'm pretty sure it uses dynamic and then uses JObject to parse it out. However, your code is the JavaScript side not the C# side. Can you list the C# code for the JObject based controller here or update the post above?

Thanks for your excellent help with us normal's

Bob Baldwin aka VSDotNetGuy


Eniela
May 18, 2020

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

I use LongPathTool and it has been pretty easy. πŸ˜ƒ


Keyur Patel
May 17, 2020

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

switchMap flatens. Meaning to get value emitted by inner observable, we don't need to nest subscribe(twice). switchMap cancels all the Inner Observable subscriptions excepts the last inner subscription.

const getData = (example,param) => of(`${example}  API returns square: ${ param * param}`).pipe(delay(3000)); //

// using regular map
// notice subscribe() twice(example 1) because it is Observable of Observable of string.Obervable<Observable<string>>
// from() returns observable which is piped & then map() calls getData which returns Observable(Inner) instead of Value.
// that is why pipe returns Observable of Observable. Obervable<Observable<string>>
from([4, 6, 8, 10] ).pipe(
  map( param => { // param is valued emitted by the source of Observable(Outer/Parent Array)
    console.log('param: ', param); // param:  4, param:  6, param:  8, param:  10
    return getData('Example 1', param);
  })
).subscribe( outerObsValue => {
  console.log('outerObsValue: ', outerObsValue); // Observable object
  outerObsValue.subscribe(val => console.log(val));
}); // Example 1  API returns square: 16

from([1, 2, 3, 4]).pipe(
  map(param => getData('Example 2', param)),
  switchAll()
). subscribe( val => console.log(val));

from([1, 2, 3, 4]).pipe(
  switchMap( param => getData('Example 3', param))
).subscribe(val => console.log(val));

Harold Lee
May 14, 2020

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

Hey Rick,

Have you tried the 'LongPathTool' program. After my free download, virtually two years ago, it has never let me down.

Thank Me later.

Regards,

Lee.


Mike Salway
May 14, 2020

re: Fixing Visual Studio Intellisense Errors

I've still got this problem in the latest Visual Studio 2019, clearly Microsoft aren't very interested in fixing it. If you've got a lot of solutions, it can get very annoying. This command should destroy all .vs folders recursively from wherever you run it. Test it first though!

FOR /d /r . %%d IN (.vs) DO @IF EXIST "%%d" rd /s /q "%%d"


Povilas Panavas
May 13, 2020

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

Hi!

My issue was that it was logging into EventLog (3.1 core, and happens only on Windows machines). Windows locked up the file after about a month in prod, and logging started to crash together with API requests.

After that I've realised that Console is on by default as well, and from experience I knew how slow it was. And wanted to check online if it's still the same. This landed me on this website.

However, today after spending 3 hours testing deployments in Azure (apps run on App Service Plans), I CAN TELL THAT CONSOLE HAS NO IMPACT ON PERFORMANCE when using deployments in Azure with App Service Plan (Windows).

I think that's what Sebastian is saying. Any Console logs are disregarded, so it's almost the same as changing logging Level.

However, I can confirm that locally, the difference in speed was 10+ times when running as console app or using IIS express.

My point is, that as long as you hosting it in App Service Plan (Windows), console doesn't matter.

Anyone has performance results to prove that Console reduces speed on APIs hosted in App Service Plans using Windows (IIS)?

My test was simply to use ConfigureWebHostDefaults (which will provide four logging providers as can be seen in documentation), and to put no configuration at all in *.json files. That means I used totally default logging settings.

To benchmark I used the same app as the author here, and settings were 60 seconds, and threads 200 and 500. In both cases, there's no noticeable speed difference between using Console and not.

I couldn't believe results, so I tried JMeter, but again, no impact when using console.

And thank you for this detailed article, it helped me understand better how defaults work.


Spark
May 13, 2020

re: A WebAPI Basic Authentication Authorization Filter

Hi Rick

we are facing an issue, on HTTPS we are not able to get any token in request header.. Any idea what can be the issue?


Rick Strahl
May 12, 2020

re: Back to Basics: When does a .NET Assembly Dependency get loaded

@John - yes you can manually load assemblies, but you should very rarely have to do this. The only time this is necessary is to create a top level instance of some type dynamically when the host assembly was not loaded before. This means loading via Reflection most likely. If there's a reference in your code to the type then its assembly should get loaded when that code is executed.

If that's not happening then you probably have different problem: Either the assembly is missing altogether or assembly resolution is not working and finding that file.


John Honnay
May 12, 2020

re: Back to Basics: When does a .NET Assembly Dependency get loaded

Hi Rick, Thanks much for such a wonderful article. It really helps me to understand some basics πŸ˜ƒ

I've a question on how this works in .Net core. I noticed that by referring an assembly as a dependency or having a using statement in the code will not load assembly to the memory. .Net core will look for any usage in the code and will not load if its can't find any usage. Is there any way I can load the assembly without loading it. In my case this is important as we have a pre-compiled code which uses the dependent assembly but its loaded dynamically. But now I'm getting an error when I try to execute the code as .Net core is not loading the required assembly even though its referenced. Thanks much for your help πŸ˜ƒ


BerndK
May 08, 2020

re: Watch out for XmlDocument.PreserveWhitespace when dealing with Digital Signatures

PreserveWhitespace - very good point. But as far as I understood, the signature's info is also part of the hash (which makes perfect sense) so it is also critical, that the signature's whitespaces won't change. If you handle xml via XDocument and .ToString, this will also add unwanted whitespaces to the signature. Better not touch the file any more after signed.


Dan
May 08, 2020

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

Thank you for this. Maybe someone should inform the MS staff on the support forums about this so I don't waste my time reading their solutions that don't work!


Mike
May 07, 2020

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

This is a fantastic article. Thank you so much for explaining this. Do you have an example of setting up an InputFormatter for .NET Core 3.1? This seems to no longer work. I would love to be able to use FromBody so my Swagger docs correctly show that the body is required.

Thank you.


ggja
May 06, 2020

re: Static Constructor Failures and Declaration Order

Fields are initializing in decloration order? No way!


chris macgowan
May 05, 2020

re: Accessing Configuration in .NET Core Test Projects

Hi - Cool implementation. I have been trying to implement appsetting.json for AppConfig and did not know it was not supported in the VS2019 Test Project. Thanks for your project πŸ˜ƒ

Everything is building - where do I put the data objects (see below) I need to implement this somewhere correct?

public class Macgowan
{
    public string ApplicationName { get; set; }
    public string ConnectionString { get; set; }
    public string ApplicationBasePath { get; set; }
    public string ApplicationHomeUrl { get; set; }

    public Email email;
}

public class Email
{
    public string MailServer { get; set; }
    public string MailServerUsername { get; set; }
    public string MailServerPassword { get; set; }
    public string SenderName { get; set; }
    public string SenderEmail { get; set; }
    public string AdminSenderEmail { get; set; }
    public Boolean UseSsl { get; set; }
}

I'm going to post the rest of the implementation just for reference.


public class AppConfiguration
{
    // We are testing this >>>
    public static IConfigurationRoot configuration;

    private IConfigurationRoot GetIConfigurationRoot()
    {
        try
        {
            // Build configuration
            configuration = new ConfigurationBuilder()
                .SetBasePath(GetConfigurationFilePath())
                .AddJsonFile("appsettings.json", optional: true)
                .Build();
        }
        catch (Exception e)
        {
            // Error loading the application configuration file 
        }

        return configuration; 
    }


    public AppConfiguration GetApplicationConfiguration()
    {
        var configuration = new AppConfiguration();

        var iConfig = GetIConfigurationRoot();

        iConfig
            .GetSection("Macgowan")
            .Bind(configuration);

        return configuration;
    }
}

This is the test implementation


public class BaseFramework
{
    private AppConfiguration appConfiguration;

    public BaseFramework()
    {

        appConfiguration = new AppConfiguration();
        appConfiguration = appConfiguration.GetApplicationConfiguration();

        var temp = appConfiguration.Macgowan.ApplicationName;

    }
}

Thanks for your help in advance

Ciao, Chris


Jesse Slicer
May 05, 2020

re: Static Constructor Failures and Declaration Order

At a cursory glance, it seems like the class has two responsibilities: process license information and then state/lifetime management of the license configuration class itself (factory, for lack of a better word). Perhaps this could be split into two classes with their respective responsibilities and the hidden Catch-22 simply goes away.


Franck
May 03, 2020

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

I spent a morning on a doomned folder that I couldnt remove and I finally tried these command. All I can say is THANK YOU for sharing this. I really didnt know this command.


Michael R
May 02, 2020

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

I revisit this question myself every couple of years. I've never liked the javascript:void(0) as its not the intent of the attribute -- a new URL or location. JavaScript should be done under onclick, onsubmit, onmouseover, etc. which is what they were designed for. I'm always annoyed by the standard solution of # which reloads the page. Using #0 seems like a good compromise.

The option that I've been leaning towards lately is repeating the link name in the href so the status bar reference looks normal. ie: <a id="menuAbout" href="about">About</a> This works well for simple one-word links, and displays for multiple words, but fails validation (having a space which is an illegal character in the path segment). From a source coding standpoint, the lack of a file extension then reminds me that the link is handled by an eventHandler.


Archie Marler
May 01, 2020

re: RequestValidation Changes in ASP.NET 4.0

Hi Chris Halcrow (or anyone)

I'm having exactly the same issue, albeit 11 years later!, where this works on my development machine but not on the live server. I have 2.0 (and 3,3.5,4.x) frameworks installed on both machines. The WebConfig contains both entries and they're not accidently in a location tag but still get the "potentially dangerous request" error warning.

Did you find a solution?

Thanks


Laurent Bugnion
April 30, 2020

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

Hey Rick πŸ˜ƒ small typo in your last code snippet, check the semicolon πŸ˜‰

Take care Laurent


Jakob StrΓΈm
April 29, 2020

re: Using Let's Encrypt with IIS on Windows

Just wanted to say that i have always enjoyed your posts. You keep everything at a level that's easy to read. I'm pretty well "versed" in IT in general, and doing software development and Cloud architecture, but sometimes all the articles i read, is well written, but to "heavy" for light reading. You always keep it simple and to the point, so good job πŸ‘ πŸ˜ƒ


Rick Strahl
April 27, 2020

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

@Arian - sure. But most likely you'd want to handle that at the Web Server front end, not in your application. So if you're hosting on Windows with IIS you'd use IIS Rewrite to perform that task. On Linux you'd use the nginX or whatever to do the same in the nginX configuration before it hits your application.

That said, you can can do this inside of your app too - after all it's a Redirect which is a valid HTTP response from your application and it can go across domains if necessary.


Arian
April 27, 2020

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

Great article as always. Question, say I have an asp.net core web app servicing www.mainsite.com, is it possible to use URL Redirect to have all paths (ie. www.mainsite.com/api/*) to be serviced by a second asp.net core web app?


Xiul
April 19, 2020

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

Hi, great solution, I can't delete that folder with all others options... but yours works!!! yeahhhh....


Gopinath Sundharam
April 16, 2020

re: External Network Access to Kestrel and IIS Express in ASP.NET Core

Hi Rick, I should have found this article 2 days ago and saved a crap amount of time. You rock dude!


Raphael
April 15, 2020

re: Creating Angular Synchronous and Asynchronous Validators for Template Validation

Hey there, that's an awesome post there. I was wondering however. How would you do a really debounced async validator. Your current example sends a request with every keystroke. How can I debounce that in a way that it would send the first request to the server after a given timeout/debounce time and not produce 7 server calls for a 7 character word to check?


Alexey
April 14, 2020

re: Bootstrap Modal Dialog showing under Modal Background

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.addedNodes && mutation.addedNodes.length > 0) {
      // element added to DOM
      const hasClass = [].some.call(mutation.addedNodes, (el) => {
        return el.classList.contains('modal-backdrop');
      });
      if (hasClass) {
        // element has class `MyClass`
        $('.modal-backdrop').appendTo('DEFINEWHERETOAPPENDIT');
        console.log('element ".modal-backdrop" added');
      }
    }
  });
});

const config = {
  attributes: true,
  childList: true,
  characterData: true,
};

observer.observe(document.body, config);

Check this, work good on all modals. Add script at a bottom of the page.

https://stackoverflow.com/questions/10415400/jquery-detecting-div-of-certain-class-has-been-added-to-dom


Chris
April 13, 2020

re: Entity Framework and slow bulk INSERTs

Rick,

Just wanted to say a big thank you for this. I think context bloat was causing us some significant pain on a bulk insert operation using EF Core 3. Obviously AutoDetectChanges is now is a slightly different place inside DBContext.ChangeTracker, but it still works the same way. I am still waiting for my transaction to commit, but the preliminary results in the log seem to indicate a significant performance increase over single context with AutoDetect enabled. Thank you so much for taking the time to post this it continues to be very helpful.


Earthbound_X
April 11, 2020

Chris
April 10, 2020

re: Entity Framework and slow bulk INSERTs

Rick,

Just wanted to say a big thank you for this. I think context bloat was causing us some significant pain on a bulk insert operation using EF Core 3. I am still waiting for my transaction to commit, but the preliminary results in the log seem to indicate a significant performance increase over single context with AutoDetect enabled. Thank you so much for taking the time to post this it was very helpful.


Cory Harkins
April 07, 2020

re: Built-in GZip/Deflate Compression on IIS 7.x

Thank you for this advice and guidance. This is the only reliable way I've found to get Gzip or deflate to work on IIS 10. Even Azure support couldn't get it done for me.


Rick Strahl
April 06, 2020

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

The problem is that the WebSocket for port 5001 should probably be wss:// not ws://. SSL connections require an SSL socket so that's why that's failing.

Now I'm not sure why that's not being generated into the page correctly. If your page is https:// then the you should have this in your generated page script.

If it's https:// you should have:

var host = 'wss://localhost:5001/__livereload';

If it's http:// you should have:

var host = 'ws://localhost:5001/__livereload';

If you're seeing the latter in an https:// page which I think is what's failing for you, you are likely not using the latest version because it should generate the appropriate WebSocket URL in the C# code:

if (!string.IsNullOrEmpty(config.WebSocketHost))
    hostString = config.WebSocketHost + config.WebSocketUrl;
else
{
    var prefix = context.Request.IsHttps ? "wss" : "ws";
    hostString = $"{prefix}://{host.Host}:{host.Port}" + config.WebSocketUrl;
}

Andy
April 05, 2020

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

Very cool middleware indeed. Tried to put it in action (.netcore 3.1) Failed with the following error msg. Any suggestion? Thank you for sharing..

Websocket connection to β€˜ws://localhost:5001/__livereload' failed: Connection closed before receiving a handshake response


Rick Strahl
April 05, 2020

re: Use IIS Application Initialization for keeping ASP.NET Apps alive

@Pravin - it's not possible. Built into IIS when config changes are made the Application domain restarts. No way to make that not happen.


Pravin Jaiswal
April 04, 2020

re: Use IIS Application Initialization for keeping ASP.NET Apps alive

How to Avoid Application Domain / Pool Recycling or Restart in case of config changes.. How to achieve the same ? (ASP.Net)


Tsiro
April 01, 2020

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

Hi, Thanks for the article, very useful indeed. I have a similar asp.net app structure with a global.asax where unity container is configured. Is there a way to use objects injected in Application_Start() in owin startup class?


AnthonyV
March 30, 2020

re: Dealing with Anti-Virus False Positives

This has also been an ongoing battle for me.

My current solution is to have my build script automatically submit to virustotal via their API and fail if the success ratio is too low.

Often I can get success just by rebuilding all of the files.

I am almost at the point of sending automatic emails to the worst AV vendors with the false positives.

Anthony


Rick Strahl
March 26, 2020

re: Bypassing IIS Error Messages in ASP.NET

@Ferhat - You can use Failed Request Tracing and Logging to provide more info on failures in IIS. Enable on the site or the entire server and look in the relevant log folders (\inetpub\logs\FailedReqLogFiles) for more info.


Ferhat
March 26, 2020

re: Bypassing IIS Error Messages in ASP.NET

Thanks for the article. We have been trying to figure out why our new API was generating 500 errors after our deployment. Once we figure out IIS was intervening with the response, it was your article that allowed us to figure out what was actually going on and fix the issues. Thanks a lot, that issue was frustrating for us and we were able to fix it right away with your article.


David Elyk
March 25, 2020

re: Troubleshooting Windows Sleep Insomnia

Replying to @Jesse

I just ran across the same issue and finally tracked it down.

That Backup Scan is being run by windows task scheduler and if you try to make changes you will get a permission error even if you are running as Administrator.

Task Scheduler is set to run as SYSTEM, so you either have to grab ownership, make your changes, then set it back (I guess?) to SYSTEM.

-Or-

I installed Psexec.exe from Sysinternals and invoked Task Scheduler with it:

psexec -sid %windir%\system32\mmc.exe /s taskschd.msc

Then you can make changes and actually save them.

Task Scheduler Library > Microsoft > Windows > UpdateOrchestrator Click Properties > Click Conditions Tab

Now you can clear the Wake the Computer to run this task checkbox


Rick Strahl
March 24, 2020

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

@Carlos - Sorry I don't know but that sounds like an assembly that's not getting copied to the output folder properly.


Lex Li
March 23, 2020

re: ASP.NET Core and CORS Gotchas

I doubt whoever reported issues with IIS/IIS Express has enabled Windows authentication, which blocks anonoymous preflight requests.

For IIS the out-of-band CORS module can ease the pains, but for IIS Express Microsoft didn't have an installer. So I wrote a few PowerShell scripts to help https://github.com/lextm/iisexpress-cors


Carlos
March 23, 2020

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

Hello Rick, Thanks for the post. I am getting a similar error (500.0) but when I go to the event log I get: "Unable to find hostfxr directory at C:\dev\Repos\fina-resort-tax\src\ResortTax.Web.External\host\fxr". I am upgrading my project to .net core 3.0 from 2.2 and can't even run the application in Visual Studio 2019 v16.4.6. The application uses the Angular/dotnet template. Any hints will be appreciated. I've spent 2 days on this. Thank


Lukas
March 23, 2020

re: External Network Access to Kestrel and IIS Express in ASP.NET Core

Thank you for the quick reply! Sadly this seems like a deal-breaker for my project. Not to spam this thread an go too off-topic, but you seem to be quite the expert in this field so maybe you could direct me to a different approach: i wanted to have a simple pier to pier websocket application. (A client would start a edge kestrel and submit it's IP to a db where another client would then connect to the given IP) any ideas on how to achieve this in a .netcore environment?

Thanks


Rick Strahl
March 23, 2020

re: External Network Access to Kestrel and IIS Express in ASP.NET Core

@Lukas - you need to be an Administrator to do it so that's a problem if your app is not running as an Admin.


Lukas
March 21, 2020

re: External Network Access to Kestrel and IIS Express in ASP.NET Core

Hi, Can i open the port programmatically in order to have a server that's accessable from outside out of the box?


Rick Strahl
March 19, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

@Dbsquared - Personally I feel like ASP.NET Core's behavior oversteps its bounds by doing this sort of fixup. It should default to the stock behavior which is to return raw data results, and set flags to override to more 'open to interpretation' behavior.

To me a 204 response makes no sense for an endpoint that can return a JSON result. A 204 response should be reserved for results that never return data (ie. void results).


Rick Strahl
March 19, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

@Dbsquared - That's open to interpretation. If you ask your server application handler to return a typed result from a JSON endpoint and then it doesn't that's just not right. What should Angular do in that case? Assume a 204 is null? That's not cool either. I think Angular could maybe do something different here but in my view the behavior is as I would expect it - I'm asking it to expect a typed result and the server didn't give it to me. If the result is a null JSON response, Angular works properly because that matches the signature of the HttpClient.