How to perform validation using PostSharp in C#

Maria J. Danford

You may frequently want to validate parameters in your approaches to be certain they have legitimate data. Most importantly, you may frequently want to protect your publicly exposed API approaches by ensuring that the parameters in those people approaches have legitimate values. This would be certain that your APIs do the job continually. The remedy to this problem is by utilizing part-oriented programming, or AOP.

Factor-oriented programming separates the considerations of your application, reduces code duplication and litter, and increases the maintainability and readability of your code. There are a number of equipment out there that you can use to implement AOP in your purposes. PostSharp is one of the most greatly applied AOP frameworks. This write-up discusses how we can take benefit of PostSharp to validate the parameters of approaches in C#.

To do the job with the code illustrations supplied in this write-up, you must have Visible Studio 2019 set up in your procedure. If you don’t currently have a duplicate, you can download Visible Studio 2019 in this article.

Create a .Web Main console application undertaking in Visible Studio

Initial off, let us build a .Web Main console application undertaking in Visible Studio. Assuming Visible Studio 2019 is set up in your procedure, observe the actions outlined underneath to build a new .Web Main console application undertaking in Visible Studio.

  1. Start the Visible Studio IDE.
  2. Click on on “Create new undertaking.”
  3. In the “Create new project” window, decide on “Console App (.Web Main)” from the record of templates shown.
  4. Click on Next.
  5. In the “Configure your new project” window, specify the name and area for the new undertaking.
  6. Click on Create.

We’ll use this undertaking to do the job with PostSharp in the subsequent sections of this write-up.

What is part-oriented programming?

Factor-oriented programming is a programming style that enables you to determine precise insurance policies that, in change, can be applied to determine and control the cross-reducing considerations in an application. In essence, AOP is a programming paradigm that makes it a lot easier to adapt your application to adjustments.

PostSharp is one of the most popular frameworks applied to implement AOP in purposes. You can take benefit of PostSharp’s compile-time weaving characteristics to eradicate repetitive code and solidify your application. PostSharp inspects the compiled IL code, then attaches steps to the body of each approach on which an part has been described using one or a lot more characteristics.

Create a customized ParameterAttribute abstract foundation class in C#

In your new console application undertaking, build a customized attribute class named MethodParameterAttributeBase as revealed in this article:

[AttributeUsage(AttributeTargets.Parameter)]
public abstract class MethodParameterAttributeBase : Attribute

    public abstract void VerifyMethodParameter(ParameterInfo parameter, item price)

The MethodParameterAttributeBase abstract class extends the Program.Attribute class and has the declaration of a approach named VerifyMethodParameter.

Create a NotNullOrEmpty concrete class in C#

Next we’ll build a concrete class that will increase the abstract foundation class we developed formerly. This class will override the VerifyMethodParameter approach to examine if the price handed in the parameter is null or vacant.

Create a class named NotNullOrEmpty that extends the abstract foundation class called MethodParameterAttributeBase as revealed in the code listing underneath.

public class NotNullOrEmpty : MethodParameterAttributeBase
   
        public string Information get established
        public override void VerifyMethodParameter
        (ParameterInfo parameter, item price)
       
            //We’ll require to compose code in this article to validates the parameters
       
   

The Information assets of the MethodParameterAttributeBase class is applied to retail outlet the message shown when one or a lot more parameters have vacant or null values. The VerifyMethodParameter approach accepts an instance of the Program.Reflection.ParameterInfo class as perfectly as an instance of the item class as a parameter. Though the former retrieves metadata about the parameters handed to the approach, the latter outlets the parameter values. The metadata about the parameters includes the name and sort of the parameters and their characteristics.

Check for null or vacant parameter values in C#

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

public override void VerifyMethodParameter(ParameterInfo parameter, item price)
       
            if (price == null)
                throw new ArgumentNullException(parameter.Name, Information)
            if (price != null && price.ToString().Length == )
                throw new ArgumentException(Information, parameter.Name)
       

When the values contained in the parameters are vacant or null, proper exceptions are thrown. If the price of the parameter is null, then an instance of ArgumentNullException is thrown if the price of the parameter is vacant, then an instance of ArgumentException is thrown.

Listed here is the total source code of the NotNullOrEmpty class:

[Serializable]
[AttributeUsage(AttributeTargets.Parameter)]
public class NotNullOrEmpty : MethodParameterAttributeBase
   
        public string Information get established
        public override void VerifyMethodParameter
        (ParameterInfo parameter, item price)
       
            if (price == null)
                throw new ArgumentNullException(parameter.Name, Information)
            if (price != null && price.ToString().Length == )
                throw new ArgumentException(Information, parameter.Name)
       
   

Create a ValidateParameterAttributes class in C#

The ValidateParameterAttributes class extends the OnMethodBoundaryAspect class and overrides the OnEntry approach. Here’s where by you will require to compose the vital logic to iterate by way of the parameters assortment and verify each parameter.

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

Take a look at your PostSharp-validated AOP application

Last but not least, in this article is how you can test your AOP console application from the Main approach.

 class Program
   
        [ValidateParameterAttributes]
        public static void Screen([NotNullOrEmpty
        ("Are unable to be null or vacant...")] item obj)
       
            Console.WriteLine(obj.ToString())
       
        static void Main(string[] args)
       
            Screen(null)
            Console.Read through()
       
   

When you run this application, the output will appear as revealed in Figure one.

postsharp aop in csharp 01 IDG

Figure one: PostSharp in action!

You could increase this implementation by caching the facts for all parameters of the approaches. You could also cache the ValidateParameterAttributes situations that embellish the method’s parameters. You could then take benefit of these cached situations to complete validation checks at runtime. We’ll discuss this and other exciting characteristics in PostSharp in a long run submit in this article.

Copyright © 2021 IDG Communications, Inc.

Next Post

The public cloud could evolve like streaming services

Streaming solutions, the type we use from Apple Television set, Roku, smart TVs, mobile units, or other programs are beginning to glance a large amount alike in phrases of the articles that they offer—no issue if you’re spending for them or not. Scenario in stage, all through the pandemic I […]

Subscribe US Now