Rest API Exception handling in Asp.net core using built-in middleware

Hello dear developers and software crafters!
How do you feel today?

Some time ago I was working on an API project that had to consume lots of micro services that had responses serialized in JSON. Since I was using async methods I was implementing the typical tuple success, Object methods.

Out of curiosity I asked developers from other teams how they handled the Rest response codes and exceptions while complaining about the verbosity of my solution. Then after many shrugs a colleague told mi about Asp.net core middleware to trap exceptions.

Here is a piece on the subject that explains the process

https://blogs.msdn.microsoft.com/brandonh/2017/07/31/using-middleware-to-trap-exceptions-in-asp-net-core/

I hope you enjoy this piece as much as I did.

Happy coding and rememberā€¦ there is life beyond coding šŸ˜Š

When working with files

Hello my dear developers!

How do you feel today?

These days I’ve been reviewing some code involving JSON and file managing, as always you are supposed to know the 101 on how to work with files, storing, opening, editing, etc.

But the tricky thing always comes when you want to make sure that a file exists and you get false positives and everything starts throwing weird exceptions that you didn’t expect. You at that point start spending your precious time chasing ghost’s through a hundred break points, stepping in to execution and such.

“Good if I could remember… I’ve had this one before”, I thought. There’s some option called open create or something (FileMode.OpenOrCreate) but now I’m using static methods from File Class such as WriteAllText() or ReadAllText() and those don’t take this options. Da@# it!

So after some thinking and a lot of rushĀ I went in to “I don’tĀ give a crap about technical debt, I just wanna finish mode” and started writing the following code every time I wanted to get a file from storage either to read o write on it.

 

var fs = File.Open(path, FileMode.OpenOrCreate);
fs.Close();

 

“God this is crappy code I can’t believe I did it again, now if this doesn’t work I’ll have to go fixing it all over the project”, IĀ felt.

Thereafter my guilt grew unbearable so I started developing a much neater code that centralizes everything on a method called GetPath, that has a bool createIfNotExists that when set to true it executes the code shown before and else you can do things however you like regarding how to ensure file existence.

public string GetPath(string fileName, string fileExtension, bool createIfNotExists = false, string folderPath = "")
{
    if(string.IsNullOrWhiteSpace(_basePath))
    {
        throw new IOException("File Manager needs a basePath to work with");
    }
    string path = null;
    if (!string.IsNullOrWhiteSpace(fileName) && !string.IsNullOrWhiteSpace(fileExtension))
    {
        if (fileExtension.Contains("."))
        {
            fileExtension = fileExtension.Replace(".", "");
        }
        if (string.IsNullOrWhiteSpace(folderPath))
        {
            folderPath = "";
        }
        else if (!folderPath.EndsWith(@"\"))
        {
            folderPath += @"\";
        }
        //this ensures directory creation
        if (!string.IsNullOrWhiteSpace(folderPath) && !Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
                
        var baseAndFolder = string.Format(@"{0}\{1}", _basePath, folderPath);
        if(!baseAndFolder.EndsWith(@"\"))
        {
             baseAndFolder += @"\";
        }
        baseAndFolder= baseAndFolder.Replace(@"\\", @"\");
        path = string.Format(@"{0}{1}.{2}", baseAndFolder, fileName, fileExtension);
        path = path.Replace(@"\\", @"\");
        if (createIfNotExists)
        {
             //this ensures file creation
             var fs = File.Open(path, FileMode.OpenOrCreate);
             fs.Close();
        }
    }
    return path;
}

 

If you’d like to have a pick at the complete project you have it here it’s the Things that I forget when I sneeze project evolved.

I know that this is not the most optimal solution so I encourage everybody that comes with a better one to leave a comment on how to improve it in any way.

Happy coding and remember…there is life beyond codingšŸ™‚

Unit testing sharning json file as app config

Hello my dear developers!

How do you feel today?

In many projects, I’ve been told to change the model of app .Ā used for some other, for instance in a cross-platform mobil app I had to read the configuration from a config.json file that could be changed every week being sent by e-mail to the device. Obviously the file had to be overridden.

So,that, presented a challenge for unit testing my classes.

This might be conflicting since I now that ConfigurationManager is so good at it’s job and so on, but my concert was to test he exact same setting from my front end in my unit tests, so I found this nice article that explains how to share items as a link

Using this I could write one file in my “main” application and consuming it from the unit test project as a link thus not having to maintain two different sets of configurations.

As I said this is for a very specific scenario and I know that common sence dictates using app.config and web.config having two scenarios for preproduction and production, but I thought that if some one was interested I’d just post it.

Just for the sake of having it written somewhere, always remember to set your Copy to Output Directory option to Copy always for your json files, since the default is Do not copy.

config-json-copy-always

I hope this helps

Happy coding and remember…there is life beyond codingšŸ™‚

JSON: Dictionary with case insensitive keys

Hello my dear developers!

How do you feel today?

After some time working with Json I’ve realized that properties on .net use Pascal casing and nodes of json use camel casing. So to prevent problems with case sensitive keys I found this neat trick to avoid having to mess around with casing.

 

var dic= JsonConvert.DeserializeObject<Dictionary<string, object>>(_jsonSample);
_responseObj = new Dictionary<string, object>(dic, StringComparer.InvariantCultureIgnoreCase);

so you could do this

 

List result = new List();
//string resultsJson= _responseObj["responseData"].ToString();
string resultsJson = _responseObj["responsedata"].ToString();
var res = JsonConvert.DeserializeObject(resultsJson);

 

If you want to see it in action you can find it at JsonManager.cs of my code

Happy coding and remember…there is life beyond codingšŸ™‚

JSON: desereialization

So as I said in my two previous posts JSON: the first waveĀ and JSON introduction, I wanted a solution to avoid creating a wrapper for a modelĀ that most of the time was useless code stuffing my project.

So I saw this:

_responseObj=JsonConvert.DeserializeObject<Dictionary<string, object>>(_jsonSample);

This allowed me to break the first object in to its pieces, then I could access it by its key and deseralize it as a useful model

List<ResultEntity> result = new List<ResultEntity>();
string resultsJson= _responseObj["responseData"].ToString();
var res = JsonConvert.DeserializeObject<ResultsEntity>(resultsJson);

If you want to see it in action you can get the code at my GitHub

Happy coding and remember…there is life beyond coding šŸ™‚