RSS

Tag Archives: c#

WebApi ExceptionHandling.ExceptionHandler Sometimes Does Not Handle Global Exception. What ?!

See previous post on how to implement ExceptionHandler.

ExceptionHandler supposed to handle exception globally, but sometimes it does not… what ?!

There are few cases where ExceptionHandler will not capture exception. One of them is when CORS is enabled, see this.

To ensure ExceptionHandling to always capture exception, try:
1. If inherit from ExceptionHandler, override its method `ShouldHandle()`.

        public override bool ShouldHandle(ExceptionHandlerContext context)
        {
            return true;
        }

2. Instead of ExceptionHandling.ExceptionHandler, inherit and implement it’s interface `ExceptionHandling.IExceptionHandler`.

Advertisements
 
Leave a comment

Posted by on November 2, 2018 in General

 

Tags: , , , ,

How to Implement IExceptionLogger and IExceptionHandler in Web Api .Net

This works on Web Api 2+ and MVC 5+.

1. Create implementation of ExceptionHandler class. Note this class inherit from concrete class of ExceptionHandler, not the interface. Inherit from concrete class decrease effort to implement other methods.

using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;

namespace BlahBlahBlah.ExceptionHandler
{
    public class GlobalExceptionHandler : System.Web.Http.ExceptionHandling.ExceptionHandler
    {
        public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
        {
            // Code to handle exception...

            return base.HandleAsync(context, cancellationToken);
        }
    }
}

2. Create implementation of ExceptionLogger class. Note this class inherit from concrete class of ExceptionLogger, not the interface. Inherit from concrete class decrease effort to implement other methods.

using System.Threading;
using System.Threading.Tasks;

namespace BlahBlahBlah.ExceptionHandler
{
    public class GlobalExceptionLogger : System.Web.Http.ExceptionHandling.ExceptionLogger
    {
        public override Task LogAsync(System.Web.Http.ExceptionHandling.ExceptionLoggerContext context, CancellationToken cancellationToken)
        {
            // Code to log exception...

            return base.LogAsync(context, cancellationToken);
        }
    }
}

3. Replace default Logger and Handler.

using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using BlahBlahBlah.ExceptionHandler;

namespace BlahBlahBlah
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {            
            // Replace default exception handler and logger
            config.Services.Replace(typeof(IExceptionLogger), new GlobalExceptionLogger());
            config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

If you wonder difference between IExceptionLogger and IExceptionHandler, this is from Microsoft docs:

We provide two new user-replaceable services, IExceptionLogger and IExceptionHandler, to log and handle unhandled exceptions. The services are very similar, with two main differences:

1. We support registering multiple exception loggers but only a single exception handler.
2. Exception loggers always get called, even if we’re about to abort the connection. Exception handlers only get called when we’re still able to choose which response message to send.

Both services provide access to an exception context containing relevant information from the point where the exception was detected, particularly the HttpRequestMessage, the HttpRequestContext, the thrown exception and the exception source (details below).

 
Leave a comment

Posted by on October 12, 2018 in General

 

Tags: , , , , , ,

“The CodeDom provider type Microsoft.VisualC.CppCodeProvider could not be found” exception

This problem happened when you build project/solution in Visual Studio. Generally caused when you have compile-able files in your Visual Studio solutions but VS could not understand it.
In my case, I have infamous ‘node_modules’ folder.

To solve this issue, in Windows Explorer, I right click on it ‘node_modules’ folder and select ‘Properties’, check ‘Hidden’ under Attributes.

You can also exclude the folder. In Visual Studio Solution Explorer, right click on ‘node_modules’ and select ‘Exclude From Project’.

More reading.

 
Leave a comment

Posted by on September 12, 2018 in General

 

Tags: , , , , , , ,

C# Dynamic-Typed Parameter Trap

A little tricky lesson today in C#.

Passing a dynamic-typed parameter to a method that has defined return type (ie: string, int, etc) will not return the defined type, instead the method will return dynamic type.

class Program
{
	static void Main(string[] args)
	{
		FooBarClass fooBar = new FooBarClass();

		var result1 = fooBar.Foo("Foo");

		dynamic bar = "Bar";
		var result2 = fooBar.Foo(bar);
	}
}

public class FooBarClass
{
	public string Foo(string fooArg)
	{
		return "This is Foo";
	}
}

In the above example, type of result1 is string, but type of result2 is dynamic, even though they both call same method that return string type.
result1
result2

This is because compiler do not evaluate dynamic type until runtime therefore it can’t determine return type at compile time.

This is important to point out because if we apply extension method to result2, it will throw exception at runtime, not compile time.

Example of extension method.

public static class FozBazClass
{
	public static void Foz(this string fozArg)
	{
		fozArg = "Test..." + fozArg;
	}
}
result1.Foz(); // this will execute normally
result2.Foz(); // this will throw exception

result2 exception

Just another reason we should avoid dynamic type.

 
Leave a comment

Posted by on May 29, 2018 in General

 

Tags: , , , ,

String as a Reference Type and Immutable

In .Net, string object is reference type, however when we pass the value like this

void Main()
{
    string s = "Test";

    TestString(s);
    Console.WriteLine("TestString: " + s); // Output is: TestString: Test
}

public static void TestString(string s)
{
    s = "TestString";
}

Why is the output “TestString: Test”, we know for sure string is a reference type and we assign new value to our parameter in TestString() method.

Turn out, beside being a reference type, string is also an immutable, which mean its value can’t be modified or changed. So when we assign new value to our parameter in TestString() method, it actually create new string object. It acts like value type but it isn’t a value type, it’s a reference type with immutable behavior.

 
Leave a comment

Posted by on May 15, 2018 in General

 

Tags: , , , ,

Float, Double, Decimal Types and DivideByZeroException

Most of us know the difference between Float, Double and Decimal types in .Net is the precision.

  • Float 32 bit (7 digits)
  • Double 64 bit (15-16 digits)
  • Decimal 128 bit (28-29 digits)

But most of us scratch our head over this:

var numerator = 10;
var denominator = 0;
var resultNoException1 = (float)numerator / (float)denominator; // Result Infinity, does not throw exception
var resultNoException2 = (double)numerator / (double)denominator; // Result Infinity, does not throw exception
var resultException = (decimal)numerator / (decimal)denominator; // Throw DivideByZeroException

Suffice to say throw/catch block won’t caught any exception on resultNoException1 and resultNoException2.

Why?

Because Float and Double types are binary floating point types (or sometimes being referred to as floating point types) while Decimal is decimal floating point types.

From MSDN:

Dividing a floating-point value by zero doesn’t throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.

 

 
Leave a comment

Posted by on May 2, 2018 in General

 

Tags: , , , , , , ,

Left-Shift Operator Is Limited?

Why is left-shift operator with 32 result in lower number?

int i = 1;
(i << 0).Dump(); // Result is 1
(i << 1).Dump(); // Result is 2
(i << 2).Dump(); // Result is 3
(i << 3).Dump(); // Result is 8
(i << 10).Dump(); // Result is 1024
(i << 20).Dump(); // Result is 1048576
(i << 30).Dump(); // Result is 1073741824
(i << 31).Dump(); // Result is -2147483648
(i << 32).Dump(); // Result is 1 -> WHY?
 
Leave a comment

Posted by on March 6, 2018 in General

 

Tags: , ,

 
%d bloggers like this: