2

See the following code. The test passed when using AutoMapper, but failed when using ValueInjecter:

using NetFwTypeLib;

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        INetFwRules fwRules = policy.Rules;
        Rule rule = new Rule();

        foreach (INetFwRule fwRule in fwRules)
        {
            if (fwRule.Name == "HomeGroup Out")
            {
                //AutoMapper.Mapper.CreateMap<INetFwRule, Rule>();
                //AutoMapper.Mapper.Map(fwRule, rule);
                rule.InjectFrom(fwRule);
                break;
            }
        }
        Assert.IsTrue(rule.Name == "HomeGroup Out");
    }
}

public class Rule
{
    public string Name { get; set; }
}

Any ideas? Thanks.

Edit:

Based on Omu's answer, it seems the problem is related to COM objects, not only FirewallAPI.dll classes. So I changed title from "Can't get ValueInjecter to map FirewallAPI.dll classes" to "Can't get ValueInjecter to map COM objects".

Omu
  • 69,856
  • 92
  • 277
  • 407

1 Answers1

0

it doesn't work because doing:

fwRule.GetType().GetProperties().Count()// is 0 

or doing the same using PropertyDescriptor also return zero, it's like the object doesn't has properties

the solution is to write an injection that will take the type from where to get the properties:

public class Same<T> : ValueInjection
{
   protected override void Inject(object source, object target)
   {
       var props = typeof (T).GetInfos().ToArray();
       var tp = target.GetInfos().ToArray();
       for (var i = 0; i < props.Count(); i++)
       {
          var prop = props[i];
          for (var j = 0; j < tp.Count(); j++)
          {
            if(prop.Name == tp[j].Name && prop.PropertyType == tp[j].PropertyType)
            tp[j].SetValue(target,prop.GetValue(source, null),null);
          }
        }
      }
  }

and the usage:

rule.InjectFrom<Same<INetFwRule>>(fwRule);

this is the same as the default InjectFrom() but it reads the target properties from the supplied Type

Omu
  • 69,856
  • 92
  • 277
  • 407
  • So it seems the problem is ValueInjector can't get the real type of `fwRule`. `fwRule` is a COM object. Using `GetType()` returns `System.__ComObject`. AutoMapper works fine with COM objects because I can tell it the real type through `Mapper.CreateMap()`. Any workaround for ValueInjector? Thanks. –  Mar 21 '11 at 18:35