Ejemplo n.º 1
0
        private void AddType()
        {
            if (this.assemblyBrowser.SelectedNode is TypeNode)
            {
                TypeNode typeNode = (TypeNode)this.assemblyBrowser.SelectedNode;

                // NOTE: Allow multiple instances of the same type (this is probably common)
                //if (!this.typeDocuments.ContainsKey (typeNode.Type))
                //{
                WrappedType wrappedType = new WrappedType(typeNode.Type);

                WrappingOptions wrappingOptions = new WrappingOptions(wrappedType);
                wrappingOptions.MethodsListViewSelectedIndexChanged    += this.OnListViewSelectedIndexChanged;
                wrappingOptions.PropertiesListViewSelectedIndexChanged += this.OnListViewSelectedIndexChanged;
                wrappingOptions.EventsListViewSelectedIndexChanged     += this.OnListViewSelectedIndexChanged;

                WrappedTypeDocument document = new WrappedTypeDocument(wrappingOptions);
                document.SuspendLayout();

                document.Guid         = new Guid("A694E86E-73C0-417e-B85D-A04361C3CDC4");
                document.SizeChanged += this.OnDockControlSizeChanged;

                document.PerformLayout();

                this.documentContainer.AddDocument(document);

                //this.typeDocuments[typeNode.Type] = document;
                //}

                //this.typeDocuments[typeNode.Type].Activate ();

                document.Activate();
            }
        }
Ejemplo n.º 2
0
        public WrappingOptions(WrappedType wrappedType)
        {
            InitializeComponent();
            InitializeWrapper();

            this.wrappedType = wrappedType;

            Tuple[] acquisitionModes =
            {
                new Tuple(Acquisition.Construct,   "Construct an instance of the wrapped type"),
                new Tuple(Acquisition.Parameter,   "Pass an instance of the wrapped type as a parameter"),
                new Tuple(Acquisition.Property,    "Set an instance of the wrapped type as a property"),
                new Tuple(Acquisition.UserManaged, "Allow user to control instance management of the wrapped type")
            };

            this.acquisitionComboBox.ValueMember   = "Value1";
            this.acquisitionComboBox.DisplayMember = "Values";
            this.acquisitionComboBox.Items.AddRange(acquisitionModes);
            this.acquisitionComboBox.SelectedIndex = 0;

            this.defaultFieldName      = wrappedType.FieldName;
            this.fieldNameTextBox.Text = this.defaultFieldName;

            // Methods
            MethodInfo[] methods = wrappedType.Type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            Array.Sort <MethodInfo> (methods, this.MethodNameComparison);
            foreach (MethodInfo method in methods)
            {
                if (!method.Name.ToLower().StartsWith("get_") && !method.Name.ToLower().StartsWith("set_") &&
                    !method.Name.ToLower().StartsWith("add_") && !method.Name.ToLower().StartsWith("remove_"))
                {
                    MethodListViewItem listViewItem = new MethodListViewItem(method);
                    listViewItem.ImageIndex = (int)WrappingOptions.ImageIndices.Method;
                    this.methodsListView.Items.Add(listViewItem);
                }
            }

            // Properties
            PropertyInfo[] properties = wrappedType.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            Array.Sort <PropertyInfo> (properties, this.PropertyNameComparison);
            foreach (PropertyInfo property in properties)
            {
                PropertyListViewItem listViewItem = new PropertyListViewItem(property);
                listViewItem.ImageIndex = (int)WrappingOptions.ImageIndices.Property;
                this.propertiesListView.Items.Add(listViewItem);
            }

            // Events
            EventInfo[] events = wrappedType.Type.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            Array.Sort <EventInfo> (events, this.EventNameComparison);
            foreach (EventInfo _event in events)
            {
                EventListViewItem listViewItem = new EventListViewItem(_event);
                listViewItem.ImageIndex = (int)WrappingOptions.ImageIndices.Event;
                this.eventsListView.Items.Add(listViewItem);
            }
        }
Ejemplo n.º 3
0
 private void Set(string name, object value)
 {
     if (Wrapped != null)
     {
         PropertyInfo property = WrappedType.GetProperty(name);
         if (property != null && property.CanWrite)
         {
             property.SetValue(Wrapped, value, null);
         }
     }
 }
Ejemplo n.º 4
0
            public void DictionaryToObject()
            {
                var entity      = Entity.New(typeof(Data.InputObject));
                var wrappedType = new WrappedType(entity);

                var obj = wrappedType.FromDictionary(new Dictionary <string, object>
                {
                    { "b", 123 },
                });

                obj.ShouldNotBeNull();
            }
        private void GeneratePartialClassHeader(StringBuilder sb, bool isUserFile)
        {
            sb.AppendLine("// Generated class v" + this.htmlUnitVersion
                          + (isUserFile ? ", can be modified" : ", don't modify"));
            sb.AppendLine();
            if (!isUserFile)
            {
                sb.AppendLine("using System;");
                sb.AppendLine("using System.Collections.Generic;");
                sb.AppendLine("using System.Collections.Specialized;");
                sb.AppendLine("using System.Linq;");
                sb.AppendLine("using System.Text;");
                sb.AppendLine();
            }
            sb.Append("namespace ");
            sb.AppendLine(TargetNamespace);
            sb.AppendLine("{");

            var interfaceList = new StringBuilder();

            if (isUserFile)
            {
                sb.AppendLine("   public partial class " + TargetNameWithoutNamespace);
            }
            else
            {
                IEnumerable <Type> wrappedInterfaces = WrappedType
                                                       .GetInterfaces()
                                                       .Where(i => Repository.TypeIsWrapped(i));

                foreach (var wrappedInterface in wrappedInterfaces)
                {
                    interfaceList.AppendFormat(", {0}", Repository.GetTargetFullName(wrappedInterface));
                    Repository.MarkUsageOfType(wrappedInterface);
                }

                if (WrappedBase != null && Repository.TypeIsWrapped(WrappedBase))
                {
                    Repository.MarkUsageOfType(WrappedBase);
                }

                sb.AppendFormat(
                    "   public partial class {0} : {1}{2}\r\n",
                    TargetNameWithoutNamespace,
                    TargetBaseName,
                    interfaceList
                    );
            }

            sb.AppendLine("   {");
        }
Ejemplo n.º 6
0
        private Typewrapper RefCapableWrapper(WrappedType type, Structure s, out bool cached)
        {
            bool firstTime;
            long objectId = idgenerator.GetId(s, out firstTime);

            Debug.LogFormat(
                "Identified object type '{0}' with id {1}, firstTime={2}; in rrefDict={3}", s.KOSName, objectId, firstTime, idMap.ContainsKey(objectId)
                );
            if ((cached = !firstTime))    // Assignment intentional
            {
                idMap[objectId]["ref"] = objectId;
                return(new Typewrapper(WrappedType.Reference, objectId));
            }
            return(idMap[objectId] = new Typewrapper(type));
        }
        /// <summary>
        /// Populates this instance with its class members.
        /// </summary>
        private void PopulateWithClassMembers()
        {
            var eventInfo = WrappedType.GetEvents(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

            Members.AddRange(eventInfo.Select(ei => new ClassMemberViewModel(ei, MemberType.Event)));

            var methodInfo = WrappedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(m => !m.IsSpecialName);

            Members.AddRange(methodInfo.Select(mi => new ClassMemberViewModel(mi, MemberType.Method)));

            var propInfo = WrappedType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

            Members.AddRange(propInfo.Select(pi => new ClassMemberViewModel(pi, MemberType.Property)));

            var ctors = ((TypeInfo)WrappedType).DeclaredConstructors.Cast <ConstructorInfo>();

            Members.AddRange(ctors.Select(ci => new ClassMemberViewModel(ci, MemberType.Constructor)));
        }
Ejemplo n.º 8
0
        private object Get(string name)
        {
            if (Wrapped != null)
            {
                PropertyInfo prop = WrappedType.GetProperty(name);
                if (prop != null)
                {
                    try
                    {
                        return(prop.GetValue(Wrapped, null));
                    }
                    catch// (Exception ex)
                    {
                        return(null);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Sets the value of specified property.
 /// </summary>
 protected void SetProperty(string name, object value)
 {
     WrappedType.InvokeMember(name, BindingFlags.SetProperty, null, WrappedObject, new object[] { value });
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Gets the value of specified property.
 /// </summary>
 protected T GetProperty <T>(string name)
 {
     return((T)WrappedType.InvokeMember(name, BindingFlags.GetProperty, null, WrappedObject, null));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Invokes the method with specified name.
 /// </summary>
 protected object InvokeMethod(string name, params object[] args)
 {
     return(WrappedType.InvokeMember(name, BindingFlags.InvokeMethod, null, WrappedObject, args != null && args.Length == 0 ? null : args));
 }
Ejemplo n.º 12
0
 public Typewrapper(WrappedType type, object data = null) : base()
 {
     this["type"] = type.ToString().ToLowerInvariant();
     this["data"] = data;
 }
        private void ScanMembers(Type type)
        {
            // The special meal of today: find interfaces that is new on this class, and clashes with existing fields!

            var newInterfacesForThisSubclass =
                WrappedType
                .GetInterfaces()
                .Except(WrappedBase != null ? WrappedBase.GetInterfaces() : new Type[] { })
                .Where(i => Repository.TypeIsWrapped(i));

            var existingNames = new HashSet <string>(
                Methods.Values.Select(m => m.TargetMethodInfo.Name));

            var methodsOfNewInterfaces =
                newInterfacesForThisSubclass
                .SelectMany(il => il.GetMethods())
                .Where(m => existingNames.Contains(m.Name))
                .ToArray();

            foreach (var wmiRo in Methods.Values)
            {
                var wmi = wmiRo; // To get correct lambda closure!

                var conflictingMethods = methodsOfNewInterfaces
                                         .Where(m => wmi.TargetMethodInfo.Name == m.Name)
                                         .Where(m => IsMethodSignatureCastable(m, wmi.TargetMethodInfo))
                                         .ToArray();

                foreach (var cm in conflictingMethods)
                {
                    Console.WriteLine("Conflicting method: " + cm);
                }

                if (conflictingMethods.Any())
                {
                    throw new InvalidOperationException();
                }
            }

            // First extract all properties and methods

            IEnumerable <MethodInfo> nonObsoleteMethods = type
                                                          .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                                                          .Where(mi => (!mi.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()))
                                                          .Where(mi => (!mi.Name.Contains("<")))
                                                          // TODO: Support methods with weird names that starts with "<bridge>"
                                                          .Where(mi =>
                                                                 (type.BaseType == null ||
                                                                  type.BaseType.GetMethod(mi.Name,
                                                                                          mi.GetParameters().Select(pi => pi.ParameterType).ToArray())
                                                                  == null));

            foreach (MethodInfo method in nonObsoleteMethods)
            {
                bool wrappedAsProperty = false;

                if (method.Name.Length > 3 && method.IsPublic)
                {
                    if (method.Name.StartsWith("get") &&
                        method.ReturnType != typeof(void) &&
                        method.GetParameters().Length == 0
                        // We can't convert methods to properties that will cause the property to have the same name as the type.
                        && method.Name.Substring(3) != type.Name)
                    {
                        GetWrapperPropInfoFor(Properties, method.Name.Substring(3)).GetterMethod = method;
                        wrappedAsProperty = true;
                    }
                    else if (method.Name.StartsWith("set") &&
                             method.GetParameters().Length == 1 &&
                             method.ReturnType == typeof(void))
                    {
                        GetWrapperPropInfoFor(Properties, method.Name.Substring(3)).SetterMethod = method;
                        wrappedAsProperty = true;
                    }
                }

                if (!wrappedAsProperty)
                {
                    Methods.Add(method.ToString(), new WrapperMethodInfo(this, method));
                }
            }

            if (!type.IsAbstract)
            {
                // Extract constructors
                var nonObsoletePublicConstructors = type
                                                    .GetConstructors()
                                                    .Where(mi => (!mi.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()))
                                                    .Where(mi => mi.DeclaringType == type)
                                                    .Where(mi => !mi.IsAbstract);

                foreach (var constructor in nonObsoletePublicConstructors)
                {
                    Constructors.Add(new WrapperConstructorInfo(this, constructor));
                }
            }

            // Extract public static

            var publicStaticFields = type
                                     .GetFields(BindingFlags.Public | BindingFlags.Static)
                                     .Where(mi => (!mi.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()))
                                     .Where(f => !f.FieldType.IsInterface);

            foreach (var field in publicStaticFields)
            {
                StaticPublicFields.Add(new WrapperStaticPublicField(this, field));
            }
        }
        public void GenerateInterfaceCode(StringBuilder sb)
        {
            // {0} is namespace declarations
            // {1} is namespace of interface
            // {2} is name of interface
            // {3} is to be filled with methods and properties etc..

            var baseInterfaceString = new StringBuilder();

            foreach (var baseInterface in WrappedType.GetInterfaces().Where(i => Repository.TypeIsWrapped(i)))
            {
                Repository.MarkUsageOfType(baseInterface);
                baseInterfaceString.Append(", ");
                baseInterfaceString.Append(Repository.GetTargetFullName(baseInterface));
            }

            const string fileFmt           = @"// Wrapper for {5}
{0}

namespace {1}
{{
   public interface {2} : NHtmlUnit.IObjectWrapper{3}
   {{
{4}
   }}
}}
";
            var          namespaceIncludes =
                @"// Generated class v" + this.htmlUnitVersion + @", don't modify

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

";

            var body = new StringBuilder();

#warning HACK HACK HACK ON
            if (!WrappedType.FullName.StartsWith("org.w3c.dom."))
            {
                foreach (var wpi in Properties.Where(x => x.Value.GetterMethod != null))
                {
                    wpi.Value.GeneratePropertyCode(body);
                }

                foreach (var wm in Methods)
                {
                    wm.Value.GenerateMethodCode(body);
                }
            }

            sb.AppendFormat(fileFmt,
                            namespaceIncludes,
                            TargetNamespace,
                            TargetNameWithoutNamespace,
                            baseInterfaceString,
                            body,
                            WrappedType.FullName);
        }