Visual Studio Run Code



  • In Visual Studio I open Somepage.cshtml by double clicking it. With Somepage.cshtml as the active window when I run the project with Ctrl+F5 the Index.cshtml page opens in the browser. Is there a way to force Visual Studio to open the active page? In this scenario Somepage.cshtml?
  • เนื้อหาในคลิปจะสอนถึงวิธีการปรับแต่ง Code runner extension เพื่อให้ compile และ run.
Home / Using Code Analysis with Visual Studio 2019 to Improve Code Quality

Compile and Run C/C Code in Visual Studio Code October 28, 2020; Mar 282021. Compile and Run C/C Code in Visual Studio Code. 6 Code Help Pro March 28, 2021. Looking for IDE to compile and run C/C code Many beginner developers are searching for IDE to.

Overview

The Code Analysis feature of Visual Studio performs static code analysis to help developers identify potential design, globalization, interoperability, performance, security, and a host of other categories of potential problems. Code Analysis can be run manually at any time from within the Visual Studio IDE, or even setup to automatically run as part of a Team Build or check-in policy for Azure DevOps Server.

In this lab, you will be introduced to Code Analysis, how to configure rules sets to use, and finally how to suppress specific rules at a project and source code level.

Prerequisites

In order to complete this lab you will need the Azure DevOps Server 2019 virtual machine provided by Microsoft. Click the button below to launch the virtual machine on the Microsoft Hands-on-Labs portal.

Alternatively, you can download the virtual machine from here.

About the Fabrikam Fiber Scenario

This set of hands-on-labs uses a fictional company, Fabrikam Fiber, as a backdrop to the scenarios you are learning about. Fabrikam Fiber provides cable television and related services to the United States. They are growing rapidly and have embraced Windows Azure to scale their customer-facing web site directly to end-users to allow them to self-service tickets and track technicians. They also use an on-premises ASP.NET MVC application for their customer service representatives to administer customer orders.

In this set of hands-on labs, you will take part in a number of scenarios that involve the development and testing team at Fabrikam Fiber. The team, which consists of 8-10 people has decided to use Visual Studio application lifecycle management tools to manage their source code, run their builds, test their web sites, and plan and track the project.

Exercise 1: Introduction to Code Analysis

In this exercise, you will learn about the code analysis features in Visual Studio 2019 by configuring the rule set used, performing code analysis on a sample project, and addressing some of the warnings that are raised.

Task 1: Working with Code Analysis

  1. Log in as Sachin Raj (VSALMSachin). All user passwords are P2ssw0rd.

  2. Launch Visual Studio from the taskbar.

  3. From the Start Page, click FabrikamFiber.CallCenter.sln to open it.

  4. Select Build | Rebuild Solution from the main menu to build the solution.

  5. In Solution Explorer, right-click the FabrikamFiber.Web project node and select Properties.

  6. Select the Code Analysis tab in the project properties window.

    Note: The Code Analysis tab allows you to choose from sets of rules rather than picking and choosing from one flat list of rules.

  7. The currently selected Rule Set is Microsoft All Rules, which provides a comprehensive set of rules. As you can see, there are other rule sets to choose from based upon your needs.

    Note: If you are interested in learning how to create custom rule sets, please see this MSDN documentation.

  8. In Solution Explorer, right-click the FabrikamFiber.Web project node and select Analyze | Run Code Analysis.

  9. The Code Analysis feature runs through static code analysis rules as defined by Microsoft and displays the results in the Code Analysis window. Scroll through the list of results and read a few of them.

    Note: Depending on the version of FabrikamFiber that you are running, you may see more or less results than depicted in screenshots.

  10. Code Analysis rules can also be configured to show up as errors if desired. The warnings produced by Code Analysis provide a wealth of information including a unique ID (such as CA1020 in the screenshot above), a description of the problem or suggested fix, and the file location of the offending code.

  11. The Error List window contains a search box where you can filter code analysis results on warning number, text in the title or message of the warning, as well as filename or function name.

  12. Enter “CA1804” into the search box.

  13. Double-click the result shown in the Error List window to load the specified location in the code editor.

  14. Now we will perform the code fix necessary to resolve the warning. For CA1804, we are told that we should remove unused locals. Resolve the warning by removing the declaration of the “var report =” variable.

  15. Run the code analysis once again to verify that the warning disappears as expected. There should be one less warning than before.

Task 2: Suppressing Code Analysis warnings

  1. In this exercise, you will learn how to suppress Code Analysis warnings at the project and source level.

  2. Clear the search box in the Error List window.

  3. In the Error List window, select the first three warnings by clicking the first, holding the Shift key, and clicking the third. Imagine that we do not want to address the selected issues and no longer want them to appear when Code Analysis executes.

  4. Right-click the selected warnings and select Suppress | In Suppression File from the context menu. This will add assembly level metadata to a project level GlobalSuppressions.cs file.

  5. Open the newly created GlobalSuppressions.cs file from the FabrikamFiber.Web project in Solution Explorer to view the added code.

  6. Return to the Error List window and locate the first CA1704 warning (use the search) that suggests correcting the parameter name “serviceticket” for the method Create. Double-click it to load the associated source.

  7. Right-click the “serviceticket” parameter and select Rename… from the context menu.

  8. Change “serviceticket” to “serviceTicket” (capital “T”) and select the Apply button. The code analysis engine will now parse this as two correctly spelled words using camel casing.

  9. In the Error List, double-click the CA1704 warning for Edit to view the source. Suppose that we want to suppress this specific rule, but this time we only want it applied to the associated source file. Right-click the warning in the Error List and select Suppress | In Source.

  10. This applies a SuppressMessage attribute to the method.

  11. Run the code analysis once again for FabrikamFiber.Web and note that there are fewer warnings listed.

  12. At this point, there are additional Code Analysis warnings that we could address, but imagine that we simply want to relax the rules for now. Return to the Properties page for FabrikamFiber.Web. Switch the active Rule Set to Microsoft Managed Minimum Rules.

  13. Run the code analysis once again for FabrikamFiber.Web and note that there are even fewer warnings listed. The warnings (if any) that appear as the result of using this rule set are more likely to be problematic during runtime.

Task 3: Using Live Code Analysis

  1. In addition to discovering rule violations in the Error List, Visual Studio also offers Live Code Analysis that helps you find and address code issues as you develop. For example, locate the Edit method in ServiceTicketsController.cs. Mouse over the first instance of the this keyword to see that there is a code analysis suggestion to simplify the name.

  2. Click the Quick Fix dropdown to see that the suggestion involves removing the this keyword in order to simplify the line of code. Also note that the this keyword is used several times in this method (and many more elsewhere in the file). Select the Document option to apply this fix across the entire file.

  3. Review the change preview that outlines each change to be made and click Apply when satisfied.

  4. Note that the this keyword has been removed everywhere in the file.

  5. There are many different rules that can be easily detected and fixed using Live Code Analysis. From Solution Explorer, open FabrikamFiber.DALModelsServiceTicket.cs.

  6. Locate and select the TimeOpen property. Notice how this property is a little deeper that a typical getter, although it doesn’t do anything too resource-intensive. However, suppose it was deemed that this property did actually perform some heavy lifting that might not provide the immediate return expected from a property. In that case, the code guidelines suggest that it should be declared as a method instead so that consumers would understand that there is a potential performance concern.

  7. To make this change quickly, select the Quick Action to review the suggested code changes. Press Enter to apply.

  8. Within the method, there are multiple old-school string.Format lines. Thanks to the availability of C# string interpolation, this code could be made cleaner.

  9. To make this change quickly, select the Quick Action to review the suggested code changes. Press Enter to apply.

  10. Note how much easier this code is to follow and maintain.

  11. From Solution Explorer, open FabrikamFiber.DALDataAlertRepository.cs.

  12. This file contains the AlertRepository class it’s named for, but it also contains an IAlertRepository interface. It’s a good practice (and often required by development teams) to separate types into their own files.

  13. To make this change quickly, select the Quick Action to review the suggested code changes. Press Enter to apply.

  14. You can now see the new IAlertRepository.cs file in Solution Explorer. You could also easily update the name of a file to reflect the name (and casing) of its type after a refactoring (or vice versa).

  15. You can customize the behavior of Live Code Analysis as you like, such as by having it proactively flag specific violations. In the Visual Studio search bar, search for “c# code style”. Select the result matching the screenshot below.

  16. Update the Qualify field access with ‘this’ to Warning. This will treat all violations of this rule (referencing a member field with the this keyword) as a warning. Click OK to close the dialog.

  17. Locate the All property of the AlertsRepository class. It uses this to access a member field, which is now flagged as a warning (you may need to close and reopen the file to see the green squiggle). You may need to reopen the file to see the warning.

  18. Expand the Error List to see all the other instances of this rule violation that have now been flagged as compiler warnings. You may need to clear the search box to see the results.

Ever since VS Code was released I’ve been a big fan! It’s a great way for windows junkies like myself to have a terminal like programming scripting environment. With integration into Git, along with thousands of extensions to help me keep my code organized and formatted I began using it as my main editor for a lot of things, even PowerShell scripts.

Python

Currently, I’m on somewhat of a personal mission to learn and explore new languages, solely for the purpose of illustrating how language independent RESTful APIs are. c# is next on my list, and while it’s not a new language for me, utilizing it within Visual Studio Code is. During this “mission” I realized that there are quite a few things you need to do in order to run c# within Visual Studio Code. Initially, I was going to place these within the “How to Consume APIs with c#” blog, but realized that this probably works better standing on its own! So, let’s take a look at how to prep VS Code to run c#!

First up, some leg work..

First up, obviously install Visual Studio Code – also, if you haven’t already, download and install the .Net Core SDK. Finally, once those two are installed we can move on to getting the c# extension installed within VS Code. Note: there are a lot of extensions available to us within VS Code, so be sure we grab the right one. To do so, select ‘Extensions’ and search for ‘c#’. In the list, select the extension that contains ‘Omnisharp’ and click ‘Install’ (See below).

Initialize the Project

Alright, time to start actually building out the shell for our project – To do this we simply need to open a folder and run a few commands. From the explorer tab, click ‘Open Folder’ and point to an empty folder you would like to create your project in.

Once the folder loads we need to initialize our .net skeleton within it. To do so we will use dotnet command from the terminal. If you don’t see a terminal at the bottom of VS Code, go ahead and select ‘View->Terminal’ to display it and run the following command

This will create a couple of files within our folder structure – the project definition file (.csproj) as well as the main file (.cs) to house our code. By default, we will see the standard “Hello World” example. Also, if prompted to download any other assets, go ahead and select ‘Yes’.

If you have reached this point then a big congrats is in order – you have successfully setup your VS Code instance to run c# code!

Visual Studio Run Code Coverage

Building and Running

To build our test project let’s go ahead and run ‘dotnet build‘ within our terminal.

And likewise, to run the project code, simply execute ‘dotnet run‘ within the terminal.

Where’s my NuGet?!?!

Simply printing Hello World to the console is great and all but we all know that anything we write is much, much more complex. NuGet is functionality that those using the full-blown version of Visual Studio have come to love and depend on. NuGet is a nifty little package manager that allows us to maintain what packages and assembly references we have attached to our projects, maintaining and limiting versions and conflicts! So, it’s kind of a must that we have it within VS Code, otherwise, I’ll simply just go back to the original Visual Studio for my c# projects. Thankfully, we have a way of getting it – the nifty Visual Studio Code extensions!

Select the Extensions tab, search for Nu-Get and install NuGet Package Manager – Easy Peasy!

Visual Studio Run Code Shortcut

Now that we have NuGet installed let’s have a quick look at how we can manage our packages – the easiest way that I have found is to simply hit the ‘F1’ key to bring up the VS Command pallet – a nifty little way to run single commands within our project. From there, simply start typing the work ‘nuget’, you should see the prompts displaying available options – the one we want, is the ‘Add Package’ command.

For this example let’s add the System.Data.SQLClient package to our project. In the first prompt, you can simply input ‘System.Data’ and hit enter – this will bring up a list of all the system.data packages. From the list displayed, select your desired package, in our case SQLClient, select the desired version and away we go.

In the event that any dependencies are invalid, nuget and VS Code gives you the option to automatically resolve them. If you happen to see a message about unresolved dependencies go ahead and click ‘Restore’

And there you go – nuget successfully setup and installing packages for you! At this point, you can go ahead and through your ‘using System.Data.SqlClient’ command at the beginning of your cs files and start utilizing some of the SQL Client functionality!

As you can see there is a little bit of legwork in getting Visual Studio Code prepped and ready to run our c# code – but thankfully this is a one-time thing. Once you have it set up and configured you can use VS Code for all of your c# needs! Honestly, I gathered this information from a lot of different MS pages and blogs and hopefully getting this all on one article will help get you on the right track to getting your VS Code setup! Thanks for reading!

Visual

Visual Studio Run Code Shortcut

You might also enjoy these recent posts...

Run
  1. Friday Shorts – Visual Studio 2010 and BIDS, AJAX Toolkit Combo Boxes and the Great One No support for BIDS development in Visual Studio 2010 Ahh Man! I ended up rebuilding one of my work machines...
  2. Quick to the point – VMware Tools Installation throwing vix error code 21012 – yeah, now what?!? Ah, the subtleties of upgrading a vSphere environment – tackle the vCenter, tackle the hosts, and then take care of the...
  3. Dumping SharePoint Integrated SSRS reports to pdf using c# Anytime I’m working on any sort of coding project Google is really my savior – there is absolutely no way...
  4. VMware View on the $99 HP Touchpad Last month, being the quintessential geek that I am, I spent the greater part of one of my weekends installing...
  5. Installing offline bundles in ESXi 5 So I ran into a situation where I needed to get the HP CIM providers onto ESXi 5 in order...