Oğulcan Akca
Oğulcan Akca

Reputation: 1

How do I write my Aspect classes and my problem solves?

I have 2 errors because of my little knowledge of PostSharp (last version). My project's three aspect classes, but I only get 2 errors. When the getall method runs in my mvc project, I want log information to be generated in my database and C:/Log/Log.txt. But no logs are created. Here is what I want from you. No matter how I write the code block, my problem solves? I have some validation and Transaction processes, but I don't think it has anything to do with the error I'm getting, so there's no need for details. Firstly, I've gotten the following warning.

enter image description here

To solve this, I followed the procedure below. LogAspect and FluentValidationAspect classes have been giving error.

[LogAspect(AspectPriority = 1), FluentValidationAspect(AspectPriority = 2), TransactionScopeAspect(AspectPriority = 3)]

And again, I got the following error. (CS 7036)

enter image description here

I want to do some operations in my BookManager class. (Log, Validation, Transaction). Here are the codes;

 [LogAspect(AspectPriority = 1), FluentValidationAspect(AspectPriority = 2), TransactionScopeAspect(AspectPriority = 3)]
public class BookManager : IBookService
{

    private  IBookDal _bookDal;
    private  IPersonDal _personDal;
    
    /* private readonly IQueryableRepository<Book> _queryable; */
    public BookManager(IBookDal bookDal, IPersonDal personDal/*IQueryableRepository<Book> queryable */)
    {
        _personDal = personDal;
        /*_queryable = queryable; */
        _bookDal = bookDal;
    }
   [FluentValidationAspect(typeof(BookValidator))]
    
    public Book Add(Book book)
    {
        return _bookDal.Add(book);
    }

    public void Delete(Book book)
    {
        _bookDal.Delete(book);
    }
    [LogAspect(typeof(DatabaseLogger))]
    public List<Book> GetAll()
    {
        return _bookDal.GetList();
    }
    [TransactionScopeAspect]
    public void TransactionalOperation(Person person, Book book)
    {
        _personDal.Delete(person);
        // Business Codes
        _bookDal.Add(book);
    }

    public Book GetById(int bookId)
    {
        return _bookDal.Get(p=>p.BookId==bookId);
    }
   [FluentValidationAspect(typeof(BookValidator))]
    public Book Update(Book book)
    {
        return _bookDal.Update(book);
    }
}
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]

public class LogAspect : OnMethodBoundaryAspect
{
    
    private  Type _loggerType;
    [NonSerialized]
    private LoggerService _loggerService;
    public LogAspect(Type loggerType)
    {
        _loggerType = loggerType;
    }

    public override void RuntimeInitialize(MethodBase method)
    {

        if (_loggerType.BaseType != typeof(LoggerService))
        {
            throw new Exception("Wrong logger type.");
        }
        
        _loggerService = (LoggerService)Activator.CreateInstance(_loggerType);
        base.RuntimeInitialize(method);
    }
    public override void OnEntry(MethodExecutionArgs args)
    {
        if (!_loggerService.IsInfoEnabled)
        {
            return;
        }
        try
        {
            var logParameters = args.Method.GetParameters().Select((t, i) => new LogParameter
            {
                Name = t.Name,
                Type = t.ParameterType.Name,
                Value = args.Arguments.GetArgument(i)
            }).ToList();
            var logDetail = new LogDetail
            {
                FullName = args.Method.DeclaringType == null ? null : args.Method.DeclaringType.Name,
                MethodName = args.Method.Name,
                Parameters = logParameters
            };
            _loggerService.Info(logDetail);
        }
        catch (Exception)
        {

            
        }
        
    }
}
 [Serializable]
public class FluentValidationAspect : OnMethodBoundaryAspect
{
    Type _validatorType;
    public FluentValidationAspect(Type validatorType)
    {
        _validatorType = validatorType;
    }
    public override void OnEntry(MethodExecutionArgs args)
    {
        var validator = (IValidator)Activator.CreateInstance(_validatorType);
        var entityType = _validatorType.BaseType.GetGenericArguments()[0];
        var entities = args.Arguments.Where(t => t.GetType() == entityType);
        foreach (var entity in entities)
        {
            ValidatorTool.FluentValidate(validator, entity);
        }
    }
}

I want to tell you something that you have to consider. Also, I did assembly level logging. This is the code.

[assembly: LogAspect(typeof(JsonFileLogger), AttributeTargetTypes = "ELibrary.Library.Business.Managers.BookManager*")]

Finally I want to add, can you explain the solution of this error by rewriting the wrong block?

Upvotes: 0

Views: 147

Answers (1)

Daniel Balas
Daniel Balas

Reputation: 1850

Ordering aspects is documented here. You are getting the warning because PostSharp does not have information on the ordering of some transformations. In your case I'd add the following attribute on LogAspect:

[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, typeof(FluentValidationAspect))]

And then on FluentValidationAspect:

[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, typeof(TransactionScopeAspect))]

This should totally order those three aspects and you should get rid of warnings.

Afterwards, you were getting C# errors because your aspect constructors simply have a parameter that you did not specify. AspectPriority needs to be specified on individual attributes.

Upvotes: 0

Related Questions