joydip_kanjilal
Contributor

How to validate method parameters using PostSharp in C#

how-to
Jun 09, 20215 mins
APIsC#Microsoft .NET

Take advantage of aspect-oriented programming using PostSharp to validate method parameters in C#.

A virtual checkmark in digital system / standards / quality control / certification / certificates
Credit: Vertigo3D / Getty Images

You might often want to validate parameters in your methods to ensure they have valid data. Most importantly, you might often want to protect your publicly exposed API methods by ensuring that the parameters in those methods have valid values. This would ensure that your APIs work consistently. The solution to this problem is by implementing aspect-oriented programming, or AOP.

Aspect-oriented programming separates the concerns of your application, reduces code duplication and clutter, and improves the maintainability and readability of your code. There are several tools out there that you can use to implement AOP in your applications. PostSharp is one of the most widely used AOP frameworks. This article discusses how we can take advantage of PostSharp to validate the parameters of methods in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.

We’ll use this project to work with PostSharp in the subsequent sections of this article.

What is aspect-oriented programming?

Aspect-oriented programming is a programming style that allows you to define specific policies that, in turn, can be used to define and manage the cross-cutting concerns in an application. In essence, AOP is a programming paradigm that makes it easier to adapt your application to changes.

PostSharp is one of the most popular frameworks used to implement AOP in applications. You can take advantage of PostSharp’s compile-time weaving features to eliminate repetitive code and solidify your application. PostSharp inspects the compiled IL code, then attaches actions to the body of each method on which an aspect has been defined using one or more attributes.

Create a custom ParameterAttribute abstract base class in C#

In your new console application project, create a custom attribute class named MethodParameterAttributeBase as shown here:

[AttributeUsage(AttributeTargets.Parameter)]
public abstract class MethodParameterAttributeBase : Attribute
{
    public abstract void VerifyMethodParameter(ParameterInfo parameter, object value);
}

The MethodParameterAttributeBase abstract class extends the System.Attribute class and contains the declaration of a method named VerifyMethodParameter.

Create a NotNullOrEmpty concrete class in C#

Next we’ll create a concrete class that will extend the abstract base class we created previously. This class will override the VerifyMethodParameter method to check if the value passed in the parameter is null or empty.

Create a class named NotNullOrEmpty that extends the abstract base class called MethodParameterAttributeBase as shown in the code listing below.

public class NotNullOrEmpty : MethodParameterAttributeBase
    {
        public string Message { get; set; }
        public override void VerifyMethodParameter
        (ParameterInfo parameter, object value)
        {
            //We’ll need to write code here to validates the parameters
        }
    }

The Message property of the MethodParameterAttributeBase class is used to store the message displayed when one or more parameters have empty or null values. The VerifyMethodParameter method accepts an instance of the System.Reflection.ParameterInfo class as well as an instance of the object class as a parameter. While the former retrieves metadata about the parameters passed to the method, the latter stores the parameter values. The metadata about the parameters includes the name and type of the parameters and their attributes.

Check for null or empty parameter values in C#

The following code snippet illustrates how you can check for null or empty values in the parameters.

public override void VerifyMethodParameter(ParameterInfo parameter, object value)
        {
            if (value == null)
                throw new ArgumentNullException(parameter.Name, Message);
            if (value != null && value.ToString().Length == 0)
                throw new ArgumentException(Message, parameter.Name);
        }

When the values contained in the parameters are empty or null, appropriate exceptions are thrown. If the value of the parameter is null, then an instance of ArgumentNullException is thrown; if the value of the parameter is empty, then an instance of ArgumentException is thrown.

Here is the complete source code of the NotNullOrEmpty class:

[Serializable]
[AttributeUsage(AttributeTargets.Parameter)]
public class NotNullOrEmpty : MethodParameterAttributeBase
    {
        public string Message { get; set; }
        public override void VerifyMethodParameter
        (ParameterInfo parameter, object value)
        {
            if (value == null)
                throw new ArgumentNullException(parameter.Name, Message);
            if (value != null && value.ToString().Length == 0)
                throw new ArgumentException(Message, parameter.Name);
        }
    }

Create a ValidateParameterAttributes class in C#

The ValidateParameterAttributes class extends the OnMethodBoundaryAspect class and overrides the OnEntry method. Here’s where you’ll need to write the necessary logic to iterate through the parameters collection and verify each parameter.

 [Serializable]
 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor)]
 [ProvideAspectRole(StandardRoles.Validation)]
    public class ValidateParameterAttributes : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs eventArgs)
        {
            ParameterInfo[] parameterInfoArray =
            eventArgs.Method.GetParameters();
            Object[] args = eventArgs.Arguments.ToArray();
            for (int index = 0; index < parameterInfoArray.Length; index++)
            {
                var parameterAttributeArray = parameterInfoArray[index].
                    GetCustomAttributes<MethodParameterAttributeBase>();
                foreach (MethodParameterAttributeBase parameterAttribute
                    in parameterAttributeArray)
                    parameterAttribute.VerifyMethodParameter
                    (parameterInfoArray[index], args[index]);
            }          
            base.OnEntry(eventArgs);
        }
    }

Test your PostSharp-validated AOP application

Finally, here is how you can test your AOP console application from the Main method.

 class Program
    {
        [ValidateParameterAttributes]
        public static void Display([NotNullOrEmpty
        ("Cannot be null or empty...")] object obj)
        {
            Console.WriteLine(obj.ToString());
        }
        static void Main(string[] args)
        {
            Display(null);
            Console.Read();
        }
    }

When you run this application, the output will appear as shown in Figure 1.

postsharp aop in csharp 01 IDG

Figure 1: PostSharp in action!

You could improve this implementation by caching the information for all parameters of the methods. You could also cache the ValidateParameterAttributes instances that decorate the method’s parameters. You could then take advantage of these cached instances to perform validation checks at runtime. We’ll discuss this and other exciting features in PostSharp in a future post here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author