views:

110

answers:

6

Hi everyone,

Is there a way to have extension method on the method? Example for this would be method that takes some user object as parameter and you need to do security check if that user can use that method at the very beginning of the method. Can the method have extension method like "check can this user use me" and return bool.

Thanks.

A: 

I am not quite sure what you are looking for but this smells like declarative security to me.

Take a look at: http://msdn.microsoft.com/en-us/library/kaacwy28.aspx

Yves M.
A: 

I'm not sure if I understand your question well. However, what about this:

public static void EnsureUserHasAccess(this object obj)
{
    // check permissions, possibly depending on `obj`'s actual type
}

public static void DoSomething(this MyClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}

public static void DoSomethingElse(this MyDifferentClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}
Ondrej Tucny
A: 

Extension methods in C# are not extensions of methods (not sure I understand what that means), but methods that extend objects/classes.

If you want to inject the kind of checks you are describing into your code, you can look into PostSharp and AOP.

Oded
+1  A: 

You can't add extension method for a method with C#.

But you could use Aspect Oriented Programming (AOP) to do what you want, using PostSharp or Spring.NET for example.

madgnome
+5  A: 

You can use Aspect Oriented Programming (AOP) to implement cross-cutting security checks in your code.

In .NET you have a choice of several AOP frameworks, for example:

In particular the PostSharp documentation has some nice examples on how to implement security using AOP.

Martin Liversage
A: 

You can go with madgnome's answer, which is based on aspect programming (glad to see that somebody used that in .net) or you can use attributes and paste some code in every method that should be guarded.

Daniel Mošmondor