private static void ShowAttributes(MemberInfo attributeTarget)
        {
            var attributes = attributeTarget.GetCustomAttributes <Attribute>();

            Console.WriteLine("Attributes applied to {0}: {1}",
                              attributeTarget.Name, (attributes.Count() == 0 ? "None" : String.Empty));
            foreach (Attribute attribute in attributes)
            {
                // Вывод типа всех примененных атрибутов
                Console.WriteLine(" {0}", attribute.GetType().ToString());
                if (attribute is DefaultMemberAttribute)
                {
                    Console.WriteLine(" MemberName={0}",
                                      ((DefaultMemberAttribute)attribute).MemberName);
                }
                if (attribute is ConditionalAttribute)
                {
                    Console.WriteLine(" ConditionString={0}",
                                      ((ConditionalAttribute)attribute).ConditionString);
                }
                if (attribute is CLSCompliantAttribute)
                {
                    Console.WriteLine(" IsCompliant={0}",
                                      ((CLSCompliantAttribute)attribute).IsCompliant);
                }
                DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
                if (dda != null)
                {
                    Console.WriteLine(" Value={0}, Name={1}, Target={2}",
                                      dda.Value, dda.Name, dda.Target);
                }
            }
            Console.WriteLine();
        }
Esempio n. 2
0
        private static void ShowAttributes(MemberInfo attrbuteTarget)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(attrbuteTarget);
            Console.WriteLine("attributes applied to {0}:{1}", attrbuteTarget.Name, attributes.Length == 0?"none":String.Empty);
            foreach (var attribute in attributes)
            {
                Console.WriteLine("{0}", attribute.GetType().ToString());
                if (attribute is DefaultMemberAttribute)
                {
                    Console.WriteLine("MemberName = {0}", (attribute as DefaultMemberAttribute).MemberName);
                }

                if (attribute is ConditionalAttribute)
                {
                    Console.WriteLine("ConditionString = {0}", (attribute as ConditionalAttribute).ConditionString);
                }

                if (attribute is CLSCompliantAttribute)
                {
                    Console.WriteLine("IsCompliant = {0}", (attribute as CLSCompliantAttribute).IsCompliant);
                }

                DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
                if (dda != null)
                {
                    Console.WriteLine("Value = {0},Name={1},Target={2}", dda.Value, dda.Name, dda.Target);
                }
            }
            Console.WriteLine();
        }
        public void Name_Set_GetReturnsExpected(string name)
        {
            var attribute = new DebuggerDisplayAttribute("Value")
            {
                Name = name
            };

            Assert.Equal(name, attribute.Name);
        }
        public void Type_Set_GetReturnsExpected(string type)
        {
            var attribute = new DebuggerDisplayAttribute("Value")
            {
                Type = type
            };

            Assert.Equal(type, attribute.Type);
        }
        public void TargetTypeName_Set_GetReturnsExpected(string targetTypeName)
        {
            var attribute = new DebuggerDisplayAttribute("Value")
            {
                TargetTypeName = targetTypeName
            };

            Assert.Equal(targetTypeName, attribute.TargetTypeName);
        }
 public void Ctor_Value(string value)
 {
     var attribute = new DebuggerDisplayAttribute(value);
     Assert.Equal(string.Empty, attribute.Name);
     Assert.Equal(value ?? string.Empty, attribute.Value);
     Assert.Equal(string.Empty, attribute.Type);
     Assert.Null(attribute.Target);
     Assert.Null(attribute.TargetTypeName);
 }
        public void Target_Set_GetReturnsExpected(Type target)
        {
            var attribute = new DebuggerDisplayAttribute("Value")
            {
                Target = target
            };

            Assert.Equal(target, attribute.Target);
            Assert.Equal(target.AssemblyQualifiedName, attribute.TargetTypeName);
        }
        public void DebuggerDisplayAttribute_IsSpecifiedValue()
        {
            // Act
            DebuggerDisplayAttribute attribute = (DebuggerDisplayAttribute)Attribute.GetCustomAttribute(
                typeof(ExceptionContextCatchBlock), typeof(DebuggerDisplayAttribute));

            // Assert
            Assert.NotNull(attribute);
            string value = attribute.Value;

            Assert.Equal("Name: {Name}, IsTopLevel: {IsTopLevel}", value);
        }
        protected void GetDebuggerDisplay <TSut>(TSut sut)
        {
            _sutType = sut.GetType();

            _debuggerDisplay = _sutType.GetTypeInfo().GetCustomAttribute <DebuggerDisplayAttribute>(inherit: false);

            _debuggerDisplayPropertyInfo =
                _sutType.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance);

            _debuggerDisplayGetMethod = _debuggerDisplayPropertyInfo.GetGetMethod(true);

            _debuggerDisplayValue = _debuggerDisplayGetMethod.Invoke(sut, new object[] { });

            DebuggerDisplayText = _debuggerDisplayValue.ToString();
        }
Esempio n. 10
0
        void DebuggerDisplayAttributePropertiesRoundTrip()
        {
            DebuggerDisplayAttribute d = new DebuggerDisplayAttribute("myValue");

            d.Name   = "name";
            d.Target = typeof(AttributeTests);

            Assert.Equal("myValue", d.Value);
            Assert.Equal("name", d.Name);
            Assert.Equal(typeof(AttributeTests), d.Target);
            Assert.Equal(typeof(AttributeTests).AssemblyQualifiedName, d.TargetTypeName);

            d.TargetTypeName = typeof(DebugTests).AssemblyQualifiedName;
            Assert.Equal(typeof(DebugTests).AssemblyQualifiedName, d.TargetTypeName);
        }
Esempio n. 11
0
        /// <summary>
        /// Returns the <see cref="DebuggerDisplayAttribute"/> data of the <see cref="_sut"/>
        /// </summary>
        /// <returns>The <see cref="DebuggerDisplayAttribute"/> data of the <see cref="_sut"/>.</returns>
        protected static string GetDebuggerDisplay()
        {
            Type type = _sut.GetType();

            _debuggerDisplay = type.GetCustomAttribute <DebuggerDisplayAttribute>(inherit: false);

            _debuggerDisplayPropertyInfo =
                type.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance);

            _debuggerDisplayGetMethod = _debuggerDisplayPropertyInfo.GetGetMethod(true);

            _debuggerDisplayValue = _debuggerDisplayGetMethod.Invoke(_sut, new object[] {});

            return(_debuggerDisplayValue.ToString());
        }
Esempio n. 12
0
        void DebuggerDisplayAttributePropertiesRoundTrip()
        {
            DebuggerDisplayAttribute d = new DebuggerDisplayAttribute("myValue");
            d.Name = "name";
            d.Target = typeof(AttributeTests);

            Assert.Equal("myValue", d.Value);
            Assert.Equal("name", d.Name);
            Assert.Equal(typeof(AttributeTests), d.Target);
            Assert.Equal(typeof(AttributeTests).AssemblyQualifiedName, d.TargetTypeName);

            d.TargetTypeName = typeof(DebugTests).AssemblyQualifiedName;
            Assert.Equal(typeof(DebugTests).AssemblyQualifiedName, d.TargetTypeName);

            d.Type = "typeName";
            Assert.Equal("typeName", d.Type);
        }
        public void ConstructorTest()
        {
            DebuggerDisplayAttribute dda;

            dda = new DebuggerDisplayAttribute(null);
            Assert.AreEqual(string.Empty, dda.Value, "A1");
            Assert.IsNull(dda.Target, "A2");
            Assert.IsNull(dda.TargetTypeName, "A3");
            Assert.AreEqual(string.Empty, dda.Type, "A4");
            Assert.AreEqual(string.Empty, dda.Name, "A4");

            dda = new DebuggerDisplayAttribute("abc");
            Assert.AreEqual("abc", dda.Value, "B1");
            Assert.IsNull(dda.Target, "B2");
            Assert.IsNull(dda.TargetTypeName, "B3");
            Assert.AreEqual(string.Empty, dda.Type, "B4");
            Assert.AreEqual(string.Empty, dda.Name, "B4");
        }
        private static void TestDebuggerDisplayReferences(object obj)
        {
#if NET_4_0_ABOVE
            var attrs = obj.GetType().GetTypeInfo().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).ToArray();
#else
            var attrs = obj.GetType().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).ToArray();
#endif
            Assert.Equal(expected: 1, actual: attrs.Length);

            DebuggerDisplayAttribute dda = (DebuggerDisplayAttribute)attrs[0];
            string attrText = dda.Value;

            var references = new List <string>();
            int pos        = 0;
            while (true)
            {
                int openBrace = attrText.IndexOf('{', pos);
                if (openBrace < pos)
                {
                    break;
                }
                int closeBrace = attrText.IndexOf('}', openBrace);
                if (closeBrace < openBrace)
                {
                    break;
                }

                string reference = attrText.Substring(openBrace + 1, closeBrace - openBrace - 1).Replace(",nq", "");
                pos = closeBrace + 1;

                references.Add(reference);
            }
            Assert.NotEqual(0, actual: references.Count);

            foreach (var reference in references)
            {
                PropertyInfo pi = obj.GetType().GetProperty(reference, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo    fi = obj.GetType().GetField(reference, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                Assert.False(pi == null & fi == null);                                // must be either a property or a field
                object result = pi != null?pi.GetValue(obj, null) : fi.GetValue(obj); // make sure we can access the property or field
            }
        }
Esempio n. 15
0
        public void ProvideDebuggerDisplay(MethodData sut)
        {
            // Assert as we go
            DebuggerDisplayAttribute debuggerDisplay = sut.GetType().GetTypeInfo().GetCustomAttribute <DebuggerDisplayAttribute>(inherit: false);

            Assert.NotNull(debuggerDisplay);
            Assert.Contains("DebuggerDisplay", debuggerDisplay.Value);

            PropertyInfo propertyInfo = sut.GetType().GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance);

            Assert.NotNull(propertyInfo);

            MethodInfo getMethod = propertyInfo.GetGetMethod(true);

            Assert.NotNull(getMethod);

            string display = Assert.IsType <string>(getMethod.Invoke(sut, new object[] { }));

            Assert.Contains(sut.ToString(), display);
        }
        private static void ShowAttributes(MemberInfo attributeTarget)
        {
            // {System.Attribute[3]} Reflection.DefaultMember
            // Diagnositics.DebuggerDisplayAttribute SerializableAttribute
            var attributes = attributeTarget.GetCustomAttributes <Attribute>();

            Console.WriteLine("Attributes applied to {0}: {1}",
                              attributeTarget.Name, (attributes.Count() == 0 ? "None" : String.Empty));

            foreach (Attribute attribute in attributes)
            {
                // Display the type of each applied attribute
                Console.WriteLine("  {0}", attribute.GetType().ToString());

                if (attribute is DefaultMemberAttribute)
                {
                    Console.WriteLine("    MemberName={0}",
                                      ((DefaultMemberAttribute)attribute).MemberName);
                }

                if (attribute is ConditionalAttribute)
                {
                    Console.WriteLine("    ConditionString={0}",
                                      ((ConditionalAttribute)attribute).ConditionString);
                }

                if (attribute is CLSCompliantAttribute)
                {
                    Console.WriteLine("    IsCompliant={0}",
                                      ((CLSCompliantAttribute)attribute).IsCompliant);
                }

                DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
                if (dda != null)
                {
                    Console.WriteLine("    Value={0}, Name={1}, Target={2}",
                                      dda.Value, dda.Name, dda.Target);
                }
            }
            Console.WriteLine();
        }
Esempio n. 17
0
        /// <summary>Formats the object.</summary>
        /// <param name="argument">The argument.</param>
        /// <returns>The objects string form.</returns>
        private static string FormatObject(object argument)
        {
            if (argument == null)
            {
                return("NULL");
            }

            string formatedObject;
            List <DebuggerDisplayAttribute> arrDda = Attribute.GetCustomAttributes(argument.GetType(), typeof(DebuggerDisplayAttribute)).OfType <DebuggerDisplayAttribute>().ToList();

            if (arrDda.Count == 1)
            {
                DebuggerDisplayAttribute dda = arrDda.First();
                string val = dda.Value;
                formatedObject = argument.ToString(val);
            }
            else
            {
                formatedObject = argument.ToString();
            }

            return(formatedObject);
        }
Esempio n. 18
0
        private static void ShowAttributes(MemberInfo attributeTarget)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(attributeTarget);
            Console.WriteLine("Attributes applied to {0}: {1}",
                              attributeTarget.Name, (attributes.Length == 0 ? "None" : String.Empty));
            foreach (Attribute attribute in attributes)
            {
                // Display the  type of each applied attribute
                Console.WriteLine("  {0}", attribute.GetType().ToString());
                DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
                if (dda != null)
                {
                    Console.WriteLine("    Value={0}, Name={1}, Target={2}",
                                      dda.Value, dda.Name, dda.Target);
                }

                FlagsAttribute flags = attribute as FlagsAttribute;
                if (flags != null)
                {
                    Console.WriteLine(flags.ToString());
                    Console.WriteLine(flags.GetType().Name);
                }
            }
        }
Esempio n. 19
0
            /// <summary>
            /// Appends a parameter to the buffer.
            /// </summary>
            /// <param name="parameter">
            /// Information about the parameter to append.
            /// </param>
            /// <param name="argument">
            /// The argument that was passed to the parameter.
            /// </param>
            private void AppendParameter(ParameterInfo parameter, object argument)
            {
                bool sensitive = this.sensitiveMethod || parameter.IsDefined(typeof(SensitiveDataAttribute), false);

                try
                {
                    if (!parameter.IsReturnValue())
                    {
                        this.buffer.Append(parameter.Name);
                    }

                    this.buffer.Append('=');

                    if (argument == null)
                    {
                        this.buffer.Append("<null>");
                        return;
                    }

#if DEBUG
                    // in debug builds sensitive data may be traced with the appropriate switch; in release builds it may not
                    if (sensitive && !StyleCopTrace.Switch.TraceSensitiveData)
#else
                    if (sensitive)
#endif
                    {
                        this.buffer.Append("<obscured>");
                        return;
                    }

                    // if the argument is a string then print it with quotes
                    if (argument is string)
                    {
                        this.buffer.Append("\"" + argument + "\"");
                        return;
                    }

                    // if the argument is a type then print it as a typeof
                    if (argument is Type)
                    {
                        this.buffer.Append("typeof(" + ((Type)argument).Name + ")");
                        return;
                    }

                    // if the argument is a primitive (or pseudo-primitive) type then print it 'as is'
                    Type argumentType = argument.GetType();
                    if (argumentType.IsPrimitive || argumentType == typeof(decimal))
                    {
                        this.buffer.Append(argument);
                        return;
                    }

                    // if it has an overridden ToString method print it in curly brackets
                    MethodInfo stringMethod = argumentType.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
                    if (stringMethod.GetBaseDefinition().DeclaringType != stringMethod.DeclaringType)
                    {
                        this.buffer.Append("{" + argument + "}");
                        return;
                    }

                    // if the argument type has a DebuggerDisplayAttribute then format and print in square brackets
                    DebuggerDisplayAttribute displayAttribute =
                        (DebuggerDisplayAttribute)argumentType.GetCustomAttributes(typeof(DebuggerDisplayAttribute), true).FirstOrDefault();
                    if (displayAttribute != null)
                    {
                        MatchEvaluator evaluator = match =>
                        {
                            string       memberName   = match.Value.Replace("{", null).Replace("}", null);
                            PropertyInfo propertyInfo = argumentType.GetProperty(
                                memberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                            if (propertyInfo != null)
                            {
                                return(Convert.ToString(propertyInfo.GetValue(argument, null), CultureInfo.InvariantCulture));
                            }

                            FieldInfo fieldInfo;
                            Type      typeToInspect = argumentType;
                            do
                            {
                                fieldInfo     = typeToInspect.GetField(memberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                                typeToInspect = typeToInspect.BaseType;
                            }while (fieldInfo == null && typeToInspect != typeof(object));
                            return(fieldInfo != null?Convert.ToString(fieldInfo.GetValue(argument), CultureInfo.InvariantCulture) : "?");
                        };

                        string displayString = DebuggerDisplayFormatRegex.Replace(displayAttribute.Value, evaluator);
                        this.buffer.Append('[');
                        this.AppendTypeName(argumentType);
                        this.buffer.Append(": ").Append(displayString).Append(']');
                        return;
                    }

                    // did somebody forget to supply the parameter?
                    if (argument == Missing.Value)
                    {
                        this.buffer.Append("<missing>");
                        return;
                    }

                    // catch all - just display the type name
                    this.buffer.Append('[');
                    this.AppendTypeName(argumentType);
                    this.buffer.Append(']');
                }
                catch
                {
                    this.buffer.Append("<error>");
                }
            }
            private Builder FormatObjectRecursive(Builder result, object obj, bool isRoot, out string debuggerDisplayName)
            {
                // TODO (https://github.com/dotnet/roslyn/issues/6689): remove this
                if (!isRoot && _memberDisplayFormat == MemberDisplayFormat.SeparateLines)
                {
                    _memberDisplayFormat = MemberDisplayFormat.SingleLine;
                }

                debuggerDisplayName = null;
                string primitive = _formatter.PrimitiveFormatter.FormatPrimitive(obj, _primitiveOptions);

                if (primitive != null)
                {
                    result.Append(primitive);
                    return(result);
                }

                Type     type     = obj.GetType();
                TypeInfo typeInfo = type.GetTypeInfo();

                //
                // Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
                //
                // { { format(key), format(value) }, ... }
                // instead of
                // { [key.ToString(), value.ToString()], ... }
                //
                // This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
                // types that return an array of KeyValuePair in their DebuggerDisplay to display items.
                //
                if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
                {
                    if (isRoot)
                    {
                        result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
                        result.Append(' ');
                    }

                    FormatKeyValuePair(result, obj);
                    return(result);
                }

                if (typeInfo.IsArray)
                {
                    if (VisitedObjects.Add(obj))
                    {
                        FormatArray(result, (Array)obj);

                        VisitedObjects.Remove(obj);
                    }
                    else
                    {
                        result.AppendInfiniteRecursionMarker();
                    }

                    return(result);
                }

                DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(typeInfo);

                if (debuggerDisplay != null)
                {
                    debuggerDisplayName = debuggerDisplay.Name;
                }

                // Suppresses members if inlineMembers is true,
                // does nothing otherwise.
                bool suppressInlineMembers = false;

                //
                // TypeName(count) for ICollection implementers
                // or
                // TypeName([[DebuggerDisplay.Value]])        // Inline
                // [[DebuggerDisplay.Value]]                  // Inline && !isRoot
                // or
                // [[ToString()]] if ToString overridden
                // or
                // TypeName
                //
                ICollection collection;

                if ((collection = obj as ICollection) != null)
                {
                    FormatCollectionHeader(result, collection);
                }
                else if (debuggerDisplay != null && !string.IsNullOrEmpty(debuggerDisplay.Value))
                {
                    if (isRoot)
                    {
                        result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
                        result.Append('(');
                    }

                    FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, obj);

                    if (isRoot)
                    {
                        result.Append(')');
                    }

                    suppressInlineMembers = true;
                }
                else if (HasOverriddenToString(typeInfo))
                {
                    ObjectToString(result, obj);
                    suppressInlineMembers = true;
                }
                else
                {
                    result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
                }

                MemberDisplayFormat memberFormat = _memberDisplayFormat;

                if (memberFormat == MemberDisplayFormat.Hidden)
                {
                    if (collection != null)
                    {
                        // NB: Collections specifically ignore MemberDisplayFormat.Hidden.
                        memberFormat = MemberDisplayFormat.SingleLine;
                    }
                    else
                    {
                        return(result);
                    }
                }

                bool includeNonPublic = memberFormat == MemberDisplayFormat.SeparateLines;
                bool inlineMembers    = memberFormat == MemberDisplayFormat.SingleLine;

                object proxy = GetDebuggerTypeProxy(obj);

                if (proxy != null)
                {
                    includeNonPublic      = false;
                    suppressInlineMembers = false;
                }

                if (!suppressInlineMembers || !inlineMembers)
                {
                    FormatMembers(result, obj, proxy, includeNonPublic, inlineMembers);
                }

                return(result);
            }
Esempio n. 21
0
        private static bool AllDebuggerDisplayReferencesWork(object obj)
        {
            var attrs = obj.GetType().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false);

            if (attrs.Length != 1)
            {
                Console.WriteLine("Incorrect number of DebuggerDisplayAttributes");
                return(false);
            }

            DebuggerDisplayAttribute dda = (DebuggerDisplayAttribute)attrs[0];
            string attrText = dda.Value;

            var references = new List <string>();
            int pos        = 0;

            while (true)
            {
                int openBrace = attrText.IndexOf('{', pos);
                if (openBrace < pos)
                {
                    break;
                }
                int closeBrace = attrText.IndexOf('}', openBrace);
                if (closeBrace < openBrace)
                {
                    break;
                }
                string reference = attrText.Substring(openBrace + 1, closeBrace - openBrace - 1).Replace(",nq", "");
                pos = closeBrace + 1;
                references.Add(reference);
            }
            if (references.Count == 0)
            {
                Console.WriteLine("No referenced values");
                return(false);
            }

            foreach (var reference in references)
            {
                PropertyInfo pi = obj.GetType().GetProperty(reference, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo    fi = obj.GetType().GetField(reference, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                if (pi == null && fi == null)
                {
                    Console.WriteLine("Missing reference target {0} from type {1}", reference, obj.GetType().FullName);
                    return(false);
                }
                bool success = true;
                try
                {
                    object result = pi != null?pi.GetValue(obj, null) : fi.GetValue(obj);
                }
                catch { success = false; }
                if (!success)
                {
                    Console.WriteLine("Property get failed {0} from type {1}", reference, obj.GetType().FullName);
                    return(false);
                }
            }

            return(true);
        }
        protected override TypeDisplayData OnGetTypeDisplayData(EvaluationContext gctx, object type)
        {
            SoftEvaluationContext ctx = (SoftEvaluationContext)gctx;
            TypeDisplayData       td  = new TypeDisplayData();

            try {
                TypeMirror t = (TypeMirror)type;
                foreach (CustomAttributeDataMirror attr in t.GetCustomAttributes(true))
                {
                    string attName = attr.Constructor.DeclaringType.FullName;
                    if (attName == "System.Diagnostics.DebuggerDisplayAttribute")
                    {
                        DebuggerDisplayAttribute at = BuildAttribute <DebuggerDisplayAttribute> (attr);
                        td.NameDisplayString  = at.Name;
                        td.TypeDisplayString  = at.Type;
                        td.ValueDisplayString = at.Value;
                    }
                    else if (attName == "System.Diagnostics.DebuggerTypeProxyAttribute")
                    {
                        DebuggerTypeProxyAttribute at = BuildAttribute <DebuggerTypeProxyAttribute> (attr);
                        td.ProxyType = at.ProxyTypeName;
                        if (!string.IsNullOrEmpty(td.ProxyType))
                        {
                            ForceLoadType(ctx, td.ProxyType);
                        }
                    }
                }
                foreach (FieldInfoMirror fi in t.GetFields())
                {
                    CustomAttributeDataMirror[] attrs = fi.GetCustomAttributes(true);
                    DebuggerBrowsableAttribute  att   = GetAttribute <DebuggerBrowsableAttribute> (attrs);
                    if (att == null)
                    {
                        var cga = GetAttribute <System.Runtime.CompilerServices.CompilerGeneratedAttribute> (attrs);
                        if (cga != null)
                        {
                            att = new DebuggerBrowsableAttribute(DebuggerBrowsableState.Never);
                        }
                    }
                    if (att != null)
                    {
                        if (td.MemberData == null)
                        {
                            td.MemberData = new Dictionary <string, DebuggerBrowsableState> ();
                        }
                        td.MemberData [fi.Name] = att.State;
                    }
                }
                foreach (PropertyInfoMirror pi in t.GetProperties())
                {
                    DebuggerBrowsableAttribute att = GetAttribute <DebuggerBrowsableAttribute> (pi.GetCustomAttributes(true));
                    if (att != null)
                    {
                        if (td.MemberData == null)
                        {
                            td.MemberData = new Dictionary <string, DebuggerBrowsableState> ();
                        }
                        td.MemberData [pi.Name] = att.State;
                    }
                }
            } catch (Exception ex) {
                ctx.Session.WriteDebuggerOutput(true, ex.ToString());
            }
            return(td);
        }
        void Target_SetNull_ThrowsArgumentNullException()
        {
            var attribute = new DebuggerDisplayAttribute("Value");

            AssertExtensions.Throws <ArgumentNullException>("value", () => attribute.Target = null);
        }
Esempio n. 24
0
        private static Func <object, string> CreateDisplay(Type type)
        {
            DebuggerDisplayAttribute[] attrs = type.GetCustomAttributes(typeof(DebuggerDisplayAttribute), inherit: true).Cast <DebuggerDisplayAttribute>().ToArray();
            if (attrs.Length == 0)
            {
                return(GetStringForObject);
            }

            DebuggerDisplayAttribute topAttr = attrs[0];

            MatchCollection matches = DisplayExpressionsRegex.Matches(topAttr.Value);

            if (matches.Count == 0)
            {
                return(GetStringForObject);
            }

            List <Func <object, object> > getters = new List <Func <object, object> >();

            foreach (Match m in matches)
            {
                string expr = m.Value.Substring(1, m.Value.Length - 2).Replace("(", String.Empty).Replace(")", String.Empty);

                MemberInfo[] members = type.GetMember(expr,
                                                      MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
                                                      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                if (members.Length == 1)
                {
                    MethodInfo method = null;

                    PropertyInfo property = members [0] as PropertyInfo;
                    if (property != null)
                    {
                        method = property.GetGetMethod();
                    }

                    if (method == null)
                    {
                        method = members [0] as MethodInfo;
                    }

                    if (method != null && method.ReturnType != typeof(void))
                    {
                        getters.Add(o => method.Invoke(o, null));
                        continue;
                    }

                    FieldInfo field = members [0] as FieldInfo;
                    if (field != null)
                    {
                        getters.Add(field.GetValue);
                        continue;
                    }
                }

                getters.Add(o => m.Value);
            }

            return(o =>
            {
                StringBuilder builder = new StringBuilder(topAttr.Value);

                for (int i = 0; i < matches.Count; ++i)
                {
                    builder.Replace(matches [i].Value, GetStringForObject(getters [i] (o)));
                }

                return builder.ToString();
            });
        }
            private Builder FormatObjectRecursive(Builder result, object obj, bool quoteStrings, MemberDisplayFormat memberFormat, out string name)
            {
                name = null;
                string primitive = _language.FormatPrimitive(obj, quoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers);

                if (primitive != null)
                {
                    result.Append(primitive);
                    return(result);
                }

                object originalObj  = obj;
                Type   originalType = originalObj.GetType();

                //
                // Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
                //
                // { { format(key), format(value) }, ... }
                // instead of
                // { [key.ToString(), value.ToString()], ... }
                //
                // This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
                // types that return an array of KeyValuePair in their DebuggerDisplay to display items.
                //
                if (originalType.IsGenericType && originalType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
                {
                    if (memberFormat != MemberDisplayFormat.InlineValue)
                    {
                        result.Append(_language.FormatTypeName(originalType, _options));
                        result.Append(' ');
                    }

                    FormatKeyValuePair(result, originalObj);
                    return(result);
                }

                if (originalType.IsArray)
                {
                    if (!VisitedObjects.Add(originalObj))
                    {
                        result.AppendInfiniteRecursionMarker();
                        return(result);
                    }

                    FormatArray(result, (Array)originalObj, inline: memberFormat != MemberDisplayFormat.List);

                    VisitedObjects.Remove(originalObj);
                    return(result);
                }

                DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(originalType);

                if (debuggerDisplay != null)
                {
                    name = debuggerDisplay.Name;
                }

                bool suppressMembers = false;

                //
                // TypeName(count) for ICollection implementers
                // or
                // TypeName([[DebuggerDisplay.Value]])        // Inline
                // [[DebuggerDisplay.Value]]                  // InlineValue
                // or
                // [[ToString()]] if ToString overridden
                // or
                // TypeName
                //
                ICollection collection;

                if ((collection = originalObj as ICollection) != null)
                {
                    FormatCollectionHeader(result, collection);
                }
                else if (debuggerDisplay != null && !String.IsNullOrEmpty(debuggerDisplay.Value))
                {
                    if (memberFormat != MemberDisplayFormat.InlineValue)
                    {
                        result.Append(_language.FormatTypeName(originalType, _options));
                        result.Append('(');
                    }

                    FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, originalObj);

                    if (memberFormat != MemberDisplayFormat.InlineValue)
                    {
                        result.Append(')');
                    }

                    suppressMembers = true;
                }
                else if (HasOverriddenToString(originalType))
                {
                    ObjectToString(result, originalObj);
                    suppressMembers = true;
                }
                else
                {
                    result.Append(_language.FormatTypeName(originalType, _options));
                }

                if (memberFormat == MemberDisplayFormat.NoMembers)
                {
                    return(result);
                }

                bool   includeNonPublic = memberFormat == MemberDisplayFormat.List;
                object proxy            = GetDebuggerTypeProxy(obj);

                if (proxy != null)
                {
                    obj = proxy;
                    includeNonPublic = false;
                    suppressMembers  = false;
                }

                if (memberFormat != MemberDisplayFormat.List && suppressMembers)
                {
                    return(result);
                }

                // TODO (tomat): we should not use recursion
                RuntimeHelpers.EnsureSufficientExecutionStack();

                result.Append(' ');

                if (!VisitedObjects.Add(originalObj))
                {
                    result.AppendInfiniteRecursionMarker();
                    return(result);
                }

                // handle special types only if a proxy isn't defined
                if (proxy == null)
                {
                    IDictionary dictionary;
                    if ((dictionary = obj as IDictionary) != null)
                    {
                        FormatDictionary(result, dictionary, inline: memberFormat != MemberDisplayFormat.List);
                        return(result);
                    }

                    IEnumerable enumerable;
                    if ((enumerable = obj as IEnumerable) != null)
                    {
                        FormatSequence(result, enumerable, inline: memberFormat != MemberDisplayFormat.List);
                        return(result);
                    }
                }

                FormatObjectMembers(result, obj, originalType, includeNonPublic, inline: memberFormat != MemberDisplayFormat.List);

                VisitedObjects.Remove(obj);

                return(result);
            }
Esempio n. 26
0
        protected override TypeDisplayData OnGetTypeDisplayData(EvaluationContext ctx, object gtype)
        {
            CorType type = (CorType)gtype;

            CorEvaluationContext wctx = (CorEvaluationContext)ctx;
            Type t = type.GetTypeInfo(wctx.Session);

            if (t == null)
            {
                return(null);
            }

            string proxyType          = null;
            string nameDisplayString  = null;
            string typeDisplayString  = null;
            string valueDisplayString = null;
            Dictionary <string, DebuggerBrowsableState> memberData = null;
            bool hasTypeData = false;

            foreach (object att in t.GetCustomAttributes(false))
            {
                DebuggerTypeProxyAttribute patt = att as DebuggerTypeProxyAttribute;
                if (patt != null)
                {
                    proxyType   = patt.ProxyTypeName;
                    hasTypeData = true;
                    continue;
                }
                DebuggerDisplayAttribute datt = att as DebuggerDisplayAttribute;
                if (datt != null)
                {
                    hasTypeData        = true;
                    nameDisplayString  = datt.Name;
                    typeDisplayString  = datt.Type;
                    valueDisplayString = datt.Value;
                    continue;
                }
            }

            ArrayList mems = new ArrayList();

            mems.AddRange(t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
            mems.AddRange(t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));

            foreach (MemberInfo m in mems)
            {
                object[] atts = m.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false);
                if (atts.Length == 0)
                {
                    atts = m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false);
                    if (atts.Length > 0)
                    {
                        atts[0] = new DebuggerBrowsableAttribute(DebuggerBrowsableState.Never);
                    }
                }
                if (atts.Length > 0)
                {
                    hasTypeData = true;
                    if (memberData == null)
                    {
                        memberData = new Dictionary <string, DebuggerBrowsableState> ();
                    }
                    memberData[m.Name] = ((DebuggerBrowsableAttribute)atts[0]).State;
                }
            }
            if (hasTypeData)
            {
                return(new TypeDisplayData(proxyType, valueDisplayString, typeDisplayString, nameDisplayString, false, memberData));
            }
            else
            {
                return(null);
            }
        }