Category Archives: C#

Posts containing C# code

C# tricks: Securing your controllers

This article is dedicated to the ExileOffice team – revolutionizing the way we run our business in Exilesoft.

As applications move more and more of their business logic to the client side, it falls upon us to simplify what’s left on the server to avoid distractions. My previous article shows how I get rid of lot of the boring and noisy code.

There is one thing that the server will always be responsible for: Security. Much functionality can be moved to the client side, but we have no way of stopping users from hacking our client-side code or faking requests.

In this article, I extend upon the generic controllers to handle the one of the most important aspects of security: Authorization.

This is not your data!

The first order of business is to ensure that only logged in users can access our controller. This is trivially done with AuthorizationAttribute:

Here, our custom AuthorizationAttribute sets a property by looking for the Company of the currently logged in user in the database. You probably want to cache this in a session.

The second problem is to ensure that the user can only read and write data.

According to my previous article, we want to move as much as possible of the boilerplate logic into a generic EntityController. Here we add authorization:

Here, we give the controllers a virtual AccessFilter property. Whenever we read data, we need to run it through the access filter, and whenever we write data, we need to check that the data matches the filter.

It’s up to each entity controller to determine how to match the data. Here is an example for PersonData:

The clue here is to ensure that PersonController can only get at Persons through the Entities collection. This collection is always filtered with the Company that the user has access to.

The code will resolve to simply: db.Persons.Where(p => p.Company == Request.Properties["UserCompany"]).Where(p => p.Type == PersonType.Admin && p.City == city).Select(p => new { p.FirstName, p.LastName }). By using the filtered Entities, we can ensure that we never accidentally forget to apply the users company.

Posted in C#, Code, English | Leave a comment

The madness of layered architecture

I once visited a team that had fifteen layers in their code. That is: If you wanted to display some data in the database in a web page, that data passed through 15 classes in the application. What did these layers do? Oh, nothing much. They just copied data from one object to the next. Or sometimes the “access object layer” would perform a check that objects were valid. Or perhaps the check would be done in the “boundary object layer”. It varied, depending on which part of the application you looked.

Puzzled (and somewhat annoyed), I asked the team why they had constructed their application this way. The answer was simple enough: They had been told so by the expensive consultant who had been hired to advice on the organization’s architecture.

I asked the team what rationale the consultant had given. They just shrugged. Who knows?

Today, I often visit teams who have three to five layers in their code. When asked why, the response is usually the same: This is the advice they have been given. From a book, a video or a conference talk. And the rationale remains elusive or muddled at best.

Why do we construct layered applications?

There’s an ancient saying in the field of computing: Any problem in computer science can be solved by adding a layer of indirection.

Famously, this is the guiding principle behind our modern network stack. In web services SOAP performs method calls on top of HTTP. HTTP sends requests and receives responses on top of TCP. TCP streams data in two directions on top of IP. IP routes packets of bits through a network on top of physical protocols like Ethernet. Ethernet broadcasts packets of bits with a destination address to all computers on a bus.

Each layer performs a function that lets the higher layer abstract away the complexities of for example resending lost packets or routing packets through a globally interconnected network.

The analogy is used to argue for layers in enterprise application architecture.

But enterprise applications are not like network protocols. Every layer in most enterprise application operates at the same level of abstraction.

To pick on a popular example: John Papa’s video on Single Page Applications uses the following layers on the server side (and a separate set on the client side): Controllers, UnitOfWork, Repository, Factories and EntityFramework. So for example the AttendanceRepository property in CodeCamperUnitOfWork returns a AttendanceRepository to the AttendanceController, which calls GetBySessionId() method in AttendanceRepository layer, which finally calls DbSet.Where(ps => ps.SessionId == sessionId) on EntityFramework. And then there’s the RepositoryFactories layers. Whee!

And what does it all do? It filters an entity based on a parameter. Wat?!

(A hint that this is going off the rails is that discussion in the video presentation starts with the bottom and builds up to the controllers instead of outside in)

In a similar Java application, I have seen – and feel free to skip these tedious details – the SpeakersController.findByConference calls SpeakersService.findByConference, which calls SpeakersManager.findByConference, which calls SpeakersRepository.findByConference, which constructs a horrific JPAQL query which nobody can understand. JPA returns an @Entity which is mapped to the database, and the Repository, or perhaps the Manager, Service or Controller, or perhaps two or three of these, will transform from Speaker-class to another.

Why is this a problem?

The cost of code: A reasonable conjecture would be that the cost of developing and maintaining an application grows with the size of the application. Adding code without value is waste.

Single responsibility principle: In the above example, the SpeakerService will often contain all functionality associated with speakers. So if adding a speaker requires you to select a conference from a drop-down list, the SpeakerService will often have a findAllConferences method, so that SpeakersController doesn’t need to also have a dependency on ConferenceService. However, this makes the classes into functionality magnets. The symptom is low coherence: the methods of one class can be divided into distinct sets that are never used at the same time.

Dumb services: “Service” is a horrible name for a class – a service is a more or less coherent collection of functions. A more meaningful name would be a “repository” for a service that stores and retrieves objects, a Query is a service that selects objects based on a criteria (actually it’s a command, not a service), a Gateway is a service that communicates with another system, a ReportGenerator is a service that creates a report. Of course, the fact that a controller may have references to a repository, a report generator and a gateway should be quite normal if the controller fetches data from the database to generate a report for another system.

Multiple points of extension: If you have a controller that calls a service that calls a manager that calls a repository and you want to add some validation that the object you are saving is consistent, where would you add it? How much would you be willing to bet that the other developers on the team would give the same answer? How much would you be willing to bet that you would give the same answer in a few months?

Catering to the least common denominator: In the conference application we have been playing with, DaysController creates and returns the days available for a conference. The functionality needed for DaysController is dead simple. On the other hand TalksController has a lot more functionality. Even though these controllers have vastly different needs, they both get the same (boring) set of classes: A Controller, a UnitOfWork, a Repository. There is no reason the DaysController couldn’t use EntityFramework directly, other than the desire for consistency.

Most applications have a few functional verticals that contain the meat of the application and a lot of small supporting verticals. Treating them the same only creates more work and more maintenance effort.

So how can you fix it?

The first thing you must do is to build your application from the outside in. If your job is to return a set of objects, with .NET EntityFramework you can access the DbSet directly – just inject IDbSet in your controller. With Java JPA, you probably want a Repository with a finder method to hide the JPAQL madness. No service, manager, worker, or whatever is needed.

The second thing you must do is to grow your architecture. When you realize that there’s more responsibilities in your controller than deciding what to do with a user request, you must extract new classes. You may for example need a PdfScheduleGenerator to create a printable schedule for your conference. If you’re using .NET entity framework, you many want to create some LINQ extension methods on e.g. IEnumerable (which is extended by IDbSet)

The third and most important thing you must do is to give your classes names that reflect their responsibilities. A service should not just be a place to dump a lot of methods.

Every problem in computer science can be solved by adding a layer of indirection, but most problems in software engineering can be solved by removing a misplaced layer.

Let’s build leaner applications!

Posted in C#, English, Java, Software Development | Tagged | 17 Comments

C# Tricks: Slimming down your controllers

This blog post is dedicated to my colleague Seminda who has been experimenting with how to create simple and powerful web applications. Thank you for showing me your ideas and discussing improvements with me, Seminda.

I find many C# applications have much unnecessary code. This is especially true as the weight of the business logic of many applications are shifting from the backend to JavaScript code in the web pages. When the job of your application is to provide data to a front-end, it’s important to keep it slim.

In this article, I set out to simplify a standard MVC 4 API controller by generalizing the functionality, centralizing exception handling and adding extension methods to the DB set that is used to fetch my data.

If you generate an API controller based on an existing Entity and remove some of the noise, your code may look like this:

This code is a simplified version of what the API 4 Controller wizard will give you. It includes a GetPerson method that returns a person by Id, PostPerson which saves a new person, GetPeople which returns all people in the database, GetAdminsInCity, which filters people on city and type and DeletePerson which finds the person with the specified Id and deletes it.

I have replaced DbContext and IDbSet with interfaces instead of the concrete subclass of DbContext makes it easy to create tests that use a double for the database, for example MockDbSet.

Generify the controller

This is easy and safe as long as things are simple. As a general tip, rename you methods to “Get”, “Post” and “Index” rather than “GetPerson”, “PostPerson” and “GetPeople”. This will make it possible to generalize the controller thus:

The generic EntityController can be used for any class that is managed with EntityFramework.

Exception handling

I will dare to make a bold generalization: Most of the bugs that remain in production software are in error handling. Therefore I have a very simple guideline: No catch blocks that don’t rethrow another exception.

The actual handling of exceptions should be centralized. This both makes the code easier to read and it ensures that exceptions are handled consistently. In MVC 4, the place to do this is with a ExceptionFilterAttribute.

We can thus simplify the EntityController:

The HandleApplicationException looks like this:

This code code of course add special handling of other types of exceptions, logging etc.

DbSet as a repository

But one piece remains in PersonController: The rather complex use of LINQ to do a specialized query. This is where many developers would introduce a Repository with a specialized “FindAdminsByCity” and perhaps even a separate service layer with a method for “FindSummaryOfAdminsByCity”.

If you start down that path, many teams will choose to introduce the same layers (service and repository) even when these layers do nothing and create a lot of bulk in their applications. From my personal experience, this is worth fighting against! Needless layers is the cause of a huge amount of needless code in modern applications.

Instead, you can make use of C# extension methods:

The resulting controller method becomes nice and encapsulated:

The extension methods can easily be reused and can be freely combined.

Conclusions

With these tricks, most of your controllers would look something like this:

That’s pretty minimal and straightforward!

I’ve showed three tricks to reduce the complexity in your controllers: First, parts of your controllers can be generalized, especially if you avoid the name of the entity in action method names; second, exception handling can be centralized, removing noise from the main application flow and enforcing consistency; finally, using extension methods on IQueryable<Person> gives my DbSet domain specific methods without having to implement extra layers in the architecture.

I’d love to hear if you’re using these approach or if you’ve tried something like it but found it lacking.

Posted in C#, Code, English, Software Development | 4 Comments

Horizontal reuse in JavaScript and C#

In his article Horizontal Reuse: An Alternative to Inheritance Toby Inkster compares how to implement multiple inheritance or mixins in Java, Perl, PHP and Ruby. It’s a very interesting comparison of programming languages features and well worth the read.

Toby writes:

In class-based object-oriented programming, when there are classes that appear to share some functionality, this is often a time when people will refactor them into two subclasses of a common base class, avoiding repetition.

Toby gives an example of a Tractor class and a Horse class which can both pull_plough to help on the farm.

However, Horse already inherits from Animal, and Tractor already inherits from Vehicle. […] So ruling out multiple inheritance, what other possibilities do we have?

In this blog-post, I would like to extend (mixin?) Toby’s examples with two of my favorite languages: JavaScript and C#.

JavaScript

JavaScript doesn’t implement classical object-oriented classes, but instead uses prototypes. JavaScript doesn’t have a built-in mixin concept available, but the flexibility of the languages makes it easy for us to create one from scratch:

These mixins acts just as Ruby’s mixins, but like much of JavaScript, it falls on us to create the mechanism for reuse ourselves. There are many libraries out there that aim to do just this, but it’s useful to understand the underlying code.

Just like with Ruby, if we added the Hitchable mixin to Horse and forgot to implement go, JavaScript would only warn us when we tried to call horse.pull_plough().

C#

C# offers extension methods which aim to do the same thing as defender methods in Java, but rather than having to add the methods to the interface, C# allows us to put the extension methods in an independent static class.

Just like Toby’s Perl example, all the important qualities of horizontal reuse are covered, but very differently from the Perl example: We have a name for the common behavior, the Hitchable class specifies what’s needed to make something pull a plough (the IGo interface) and we get an error message from the compiler if we try to PullPlough on something that doesn’t implement IGo.

The difference is that the compiler has no idea that we may want to make Horse Hitchable before we try to call MyHorse.PullPlough().

The C# approach has one big advantage: Anyone can create the Hitchable static class. Neither Vehicle, IGo or Horse needs to know about it’s existence.

The flip-side of this is that the only type that we can assign both Horses and Tractors to is the IGo interface.

Conclusion

Different languages offer different mechanisms for horizontal reuse. JavaScript reminds a lot of Ruby, but requires more manual work for the developer. C# has a totally different approach from other languages that offers some unique strengths, but also has limitations compared to the Perl and PHP approaches.

Make sure that you check out Toby Inkster’s article for four other languages each with their unique approach: Java, Ruby, PHP and Perl.

As developers in one programming language, it is useful to know what solutions are offered in other programming languages for the same problems that we face ourselves. For programming language designers, we live in a golden age with lots of different ideas that I hope may cross-pollinate between modern programming languages.

Posted in C#, Code, English, JavaScript | Leave a comment

Sweet C# test syntax

Two of my favorite libraries in C#: FluentAssertions and NUnit (of course). NUnit has a “hidden” gem (that is, it’s well documented, yet few developers use it): [TestCase]. Look at this:

The [TestCase] lets us easily have several test cases implemented by the same method. FluentAssertions adds the Should() extension method to all objects (and primitives, too) that let’s us write things like ToRoman(3333).Should().Be("MMMCCCXXXIII").

Add some sugar to your C# tests today. What’s your favorite ways of writing sweeter tests?

Posted in C#, Code, English, Unit testing | 3 Comments

Let’s reinvent more wheels!

When I learned math in elementary school, I would reach for my calculator. But my father stopped me: “You only get to use the calculator when you can do math without it.” As you can imagine, at the time I though this was unfair and unreasonable, but later I have discovered what advantage it is to understand the basics before you reach for a powerful tool.

Many developers are focused on what fancy framework they will learn next. Or what programming language might solve all their problems. Before we reach for the tools, it’s useful to learn how they really work. My motto is: “I will not use a framework I would be unable to recreate.” It is of course, too time consuming to create a framework as complete as many of those available, but I should at least be able to solve all the normal cases myself.

Having recreated the behavior of a framework means that I will understand how the framework is implemented. I get better intuition about how to use the framework, I understand more quickly what the problem might be when something doesn’t work, and last, but not least: I understand when the framework is harming me more than it’s helping me.

An example I have enjoyed using is to create a web application in Java without framework. I may use a simple domain like creating an address book where you can register your contacts and search for them. In honor of my C#-friends, I have solved the same task in C#: How to make a web application without MVC, without ASP.NET or even without IIS.

Test-driven development is an essential tool for me to think clearly. I’ve made an exception from the calculator rule above and used a few testing libraries: SimpleBrowser.WebDriver, FluentAssertions and NUnit. This test demonstrates the behavior that I want from the application when I’m done:

I add an empty class for My.Application.WebServer and the test will fail at the line browser.Url = server.BaseUrl as there is not real server.

To implement the server, I’m using a cute small class which is part of the .NET core library: System.Net.HttpListener. Here are the essentials:

Running the test again, I get one step further. This time, I am told that the test can’t find the link to “Add contact”. No big surprise, as I’m not serving any HTML! A small change in the WebServer code will fix this:

Then we just have to create a simple implementation for AddressBookController.Service:

Again, the test will get one step further. Now we can see that the main page is presented with the links “Add contact” and “Find contact“. After Click()ing “Add contact” the test will of course fail to find the field fullName as we have not created the form yet. The method HandleGetRequest inspects the URL to determine which page should be displayed:

We’re almost done saving contacts. The test fails to find the link “Find contact” after submitting the form. The method Service must be modified to handle POST requests and perform a redirect back to the menu:

We are still missing the form to search for contacts. We’ll get some help from the copy/paste pattern:

The next error is obvious – we need to actually include the contacts in the response:

The only thing missing is to store the contacts when we post the “Add contact” form:

One last check is failing: We’re failing to filter contacts to the query:

All that remains to turn this into a real application is to use a real database and correct the obvious security vulnerability when we display contacts. The AddressBookWebServer could have a Main method to enable you to run the code. But I’ll leave these issues as an exercise to you, dear reader.

This article has showed how HTTP really works and how frameworks like ASP.NET MVC work behind the curtains. There are many details that we’re glad that the framework can fix for us, like the character encoding and reading the contents of a POST request. And there are many things that turn out to be not as hard as you’d think, like a real “redirect-on-post” pattern. In more than one project, I’ve realized that after spending a few days understanding the underlying technology, I could deliver the project much better and faster without the “obvious”, popular frameworks that everyone recommend that you use.

Did I reinvent the wheel in this article? You could argue that I did, but let me stretch the metaphor of “reinventing the wheel” as far as possible:

My experience is that many “cars” today have misaligned wheels where the axel isn’t mounted in the center. Maybe the wheel was poorly constructed, or maybe the car was just assembled wrong. Maybe we notice that the car is bouncing because two of the wheels have a misaligned axel. And then we spend a lot of work trying to adjust these wheels to synchronize the bouncing. Finally we publish articles about the nice even undulations of our car after aligning the errors in the wheels.

If we have some experience contructing one or two “wheels”, it’s possible that we’re able to identify the real problems with the “wheels” we were given, so we can determine which “wheels” are good and which “wheels” are bad. Not to mention: We may learn how to use them properly.

Reinvent wheels you don’t understand, don’t use a framework you couldn’t have made yourself and don’t use a calculatore before you understand math.

This article was previously published in Norwegian in Torbjørn Marø’s programming blog

Posted in C#, Code, English | 6 Comments

Top 5 Reasons .NET is Better Than Java

  1. Attributes. Keeps getting better ‘n better. Check out Extensible C#, Clemens Vasters new demos, and the underutilized ContextBoundObject
  2. ADO.NET. The ADO.NET model for modeling and transporting data hits right on the spot.
  3. Better FFI. P/Invoke wins against JNI, hands down (too bad it is probably overused, though)
  4. Not EJBs! Getting rid of the defunct EJB model saves a lot of headaches.
  5. Better UI. For the user, that is, not the developer!
Posted in C#, English, Java, Technology | Comments Off on Top 5 Reasons .NET is Better Than Java

Top 5 Reasons Java is Better Than .NET

  1. Open Source Community. The number of excellent open-source tools for Java is staggering. Look at HSqlDb, BeanShell, Eclipse, Recoder, JGraph, Tomcat, JBoss, and many more. More importantly, the Java community has proven much more interested in doing it the open-source way.
  2. Eclipse. Already mentioned, but it deserves a point of its own. Eclipse is a better IDE than VS.NET!
  3. Checked Exceptions.
  4. Less Native Code & more code reliability. .NET still has some weird crashes. Despite much improvement, I have still experienced DLL-Hell light.
  5. More mature libraries.
Posted in C#, English, Java, Technology | Comments Off on Top 5 Reasons Java is Better Than .NET