I didn’t know it was this easy to handle Exceptions in .Net Core Web API. EasyException !!

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: trycatchfinally, and throw.

Now that we have come to an era on Middlewares we now use a middle to handle all kinds of Exception at one place.

This is where EasyExceptions comes in. Click here

This Lightweight Library removes your headache of defining a error response standard and just let you think about handling exceptions and what error code to be returned.

The library Implements the standard model suggested by Microsoft to handle errors/faults in system and correclty respond to it.

The Library lets you implement all the logics you want when an exception takes place in your system, and then later converts the ErrorResponse to client/users .

How to Use the Library?

Using the library is really simple.

You might have different exception in you system.

Say a domain Exception,

public class ProfileDomainException : Exception
{
   public ProfileDomainException(string message) : base(message)
   {
   }
}

and just like this many more.

So you Implement an interface Exposed by the EasyExtention library IErrorHandlingService as below\

you can Implement the above Interface like the below sample.

using EasyException.Abstractions;

 public class ErrorHandlingService : IErrorHandlingService
    {
        public Task<ErrorResponse> HandleException(Exception exception)
        {
            switch (exception)
            {
                case ProfileApiException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "ApiError", Message = exception.Message });

                case ProfileDomainException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "DomainError", Message = exception.Message });

                case ProfileApplicationException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "AppError", Message = exception.Message });

                default:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "InternalError", Message = exception.Message });
            }
        }
    }

Now , in the StartUp.cs you can then register your Implementation as a singleton

 public void ConfigureServices(IServiceCollection services)
 {
  services.AddSingleton<IErrorHandlingService,ErrorHandlingService>();
  ...
  

And then configuring the app builder you can tell the app to use the middleware.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
   app.UseEasyExceptionHandling();
   ...
   

Now we can see the response can be in the below format .

ErrorResponse : Object
PropertyTypeRequiredDescription
errorErrorThe error object.
Error : Object
PropertyTypeRequiredDescription
codeStringOne of a server-defined set of error codes.
messageStringA human-readable representation of the error.
targetStringThe target of the error.
detailsError[]An array of details about specific errors that led to this reported error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
InnerError : Object
PropertyTypeRequiredDescription
codeStringA more specific error code than was provided by the containing error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
{
    "code": "BadArgument",
    "message": "Previous passwords may not be reused",
    "target": "password",
    "innererror": {
      "code": "PasswordError",
      "innererror": {
        "code": "PasswordDoesNotMeetPolicy",
        "minLength": "6",
        "maxLength": "64",
        "characterTypes": ["lowerCase","upperCase","number","symbol"],
        "minDistinctCharacterTypes": "2",
        "innererror": {
          "code": "PasswordReuseNotAllowed"
        }
      }
    }
  }

ITs Done !! Its that easy. All you logic of handling the exceptions are now in one place.

Thanks

Happy Coding!

Execute a piece of C# code anytime in VS Code using .NET Interactive Notebooks

.Net Interactive Notebooks is an extension being developed by Microsoft, and this extension adds support for using .NET Interactive in a Visual Studio Code notebook.

The source code to this extension is available on https://github.com/dotnet/interactive and licensed under the MIT license.

Getting Started

  1. Install the latest Visual Studio Code.
  2. Install the latest .NET 5 SDK
  3. Install the .NET Interactive Notebooks extension from the marketplace.

Before this we used to go and find some online tools or LINQ Pad to run our C# code to check the output. But creating a sample project just to check a logic has never been easy. But now this has been made even simpler with the .NET Interactive.

Basically what it does is allow you to write your code and execute there itself, to check the output.

Screenshot of a Vs Code .Net Interactive Tab.

In the above screenshot we can see its so easy to just print Hello world there itself, This is quick and save a lot of time. You can also save this file and load and run the part of code you want to execute. You could also share this file with some one and make it easier to just execute the part of code he/she wants.

How to Use the Extention ?

Once you have installed the extension press Ctrl + Shift + P to open the Command tab and select the option .NET Interactive Create new blank notebook as shown below. This will create a new notebook which you can save and share.

Hope you loved this insight.

Happy Coding.

“Unable to verify secret hash for client ” error from my Amazon Cognito user pools API when called from AWS Lambda ?

When I try to invoke my Amazon Cognito user pools API, I get an “Unable to verify secret hash for client <client-id>” error. How do I resolve the error?

As per documentation

When a user pool app client is configured with a client secret in the user pool, a SecretHash value is required in the API’s query argument. If a secret hash isn’t provided in the APIs query argument, then Amazon Cognito returns an Unable to verify secret hash for client <client-id> error.

– AWS Docs

But still even after passing the SECRET_HASH this still doesn’t behave correctly when using ADMIN_NO_SRP_AUTH. This should not be generated when using the ADMIN_NO_SRP_AUTH

I am trying to do this via AWS Lambda here.

So, There is a simple solution to this.

Go to App Clients in your cognito.

You should see a list of client as there can be more than on app client in an user pool.

Now, click on show details, and you should see a text box showing CLIENT SECRET

If this shows up with a secret key the work arround is to delete the app client for the user pool and create a new one

uncheck the checkbox for Generate Client Secret

To Remember
enter image description here
Please remember to uncheck the above checkbox.

We can now remove the Client secret from the Auth Parameters

The request would now look like shown below.

    public AdminInitiateAuthRequest CreateAdminInitiateAuthRequest(AdminInitiateAuthRequestModel apiRequest)
    {
        if (String.IsNullOrEmpty(apiRequest.Username) || String.IsNullOrEmpty(apiRequest.Password))
            throw new Exception("Bad Request");

        AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest();
        authRequest.UserPoolId = _poolId;
        authRequest.ClientId = _appClientId;
        authRequest.AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH;
        authRequest.AuthParameters = new Dictionary<string, string>();
        authRequest.AuthParameters.Add("USERNAME", apiRequest.Username);
        authRequest.AuthParameters.Add("PASSWORD", apiRequest.Password);
        return authRequest;
    }

Code Coverage in .NET Core Projects

If you have created a unit test project in .NET Core, then you must have noticed a NuGet package, coverlet.collector, is installed in the default project templates for MSTest and xUnit. What does this NuGet package do?

The coverlet documentation (link) tells us that coverlet is a cross platform code coverage framework for .NET, with support for line, branch and method coverage. It means that we are able to check the code coverage for .NET Core applications using coverlet.

Creating the Coverage Report

Install the NuGet package coverlet.msbuild to the MSTest project using the following command.
dotnet add package coverlet.msbuild
The pre-installed NuGet package coverlet.collector doesn’t work with the dotnet test command. Thus, we need to install the coverlet.msbuild package in order to generate coverage reports in the CI pipeline. This NuGet package integrates coverlet with the .NET build system, so that coverlet will compute code coverage after tests.

Run  dotnet test command to generate a coverage report.

dotnet test /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=lcov

Several parameters are passed into the dotnet test command. The first one, CollectCoverage=true, means we want to collect code coverage.

The second parameter, CoverletOutput, specifies the output file destination, which is in the TestResults folder. The most commonly available .gitignore file for .NET projects sets the TestResults folder to be ignored for version control. Thus, we will put testing related things into the TestResults folder, so that they won’t be accidentally committed to our code repository if coverage reports are generated locally.

The third parameter, CoverletOutputFormat, indicates the report file format, which is lcov in this case. The coverlet supports many formats, such as opencoverjsonlcovcoberturateamcity, and so on. In this project, we will stick with the lcov format, because the GitHub Actions for coveralls.io uses the lcov format.

If we run the command, then we will see the Console output like the following screenshot.

The Console output of dotnet test with coverlet

The Console output writes out the generated coverage report file path and the coverage metrics, which give us a glimpse of the coverage rates. The generated coverage.info file contains much more detailed information on the line hits, but it is not so readable as compared to the reports after parsing and transformation by specialized tools. We will use an online report service from coveralls.io to visualize the code coverage.

Open Source Testing Tools in C#

NUnit

NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit

Go To NUnit

NUnitForms

NUnitForms is an NUnit extension for unit and acceptance testing of Windows Forms applications.

Go To NUnitForms

dotunit

dotunit is a port of JUnit (www.junit.org) to the Microsoft .net platform. This testing framework allows for automated unit and functional tests which are vital for refactoring and regression testing.

Go To dotunit

VSNUnit

VSNUnit is an integration tool that allows you to execute your NUnit tests from within the IDE. Instead of dumping the results as a text stream to the output window, VSNUnit provides the graphical tree view that NUnit and JUnit users have come to love. The tree view is a dockable toolwindow inside the IDE, allowing you to integrate it with your standard development environment layout.

Go To VSNUnit

EasyMock.NET

EasyMock.NET is a class library that provides an easy way to use mock objects for given interfaces or remote objects

Go To EasyMock.NET

Dot NetUnit

An implementation of XUnit testing framework

Go To Dot NetUnit

MbUnit

MbUnit is an evolutive Unit Test Framework for .Net. It provides new fixtures as well as the framework to create new ones. MbUnit is based QuickGraph, a directed graph library for C#. MbUnit is a superset of NUnit. Now that NUnit has become mainstream and is evolving MbUnit is where much of the action is going on.

Go To MbUnit

Zanebug

Zanebug is an advanced unit testing application for .NET. It provides full support for existing NUnit tests, performance metrics, multiple test iterations, in-depth error information, pass / fail stats, perfmon integration, result graphing, etc.

Go To Zanebug

DotNetMock

DotNetMock is a framework and a library to facilitate the use of MockObjects for unit testing on the .NET platform. It supports the creation of your own MockObjects as well as the dynamic creation of MockObjects. It supports almost any version of NUnit, and MbUnit. DotNetMock DynamicMocks can mock interfaces at runtime and can even modify ref/out parameters.

Go To DotNetMock

Rhino.Mocks

Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It’s a hybrid approach between the pure Record/Replay of EasyMock.Net’s model and NMock’s expectation based model.

Go To Rhino.Mocks

csUnit

Inspired by JUnit, csUnit brings the power of unit testing to the .NET framework. csUnit is your key to unit testing and test-driven development using .NET languages such as C#, Visual Basic .NET, Visual J#, or Managed C++. csUnit provides versions for VS2002, VS2003, and VS2005 with add-in support. Of course there is also a stand-alone GUI application and a command line. csUnit is open-source but its license (zlib/libpng) also allows for using csUnit or parts of it in closed-source and commercial projects.

Go To csUnit

NUnitAddin

NUnitAddin is a simple addin for VisualStudio 2005 used in association with NUnit framework. The NUnit Addin allows you to run unit tests inside Visual Studio 2005. Features: * Read Visual Studio 2005 files: .sln * Build visual tree from .sln files * Run tests in Visual Studio 2005

Go To NUnitAddin

SystiN

System testing in .Net is a port of the Systir tool from ruby to C#. It allows users to specify plain english text software requirements that can then become executable tests.

Go To SystiN

XtUnit

XtUnit is a unit testing extension for .Net based frameworks. It uses the interception application block to provide runtime abilities of rolling back any changes that were made to the database during Data related unit tests.

Go To XtUnit

Gallio/MbUnit

The Gallio Automation Platform is an open, extensible, and neutral system for .NET that provides a common object model, runtime services and tools (such as test runners) that may be leveraged by any number of test frameworks.

Go To Gallio/MbUnit

Nester

Nester is a tool for mutation testing of your C# source code in order to assess the adequacy of your unit tests. It involves modification of programs to see if existing tests can distinguish the original program from the modified program.

Go To Nester

QAliber

QAliber includes 2 projects: a Visual Studio plug-in and Test Builder + Runner as execute framework. Visual Studio plug-in help writing automatic tests over GUI with control browser and record/play capabilities (but not only, since this project incorporate into development solution API testing is easy to do) The Test Builder is a framework for creating a scenario by simply drag and drop of created building blocks. It already provide big repository of test blocks performing most tasks without coding.

Go To QAliber

Check if Silverlight is available on the browser? Detect if Silverlight is Installed !!

Though its 2020, and its time the cutting edge JavaScript libraries and frameworks are dominating the web market space. There are still some legacy code still using the .NET Frameworks and somewhere kept still in use and no one dare to affect the running business and why should one invest on something which is still capable of running. We would discuss the pros and cons of this in my different blog.

So, if you are the one still supporting this kind on application, and what to check in your client browser supports Silverlight or not here is a piece of code that would save you.

function checkSilverlightInstalled()
{
    var isSilverlightInstalled = false;
    try
    {
       //check on IE
       try
       {
            var slControl = new ActiveXObject('AgControl.AgControl');
            isSilverlightInstalled = true;
       }
       catch (e)
       {
        //either not installed or not IE. Check Firefox
         if ( navigator.plugins["Silverlight Plug-In"] )
         {
            isSilverlightInstalled = true;
         }
       }
    }
    catch (e)
    {
        //we don't want to leak exceptions. However, you may want
        //to add exception tracking code here.
    }


    return isSilverlightInstalled;
}

Get started with .NET Core

This article provides information on getting started with .NET Core. .NET Core can be installed on Windows, Linux, and macOS. You can code in your favorite text editor and produce cross-platform libraries and applications.

If you’re unsure what .NET Core is, or how it relates to other .NET technologies, start with the What is .NET overview. Put simply, .NET Core is an open-source, cross-platform implementation of .NET.

Create an application

First, download and install the .NET Core SDK on your computer.

Next, open a terminal such as PowerShellCommand Prompt, or bash. Type the following dotnet commands to create and run a C# application:.NET Core CLI

dotnet new console --output sample1
dotnet run --project sample1

You should see the following output:Console

Hello World!

Congratulations! You’ve created a simple .NET Core application. You can also use Visual Studio CodeVisual Studio (Windows only), or Visual Studio for Mac (macOS only), to create a .NET Core application.