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.

Copyright © 2021 IDG Communications, Inc.


#validate #method #parameters #PostSharp

Source link