Asp.Net 5 Development Notes (DotNet Core 3.1 Study Notes)


Study Notes to use when programming in .Net 6 and Visual Studio 2019

[Note]: Did you know that you can get access to the Application Wide Error? you get the specify error message that caused the Exception in another Controller by calling this.Problem() function. This method should be called from a Controller as it is a Function drived from a ControllerBase classs.

[Note]: Did you know that you could actually return a PartialView from a Controller, this is helpful when you are trying to have one single source of truth to handle all the returned Resources. You can return the PartialView from a Controller Action by simply return PartialView(NameOfThePartialView);


- What Controllers can return, e.g JSON(), NoContent(), ActionResult() (Find out More information about this)

- Find out if you can run or call a function in a controller from Dotnet console like in drupal or Rails. In Rails, you can run an individual function from the Rails Console.

Find out how to inject a class model in the Razor page in Dotnet core 2.2 dependency injection in frontend.

- Remember, two ways to spin up a docker container 1 by Docker compose and another is by using a command in PowerShell or similar.


[NB] You can create a model for data coming from a store procedure, remember this model in DBContext can not be used to insert data, it can only be used to read from the stored proc.

Controllers
- When working with Controllers you can choose to return ActionResults that enables you to return status codes via functions in the Controller's Action. Very handy

Debugging Asp.Net 5 Application Notes

1. If you are developing using Dot Net Core 2.2 and you want to access the application you are developing running on https://localhost:5001 from another computer on the Local Area Network (LAN) follow the instruction below:

- Adjust your launchSettings.json file found under Properties (three steps below your Project name (not the Solution Name), depending on your project structure) 

- Adjust the applicationUrl to listen on for traffic from all IP address/ Network interfaces as follow: "applicationUrl": "https://0.0.0.0:5001"
- Open up port 5001 to allow TCP connection from the Firewall.
[NB] Take it to another level, if you want to debug the proxy x-forwarded headers this will be ideal for testing.

- Now start your application and make sure the application is able to start on port 5001 on the local machine.
- Try to type the full Local Address of the computer running the application (Localhost) from another computer on the same network e.g. https://459.30.0.30:5001  you should be able to access Dot Net Core application and start debugging from there.


C# 9

1. The way you select the columns you need in Linq is by using (from b in _context.ModalName.include(a = a.name).include(b= b.name) select b)

 

Examples of Good Software Best Practices (Good Practices)

1. Follow DRY Principle, do not repeat yourself. If you find yourself working on a piece of code twice simplify the code as soon as possible to avoid code convolution or Technical Debt.

2. Do not embedded URL literals in the C# code, always put those in the config file

3. When using IConfiguration Interface and would like to get values from the appSettings.json use _config.GetValues() as this will allow you to get values with a comma in them.

4. Use String interoperability as possible, it is cleaner and safe that way. Avoid concatenating strings using plus signs it is expensive compared to the cheap way of using String Interporation.

5. Use a controller for calling functions from other classes, avoid implementing more code in a Controller. Controllers were made mainly for routing.

6. CTL + RR for refactoring in Visual Studio 2019


C# Asp.Net 5 Programming Notes

7. Make sure that every function performs only one or two tasks, the rest of the logic should be separated into private functions that get used in other functions. The private functions should return an object of the type of class if you like.

8. If you want the code to return fast to the UI so that the user can see the UI rendering while some of the code executes in the background in C#, then consider configuring ConfigureAwait(false) this code allows the request to return to the UI thread as fast as possible while logic executes on the Background Thread.
-It is important that the function of requesting data or response from an async function to utilize await. This tells the Compiler to notify the function when all resources are available from the function retrieving the data.

9. Always use _context.ModalName.AsNoTracking() when retrieving readonly data. This is faster as compaired to _context.ModalName.FirstOrDefault(Lambda Expression Here).

Tips: If you want to get a path to the folder using Powershell, just drag the whole folder and drop it in Powershell.

[NB] If you ever wondered why the WebApi function was not found when you have used routes() in your Web API:

  1. Make sure that the [Route("")] does not start with a / . Make it look like [Route("SomeFunctionName")]



    EF Core Database First

[NB] How to scaffold Modals from a Database in a Database First Scaffolding

- Make sure you install:

  1. dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  2. dotnet add package Microsoft.EntityFrameworkCore.Design
  3. dotnet tool install --global dotnet-ef
  1. dotnet ef dbcontext scaffold "Server=IPAddress\DatabaseInstance;Database=DatabaseName;Trusted_Connection=False;User ID=UserName;Password=pass" Microsoft.EntityFrameworkCore.SqlServer -o Models

  2. Make a ConnectionString in appsettings.json
    {
        "ConnectionStrings": {
                                "DefaultConnection": "Server=IP,1433;Database=DB;Persist Security Info=True;User ID=UserID;Password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;"
        },
        "Logging": {
            "LogLevel": {
                "Default": "Information",
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Information"
            }
        },
    
    
        "Payment": {
            "prod": {
                "api": "",
                "pass": ""
            },
            "dev": {
                "api": "",
                "pass": "",
                "ID": ""
            }
        },
        "Email": {
            "API": {
                "api": "",
                "pass": ""
            }
        },
        "AllowedHosts": "*"
    }
    



    Asp.Net Core 3.1 Conference July 2020 Notes
  3. use GRPC for streaming data to the client whenever the data is available
    - Create a GRPC Project
    - Add a client Project to consume GRPC project (More like an API but the API cannot stream data to the client whenever it's available)
    - Add a Protobaf file that defines the schema of the GRPC Data Contract
    - The Client can then use the Data Structure in the GRPC to integrate the code.


  4. Good Practices when developing Asp.net Core Application

    - Make sure that services do not call other services, if you do, you will get a Dependency Injection Circular Error. That simply means, that there are too many dependency injections calling other services. This is a nono as it violates a principle.
    Read Here: https://stackoverflow.com/questions/46354041/dependency-injection-circular-dependency-net-core-2-0/52134972

    - Naming Conversion: You should start the names of the function with a capital letter
     
    Reference Manager
  5. When you are developing an application, right-click on the application and add a reference, the window that pops up gets all the dll in System32 and SysWOW64 Folder. It is up to you to use that dll in your applications. For example, you could use a dll about Windows performance functionality in your application by adding a reference of the COM library to your application.
     

References

https://www.learnentityframeworkcore.com/walkthroughs/existing-database

https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-3.1







For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]