Follow @RoyOsherove on Twitter

HOWTO: Let the user Filter object property values dynamically

I am currently creating a project where a user can see trace messages from older applications written in VB 6.0. we have a trace utility that throws traces using COM.  iIdecided i would try to write a client in C#. the user should have the ability to filter the traces that he sees, based on regular expressions.

So i have my TraceMessage Objects with their properties and stuff, and i created a FILTER object that decides whether a certain message passes the filter. however, i DID NOT want the filter to be built Hard coded to the properties of the Message, as the Message could take many shapes and can (in the future) come from many sources and have different properties.

Reflection to the rescue - I created a small function that uses reflection and lets the user decide for each filter, what property he wants to check, and the needed value it should have. it turned out pretty easy, and pretty cool. My FINAL goal i think would be to let the user use not only regular expression since those need learning and not everyone knows them ,but to let the user write "AND (X OR Y) OR Z..." etc... still have no idea how to do that though.

there must be a way to evaluate expressions in .NET, shouldnt there... if anyone knows how, please notify me. Thanks. Anyway, heres the code: 

//the actual work:

Public bool Passes(TraceMessage msg)
  {
   try
   {
    Type t  = msg.GetType();
    PropertyInfo pinfo = t.GetProperty(m_NeededName);
    if (pinfo==null)
     return false;
    if (pinfo.CanRead )
    {
     string val =  (string)pinfo.GetValue(msg,null).ToString();
     if (Regex.IsMatch(val,m_NeededValue))
     {
      return true;
     }
    }
    return false;
   }
   catch(Exception e)
   {
    throw e;
   }
   
  }

 

//How to use this:

private void OnTrace(TraceListener listener,ArrayList traces)
  {
   Filter f = new Filter("Message","=");
   foreach(TraceMessage msg in traces)
   {
    if (f.Passes(msg))
     WriteTrace(msg);
   }
  }

AppSettings Coolness

App.Config Magic