Archive

Posts Tagged ‘Reflection’

Setting a read-only private field

July 14th, 2011 No comments

I found this in Jimmy Nilsson’s book, Applying Domain-Driven Design… 

For me, I can see using this when rehydrating object sent over the wire or pulled from a database.  If your class uses a self-created GUID to determine uniqueness, then you’d have to override that value when building an object up with predetermined values.

Anyway, here’s the code.

Read more…

Tags: ,

Creating a single instance application per machine.

May 29th, 2011 No comments

(Another snippet I originally posted to CodeKeep.)

Read more…

Creating and reading Custom Attributes within an assembly

May 29th, 2011 No comments

(Another snippet I originally posted to CodeKeep.)I’m realizing most of the code I kept on CodeKeep is fairly old, circa .Net 3.0. 

Code:

IPlugin Interface:

 

 
public interface IPlugin
{
  void Run();
}

 

IPluginAttribute:

 

 
[AttributeUsage(AttributeTargets.Class)]
public class PluginAttribute : Attribute
{
  private readonly Guid guid;
  private readonly string requiredRight;
  private readonly string menu; 

  /// <summary>
  /// Gets a GUID that identifies the plugin. This identifier should
  /// remain constant between plugin versions.
  /// </summary>
  public Guid Guid { get { return guid; } } 

  /// <summary>
  /// Gets the Active Directory right that users must have in order
  /// to use the plugin. The plugin itself is not expected to verify
  /// user rights.
  /// </summary>
  public string RequiredRight { get { return requiredRight; } } 

  /// <summary>
  /// Gets a tab-delimited string that represents the desired menu
  /// hierarchy into which the plugin should be placed.
  /// </summary>
  /// <remarks>
  /// After separation into <c>n</c> strings, the first <c>n - 1</c>
  /// strings represent menu sub-levels, and the last string represents
  /// the menu entry that should launch the plugin. If this property
  /// is null or the empty string, the plugin should not be placed in
  /// any menu structure.
  /// </remarks>
  public string Menu { get { return menu; } } 

  /// <summary>
  /// Initializes a new instance of the <c>PluginAttribute</c>
  /// class with the specified values for the <see cref="Guid" />,
  /// <see cref="RequiredRight" />, and <see cref="Menu" />properties.
  /// </summary>
  /// <param name="guid" />A <see cref="System.Guid" />that uniquely
  /// identifies the plugin.
  /// <param name="requiredRight" />A string that names a required Active
  /// Directory right
  /// <param name="menu" />A string representing the desired menu
  /// hierarchy.
  public PluginAttribute(Guid guid, string requiredRight, string menu)
  {
    this.guid = guid;
    this.requiredRight = requiredRight;
    this.menu = menu;
  } 

  public PluginAttribute(string guidText, string requiredRight, string menu) : this(new Guid(guidText), requiredRight, menu)
  {
  } 

  /// <summary>
  /// Initializes a new instance of the <c>PluginAttribute</c>
  /// class with the specified values for the <see cref="Guid" />and
  /// <see cref="RequiredRight" />properties. The <see cref="Menu" />
  /// property is set to the empty string.
  /// </summary>
  /// <param name="guid" />A <see cref="System.Guid" />that uniquely
  /// identifies the plugin.
  /// <param name="requiredRight" />A string that names a required Active
  /// Directory right
  public PluginAttribute(Guid guid, string requiredRight) : this(guid, requiredRight, "")
  {
  } 

  public PluginAttribute(string guidText, string requiredRight) : this(guidText, requiredRight, "")
  {
  }

}

 

Attribute Tag in the assembly:

 

 
[Plugin("GUID","AccessRights","Topic\tSubtopic\tName")] 

 

Lookup:

 

IEnumerable types = thisAssembly.GetTypes();
foreach (Type type in types)
{ 
  if (
    (typeof(IPlugin).IsAssignableFrom(type) && 
    (type.GetCustomAttributes(true).Count() > 0)
  )
  { 
    var objs = .GetCustomAttributes(true);
    foreach (object obj in type.GetCustomAttributes(true))      
    { 
      var pa = obj as PluginAttribute;
      if (pa != null)
      {
          str.Append("\t" + obj.GetType() + ": \t" + obj + Environment.NewLine);          
          str.Append("\tGuid:          " +  pa.Guid + Environment.NewLine);
          str.Append("\tMenu:          " +  pa.Menu + Environment.NewLine);
          str.Append("\tRequiredRight: " +  pa.RequiredRight + Environment.NewLine);
          str.Append("\tTypeId:        " +  pa.TypeId + Environment.NewLine);
          str.Append(Environment.NewLine);
        }
      }
 
    }
  }
}
 

Implements interface?

May 29th, 2011 No comments

(Another snippet I originally posted to CodeKeep.)

Change ‘IPlugin’ to suit your needs.

 

Code:

Assembly thisAssembly = AssemblyBuilder.LoadFrom(pathToAssembly);

IEnumerable<Type> types = thisAssembly.GetTypes();
types = from t in types
    orderby t.Name
    select t;

foreach (Type type in types)
{
  if (typeof(IPlugin).IsAssignableFrom(type))
  {
    // Implements the IPlugin interface
    // Do something interesting
  }
}

Where am I? (Using reflection to determine location in the execution)

May 29th, 2011 No comments

(Another snippet I originally posted to CodeKeep.)

Using reflection inside a method to determine where you are in the control flow via the output window.

This is another snippet I used to have on CodeKeep.net.

I like to put a lot of debugging statements in my code and tracking the code exec is much easier if I know which methods are being called.  I don’t do this so much anymore as VS2010 has greatly improved debugging over VS2008 and VS2005.

Code:

string callingAssemblyName = System.Reflection.Assembly.GetCallingAssembly().FullName;
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();

 

Usage:

using System.Diagnostics;

Debug.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "() called.");

or

string methodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(methodName + "(" + <method args> + ") called.");

Debug.WriteLine(methodName + "() ending.");

About ViewModel for C# project

October 1st, 2010 No comments

I find myself looking up this code, time and time again.

<shrug>

using System.Reflection;

namespace <AppName>.Ux.ViewModel
{

    public class AboutViewModel : ViewModelBase
    {

        public string Title { get; private set; }
        public string Description { get; private set; }
        public string Configuration { get; private set; }
        public string Company { get; private set; }
        public string Product { get; private set; }
        public string Copyright { get; private set; }
        public string Trademark { get; private set; }
        public string Culture { get; private set; }

        public AboutViewModel()
        {
            var caller = Assembly.GetExecutingAssembly();

            Title = ((AssemblyTitleAttribute) caller.GetCustomAttributes(typeof (AssemblyTitleAttribute), false)[0]).Title;
            Description = ( (AssemblyDescriptionAttribute)caller.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)[0] ).Description;
            Configuration = ((AssemblyConfigurationAttribute) caller.GetCustomAttributes(typeof (AssemblyConfigurationAttribute), false)[0]).Configuration;
            Company = ( (AssemblyCompanyAttribute)caller.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false)[0] ).Company;
            Product = ( (AssemblyProductAttribute)caller.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0] ).Product;
            Copyright = ( (AssemblyCopyrightAttribute)caller.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0] ).Copyright;
            Trademark = ( (AssemblyTrademarkAttribute)caller.GetCustomAttributes(typeof(AssemblyTrademarkAttribute), false)[0] ).Trademark;
            Culture = ( (AssemblyCultureAttribute)caller.GetCustomAttributes(typeof(AssemblyCultureAttribute), false)[0] ).Culture;

        }

    }

}

App version by the deployment method

January 10th, 2010 No comments

I have several clickonce deployments. And it gets old having to manually increament my version numbers in the AssemblyInfo file especially when my deployment method does that on it’s own.

So… Here’s my solution. Read more…

Examining an assembly through reflection

December 9th, 2009 No comments

Below is code loading and examining an assembly.

Problem:

You want to open an assembly to see what’s inside with as little effort as possible.

Solution:

I’m sure there are easier ways but this works…

Code:

Read more…

Reflection within a method

November 24th, 2009 No comments

Who am I?
Where am I?

Have you ever asked that question while examining your code? Before I learned about the Call Stack in Visual Studio 2010, I faced that problem often. I’d have a million of these little debugging statements scattered throughout my code.

string callingAssemblyName = System.Reflection.Assembly.GetCallingAssembly().FullName;
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();

Usage:

using System.Diagnostics;

Debug.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "() called.");

or

string methodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
Debug.WriteLine(methodName + "(" + <method args> + ") called.");
...
Debug.WriteLine(methodName + "() ending.");
Tags: ,

Know thy self (thru Reflection)

September 7th, 2009 No comments

I like to display the version number in the status bar of my applications. Here’s a way to get that information at run-time via reflection.

private void DisplayVersion()
{
	Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
	lblVersion.Content = "v" + v.Major + "." + v.Minor + "." + v.Build + "." + v.Revision;
}
Tags: