Recent Comments



Rick Strahl
Friday

re: Creating a .NET Global Tool from an existing Console Application

@Jon - sure you can do that, but you're still dependent on the .NET Core SDK and Runtime to run this. Global tool solves this problem. Having a .bat/ps1 file to do this for you is a bit hokey at least for a non-internal tool. Note that you can do a local install via dotnet tool install with a --add-source= pointing at a local folder which gives you a global tool without having to install from a public package manager.


granadaCoder
Friday

re: Strongly Typed Configuration Settings in ASP.NET Core

Thanks @Sean Fackrell. That is the "collection" example and magic syntax sugar (the "List" comment) that I needed. Thanks Ricks for the post.


Allen Salinas
Friday

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

Thank's a lot for this information. After many days trying to figure it out, this post helped me to do it. Again, thanks from Colombia.


Jon Seeley
Thursday

re: Creating a .NET Global Tool from an existing Console Application

Rick your post for this was quite timely as I had just barely decided to convert an old full framework console application over to .NET Core last week. I hadn't even got far enough to try to run it outside the debugger when I happened to pull up your blog and lo!, you're telling me that it won't compile as an exe.

For what it's worth, I figured you can also just create a simple batch file to put alongside your application and have dotnet MyConsoleApplication.dll -c Release %* (or %1, %2, etc for passed in arguments)?


Dan
Tuesday

re: More on ASP.NET Core Running under IIS

I just wanted to thank you for this, it just saved me major headaches. We were doing performance testing on our new .net core app and we were getting horrible results compared to our previous version (non-core). This was the only article I could find that hinted at static files being the issue and so I switched it to use IIS to serve the static files and we instantly saw a 400% increase in performance. Thanks!


Reginaldo Villela
Tuesday

re: Multi-Targeting and Porting a .NET Library to .NET Core 2.0

Hey Rick!

thanks for answering me.

I did the following to solve my problem.

For each framework version, I changed the AssemblyName of each output. So I can get a file with a different name for each version of the framework. See below how it was:

<PropertyGroup Condition="'$ (TargetFramework)' == 'net471'">
  <AssemblyName>DbConnector.Net471</AssemblyName>
  <DefineConstants>NET471;NETFULL</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition="'$ (TargetFramework)' == 'net472'">
  <AssemblyName>DbConnector.Net472</AssemblyName>
  <DefineConstants>NET472;NETFULL</DefineConstants>
</PropertyGroup>

Rick Strahl
November 10, 2018

re: Multi-Targeting and Porting a .NET Library to .NET Core 2.0

You know I'm not sure if you can change the name of the assembly in an SDK project. I think the project is what determines the output of the package. You could however rename the file after build and that should work - there's nothing magical about the file name as it's just a container for the binary module.


Rick Strahl
November 10, 2018

re: Slow Connections with Sql Server

I've never seen problems with . for local servers either with SQL (which definitely works) or with server designations from a command prompt or powershell.


JustMe
November 10, 2018

re: Slow Connections with Sql Server

In the connection string, do not use the . [dot] or local for 'server'. Use localhost or an FQDN instead. While the . [dot] or local are valid (and still documented), they no longer work well with newer Windows/SQL/Powershell versions. Not sure if this fixes slow connections, but it resolves quite a few other issues including failed connections. Unfortunately, Microsoft is unwilling to document this new behavior.


Reginaldo Villela
November 09, 2018

re: Multi-Targeting and Porting a .NET Library to .NET Core 2.0

Hey Rick, how's going?

Congrats for article... awesome!

Is it possible to change the name of the DLLs by putting the framework version at the end (Ex: myconectionNet471.dll) and generating all in the same directory?

Thanks! Reginaldo VIllela


Steve
November 09, 2018

re: Dealing with Anti-Virus False Positives

Hi Rick

Thanks for this article. Just ran into a similar issue after upgrading InstallShield to 2018 R2. Swapped to Inno Setup and the Anti-virus false-positives disappeared.

Maybe something to do with not recognising the latest InstallShield version?

Thanks once again.

Steve


Mizumaky
November 07, 2018

re: Windows 10 Bash Shell Network Connectivity not working?

Tried many methods which didnt work when finally TURNING OFF my Kaspersky Free ANTIVIRUS helped me with the network problems. (by turning off i dont mean just pausing protection)


James MacIvor
November 05, 2018

re: ASP.NET Core and CORS Gotchas

Just a note for anyone who's having a rough time on an Azure deployment and somehow reads down this far. If you configure CORS in Azure via the portal then it will override your code CORS policies. This means that if you are using .WithCredentials and .AllowAnyHeader and etc then all of that will inexplicably stop working. Once you remove the Azure configuration then it will work normally.

You should add your any string values (like origin) as an AppSetting, but let ASP .NET Core (and not Azure) handle the CORS implementation.


Rick Strahl
November 04, 2018

re: Web Assembly and Blazor: Re-assembling the Web

When it comes to browser client side stuff, Microsoft has just never gotten it right. Never. Ever. So all the trepidation I hear from you in the comments - I agree and I said so in the post. I do like the way Blazor works, but after talking with a number of people outside of the Microsoft space in the last few weeks I'm almost certain that Blazor will be complete failure because nobody outside of the Microsoft already using Razor and server side ASP.NET space will get it. That's too small of a market to make a difference and for something like this to survive I think. The eco-system will just be too small to be functional and to be carried forward. Even it if becomes moderately popular in the MS space, Microsoft is likely to lose interest and ditch it just like all other client side technology.

I'd change my mind if MS would step up and push this in a bigger more public way, but that's clearly not happening at this point. If that doesn't change, Blazor is destined to be a niche tool...


Felice Ferri
November 04, 2018

re: LINQ to SQL and attaching Entities

Had exactly the same problem.

In my case, the problem was because I was using the same Context to perform a Query.

I mean, I looked for the Record if it didn't exists I did an InsertOnSubmit, if it did exists I did an Attach and there is where it failed (Did everything, rowversion column, tagged as timestamp in the .dbml etc)

When I decided to create to different instances of the Context, one for the search of the existence of the record, dispose that and then instantiate a new one for the Attach/Insert is just worked.


Adam
November 03, 2018

re: Web Assembly and Blazor: Re-assembling the Web

Adding to the comment above... It is sad the way Microsoft has been going about this. I'm sure all of us remember the massive hype around the release of Angular by Google, which in early versions was less functional than Blazor at this point, but still got an official release! It feels like Microsoft 'fell' into Blazor by accident, only to reveal that it does NOT match it's corporate bottom line - the increase of revenue of Server-side platforms/Services/resources - also known as Azure. So, in order to enjoy the benefit of all the interest in Blazor they will release some server side functionality... instead of that it is supposed to be - client side code running by the Browser. Sorry to be the one to rain on this parade, I would be happy to be proven wrong, Adam 😦


Chris Bailiss
October 30, 2018

re: Capturing Performance Counter Data for a Process by Process Id

Useful code Rick, thanks.

Re: the problem described above of counters shuffling, e.g. when one instance of chrome closes. I took the following approach:

  • Use the .NET Process class to track all running instances of the EXE I am interested in monitoring.
  • When any of these instances exits, I get all of the perf counters again using GetPerfCounterForProcessId().

This approach works because the .NET Process class is quite lightweight and it means I don't need to continuously call the heavy (but useful) GetPerfCounterForProcessId() to validate that none of the instances have shuffled around. It is still a faff though. It's fairly unbelievable Windows has been around for so long and there is still no way to directly lookup a Performance Counter using a Process ID...


Adrian
October 30, 2018

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

As for binding to non-localhost URL in Kestrel, why not just modify the applicationUrl in launchSettings.json?


Rick Strahl
October 29, 2018

re: Slow Connections with Sql Server

@Scott - Yeah that's what I thought - but I tried on a few different machines including a VM that's not part of any Windows network. Each one of them is slow. And you would think named pipes would first look for local connections before jumping to another machine given that it's an explicit server specification. I use named pipes via code in some local applications on my dev machines for inter-process communication and that's not slow - connections/responses with that are instant.


pixelda
October 29, 2018

re: Easy Configuration Binding in ASP.NET Core - revisited

I'm using MVC 2.1 and it is likely that services.AddConfiguration() is now part of the internal start up. As always Rick, an informative and useful article


Scott Ferguson
October 28, 2018

re: Slow Connections with Sql Server

From my understanding, if anything, Named Pipes should be quicker than TCP/IP. I wonder if the fact that you're not seeing that is more of a reflection of your network?

Anyway, according to the MS docs: "Generally, TCP/IP is preferred in a slow LAN, WAN, or dial-up network, whereas named pipes can be a better choice when network speed is not the issue, as it offers more functionality, ease of use, and configuration options."

Check it out for yourself here: https://docs.microsoft.com/en-us/sql/tools/configuration-manager/choosing-a-network-protocol?view=sql-server-2014


Paul
October 28, 2018

re: Fixing Visual Studio Intellisense Errors

One thing to add to this, particularly in older versions of VS, is that hibernating or sleeping your laptop, after a long day's night, can also play hokey with the old IntelliSense.


Ayush Choudhary
October 27, 2018

re: Entity Framework and slow bulk INSERTs

Hi Rick,

Can you explain how batching will work here. I am reading the IIS Logs and creating JSON line by line and pushing to API.

Here is my API:

public async Task Post(IISLog iislog) { if (!ModelState.IsValid) { return BadRequest(ModelState); }

        db.IISLogs.Add(iislog);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = iislog.Id }, iislog);
    }

Gilson
October 26, 2018

re: WCF WS-Security and WSE Nonce Authentication

Hi Rick, good afternoon.

Thanks for this article.

I'm following it, but I'm getting the error: System.ServiceModel.FaultException: 'The message has expired'

Already tried add:

binding.OpenTimeout = new TimeSpan (0, 10, 0);

binding.CloseTimeout = new TimeSpan (0, 10, 0);

binding.SendTimeout = new TimeSpan (0, 10, 0);

binding.ReceiveTimeout = new TimeSpan (0, 10, 0);

But I still get that error.


Steve Harrison
October 24, 2018

re: Excluding the node_modules Folder in Visual Studio WebSite Projects

Although the trick of hiding the folder didn't work for me in VS 2017, you explained the nature of the problem perfectly, and that's half the battle. Thanks!


Eric Newton
October 24, 2018

re: Which .NET Core Runtime Download do you need?

Wow, this is a great breakdown summary and big picture info for NetCore

Thanks for this, Rick!


arnc
October 22, 2018

re: WCF WS-Security and WSE Nonce Authentication

Very good post. In my project, I need to add both BinarySecurityToken and UsernameToken together and I applied this solution, .NET doesn't allow me to add UsernameToken part. Is there any way for that?

Thanks in advance.


Shruthy
October 22, 2018

re: jQuery-resizable and Table Column Resizing

Hi Rick, The code on table column resizing is good. But you can also show the content inside the cell editable while resizing the column.


zameer fouzan
October 22, 2018

re: Easy Configuration Binding in ASP.NET Core - revisited

I used your singleton example in my application and noticed that as of version 2.1.403,

services.AddConfiguration()

is not supported and all works just fine without it.

Not sure if it is done implicitly by IConfiguration. Need to figure it out .

Thanks for a great example.


Matt
October 19, 2018

re: Tip: Open Visual Studio Code from Visual Studio as an External Tool

Awesome tip - I too have found myself using Visual Studio and VS Code at the same as of late.


Chris
October 18, 2018

re: Resetting Entity Framework Migrations to a clean Slate

How about this?

  1. Remove the _MigrationHistory table from the Database
  2. Build project solution - to be safe
  3. Update-Database -Script
  4. Remove everything in script except for the create _MigrationHistory table and entires
  5. Apply the the modified script to IndviewQS1 database

Alex
October 18, 2018

re: Accessing Configuration in .NET Core Test Projects

Very useful post. Thanks Also for missing packages, the search box in MSDN is (finally) pretty handy, so queries by extension methods take you to the missing DLL.

https://docs.microsoft.com/en-gb/dotnet/api/index?view=aspnetcore-2.1


Austin Salgat
October 15, 2018

re: GZip/Deflate Compression in ASP.NET MVC

For those curious, here is a version updated for ASP.NET Web Api 2 (the CompressedContent class is copied from: https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/Content/CompressedContent.cs).

    // SOURCE: https://weblog.west-wind.com/posts/2012/Apr/28/GZipDeflate-Compression-in-ASPNET-MVC
    /// <summary>
    /// Attribute that can be added to controller methods to force content
    /// to be GZip encoded if the client supports it
    /// </summary>
    public class CompressContentAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// Override to compress the content that is generated by
        /// an action method.
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            GZipEncodePage(actionExecutedContext);
        }

        /// <summary>
        /// Determines if GZip is supported
        /// </summary>
        /// <returns></returns>
        public static bool IsGZipSupported(HttpActionExecutedContext actionExecutedContext)
        {
            var acceptEncodings = actionExecutedContext.Request.Headers.AcceptEncoding.Select(entry => entry.Value).ToList();
            return acceptEncodings.Contains("gzip") || acceptEncodings.Contains("deflate");
        }

        /// <summary>
        /// Sets up the current page or handler to use GZip through a Response.Filter
        /// IMPORTANT:  
        /// You have to call this method before any output is generated!
        /// </summary>
        public static void GZipEncodePage(HttpActionExecutedContext actionExecutedContext)
        {
            var response = actionExecutedContext.Response;
            if (response == null) return;

            if (IsGZipSupported(actionExecutedContext))
            {
                var acceptEncoding = actionExecutedContext.Request.Headers.AcceptEncoding.Select(entry => entry.Value);

                response.Content = acceptEncoding.Contains("gzip") ? 
                    new CompressedContent(response.Content, "gzip") : 
                    new CompressedContent(response.Content, "deflate");
            }

            // Allow proxy servers to cache encoded and unencoded versions separately
            response.Headers.Add("Vary", "Content-Encoding");
        }
    }

Jason Robert
October 11, 2018

re: Tip: Open Visual Studio Code from Visual Studio as an External Tool

Nice tip Rick! I've used External Tools in the past but, haven't thought of wiring up VS Code. Great idea for those who like to do backend api work in Visual Studio and front end tasks in VS Code.


Brian
October 10, 2018

re: Gotcha: Entity Framework gets slow in long Iteration Loops

Thanks for this! Very relevant to EF Core. Using a new context for each time through a loop shaved a 13 minute process to 17 seconds!


Jedidiah May
October 09, 2018

re: Tip: Open Visual Studio Code from Visual Studio as an External Tool

I love working in Visual Studio code, but hated having to switch out different projects. Love this information. Thanks! I just set it up, and it works beautifully! Spot-on directions and easy to follow screenshots.


Francesco R.
October 09, 2018

re: Creating Single Instance WPF Applications that open multiple Files

Thank you, beautiful post. Very helpful and straightforward.

Francesco.


Rick Strahl
October 07, 2018

re: Tip: Open Visual Studio Code from Visual Studio as an External Tool

Thanks for the extra tips Eric.

FWIW, For Markdown Monster I like to associate .md file with the Markdown Monster executable in the Open With dialog.


Eric N Smith
October 07, 2018

re: Tip: Open Visual Studio Code from Visual Studio as an External Tool

"The one downside to External Tools is that they are not easily exportable"

I'm a big fan of External Tools as well. (I even have one for MarkdownMonster). The link directions here work fine for me for exporting the tools. It doesn't do the shortcuts though. For that Mads has a plugin.


Ashok
October 04, 2018

re: Strongly Typed Configuration Settings in ASP.NET Core

Hi Rick,

Very nice and useful article. I spent two weekends in figuring out why IEmailSender is not getting initialized properly. Finally I stumbled upon your article and got clarity on how configurations are getting injected in ASP.Net Core 2.

Keep up the good work 😃

Cheers, Ashok


Rick Strahl
October 04, 2018

re: Strongly Typed Configuration Settings in ASP.NET Core

Not sure what you mean by Repo pattern. You mean Dependency Injection?

If you don't want to use that you can have a static property on your data layer that you can populate during initialization of the application. Just set the static property and then you have it anywhere.

I tend to do that myself because like you I have some components that may not be part of DI and a static is easy to hold this stuff with in lieu of DI on the few occasions where it's not available.


Johann
October 04, 2018

re: Rendering ASP.NET MVC Views to String

Very nice article and very useful code, indeed, but I came across something and cannot seem to find a reason for it other than my lack of understanding the RazorView Engine well enough.

Creating a partial view with a model and then attempting to use HTML Helpers (eg @Html.DisplayFor(m => m.SomeProperty)) results in a NullReferenceException occuring when calling view.Render(ctx, sw);. It took me some time to figure out I should just go with @Model.SomeProperty to prevent the NullReferenceException. Any idea on why?


mark
October 03, 2018

re: Strongly Typed Configuration Settings in ASP.NET Core

If I am not using the repo pattern, is the another way/best practice to pass the config/app settings to my datalayer? Currently my dbstring is in the data layer in a class, but I want to move it to appSettings or somewhere else(encrypted of course). Just not sure how to get it down to my data layer from the controller without passing it in the method call or injecting it somehow? Thanks and nice article. I guess I will use the repo pattern next time, ugh...


Susheel
September 28, 2018

re: Accessing Configuration in .NET Core Test Projects

@Kevin,

Following additional packages are required.

Setting the base path of the app with SetBasePath. SetBasePath is made available to an app by referencing the Microsoft.Extensions.Configuration.FileExtensions package. Resolving sections of configuration files with GetSection. GetSection is made available to an app by referencing the Microsoft.Extensions.Configuration package. Binding configuration to .NET classes with Bind and Get. Bind and Get are made available to an app by referencing the Microsoft.Extensions.Configuration.Binder package. Get is available in ASP.NET Core 1.1 or later.


Sudhir
September 28, 2018

re: Angular Select List Value not binding with Static Values

Thank you so much. I spent almost half a day to find out its just a "" + value to bind value to select element.


Tolga
September 26, 2018

re: WCF WS-Security and WSE Nonce Authentication

Is it possible to make nonce authentication in .Net Standards 2.0?

I could not manage to use the CustomCredentials in my code.

Thanks for your feedback in advance


Markus
September 25, 2018

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

Hi Rick,
thanks for your article! I had a quite strange problem that surfaced as an IOException stating "An established connection was aborted by the software in your host machine". After verifying that the problem lies on my server (not the other side), I found that it must have something to do with HttpWebRequest authentication:

  • The abort always occured on the second request to the same server (but different url).
  • Fiddler showed me that the request actually was sent and got a correct response, nevertheless .NET threw the error.
  • Fiddler also showed me that the erroneous request did not send the Authentication header although HttpWebRequest.PreAuthenticate was set and it was not the first request (no 401 challenge).

Your blog to the rescue: I manually created the Authentication header according to your example and disabled HttpWebRequest.PreAuthenticate as well as HttpWebRequest.Credentials. And the IOException was gone.


Bilal Haidar
September 16, 2018

re: Easy Configuration Binding in ASP.NET Core - revisited

Hello @Rick,

if you can think of a good example or use case please chime in with a comment I would love to elaborate this point here.

Reading David's tweet above, I believe, when you are building a modular application in ASP.NET Core, where multiple modules need to "inject" something that needs to be retrieved later by a certain "Core" module (assuming you need to collect settings from all modules in the app). Then, by using services.Configure() multiple times (each module will be using it), then this way, the ASP.NET Core Framework would collect all instances from all modules and make them available for you.

For instance, you might define a Dictionary read-only property inside a custom Options class and then each module would read that dictionary and append to it some settings or whatever the business logic you need.

The end result is that the custom Options class having its read-only dictionary property, collecting all values that were added by all modules.

That's how I could think of it!

What do you think?