Skip to content

yunji0387/dotnet_commands

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 

Repository files navigation

.NET Commands

Prerequisite

(click to expand/hide)

Learning Source

(click to expand/hide)

Table of Contents

  1. Set up development environment
  2. How to create, build & run .NET project
  3. How to change .NET project's .NET framework version
  4. How to create, build & run c#
  5. How to install/uninstall/restore/check a package/dependency
  6. How to debug .NET code in VS Code
  7. File system in .NET
  8. Web API with ASP.NET Core controllers
  9. Minimal API with ASP.NET Core, and .NET
  10. Use .NET HTTP REPL command-line tool to make HTTP requests

Set up development environment

(click to expand/hide)
  1. Download and install Visual Studio 2022
    • In the visual studio workloads, install the following:
      • ...
  2. Download and install both .NET SDK and Visual Studio Code.

How to create, build & run .NET project

(click to expand/hide)
  1. create c# project
    • in Terminal run:
    dotnet new console -f net6.0
    • This command creates a Program.cs file in your folder with a basic "Hello World" program already written, along with a C# project file named DotNetDependencies.csproj. You should now have access to these files.
      -| obj
      -| DotNetDependencies.csproj
      -| Program.cs
  2. In terminal, run:
    dotnet run

How to change .NET project's .NET framework version

(click to expand/hide)
  • In your project, located to .csproj file
  • Find the in
  • change it to desired .net version
    <PropertyGroup>
      <TargetFramework>net6.0</TargetFramework>
      ...
    </PropertyGroup>

How to create, build & run c#

(click to expand/hide)
  1. make sure to have .NET SDK install
  2. make sure to have c# extension install in vs code
  3. create c# project
    • in Terminal run:
    dotnet new console -o ./CsharpProjects/TestProject
  4. build c# project
    • first make sure terminal path located in the project folder, then run:
    dotnet build
  5. run c# project
    • first make sure terminal path located in the project folder and has done step 4, then run:
    dotnet run

How to install/uninstall/restore/check a package/dependency

(click to expand/hide)
dotnet add package <dependency name>
  • To check your installed package list

    dotnet list package
    dotnet list package --include-transitive
  • To restore (when you create or clone a project)

    dotnet restore
  • To delete

    dotnet remove package <name of dependency>
  • Find and update outdated packages

    dotnet list package --outdated
    dotnet add package <package name>

How to debug .NET code in VS Code

(click to expand/hide)
  • Useful tutorial
  • Remeber to change console setting in launch.json from "internalConsole" to "integratedTerminal" when you want debug console to handle terminal input.

Debug - write information to output windows

Useful source 1, Useful source 2

  1. import Debug methods library
    using System.Diagnostis;
  2. example:
    using System.Diagnostics;
    
    int result = Fibonacci(5);
    Console.WriteLine(result);
    
    static int Fibonacci(int n)
    {
        Debug.WriteLine($"Entering {nameof(Fibonacci)} method");
        Debug.WriteLine($"We are looking for the {n}th number");
        int n1 = 0;
        int n2 = 1;
        int sum;
    
        for(int i=2; i<=n ; i++)
        {
            sum = n1 + n2;
            n1 = n2;
            n2 = sum;
            Debug.WriteLineIf(sum == 1, $"sum is 1, n1 is {n1}, n2 is {n2}");
        }
        return n == 0 ? n1 : n2;
    }

Debug - check for conditions with Assert

Useful source

Example:

using System.Diagnostics;

// See https://aka.ms/new-console-template for more information

int result = Fibonacci(6);

static int Fibonacci(int n)
{
    int n1 = 0;
    int n2 = 1;
    int sum;

    for (int i = 2; i <= n; i++)
    {
        sum = n1 + n2;
        n1 = n2;
        n2 = sum;
    }
    // If n2 is 5 continue, else break.
    Debug.Assert(n2 == 5, "The return value is not 5 and it should be.");
    return n == 0 ? n1 : n2;
}
  1. Run with debugging mode You should see below message in your debug console:
    ---- DEBUG ASSERTION FAILED ----
    ---- Assert Short Message ----
    The return value is not 5 and it should be.
    ---- Assert Long Message ----
    
       at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
       at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3
    
  2. Run with terminal "dotnet run" You should see below message in your terminal:
    Process terminated. Assertion failed.
    The return value is not 5 and it should be.
       at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
       at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3
    
    • To run without Assertion with terminal, use:
      dotnet run --configuration Release

File system in .NET

(click to expand/hide)

useful resource

Searching methods

(click to expand/hide)

List all directories

IEnumerable<string> listOfDirectories = Directory.EnumerateDirectories("stores");

foreach (var dir in listOfDirectories) {
    Console.WriteLine(dir);
}

List files in a specific directory

IEnumerable<string> files = Directory.EnumerateFiles("stores");

foreach (var file in files)
{
    Console.WriteLine(file);
}

List all content in a directory and all subdirectories

// Find all *.txt files in the stores folder and its subfolders
IEnumerable<string> allFilesInAllFolders = Directory.EnumerateFiles("stores", "*.txt", SearchOption.AllDirectories);

foreach (var file in allFilesInAllFolders)
{
    Console.WriteLine(file);
}

Determine the current directory

Console.WriteLine(Directory.GetCurrentDirectory());

Work with special directories

string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Special path characters

To help you use the correct Directory Separator in different operating systems(ex. macOs, Windows)

Console.WriteLine($"stores{Path.DirectorySeparatorChar}201");
// returns:
// stores\201 on Windows
//
// stores/201 on macOS

Join paths

Console.WriteLine(Path.Combine("stores","201")); // outputs: stores/201

Determine filename extensions

Console.WriteLine(Path.GetExtension("sales.json")); // outputs: .json

Get everything you need to know about a file or path

string fileName = $"stores{Path.DirectorySeparatorChar}201{Path.DirectorySeparatorChar}sales{Path.DirectorySeparatorChar}sales.json";

FileInfo info = new FileInfo(fileName);

Console.WriteLine($"Full Name: {info.FullName}{Environment.NewLine}Directory: {info.Directory}{Environment.NewLine}Extension: {info.Extension}{Environment.NewLine}Create Date: {info.CreationTime}"); // And many more

create methods

(click to expand/hide)

Create directories

Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "stores","201","newDir"));

Make sure directories exist

bool doesDirectoryExist = Directory.Exists(filePath);

Create files

File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "greeting.txt"), "Hello World!");

Read and write to files methods

(click to expand/hide)

Read data from files

File.ReadAllText($"stores{Path.DirectorySeparatorChar}201{Path.DirectorySeparatorChar}sales.json");

The return object from ReadAllText is a string.

{
  "total": 22385.32
}

Parse data in files

In bash, add "json.NET" package

dotnet add package Newtonsoft.Json

Then, add using Newtonsoft.Json to the top of your class file:

using Newtonsoft.Json; 

And use the JsonConvert.DeserializeObject method:

var salesJson = File.ReadAllText($"stores{Path.DirectorySeparatorChar}201{Path.DirectorySeparatorChar}sales.json");
var salesData = JsonConvert.DeserializeObject<SalesTotal>(salesJson);

Console.WriteLine(salesData.Total);

class SalesTotal
{
  public double Total { get; set; }
}

Write data to files

var data = JsonConvert.DeserializeObject<SalesTotal>(salesJson);

File.WriteAllText($"salesTotalDir{Path.DirectorySeparatorChar}totals.txt", data.Total.ToString());

// totals.txt
// 22385.32

Append data to files

var data = JsonConvert.DeserializeObject<SalesTotal>(salesJson);

File.AppendAllText($"salesTotalDir{Path.DirectorySeparatorChar}totals.txt", $"{data.Total}{Environment.NewLine}");

// totals.txt
// 22385.32
// 22385.32

Web API with ASP.NET Core controllers

(click to expand/hide)

Minimal API with ASP.NET Core, and .NET

(click to expand/hide)

Use .NET HTTP REPL command-line tool to make HTTP requests

(click to expand/hide)

How to install

  • In terminal, run:
    dotnet tool install -g Microsoft.dotnet-httprepl
  • If the HttpRepl tool warns Unable to find an OpenAPI description, the most likely cause is an untrusted development certificate.
    dotnet dev-certs https --trust

How to run

  • Make sure that your project is still running on localhost
  • In new terminal, run:
    httprepl https://localhost:{PORT}

title

(click to expand/hide)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published