Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Intercept Method Calls in C# based on Attributes

0.00/5 (No votes)
18 Mar 2011CPOL 17.8K  
Interceping Method Calls based on Attributes
See http://stackoverflow.com/questions/25803/how-do-i-intercept-a-method-call-in-c/5345043#5345043[^] For more information on the problem at hand and other solutions...
My Solution is as follows

C#
[WebMethod]
public object InvokeMethod(string methodName, Dictionary<string, object> methodArguments)
{
  try
  {
    string lowerMethodName = '_' + methodName.ToLowerInvariant();
    List<object> tempParams = new List<object>();
    foreach (MethodInfo methodInfo in serviceMethods.Where(methodInfo => methodInfo.Name.ToLowerInvariant() == lowerMethodName))
    {
      ParameterInfo[] parameters = methodInfo.GetParameters();
      if (parameters.Length != methodArguments.Count()) continue;
      else foreach (ParameterInfo parameter in parameters)
      {
        object argument = null;
        if (methodArguments.TryGetValue(parameter.Name, out argument))
        {
          if (parameter.ParameterType.IsValueType)
          {
            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(parameter.ParameterType);
            argument = tc.ConvertFrom(argument);

          }
          tempParams.Insert(parameter.Position, argument);

        }
        else goto ContinueLoop;
      }

      foreach (object attribute in methodInfo.GetCustomAttributes(true))
      {
        if (attribute is YourAttributeClass)
        {
          RequiresPermissionAttribute attrib = attribute as YourAttributeClass;
          YourAttributeClass.YourMethod();//Mine throws an ex
        }
      }

      return methodInfo.Invoke(this, tempParams.ToArray());
ContinueLoop:
      continue;
    }
    return null;
  }
  catch
  {
    throw;
  }
}
[WebMethod]
   public void BroadcastMessage(string Message)
   {
       //MessageBus.GetInstance().SendAll("<span class='system'>Web Service Broadcast: <b>" + Message + "</b></span>");
       //return;
       InvokeMethod("BroadcastMessage", new Dictionary<string, object>() { {"Message", Message} });
   }

   [RequiresPermission("editUser")]
   void _BroadcastMessage(string Message)
   {
       MessageBus.GetInstance().SendAll("<span class='system'>Web Service Broadcast: <b>" + Message + "</b></span>");
       return;
   }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)