Showing posts with label reflection. Show all posts
Showing posts with label reflection. Show all posts

Friday, January 27, 2012

Removing Strong Name from .NET assembly

First in 10+ years of .net practice I had to solve removing the strong name from the assembly and recompiling it after the export with Reflector.

The need for that was caused by customer’s extra security/audit requirements which could not be satisfied through a standard extensibility in MS CRM 3.0. And let us say MS CRM 3.0 is a very old lady now, so one can hardly expect year 2005 code to meet year 2012 security standards.

I found two solutions over the web:

http://blog.fredrikhaglund.se/blog/2009/02/06/how-to-patchfixhack-someone-elses-assembly/

http://www.codeproject.com/Articles/15374/Removing-Strong-Signing-from-assemblies-at-file-le

I was happy I didn’t have to resort to a second one – quite heavier weight for what I needed. First one worked as a charm.

By the way  I tried side by side latest .NET reflector from Red Gate with the last not expired version of original Reflector and should say that I didn’t notice any value added in Red Gate’s version. Nothing to advocate a sudden price tag and 1+ year of ownership, SHAME!

As for decompile and recompile of a CRM assembly in question, just few issues I ran into:

Compiler limit exceeded: Line cannot exceed 2046 characters (CS1034) - C:\CRM\PROJECTS\components.core\Microsoft\Crm\SystemCustomization\Security.cs:31,2046

That was solved easily with splitting the line into several instructions.

Microsoft.Crm.CalendarUtil:

Operator '>=' cannot be applied to operands of type 'System.DayOfWeek' and 'int' (CS0019) - C:\CRM\PROJECTS\components.core\Microsoft\Crm\CalendarUtil.cs:157,17

Corrected version of a method would look like (trick is in casting the enums to int):

public static DateTime GetFirstDayInCalendar(DateTime date)
{
    date = new DateTime(date.Year, date.Month, 1, 0, 0, 0);
    int weekStartDayCode = OrganizationSettings.Current.WeekStartDayCode;
    if ((int)date.DayOfWeek >= weekStartDayCode)
    {
        return date.AddDays((double) (((int)date.DayOfWeek - weekStartDayCode) * ~(int)DayOfWeek.Sunday));
    }
    return date.AddDays((double) ((((int)date.DayOfWeek + 7) - weekStartDayCode) * ~(int)DayOfWeek.Sunday));
}

And again, always something to learn! I was really puzzled with that tilda operator in front of DayOfWeek.Sunday so was glad to learn about it: http://stackoverflow.com/questions/387424/what-is-the-tilde-in-a-c-sharp-enumeration

This is it. Hope my positive experience will ease your decisions once you stay in front of a similar task!

Sunday, April 19, 2009

My first naive look at MS Cci – inspect your managed dll versions

As there have been few announcements already on MS Common Compiler Infrastructure going open source on Codeplex, I thought it could be fun to give it a first naive try for one of my current needs:

- Create an inventory of assembly versions deployed in production/test

I started with downloading the sources and looking around:

image I was quite focused on the ability to read the assembly so PeReader and PEReaderTests were most principal for my needs.
In particular ModuleReaderTest was the most interesting to study.
I had to get xunit from the codeplex and put it to the correct relative location. Other than that no extra steps were required to get the code to compile.
After really short while, I got to a very concise code. First a HostEnvironment, that as I understood at the first glance is a context and “cache” resolver for your module/assembly read operations:

using System;
using Microsoft.Cci;
 
namespace Tools.Net.Cci.Samples
{
    internal class HostEnvironment : MetadataReaderHost
    {
        PeReader peReader;
        internal HostEnvironment()
        {
            this.peReader = new PeReader(this);
        }
        public override IUnit LoadUnitFrom(string location)
        {
            return this.peReader.OpenModule(BinaryDocument.GetBinaryDocumentForFile(location, this));
 
        }
    }
}

And secondly the utility itself:

using System;
using System.IO;
 
using Microsoft.Cci;
 
namespace Tools.Net.Cci.Samples
{
    class Program
    {
        static HostEnvironment env;
 
        static void Main(string[] args)
        {
            if (args == null || args.Length != 2)
            {
                Console.WriteLine("Usage: assemblyversion path searchPattern");
                Console.WriteLine("Usage: assemblyversion \"c:\\product\" *.dll");
            }
            else
            {
                env = new HostEnvironment();
 
                AnalyzeDir(args[0], args[1]);
            }
        }
 
        private static void AnalyzeDir(string path, string searchPattern)
        {
            if (Directory.Exists(path))
            {
                string[] files = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
 
                foreach (string file in files)
                {
                    try
                    {
                        IAssembly assembly =
                            (IAssembly)env.LoadUnitFrom(file);
 
                        Console.WriteLine(
                                String.Format("{0}|{1}|{2}|{3}",
                                    assembly.AssemblyIdentity.Location,
                                    assembly.AssemblyIdentity.Name,
                                    assembly.AssemblyIdentity.Version));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(
                            String.Format("{0}|{1}|{2}|{3}",
                                    file,
                                    Path.GetFileName(file),
                                    "N/A",
                                    ex.Message));
                    }
                }
            }
        }
    }
}

For the unmanaged dlls call to the LoadUnit was resulting in the exception, so excuse my naive try/catch for this, subject to study more soon.
Definitely Cci represents a good competitor to Mono.Cecil, and you can read a Jb Evain’s opinion on it and Cecil here: http://evain.net/blog/articles/2009/04/18/cecil-and-the-cci
Another good entry on Cci/Cecil vs System.Reflection is from who else than Patrick Smacchia: http://codebetter.com/blogs/patricksmacchia/archive/2008/03/18/mono-cecil-vs-system-reflection.aspx

My next point of naive interest will be to see how CCI handles (if at all) pseudo attributes.

You can get the complete solution here: http://code.google.com/p/toolsdotnet/source/browse/trunk/Tools.Net/spikes/Cci/Cci.sln
And utility itself can be downloaded from here: http://cid-c651f6a9f36fb87d.skydrive.live.com/self.aspx/Public/assemblyversion.exe

Here is the sample usage of the utility:

assemblyversion.exe "C:\dev\svn\Tools.Net\spikes\Cci\Tools.Cci.Samples\bin\Debug" *.dll

and output:

C:\dev\svn\Tools.Net\spikes\Cci\Tools.Cci.Samples\bin\Debug\Microsoft.Cci.MetadataHelper.dll|Microsoft.Cci.MetadataHelper|0.0.0.2|
C:\dev\svn\Tools.Net\spikes\Cci\Tools.Cci.Samples\bin\Debug\Microsoft.Cci.MetadataModel.dll|Microsoft.Cci.MetadataModel|0.0.0.2|
C:\dev\svn\Tools.Net\spikes\Cci\Tools.Cci.Samples\bin\Debug\Microsoft.Cci.PeReader.dll|Microsoft.Cci.PeReader|0.0.0.2|

Very raw, but subject to improve…

Friday, October 19, 2007

CustomAttributesData and NamedParameter of an Array type


After submitting a piece of work to Spring.NET, which was included in the release candidate 2 of version 1.1 following issue was raised on the Spring.NET forums http://forum.springframework.net/showthread.php?p=9286:

[InvalidCastException: Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection `1[System.Reflection.CustomAttributeTypedArgument]' to type 'System.Array'.]
System.Reflection.Emit.CustomAttributeBuilder.Emit Value(BinaryWriter writer, Type type, Object value) +701
System.Reflection.Emit.CustomAttributeBuilder.Init CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues) +1448
System.Reflection.Emit.CustomAttributeBuilder..cto r(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues) +24

Issue happened for the custom attribute of type:

[Transaction(ReadOnly = false, NoRollbackFor = new Type[] {typeof (...)})]

The reason behind exception is how CustomAttributeData handles this "array" type of metadata when it creates attribute arguments:

internal CustomAttributeTypedArgument(Module scope, CustomAttributeEncodedArgument encodedArg)
{
    CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType;
    switch (encodedType)
    {
// Many cases omitted, see the code with Reflector ...

//Bringing attention to this case, as this is exactly what is not resolved yet in the Mono.Cecil at the moment of this writing (Though trivial to work around for)
case CustomAttributeEncoding.Type:
            this.m_argumentType = typeof(Type);
            this.m_value = null;
            if (encodedArg.StringValue != null)
            {
                this.m_value = ResolveType(scope, encodedArg.StringValue);
                return;
            }
            break;

// And bellow is the point that explains the issue with the arrays  in the custom attributes       
case CustomAttributeEncoding.Array:
        {
            Type type;
            encodedType = encodedArg.CustomAttributeType.EncodedArrayType;
            if (encodedType == CustomAttributeEncoding.Enum)
            {

                // This case should be checked - no Spring.NET init tests for this case now
                type = ResolveType(scope, encodedArg.CustomAttributeType.EnumName);


            }
            else
            {

                // This case should be checked - no Spring.NET init tests for this case now
                type = CustomAttributeEncodingToType(encodedType);
            }
            this.m_argumentType = type.MakeArrayType();
            if (encodedArg.ArrayValue == null)
            {
                this.m_value = null;
                return;
            }
            CustomAttributeTypedArgument[] array = new CustomAttributeTypedArgument[encodedArg.ArrayValue.Length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = new CustomAttributeTypedArgument(scope, encodedArg.ArrayValue[i]);
            }

           And this is the point that gives us troubles now, can't say that returning it as a

           ReadOnly is a bad idea, guys are right, so we will need to cope with such a case with a bit of a work around.
            this.m_value = Array.AsReadOnly<CustomAttributeTypedArgument>(array);
            return;
        }
        default:
            this.m_argumentType = CustomAttributeEncodingToType(encodedType);
            this.m_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedType);
            break;
    }
}

It is quite relevant to check though what is the Array.AsReadOnly<T> implementation.

public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array)
{
    if (array == null)
    {
        throw new ArgumentNullException("array");
    }
    return new ReadOnlyCollection<T>(array);
}

Great! This is quite straightforward and deterministic to build a workaround around :).

Solution was to add extra Resolve method with the argument value parameter that is transforming the System.Collections.ObjectModel.ReadOnlyCollection `1[System.Reflection.CustomAttributeTypedArgument] to the array of the original type.

As we can pass the same through the constructor argument, same resolution should be applied to the constructor arguments. Subject to create tests for and apply.

Wednesday, October 3, 2007

Applying Mono.Cecil solution to the Spring.NET Jira-606

WORK IN PROGRESS

Finding the place for the cut.

Current stack of execution for the type's custom attribute copy is (from the bottom up):

Spring.Core.dll!Spring.Util.ReflectionUtils.CreateCustomAttribute(System.Type type = {Name = "CustomTestAttribute" FullName = "Spring.Wcf.Services.WcfServiceProxyFactoryTests+CustomTestAttribute"}, object[] ctorArgs = {Dimensions:[0]}, System.Attribute sourceAttribute = {Spring.Wcf.Services.WcfServiceProxyFactoryTests.CustomTestAttribute}) Line 688
Spring.Core.dll!Spring.Util.ReflectionUtils.CreateCustomAttribute(System.Type type = {Name = "CustomTestAttribute" FullName = "Spring.Wcf.Services.WcfServiceProxyFactoryTests+CustomTestAttribute"}, System.Attribute sourceAttribute = {Spring.Wcf.Services.WcfServiceProxyFactoryTests.CustomTestAttribute}) Line 772
Spring.Core.dll!Spring.Util.ReflectionUtils.CreateCustomAttribute(System.Attribute sourceAttribute = {Spring.Wcf.Services.WcfServiceProxyFactoryTests.CustomTestAttribute}) Line 788
Spring.Core.dll!Spring.Proxy.AbstractProxyTypeBuilder.ApplyTypeAttributes(System.Reflection.Emit.TypeBuilder typeBuilder = {Name = "CompositionAopProxy_6a4ecf7bdbd8440396704c96dd555e9e" FullName = "CompositionAopProxy_6a4ecf7bdbd8440396704c96dd555e9e"}, System.Type targetType = {Name = "WcfServiceImpl" FullName = "Spring.Wcf.Services.WcfServiceProxyFactoryTests+WcfServiceImpl"}) Line 238
Spring.Aop.dll!Spring.Aop.Framework.DynamicProxy.CompositionAopProxyTypeBuilder.BuildProxyType() Line 84
Spring.Aop.dll!Spring.Aop.Framework.DynamicProxy.CachedAopProxyFactory.BuildProxyType(Spring.Proxy.IProxyTypeBuilder typeBuilder = {Spring.Aop.Framework.DynamicProxy.CompositionAopProxyTypeBuilder}) Line 79

Spring.Aop.dll!Spring.Aop.Framework.DynamicProxy.DefaultAopProxyFactory.CreateAopProxy(Spring.Aop.Framework.AdvisedSupport advisedSupport = {Spring.Aop.Framework.ProxyFactory:

1 interfaces=[[Spring.Wcf.Services.WcfServiceProxyFactoryTests+IWcfService] -> target[Spring.Wcf.Services.WcfServiceProxyFactoryTests+WcfServiceImpl]];

1 pointcuts=[DefaultPointcutAdvisor: pointcut=[TruePointcut.TRUE] advice=[Spring.Aop.Interceptor.NopInterceptor]];

targetSource=[Singleton target source (not dynamic): target=[Spring.Wcf.Services.WcfServiceProxyFactoryTests+WcfServiceImpl]];

advisorChainFactory=Spring.Aop.Framework.HashtableCachingAdvisorChainFactory;

proxyTargetType=False; proxyTargetAttributes=True; exposeProxy=False; isFrozen=False; optimize=False; aopProxyFactory=Spring.Aop.Framework.DynamicProxy.CachedAopProxyFactory; }) Line 91

Spring.Aop.dll!Spring.Aop.Framework.AdvisedSupport.CreateAopProxy() Line 1391
Spring.Aop.dll!Spring.Aop.Framework.ProxyFactory.GetProxy() Line 92
Spring.Wcf.Tests.exe!Spring.Wcf.Services.WcfServiceProxyFactoryTests.TestWcfBasicHttpBindingWithAop() Line 101
Spring.Wcf.Tests.exe!Spring.Program.Main(string[] args = {Dimensions:[0]}) Line 15

Walking the stack of the test execution brings us to the ApplyTypeAttributes method of \Spring.Core\Proxy\AbstractProxyTypeBuilder.cs. Its signature is equivalent to the signature of the method created during the proof of concept work:

CopyTypeAttributes(Type source, TypeBuilder target)

With parameters named in quite an opposite way but meaning the same as those in ApplyTypeAttributes.
The idea was to have a less granular API than the current of the ReflectionUtils, with few reasons behind it.

ApplyTypeAttributes signature and body:

protected virtual void ApplyTypeAttributes(TypeBuilder typeBuilder, Type targetType)
        {
            foreach (object attr in GetTypeAttributes(targetType))
            {
                if (attr is CustomAttributeBuilder)
                {
                    typeBuilder.SetCustomAttribute((CustomAttributeBuilder)attr);
                }
                else if (attr is Attribute)
                {
                    typeBuilder.SetCustomAttribute(
                        ReflectionUtils.CreateCustomAttribute((Attribute) attr));
                }
            }
        }

lends itself to the natural application of a Mono.Cecil proof of concept method created.

Sequence of changes.

  • Creating ReflectionUtils2 class side by side with a ReflectionUtils.
  • Changing the signature of the method to be

CopyTypeAttributes(TypeBuilder typeBuilder, Type targetType)

        So it just matches fully the current convention of the ApplyTypeAttributes method.

  • Adding Mono.Cecil.dll into the C:\DEV\OpenSource\Spring.Net\lib\Net\2.0 folder and creating the reference to it from the Spring.Core project.

Pitfalls.

  • Nested types.

Nested types FullName notation is as: Spring.Wcf.Services.WcfServiceProxyFactoryTests+WcfServiceImpl
Mono.Cecil notation for the same is:
Spring.Wcf.Services.WcfServiceProxyFactoryTests/WcfServiceImpl

For nested types which refer to the nested attributes the Mono.Cecil scope is different than for the regular classes (and namespace value is empty). That is to be communicated with the Mono.Cecil author if he is interested, but workaround is very simple:

if (typeReference.Scope is Mono.Cecil.ModuleReference)
{
    return typeReference.Module.Assembly.Name.ToString();
}
if (typeReference.Scope is Mono.Cecil.AssemblyNameReference)
{
    return typeReference.Scope.ToString();
}
// TODO: Use resource string, but Spring.NET is not using resources... ask Mark/Bruno (SD)
throw new NotImplementedException("GetAssemblyFullName method is not implemented " +
    " to work for the {0} type of scope. Only supported scopes are " +
    "Mono.Cecil.ModuleReference, Mono.Cecil.AssemblyNameReference");

  • System and GAC'ed types

I really expected an issue to happen when copying attributes from the system or GAC'ed types, but there was no problem with that as we fed to Mono.Cecil the location of system or GAC'ed assemblies as:

System.Type - C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
System.Web.Services.WebService - C:\WINDOWS\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.
Web.Services.dll
  • Security

Though as follows from the above note on GAC'ed and System types there will be security implications for access rights to read those dlls. Normally the service account would have those rights (as those in the Worker Process group) but still, in case when it is impersonated account that is coming and we read assembly in this context it may cause a problem then.
Though the same constraints and conditions apply as in case of ASP.NET apps (or any) for example.

  • Performance

It takes quite a while to Mono.Cecil to read through the System.Web.Services.dll assembly (less then 1 minute but close to it). Mono.Cecil.AssemblyFactory.GetAssembly method parses all of the types inside the assembly. Lets see if there is any way how to limit it only to reading the metadata for type we are interested into...
And I'm quite sorry to Cecil! It turns out that I had tracepoints all over the place onto Cecil's code and that caused quite a delay when it ran. I tried to profile it (no debugger then) and it was just instant, I removed the tracepoints and again it is just instant on the mscorlib even. Me bad! Though as now I can get into the milliseconds copy attributes for System.Type, it shows that there is a problem for the ComDefaultInterface(Type) to be copied.

  • Compiler resolved values

We do use text editor when we create the code, which means that we are pretty limited into what we can put into our custom attributes constructor, as it should be pretty static content. There is a twist though, as compiler can still do some static resolutions!
What happens here is that for the following definition of the Type attributes, the ComDefaultInterfaceAttribute is applied with typeof resolved during the compile time.

I believe that it is the only compiler resolvable entity right now in .NET. It means that it is still static, though question is what are metadata available to us to bring it back to life as Type. Lets step back a bit and add the scenario to the tests!

Ok, added, and as one could expect it is the fully qualified type name, yupiee anyway :).

if (!attribute.Resolved) attribute.Resolve();

To be continued tomorrow....

Tuesday, September 18, 2007

Copying custom attributes with CustomAttributeData

The story of Spring.NET solution for copying of custom attributes from the original class to the proxy continues with a new member of a .NET2.0 family - System.Reflection.CustomAttributeData http://msdn2.microsoft.com/en-us/library/system.reflection.customattributedata.aspx

Mark Pollack re-pointed me into this direction a day ago. Truly I tried to execute CustomAttributeData.GetCustomAttributes from the debugger line before trying the Mono.Cecil approach few weeks ago, but it threw exception to me and I happily progressed to Mono.Cecil without caring about it.

Mark is absolutely right though that solution by means of only .NET framework would be the best one.
Lets take another look onto the class and how it can be useful in our case.

Applying the code from the msdn sample to the test class:

[CustomTest(100, -100, ReadWriteProperty = "Test of a read write property")]
[ServiceBehavior(
    Name = "WcfServiceWithServiceBehavior",
    ConfigurationName = "WcfService",
    Namespace = "http://spring.net/wcf.tests/2006")]
[WebService(
    Namespace="http://springframework.net/webservices/" ,
    Name = "WcfAndWebService"
    )]
public class WcfAndWebService : WebService, IWcfService
{

  Brings the following result: 

[System.Web.Services.WebServiceAttribute(Namespace = "http://springframework.net/webservices/", Name = "WcfAndWebService")]
   Constructor: Void .ctor()
   Constructor arguments:
   Named arguments:
      MemberInfo: System.String Namespace
      Type: System.String Value:
http://springframework.net/webservices/
      MemberInfo: System.String Name
      Type: System.String Value: WcfAndWebService
[System.ServiceModel.ServiceBehaviorAttribute(Name = "WcfServiceWithServiceBehavior", Namespace = "
http://spring.net/wcf.tests/2006", ConfigurationName = "WcfService")]
   Constructor: Void .ctor()
   Constructor arguments:
   Named arguments:
      MemberInfo: System.String Name
      Type: System.String Value: WcfServiceWithServiceBehavior
      MemberInfo: System.String Namespace
      Type: System.String Value:
http://spring.net/wcf.tests/2006
      MemberInfo: System.String ConfigurationName
      Type: System.String Value: WcfService
[Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute((Int32)100, (Int32)-100, ReadWriteProperty = "Test of a read write property")]
   Constructor: Void .ctor(Int32, Int32)
   Constructor arguments:
      Type: System.Int32 Value: 100
      Type: System.Int32 Value: -100
   Named arguments:
      MemberInfo: System.String ReadWriteProperty
      Type: System.String Value: Test of a read write property

Test class is not picked up randomly. The fact that test runs proves that issue of CustomAttributeData with WebService attribute http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=161522 really seems to be fixed (though still a mystery, how it has been applied? Would not a guy with a clean .NET 2.0 redistributable face this problem?)
I created a post on msdn forum thread dedicated to this issue http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=542365&SiteID=1. Lets see if there is going to be a response.

UPDATE!: Just after an hour, there is a response and Peter Ritchie says:
"Yes, there was a security update that was released recently that had some various other fixes. If you've downloaded and installed .NET 3.5 Beta 2, or Visual Studio 2008 Beta 2; you've also installed .NET 2.0 Service Pack 1 beta."
This explains why I had an exception 6 weeks ago but not now!
It also means that if your system is running on clean .NET 2.0 install you will still have this exception unless you install .NET 2.0 Service Pack 1 beta (on your production system?!)


Here is the list of all other issues logged for this class on the vs feedback site:
https://connect.microsoft.com/VisualStudio/feedback/SearchResults.aspx?SearchQuery=CustomAttributeData

CustomAttributeData.GetCustomAttributes throws exception when type has a WebService attribute
Opened By  GaboG 
ID  161522
Status  Closed
Resolution  Fixed
Opened  7/11/2006
Closed  10/16/2006

CustomAttributeData throws when attribute has a public Enum property
Opened By  Fabian Schmied 
ID  296032
Status  Active
Opened  8/31/2007

CustomAttributeData does not have a GetCustomAttributes overload for type
Opened By  RichardGrimes 
ID  98478
Status  Closed
Resolution  By Design

CustomAttributeData for SecurityPermission Constructor does not contain arguments that match it's signature
--------------------------------------------------------------------------------
When I retrieve CustomAttributeData for a SecurityAttribute, the arguments are missing and don't match the signature of the constructor for the SecurityAttribute.
--------------------------------------------------------------------------------
Opened By  nywarrior 
ID  94803
Status  Closed
Resolution  Not Reproducible

Only issue #2 is still marked as active and I was able to reproduce it. This issue is caused by the fact that System.Enum type returns false for its IsEnum method and IsValueType is false as well :):).

I can see the design where using of the Enum type field for the attribute can be pretty alright. [CommonAttribute(MyEnum.MyTypeId)] where CommonAttribute is located in the common library and developer uses her library enum member.

Wrapping it up for a moment here, enough blah for the CustomAttributeData, hopefully enough material for Mark to review the applicability for Spring.NET 1.1.

Monday, August 6, 2007

Spring.NET - Introspection vs. Reflection. Use of Mono.Cecil library.

Thanks to Bruno Baia and Mark Pollack for pointing me to the Mono.Cecil introspection library. The focus of the previous post on this subject were limitations of System.Reflection library in relation to copying custom attributes from the original type to the target type.

High level inspection of Mono.Cecil showed that library looks very promising for resolving the custom attributes issue and far beyond this.

I only targeted some proof of concept for this time, and code to follow can be pretty naive at some places and only counts now with copying of type attributes from one type to another (not including methods, properties, parameters' attributes). Though it should be pretty straight forward to evolve to the fully fledged solution.

Proof of concept code:

Helper method signature is

void CopyAttributes(Type source, TypeBuilder target)

First, I tried to follow the current ReflectionUtils signature for this which would look like:

public static CustomAttributeBuilder CreateCustomAttribute(
            Type type, object[] ctorArgs, Attribute sourceAttribute)

Though I ran quite soon into the necessity to find the attribute passed in this method call via Cecil (which leads to the question of attributes equality). Realizing that that would take quite an effort to resolve, may still be error prone and there is no any real value in being this granular, I decided to go with the high-level signature presented above.  I can imagine some interceptor to be passed in as a parameter to influence the attributes copy process.

Find the TypeDefinition of the source type from which we want to copy attributes.

Mono.Cecil.TypeDefinition matchedType = GetTypeMatchFromAssembly(source, Mono.Cecil.AssemblyFactory.GetAssembly(source.Assembly.Location));
GetTypeMatchFromAssembly method simply iterates through the assembly and finds a type based onto the FullName match which for the given assembly should be unique.

Iterate through the collection of the type's custom attributes.

foreach (Mono.Cecil.CustomAttribute attribute in matchedType.CustomAttributes)

Create constructor parameter types and values arrays.

    object[] parameterValues = new object[attribute.Constructor.Parameters.Count];
    Type[] parameterTypes = new Type[attribute.Constructor.Parameters.Count];

    for (int i = 0; i < attribute.Constructor.Parameters.Count; i++)
    {
        parameterTypes[i] =
            Type.GetType(attribute.Constructor.Parameters[i].ParameterType.FullName);
        parameterValues[i] = attribute.ConstructorParameters[i];
    }

The abilities given by Cecil in this area are of great use for our task. If we compare with current workarounds present in Spring:

public static Type[] GetTypes(object[] args)
{
   ....
   paramsType[i] = (arg != null) ? args[i].GetType() : typeof(object);
  

This above line of code from ReflectionUtils is definitely a big workaround which may pick the wrong ctor actually. Though, Spring.NET is not utilizing this code path I believe, as array of objects would be always empty, due to other workarounds.

Create ConstructorInfo and set the custom attribute on a typeBuilder.

ConstructorInfo constructor = Type.GetType(
    attribute.Constructor.DeclaringType.FullName + "," +
    attribute.Constructor.DeclaringType.Scope, true).GetConstructor(
    parameterTypes);

target.SetCustomAttribute(new CustomAttributeBuilder(
    constructor, parameterValues));

The above code is absolutely precise about the constructor it is creating based onto parameter types and values. Which again is not achievable by means of pure Reflection in the current Spring.NET implementation.

Unit test output

In the unit test a type of TargetType is created, its typeBuilder is passed to the proof of concept method along with a source type.

TypeBuilder typeBuilder = CreateTestTargetTypeBuilder();

Type sourceType = typeof(TypeWithTestAttribute);
Type targetType = typeBuilder.CreateType();

Console.WriteLine(DumpMemberAttributes(sourceType));
Console.WriteLine(DumpMemberAttributes(targetType));

ReflectionUtils2.CopyAttributes(sourceType, typeBuilder);

targetType = typeBuilder.CreateType();

Console.WriteLine("*Target Type after copying attributes:");
Console.WriteLine(DumpMemberAttributes(targetType));

Which produces the following output:

*Dump of the custom attributes for member: Dsi.Mono.Cecil.TestTypes.B.TypeWithTestAttribute(TypeInfo)
**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute

Properties:
    FirstGetterOnlyPropertyValue:99
    SecondGetterOnlyPropertyValue:-99
    ReadWriteProperty:ReadWriteProperty 2 set via class attribute ctor
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:
**Attribute of type System.Runtime.InteropServices.GuidAttribute
Properties:
    Value:263E3E90-9D06-4660-AD67-28D1BA5E0107
    TypeId:System.Runtime.InteropServices.GuidAttribute
Fields:
**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Properties:
    ReadWriteProperty:ReadWriteProperty 2 set via class attribute ctor
    FirstGetterOnlyPropertyValue:99
    SecondGetterOnlyPropertyValue:-99
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:
**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Properties:
    ReadWriteProperty:ReadWriteProperty 1 set via class attribute ctor
    FirstGetterOnlyPropertyValue:100
    SecondGetterOnlyPropertyValue:-100
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:
**Attribute of type System.SerializableAttribute
Properties:
    TypeId:System.SerializableAttribute
Fields:
*Dump of the custom attributes for member: TargetType(TypeInfo)
No Attributes present!

*Target Type after copying attributes:
*Dump of the custom attributes for member: TargetType(TypeInfo)

**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Properties:
    ReadWriteProperty:null
    FirstGetterOnlyPropertyValue:99
    SecondGetterOnlyPropertyValue:-99
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:
**Attribute of type System.Runtime.InteropServices.GuidAttribute
Properties:
    Value:263E3E90-9D06-4660-AD67-28D1BA5E0107
    TypeId:System.Runtime.InteropServices.GuidAttribute
Fields:
**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Properties:
    ReadWriteProperty:null
    FirstGetterOnlyPropertyValue:99
    SecondGetterOnlyPropertyValue:-99
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:
**Attribute of type Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Properties:
    ReadWriteProperty:null
    FirstGetterOnlyPropertyValue:100
    SecondGetterOnlyPropertyValue:-100
    TypeId:Dsi.Mono.Cecil.TestTypes.A.CustomTestAttribute
Fields:

Conclusion.

It seems that introspection and Mono.Cecil library would provide quite a benefit to Spring.NET if used. Areas of use exceed broadly the issue resolved by this proof of concept. As well as I believe one can expect much better performance in many areas from applying introspection as opposed to a Reflection.

For completeness, providing the test types used.

 

Test classes - custom attribute and class it is applied to.

using System;
using System.Collections.Generic;
using System.Text;

namespace Dsi.Mono.Cecil.TestTypes.A
{
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class CustomTestAttribute : Attribute
    {
        #region Fields
        private int firstGetterOnlyPropertyValue;
        private int secondGetterOnlyPropertyValue;
        private string readWriteProperty;
        #endregion

        #region Properties
        public int FirstGetterOnlyPropertyValue
        {
            get { return firstGetterOnlyPropertyValue; }
        }
        public int SecondGetterOnlyPropertyValue
        {
            get { return secondGetterOnlyPropertyValue; }
        }
        public string ReadWriteProperty
        {
            get { return readWriteProperty; }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("ReadWriteProperty",
                        "Value can not be null!");
                }
                readWriteProperty = value;
            }
        }
        #endregion

        #region Constructors
        public CustomTestAttribute(int firstGetterOnlyProperty) : base()
        {
            this.firstGetterOnlyPropertyValue = firstGetterOnlyProperty;
        }
        public CustomTestAttribute(int firstGetterOnlyProperty, int secondGetterOnlyPropertyValue)
            : this(firstGetterOnlyProperty)
        {
            this.secondGetterOnlyPropertyValue = secondGetterOnlyPropertyValue;
        }
        public CustomTestAttribute(int firstGetterOnlyProperty, int secondGetterOnlyPropertyValue,
            string readWriteProperty)
            : this(firstGetterOnlyProperty, secondGetterOnlyPropertyValue)
        {
            this.readWriteProperty = readWriteProperty;

        }
        #endregion
    }
}
namespace Dsi.Mono.Cecil.TestTypes.B { [CustomTestAttribute(100, -100, ReadWriteProperty = "ReadWriteProperty 1 set via class attribute ctor")] [CustomTestAttribute(99, -99, ReadWriteProperty = "ReadWriteProperty 2 set via class attribute ctor")] [CustomTestAttribute(99, -99, ReadWriteProperty = "ReadWriteProperty 2 set via class attribute ctor")] [SerializableAttribute()] [GuidAttribute("263E3E90-9D06-4660-AD67-28D1BA5E0107")] public class TypeWithTestAttribute {} }

Sunday, July 15, 2007

Introspection vs. Reflection for Spring.NET

Why "versus"?

It can be hard to explain what the difference between the two is, so I'll quote the veteran of the windows programming and debugging - John Robbins:

When I first started looking at rule development, I couldn't quite get my head around what the Introspection engine was doing. After a while, it finally dawned on me that the way to think about it was that Introspection is just manual reflection. Whereas reflection loads up the assembly and calls the types and other information in the assembly, the Introspection engine maps the assembly into memory and goes through the grind of walking all the internal tables by hand. Interestingly, if you start looking hard at the Introspection engine with the Reflector tool, you'll see that through Introspection, it also supports creating code, much like the Reflection.Emit namespace.

What is the problem for Spring.NET?

Currently, Spring.NET is using reflection and that is probably the only option at the moment that is coming for "free" with no further license implications.

Except for speed and locking, when reflection is falling short compared to the introspection?

Reflection is not providing for restoration of all of the constructs you may use in your code.


For example for custom attribute definition like:

    public class TestAttribute : Attribute
    {
        private int firstGetterOnlyPropertyValue;
        private int secondGetterOnlyPropertyValue;
        private string readWriteProperty;

        public TestAttribute(int firstGetterOnlyProperty)
        public TestAttribute(int firstGetterOnlyProperty, int secondGetterOnlyPropertyValue)
        public int FirstGetterOnlyProperty
        public int SecondGetterOnlyProperty
        public string ReadWriteProperty
    }

Imagine that we want to create a copy of this attribute from the original type to put it in a proxy. Thanks to reflection we know all the constructors the type has got, but we don't know which constructor was used to create this attribute actually. We can't just assign all properties after the creation of an attribute with a default constructor, because:

1. Property may be read only.

2. Property value from the original type set by default may not be correctly assignable to the target type (e.g. ConfigurationName of the ServiceBehaviorAttribute is null by default, but you can't set it to null via property assignment)

We may speculate that we can deduce the constructor from types and their order (not in our test case, both int, "first, second" in the names can be misleading), which can be very error-prone.

Solution beer bash*.

Probably ideal solution would be able to read the PE (Portable Executable) and tell us exactly the nuances of how attribute was applied to the member.

As I have not tried introspection by myself the following section is more about making assumptions based onto John Robbin's "Debugging .NET 2.0 Applications" book, msdn and Reflector.

Use FxCop introspection libraries to fill the gap.

FxCop library Api seems to be very focused onto the "rules" concept only, though most importantly it traverses all of the modules and members giving us an opportunity to inspect them.

Microsoft.Cci library has AttributeNode with the following type information:

public class AttributeNode : Node
{
    // Fields
    private bool allowMultiple;
    public Expression Constructor;
    public static readonly AttributeNode DoesNotExist;
    public ExpressionList Expressions;
    private bool inherited;
    public bool IsPseudoAttribute;
    public AttributeTargets Target;
    private TypeNode type;
    private AttributeNode usageAttribute;
    private AttributeTargets validOn;

    // Methods
    static AttributeNode();
    public AttributeNode();
    public AttributeNode(Expression constructor, ExpressionList expressions);
    public AttributeNode(Expression constructor, ExpressionList expressions, AttributeTargets target);
    private Attribute ConstructAttribute(InstanceInitializer constr, object[] argumentValues);
    protected Array GetCoercedArrayLiteral(ArrayType arrayType, Array arrayValue);
    protected object GetCoercedLiteralValue(TypeNode type, object value);
    public Expression GetNamedArgument(Identifier name);
    public Expression GetPositionalArgument(int n);
    public virtual Attribute GetRuntimeAttribute();
    private void GetUsageInformation();
    private void SetAttributeProperty(Property prop, Attribute attr, object val);

    // Properties
    public virtual bool AllowMultiple { get; set; }
    public virtual bool Inherited { get; set; }
    public virtual TypeNode Type { get; set; }
    public virtual AttributeTargets ValidOn { get; set; }
}

 

Where constructor of type Expression is available as a public field as well as there is an interesting method ConstructAttribute returning directly the attribute instance.
I'd speculate that Expression for the constructor would contain stuff required to instantiate the attribute exactly in the way that it is declared on a member..

That's it for the FxCop for now. I'm not going to go into more details..

Anything else (suitable for OSS**) out there to parse PEs?

Crawling through the web gave only following:

http://www.plas.fit.qut.edu.au/perwapi/

I'll take a look into this option for the next blog entry.

References and additional info:

Spring.NET jira issue as an entry point to forum discussions:
http://opensource.atlassian.com/projects/spring/browse/SPRNET-606
Interesting: object initializers in C# 3.0: http://blogs.msdn.com/wriju/archive/2007/04/12/c-3-0-enhancements-object-initializers.aspx

* beer bash = Irish for brain storming :).
**OSS - Open Source Software