chapter four

4 Manage your unmanaged resources!

 

This chapter covers

  • Discovering the underlying type of an object at compile and runtime.
  • Writing code that uses IDisposable and using statements to dispose of unmanaged resources
  • Using method and constructor overloading
  • Using attributes
  • Accepting a JSON or XML input in an endpoint and parsing it into a custom object.

In chapter 3, the CEO of Flying Dutchman Airlines, Aljen van der Meulen, assigned us a project to revamp Flying Dutchman Airlines’ backend service so that the company can integrate with a third-party system (a flight aggregator called FlyTomorow). We were given an OpenAPI specification and took a look at the database schema and the configuration, model, and view classes.

WARNING

This chapter deals with the existing codebase written in the .NET Framework. This means that there will be sloppy and incorrect code, diversions from the given requirements, and all-around bad things. We will fix them all in later chapters and migrate to .NET 5.

Figure 4.1 In this chapter, we bring Part 2 to a close. We look at the existing code base’s controller class and discuss potential improvements we can make to the code.

Our understanding of the existing code base is gradually increasing, and we have almost covered the entirety of it. In this chapter, we look at the last remaining part (the only controller in the codebase) and dive into the endpoints one-by-one.

4.1      The FlightController: assessing the GET /flight endpoint

4.1.1      The GET /flight endpoint and what it does

4.1.2      Method signature: the meaning of ResponseType and typeof

4.1.3      Collecting flight information with collections

4.1.4      Connection strings; or how to give a security engineer a heart-attack

4.1.5      Using IDisposable to release unmanaged resources

4.1.6      Querying a database with SqlCommand

4.2      The FlightController: assessing GET /flight/{flightNumber}

4.3      The FlightController: POST /flight

4.4      The FlightController: DELETE /flight/{flightNumber}

4.5      Exercises

4.6      Summary