25/06/2021

Licensing Consultant

Not just any technology

How to perform validation using PostSharp in C#

You could possibly frequently want to validate parameters in your techniques to make sure they...

You could possibly frequently want to validate parameters in your techniques to make sure they have legitimate information. Most importantly, you could possibly frequently want to guard your publicly uncovered API techniques by ensuring that the parameters in individuals techniques have legitimate values. This would make sure that your APIs operate consistently. The resolution to this trouble is by applying part-oriented programming, or AOP.

Part-oriented programming separates the issues of your application, reduces code duplication and muddle, and increases the maintainability and readability of your code. There are several resources out there that you can use to put into action AOP in your purposes. PostSharp is a person of the most greatly used AOP frameworks. This article discusses how we can consider benefit of PostSharp to validate the parameters of techniques in C#.

To operate with the code illustrations presented in this article, you should really have Visible Studio 2019 put in in your system. If you really don’t by now have a copy, you can down load Visible Studio 2019 in this article.

Make a .Net Core console application job in Visible Studio

First off, let’s produce a .Net Core console application job in Visible Studio. Assuming Visible Studio 2019 is put in in your system, observe the methods outlined below to produce a new .Net Core console application job in Visible Studio.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new job.”
  3. In the “Create new project” window, find “Console App (.Net Core)” from the listing of templates displayed.
  4. Click on Upcoming.
  5. In the “Configure your new project” window, specify the identify and site for the new job.
  6. Click on Make.

We’ll use this job to operate with PostSharp in the subsequent sections of this article.

What is part-oriented programming?

Part-oriented programming is a programming model that enables you to outline certain procedures that, in change, can be used to outline and regulate the cross-reducing issues in an application. In essence, AOP is a programming paradigm that makes it a lot easier to adapt your application to alterations.

PostSharp is a person of the most well-known frameworks used to put into action AOP in purposes. You can consider benefit of PostSharp’s compile-time weaving functions to remove repetitive code and solidify your application. PostSharp inspects the compiled IL code, then attaches actions to the entire body of just about every strategy on which an part has been outlined applying a person or additional characteristics.

Make a custom ParameterAttribute summary base course in C#

In your new console application job, produce a custom attribute course named MethodParameterAttributeBase as demonstrated in this article:

[AttributeUsage(AttributeTargets.Parameter)]
public summary course MethodParameterAttributeBase : Attribute

    public summary void VerifyMethodParameter(ParameterInfo parameter, object value)

The MethodParameterAttributeBase summary course extends the Program.Attribute course and incorporates the declaration of a strategy named VerifyMethodParameter.

Make a NotNullOrEmpty concrete course in C#

Upcoming we’ll produce a concrete course that will lengthen the summary base course we designed previously. This course will override the VerifyMethodParameter strategy to check if the value handed in the parameter is null or empty.

Make a course named NotNullOrEmpty that extends the summary base course called MethodParameterAttributeBase as demonstrated in the code listing below.

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

The Information residence of the MethodParameterAttributeBase course is used to store the message displayed when a person or additional parameters have empty or null values. The VerifyMethodParameter strategy accepts an occasion of the Program.Reflection.ParameterInfo course as perfectly as an occasion of the object course as a parameter. Even though the former retrieves metadata about the parameters handed to the strategy, the latter stores the parameter values. The metadata about the parameters incorporates the identify and sort of the parameters and their characteristics.

Look at for null or empty parameter values in C#

The subsequent 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)
                toss new ArgumentNullException(parameter.Identify, Information)
            if (value != null && value.ToString().Size == )
                toss new ArgumentException(Information, parameter.Identify)
       

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

Here is the complete source code of the NotNullOrEmpty course:

[Serializable]
[AttributeUsage(AttributeTargets.Parameter)]
public course NotNullOrEmpty : MethodParameterAttributeBase
   
        public string Information get established
        public override void VerifyMethodParameter
        (ParameterInfo parameter, object value)
       
            if (value == null)
                throw new ArgumentNullException(parameter.Identify, Information)
            if (value != null && value.ToString().Size == )
                toss new ArgumentException(Information, parameter.Identify)
       
   

Make a ValidateParameterAttributes course in C#

The ValidateParameterAttributes course extends the OnMethodBoundaryAspect course and overrides the OnEntry strategy. Here’s in which you’ll require to compose the essential logic to iterate via the parameters collection and validate just about every parameter.

 [Serializable]
[AttributeUsage(AttributeTargets.Technique | AttributeTargets.Constructor)]
 [ProvideAspectRole(StandardRoles.Validation)]
    public course ValidateParameterAttributes : OnMethodBoundaryAspect
   
        public override void OnEntry(MethodExecutionArgs eventArgs)
       
            ParameterInfo[] parameterInfoArray =
            eventArgs.Technique.GetParameters()
            Item[] 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])
                      
            base.OnEntry(eventArgs)
       
   

Take a look at your PostSharp-validated AOP application

Last but not least, in this article is how you can examination your AOP console application from the Most important strategy.

 class Program
   
        [ValidateParameterAttributes]
        public static void Screen([NotNullOrEmpty
        ("Are not able to be null or empty...")] object obj)
       
            Console.WriteLine(obj.ToString())
       
        static void Most important(string[] args)
       
            Screen(null)
            Console.Browse()
       
   

When you operate this application, the output will appear as demonstrated in Determine one.

postsharp aop in csharp 01 IDG

Determine one: PostSharp in action!

You could enhance this implementation by caching the information for all parameters of the techniques. You could also cache the ValidateParameterAttributes cases that beautify the method’s parameters. You could then consider benefit of these cached cases to carry out validation checks at runtime. We’ll talk about this and other fascinating functions in PostSharp in a long run put up in this article.

Copyright © 2021 IDG Communications, Inc.