Visual Studio Task List Feature

Visual Studio has a handy feature, Task List. Click on View->Task List.

Task list has tokens that are used to track code comments. This also acts as a shortcut to navigate to relevant code section. This list comes with 3 default tokens; TODO, HACK and !UnresolvedMergeConflict.

We can add custom tokens, if we want. Here is how;

Open Tools -> options -> Environment, you will see Task List.

Add a new custom token;

To make this feature working, All you need to do is to add comments in your code;

    /*
        HACK: I don't need serviceProviderId parameter here. The only reason I am adding this becuase this comes
        from a link in razor page list and I need to keep serviceProviderId and projectId in session. 
        Session starts here for now.
     */
    [HttpGet]
    [Route("ProjectTask/ProjectTaskList/{projectId:Guid}")]
    public async Task<IActionResult> ProjectTaskList(Guid projectId)
    {
        var result = await _httpFactoryService.GetProjectActionAsync(projectId);
        return View(result);
    }

Reference

Using the Task List

JSON Circular Reference Loop Error running Raw SQL in Web API using EF Core

I had a complex stored procedure that I needed to run using EF core in a Web API project. I cannot use LINQ to represent this query. I have followed all best practices outlined here;

Everything worked great except raw sql endpoint. It started giving me “Circular Reference loop error”. To keep thing simple, I am returning DTO from endpoint not the entity.

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'task' with type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Collections.Generic.IEnumerable`1[FM.Service.Shared.DTO.TranMasterViewDto],FM.Service.LedgerTranViewService+<GetTransactionForProjectActionAsync>d__4]'. Path 'stateMachine.<>t__builder'
......

Here is my configuration before and after the fix;

Newtonsoft Configuration in program.cs file before the fix;
}).AddNewtonsoftJson()
Newtonsoft Configuration in program.cs file after the fix;
}).AddNewtonsoftJson(
    options => 
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)

The error is gone and I am getting this results.

{
    "stateMachine": {
        "<>1__state": 0,
        "<>t__builder": {},
        "projectActionID": "82ee5154-971a-ed11-90e6-00155d717606",
        "trackChanges": false,
        "<>4__this": {}
    },
    "context": {},
    "moveNextAction": {
        "method": {
            "name": "MoveNext",

Wait…This is not what I expected. Why I am getting Tasks result where I need to see my Dto results.

It turns out that I am not returning results from my Async method but the task;

public async Task<IActionResult> GetTransactionForProjectActionAsync(Guid projectActionId)
{
   return Ok(_service.LedgerTranViewService.GetTransactionForProjectActionAsync(projectActionId, trackChanges: false));
        }

Fixing the return type has solved all of my problems;

return Ok(_service.LedgerTranViewService.GetTransactionForProjectActionAsync(projectActionId, trackChanges: false).Result);
        }
[
    {
        "id": 20221,
        "projectActionID": "82ee5154-971a-ed11-90e6-00155d717606",        
        "tranMasterDetail": [
            {
                "tranMasterId": "9358b0c5-6d30-ed11-90e8-00155d717606",
                "ledgerID": "63302216-0946-ea11-ac82-f81654967f7a",
                "tranDescription": "Rent paid",
                "tranDate": "2022-01-03T00:00:00",
                "tranFlag": 0,
                "tranAmount": 1300.00
            }
        ]
    }
]

Remove Newtonsoft ReferenceLoopHandler from program.cs file.

}).AddNewtonsoftJson()

Hope this will help someone.

Reference

https://stackoverflow.com/questions/62985907/avoid-or-control-circular-references-in-entity-framework-core

Standard Practice to Create Repository

A standard practice to create repository should always be;

  1. Main branch should always have a .gitignore and readme file.
  2. Create a working branch from main
  3. Develop feature in your working branch
  4. Before committing, do a merge from remote main to working branch and resolve any conflicts in working branch. This will help you to get team changes merged into your working branch.
  5. Commit your changes. Create a PR and you are done.

I hope this will help.

How to add gitignore file in existing solution using Visual Studio

Stop tracking the files that should be ignored in Git

How to add gitignore file in existing solution using Visual Studio

Recently I came across an issue where existing projects were showing .vs folder checked-in and being tracked. Developers were having code conflict problems and were not able to create PR request.

Here is the work around to add gitignore file in existing solution using Visual Studio.

Remove .vs folder from main branch and working branch. If there are PR policy in place, disable that for fixing this. After .vs folder removal, enable PR policy.

Open Visual Studio and make sure it’s connected to Git branch. Click on Git->Settings.

This will add gitignore file in the root of project folder. Switch to Git changes window in your working branch and commit / sync your changes.

Now we need to stop tracking all .vs folder changes that’s been created on developer machines to build and run the project. Use these magic commands, one time only;

git rm -r –cached .
git add .
git commit -am “remove ignored files”

For added piece of mind, sync your main branch and do a merge from main branch to work branch locally. Resolve any cache files and conflicts. You might need to run above three command again.

After this, Create PR and it should merge with main branch. This will take your pain away.

I hope this will help.

Standard Practice to Create Repository

Stop tracking the files that should be ignored in Git

Resolve the issue of request matched multiple endpoints in .NET Core Web API

If there are two endpoint with same route, .NET Core Web API will throw request matched multiple endpoints error. Here is an example;

// api/menus/{menuId}/menuitems
[HttpGet("{menuId}/menuitems")]
public IActionResult GetAllMenuItemsByMenuId(int menuId)
{            
    ....
}

// api/menus/{menuId}/menuitems?userId={userId}
[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenuAndUser(int menuId, int userId)
{
    ...
}

This is impossible because the actions are dynamically activated. The request data (such as a query string) cannot be bound until the framework knows the action signature. It can’t know the action signature until it follows the route. Therefore, we can’t make routing dependent on things the framework doesn’t even know yet.

Long and short, we need to differentiate the routes in some way: either some other static path or making the userId a route param. However, we don’t actually need separate actions here. All action params are optional by default. Therefore, we can just have:

[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenu(int menuId, int userId)

And then we can branch on whether userId == 0 (the default). That should be fine here, because there will never be a user with an id of 0, but we may also consider making the param nullable and then branching on userId.HasValue instead, which is a bit more explicit.

We can also continue to keep the logic separate, if we prefer, by utilizing private methods. For example:

[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItems(int menuId, int userId) =>
    userId == 0 ? GetMenuItemsByMenuId(menuId) : GetMenuItemsByUserId(menuId, userId);

private IActionResult GetMenuItemsByMenuId(int menuId)
{
    ...
}

private IActionResult GetMenuItemsByUserId(int menuId, int userId)
{
    ...
}

Have fun.

Read more here.