I am working on a code review. We have code that looks similar to this:
public int MyMethod(Message message)
{
// Check that the user has the access to the function
CheckUserHasAccessToFunction(UserName, FunctionName);
// Do the work
}
What I am wondering is: Is it possible to find all methods where the "CheckUserHasAccessToFunction" is missing. For example using regular expressions.
Which function name we test against will vary from method to method. The mapping between the function name and the method is part of the business logic, which we have implemented in code.
I think you should refactor your code in a way that you do not need to include this security check manually in every method, because - as you see - you cannot be sure if all methods perform this security check.
Have you ever worked with proxies? If so, you could add an interceptor which checks the security for you automatically. If not, tell me, then I will give you an example code snippet.
Edit: Here is a code sample which uses proxies (using Castle.DynamicProxy).
public class MyService
{
// The method must be virtual.
public virtual DoSomethingWhichRequiresAuthorization()
{
}
}
public static class MyServiceFactory
{
private static ProxyGenerator _generator;
private static ProxyGenerator Generator
{
get
{
if (_generator == null) _generator = new ProxyGenerator();
return _generator;
}
}
public static MyService Create()
{
var interceptor = new AuthorizationInterceptor();
return (MyService)Generator.CreateClassProxy(
typeof(MyService), new[] { interceptor });
}
}
public class AuthorizationInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
// invocation.Method contains the MethodInfo
// of the actually called method.
AuthorizeMethod(invocation.Method);
}
}
You would probably be better off using Attributes for this, in my opinion.
E.g.
[RequiresAuth]
public void Method()
{
}
I know this doesn't answer your question well, so apologies for that.
Related
Is there a way to modify the behavior of a static method at runtime?
for example:
Say I have this class
public class Utility {
public static void DoSomething(string data){
//...
}
}
Is there a way to do something like this:
typeof(Utility).SetMethod("DoSomething", (data) => { /*Do something else...*/ });
Such that if you call Utility.DoSomething it executes the new code?
What you want to do is pass the behavior you want as another parameter into the function.
public static void DoSomething(string data, Action<string> operation)
{
operation(data);
}
This is an oversimplified example, of course. What you actually wind up doing in your own code is going to depend on what operation actually does.
If you're trying to modify the behavior of an existing, compiled, in-production method, and cannot overload or override the method in the usual ways, the only way I know of to do that is CIL Rewriting, possibly using an Aspect Weaver.
Sure.
public class Utility {
public static Action<String> _DoSomething;
public static void DoSomething(string data){
if (_DoSomething != null) {
_DoSomething();
return;
}
// default behavior here.
}
}
And to mask the default behavior:
Utility._DoSomething = (data) => { /* do something else */ };
I don't see why you wouldn't just create a new class that inherits from Utility and define a new function that does what you want.
public class Program
{
static void Main(string[] args)
{
if (true)
{
Utility.DoSomething("TEST");
} else
{
Util1.DoSomething("TEST");
}
}
}
public class Utility
{
public static void DoSomething(string data)
{
//Perform some action
}
}
abstract class Util1 : Utility
{
public static new void DoSomething(string data)
{
//Perform a different action
}
}
I think although it is possible to do this you should ask yourself: "Why do I need this functionality"? Usually a method stays as is, and does what it is supposed to do according to its interface which is given by its name and signature. So while you can add additional logic by adding an Action<T>-parameter to your signature you should ask yourself if this won´t break the contract of the interface and therefor what the method was designed for.
Having said this you should consider either overwrite your method if the functionality you need is some kind of "making the same things differently then the parent-class" or extend it by adding a dependency into your consuming class and add some methods to that class that extent the functionality provided by the contained class (see also favour composition over inheritance)
class MyClass {
Utility MyUtility;
void ExtraMethod() { /* ... */ }
}
EDIT: As you´re using a static method the opportunity on overwriting is obsolete. However IMO that sounds like a great design-flaw.
The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.
I'd like to create a Roslyn code fix that changes attributed code such as this:
public class CommandHandler
{
[Command("Cmd1")]
public void Foo()
{
// do something
}
[Command("Cmd2")]
public void Bar()
{
// do something
}
}
to this:
public class CommandHandler
{
public void Foo()
{
// do something
}
public void Bar()
{
// do something
}
public void Execute(string command)
{
switch(command)
{
case "Cmd1":
Foo();
break;
case "Cmd2":
Bar();
break;
}
}
}
The main requirements are:
The signature for the refactoring is any method attributed with the [Command] attribute.
There can be multiple such methods in a class.
The synthesized Execute() method must preserve existing cases and add new ones.
Is it possible to create such a refactoring such that I can ask it to fix all instances in a project at one go? This is a feasibility question, to help me avoid running into a dead end, if there is one.
I would use analyzer + code fix provider for this.
The analyzer examines nodes of SyntaxKind.Attribute kind and reports a diagnostic if the attribute matches your CommandAttribute type.
The code fix provider provides both RegisterCodeFixesAsync to refactor a single attribute and a custom FixAllProvider that can refactor all attributes in a document/project/solution.
This way VS does all the heavy lifting and your code fix provider automatically gets list of all the attributes in the scope you're interested in.
I want to be able to call a differnt method on my intercepted class by using PostSharp.
Say I have the following method in my PostSharp aspect:
public override void OnInvoke(MethodInterceptionArgs args)
{
if (!m_featureToggle.FeatureEnabled)
{
base.OnInvoke(args);
}
else
{
var instance = args.Instance;
instance.CallDifferentMethod(); //this is made up syntax
}
}
The CallDifferentMethod() is another method within the class that has been intercepted. I can do some reflection magic to get the name of what I want to be called, but I can't work out how to call that method on this instance of the class. I don't want to spin up a new instance of the class
Any suggestions?
Are you casting args.Instace to your type? Based on what you wrote, I'd imagine that your "FeatureEnabled" should be defined through an interface.
public interface IHasFeature
{
bool IsFeatureEnabled { get; set; }
void SomeOtherMethod();
}
then use
((IHasFeature)args.Instance).SomeOtherMethod();
Then apply the aspect to that interface.
[assembly: MyApp.MyAspect(AttributeTargetTypes = "MyApp.IHasFeature")]
or on the interface directly
[MyAspect]
public interface IHasFeature
Update: Oops, Gael is right. Sorry about that. Use the CompileTimeValidate method to LIMIT the aspect at compile time.
public override bool CompileTimeValidate(System.Reflection.MethodBase method)
{
bool isCorrectType = (Check for correct type here)
return isCorrectType;
}
For more information, see my post http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspx
I know when is ok to use a Static Class, but my simple question is:
If there's a big problem when we're Unit-Testing our code that has some Static Class?
Is better just using a regular instances class?
Thanxs (i know there's some questions that talk about this, but all are based in particular case I just want to have a general opinion about it)
What I do is take the existing static class use as a seam, and provide an alternative implementation in a different namespace. This means that you can get the code under test with as few changes as possible -- just namespace changes. Typically I've had to do this to get round C# filesystem ops -- File.Exists etc.
Say your method basically does this:
using System.IO;
public void SomeMethod()
{
...
if(File.Exists(myFile))
{
...
}
...
}
then I'd replace that implementation of File with an alternative. The alterntive implementation should stub out any existing methods, and make calls to delegate implementations under the covers -- e.g.
namespace IO.Abstractions
{
public static class File
{
public static Func<string, string, string> ExistsImpl =
System.IO.File.Exists;
public static string Exists(string path)
{
return ExistsImpl (path);
}
}
}
Then I'd modify the original code so that it uses the new namespace:
using IO.Abstractions;
public void SomeMethod()
{
...
if(File.Exists(myFile))
{
...
}
...
}
Then, in your test, you can just provide an alternative implementation of the behaviour for File.Exists, something like:
[Test]
public void SomeTest()
{
// arrange
...
File.ExistsImpl = (path) => true; // to just default to true for every call
...
// act
someClass.SomeMethod();
// then assert
...
}
I wrote a blog with some more details recently here.