Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How return the type of a System.__COMObject in System.Type in C#

I'm doing a program and I want to do a Reflection, but for this, I need an Object of the Type class, right? to use the .GetProperties() method... So I tryed this:

Type typeName = simObjects.getType();

But the .GetType() is returning "System.__COMObject". And this is not helpfull. The same happens with .typeof(). I search and found another code, this one:

Type typeName = (Type)Microsoft.VisualBasic.Information.TypeName(simObjects);

But this method return a String, and I need it in System.Type, Can any genious please help me?

like image 676
Jovita Avatar asked Sep 10 '14 18:09

Jovita


2 Answers

I did not use reflection as I wished, but it is working pretty fine.

foreach(PropertyDescriptor descrip in TypeDescriptor.GetProperties(COMObject))
{
    if(descrip.Name == "Attribute Name")
    {
        foreach(PropertyDescriptor descrip2 in TypeDescriptor.GetProperties(descrip))
        {
           if(descrip2.Name == "sub attribute Name")
           {
           }
        } 
    }
}

This code returns the name of the attributes, for example, imagine that my COMObject has this attributes:

int age;
string name;
Son Phill;

and Son has:

int age;
string name;

In the first loop, the descrip.Name will be "age", "name" and "Phill", and in the second (suppose that the condition returns true for "Son"), "age" and "name".

like image 114
Jovita Avatar answered Sep 24 '22 17:09

Jovita


See this link on how to get the type:

http://support.microsoft.com/kb/320523

See this SO answer regarding COM objects and reflection:

https://stackoverflow.com/a/10617479/4004002

Also, do you know what the properties are ahead of time? If so you may (I've never tried it with a COM object) be able to use Dynamics instead to access the properties.

dynamic d = simObjects;
string myVariable = d.SomeProperty;

EDIT: This link explains using dynamics and COM

http://msdn.microsoft.com/en-us/magazine/ff714583.aspx

In case it disappears:

public static class WordDocument
{
    public const String TemplateName = @"Sample.dotx";
    public const String CurrentDateBookmark = "CurrentDate";
    public const String SignatureBookmark = "Signature";

    public static void Create(string file, DateTime now, String author)
    {
         // Run Word and make it visible for demo purposes
         dynamic wordApp = new Application { Visible = true };

        // Create a new document
        var doc = wordApp.Documents.Add(TemplateName);
        templatedDocument.Activate();

        // Fill the bookmarks in the document
        doc.Bookmarks[CurrentDateBookmark].Range.Select();
        wordApp.Selection.TypeText(current.ToString());
        doc.Bookmarks[SignatureBookmark].Range.Select();
        wordApp.Selection.TypeText(author);
like image 26
DVK Avatar answered Sep 24 '22 17:09

DVK