Skip to main content

Posts

Showing posts with the label Visual Studio 2017

Impress your colleagues with your knowledge about … the Immediate window

Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I want to share today is a neat trick inside the Immediate window. With the Immediate window you can debug and evaluate expressions, execute statements, and print variable values. The Immediate window evaluates expressions by building and using the currently selected project. By default when you evaluate an expression in the Immediate window, the application state will change. If that’s not something you want, you can avoid it. Just add the , nse (no side effects) postfix to an expression, and it will evaluate without changing the application state. More information: https://docs.microsoft.com/en-us/visualstudio/ide/reference/immediate-window?view=vs-2019

NuGet PackageReference–PrivateAssets

Visual Studio 2017 and .NET Core introduced the new csproj format where your NuGet packages are no longer referenced through a Packages.config file but are added to your csproj file: If you want to create a NuGet package from your project, you no longer need a separate configuration file but your csproj file can contain all the information about your NuGet package. It will automatically include all PackageReferences that you are using, so gone is all the copy/paste work. But what if you have a dependency that is purely used during development and that you don’t want to expose to projects that will consume your package? In this scenario, you can use the PrivateAssets metadata to control this behavior. There are multiple possible values that you can find in the documentation: https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#controlling-dependency-assets

EditorConfig - Let private fields start with an underscore

I find code consistency really important. This removes a lot of mental burden from the developer. One of the conventions that is quite common in C#is to use camelCase for local variables and _camelCase for private or internal fields. An example: Unfortunately this convention is not automatically enforced by Visual Studio. To fix this you can add an editorconfig file with the following rules: dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style   dotnet_naming_symbols.instance_fields.applicable_kinds = field   dotnet_naming_style.instance_field_style.capitalization = camel_case dotnet_naming_style.instance_field_style.required_prefix = _

Visual Studio 2019 - Migrate from packages.config to PackageReference

Starting from Visual Studio 2017 Version 15.7 there is built-in support for migrating project from the packages.config management format to the PackageReference format. The new format has some advantages like: Only top-level dependencies are listed Performance improvements thanks to the usage of a global-packages folder To migrate from the old to the new format, right-click on a package.config file inside your project and choose Migrate package.config to PackageReference from the context menu. This will load the following view: It gives you a clear view of the identified top-level dependencies, any transitive dependencies and possible compatibility issues. If a package is accidently flagged as transitive you can still promote it to a top-level dependency by hitting the checkbox. I’m currently in the process of migrating a big project and this makes my job so much easier! More information: https://docs.microsoft.com/en-us/nuget/reference/migrate-packages-c...

Serilog–Code Analyzer

With the introduction of Roslyn as the compiler platform in Visual Studio, we got support for Roslyn analyzers. If you never heard about it, read this great introduction here; https://andrewlock.net/creating-a-roslyn-analyzer-in-visual-studio-2017/ . Although creating your own analyzer is not that easy, using them is. And there are a lot of situations where an analyzer can prevent you from making some stupid mistakes. One example I liked was when using Serilog. Serilog is a structured logging framework where your messages are logged using message templates. Parameters used inside these message templates are serialized and stored as separate properties on the log event giving you great flexibility in searching and filtering through log data. Here is an example from the Serilog website : The Position and the Elapsed properties are stored separately from the message. Problem is that you can easily make a mistake, although the message template expects 2 parameters it is possibl...

Git–Lightweight vs Annotated tags

While investigating some ways to label our releases inside Azure DevOps I discovered that there are in fact 2 types of tags:  lightweight and annotated . From the documentation : A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit. Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too Azure DevOps Services and TFS support both annotated and lightweight tags.  Go to the Repos section(1) and select Tags from the menu(2). Now you can start searching for both tag types(3): When you type a tag name, tags are filtered. An...

ASP.NET Core IIS - Application failed to start process with commandline '%LAUNCHER_PATH% %LAUNCHER_ARGS%'

After deploying an ASP.NET Core application to IIS, it failed to start with the following error message: Application 'MACHINE/WEBROOT/APPHOST/SampleApp/' with physical root 'C:\Sites\sampleapp\' failed to start process with commandline '%LAUNCHER_PATH% %LAUNCHER_ARGS%', ErrorCode = '0x80070002' : 0. So what is going on? By default when you add a web.config file to your ASP.NET core project, the following configuration is added: You see the 2 environment variables'(%LAUNCHER_PATH%, %LAUNCHER_ARGS%) that are added to the config and also mentioned in the error message above. These 2 variables are their for Visual Studio and are replaced by Visual Studio when you try build and run your app. For example when you do a debug build, the web.config is transformed to: <aspNetCore processPath=" C:\Program Files\dotnet\dotnet.exe " arguments=" exec &quot;C:\projects\sampleapp\bin\Release\netcoreapp2.2\sampleapp.dll&q...

Visual Studio 2017 - No projects supported by NuGet in the solution

I started my day with a rather fun error message in Visual Studio. Visual Studio failed in building my application. When I took a look at the error messages I noticed that Visual Studio failed to download all dependencies from NuGet. However when I tried to open the Nuget Package Manager console, I got the following error message: A magical restart did the trick…

Visual Studio 2017–SQL Server Data Tools- Custom assemblies could not be loaded

On one of my SQL Server Reporting Services reports, I had to use some custom logic. Instead of embedding the code directly into the report, I decided to create a separate assembly which makes it easier to test and debug this code. After importing the assembly in my Visual Studio 2017 Reporting Services project, I couldn’t load the Report Designer preview window anymore. Instead I got the following error message: An error occured during local report processing. The definition of the report ‘/samplereport’ is invalid. Error while loading code module: ‘Sample.Barcode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’. Details: Could not load file or assembly ‘Sample.Barcode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified. To fix this I had to copy the DLL to the following location: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\SSRS ...

Reset your keyboard bindings after disabling Resharper

As Visual Studio was getting really slow, I decided to disable Resharper (again). If I really wanted the power of Resharper, I could always open up Rider and continue coding there. After disabling Resharper I noticed that some of my keyboard shortcuts no longer worked. The Resharper functionality was gone but it was not replaced by the Visual Studio keyboard binding. Time to fix it: Open Visual Studio and type ‘keyboard’ in the Quick search Click on Environment –> Keyboard to go to the Visual Studio options Select a Keyboard mapping scheme from the drop down menu and click Reset to activate it.

ASP.NET–Optimize build performance for solution

After updating to Visual Studio 2018 Update 15.8 I noticed a new menu option in Visual Studio under Build –> ASP.NET Compilation –> Optimize Build Performance for Solution: What does it do? ASP.NET projects carry a copy of the compiler to be able to compile views at runtime. However, on a developer machine when the copy of the compiler doesn’t match Visual Studio’s copy, your build performance is impacted on the order of 1-3 seconds per incremental build. Enabling this feature will update your project’s copy of the compiler to match Visual Studio’s which should speed up your incremental builds. When you select the menu option, you’ll get a screen that allows you to select all projects where to apply this change: After you click OK, Visual Studio will replace the Microsoft.Net.Compilers package with a newer Microsoft.CodeDom.Providers.DotNetCompilerPlatform package: Remark: This is applicable to ASP.NET Framework projects only, it does not apply to ASP.NET Core.

AsyncFixer–Avoid common async/await anti-patterns

I spend a large part of my day reviewing other people’s code. Seeing all this code over the years has brought me to at least one conclusion; software development is hard and multithreaded programming is even harder. Although the introduction of the Task Parallel Library and the async/await keywords has helped to simplify multithreaded programming a lot, I still see developers making a lot of mistakes when using async/await. A good code analyzer that I can recommend to avoid some of these mistakes is AsyncFixer . It will help you to avoid the following anti-patterns: Unnecessary async/await Methods Using Long-running Operations under Async Methods Fire & Forget Async void Methods Fire & Forget Async Call In the Using Block Implicit Downcasting from Task<T> to Task If you want to learn more about these and other mistakes, have a look at http://www.learnasync.net/ . Usage The easiest way to start using it is by adding the AsyncFixer nuget...

Visual Studio Tip–Add existing on steroids

If you want to add multiple files to a traditional Visual Studio project(not .NET Core), the default procedure is the following: Right click on your project. Choose Add –> Existing Item… Choose one or more items from the ‘Add Existing Item’ dialog and click Add . A faster alternative instead of using ‘Add existing’ is the following trick: Right click on your project and choose Unload project Right click on the unloaded project and choose Edit csproj file. Now add the following line to the MSBuild file: <Compile Include="**\*.cs" /> Visual Studio will load all .cs files it found.

C#– Creating memory efficient and side-effect free functions using the in parameter modifier

C# keeps improving and with the release of C# 7.2 we can start using the in parameter modifier . Let’s explain a situation where this can be useful: Imagine you created a big struct, that you have to pass as an argument to a function. Everytime you call this function, a new copy of this struct will be created. If this function is called a lot of times, the performance impact can be significant. A solution would be to use the ref parameter modifier. This allows us to pass a reference to the instance (value type or reference type). Unfortunately any change to the argument in the function will also impact the calling method.  To solve this the C# team introduced another keyword in which provides the ability to pass the argument as readonly . It fails at compile time if there is any code which tries to modify in the called method. Limitations: You can't use the in keyword for the following kinds of methods: Async methods, which you define by using the async mod...

Parameterized tests with MSTest

I’ve always been an NUnit or XUnit user, but from time to time I take another look at MSTest to see where Microsoft is going with their Test framework. With the latest version MS-Test 2, Microsoft introduced a new feature: parametrized tests (Do I have to mention that this feature exists for a long time in NUnit and XUnit? ). Let’s try it: Create a new Test project in Visual Studio 2017. Th test Project template already includes the MsTest.TestAdapter and MsTest.TestFramework NuGet packages. Right click on your project, select Manage NuGet packages… Update the test packages to the latest version. The default packages are a little bit outdated. Let’s write our parameterized test: Notice that there are some small differences: Instead of the TestMethod attribute, we are using the DataTestMethod attribute Instead of a method without parameters, we expect one parameter as part of our test. Now we have to provide the different possible values ...

Debugging a .NET Core project in VS 2017 - Unable to start program, An operation is not legal in the current state

When trying to debug a .NET Core application using Visual Studio 2017, attaching the debugger suddenly started to fail with the following error message: Unable to start program, An operation is not legal in the current state Starting without a debugger attached worked, but attaching the debugger later on didn’t. Rebuilding my project, restarting Visual Studio, restarting my PC, all seemed to not bring a solution to the table. This is a known issue , the solution (workaround) is to turn off JavaScript debugging on Chrome: Go to Tools –> Options –> Debugging –> General Turn off the setting for Enable JavaScript Debugging for ASP.NET (Chrome and IE) Remark: A fix will be provided in the Visual Studio 2017 15.6 release.

F# with .NET Core in Visual Studio

Microsoft has supported F# on .NET Core from the beginning. Unfortunately the same story is not true when we talk about Visual Studio integration. Before, if you wanted to use F# in combination with .NET Core, you had to use VS Code.  With the release of Visual Studio 2017 15.5, this has finally changed and Visual Studio integration is available.

Visual Studio 2017 (Enterprise) - Where are the Web performance and load testing tools?

Yesterday I wanted to do some performance testing before we put a new application into production. However when I opened Visual Studio (2017) I couldn’t find the Web performance and load testing tools. Are there no longer available in VS 2017? Luckily, they still are. But they are not installed out-of-the-box. Let’s open the Visual Studio installer and fix this: Search for Visual Studio Installer and execute it Click on More –> Modify Go to the Individual components tab, scroll to the Debugging and testing section and select Web performance and load testing tools . Click Modify to start the installation

Impress your colleagues with your knowledge about…Expression Evaluator Format Specifiers

Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago are Expression Evaluator Format Specifiers . What is it? Expression Evaluator Format Specifies come into the picture when you are debugging in Visual Studio. The part of the debugger that processes the language being debugged is known as the expression evaluator (EE). A different expression evaluator is used for each language, though a default is selected if the language cannot be determined. A format specifier , in the debugger, is a special syntax to tell the EE how to interpret the expression being examined. You can read about all of the format specifiers in the documentation . One of really useful format specifiers is the ‘ac’ (always calculate) format specifier. This format specifier will force evaluation of the expression on every step. This is...

Enabling Application Insights on an existing project

Yesterday I lost some time searching how to Enable Application Insights on an existing project in Visual Studio. I thought it was available on the context menu when you right click on your Visual Studio project, but no option found there: Turns out you need to go one level deeper ; Right click on your project Click on Add and select Application Insights Telemetry… Now you can go through the configuration wizard by clicking on Start Free :