Inheritance: MonoBehaviour
		// snippet moved from FileIOPermission (nickd) to be reused in all derived classes
		internal static SecurityElement Element (Type type, int version) 
		{
			SecurityElement se = new SecurityElement ("IPermission");
			se.AddAttribute ("class", type.FullName + ", " + type.Assembly.ToString ().Replace ('\"', '\''));
			se.AddAttribute ("version", version.ToString ());
			return se;
		}
示例#2
1
 internal ComMethodInformation(bool hasvarargs, bool hasoptional, ParameterInformation[] arguments, Type returnType, int dispId, COM.INVOKEKIND invokekind)
     : base(hasvarargs, hasoptional, arguments)
 {
     this.ReturnType = returnType;
     this.DispId = dispId;
     this.InvokeKind = invokekind;
 }
示例#3
1
        private static FieldInfo[] GetSerializableFields(Type type)
        {
            if (type.GetTypeInfo().IsInterface)
            {
                return Array.Empty<FieldInfo>();
            }

            if (!type.GetTypeInfo().IsSerializable)
            {
                throw new SerializationException(SR.Format(SR.Serialization_NonSerType, type.GetTypeInfo().FullName, type.GetTypeInfo().Assembly.FullName));
            }

            var results = new List<FieldInfo>();
            for (Type t = type; t != typeof(object); t = t.GetTypeInfo().BaseType)
            {
                foreach (FieldInfo field in t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                {
                    if ((field.Attributes & FieldAttributes.NotSerialized) != FieldAttributes.NotSerialized)
                    {
                        results.Add(field);
                    }
                }
            }
            return results.ToArray();
        }
 /// <summary>
 ///     Given a clrType attempt to return the corresponding target type from
 ///     the worksapce
 /// </summary>
 /// <param name="clrType"> The clr type to resolve </param>
 /// <param name="outTypeUsage"> an out param for the typeUsage to be resolved to </param>
 /// <returns> true if a TypeUsage can be found for the target type </returns>
 internal bool TryGetType(Type clrType, out TypeUsage outTypeUsage)
 {
     return TryGetTypeByName(
         clrType.FullNameWithNesting(),
         false /*ignoreCase*/,
         out outTypeUsage);
 }
示例#5
1
 internal static Type GetNullableType(Type type) {
     Debug.Assert(type != null, "type cannot be null");
     if (type.IsValueType && !IsNullableType(type)) {
         return typeof(Nullable<>).MakeGenericType(type);
     }
     return type;
 }
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
                if (destinationType == typeof(string)) {
                    return "EmbeddedMailObject";
                }

                return base.ConvertTo(context, culture, value, destinationType);
            }
示例#7
1
		public CodeTypeReference (Type baseType)
		{
#if NET_2_0
			if (baseType == null) {
				throw new ArgumentNullException ("baseType");
			}

			if (baseType.IsGenericParameter) {
				this.baseType = baseType.Name;
				this.referenceOptions = CodeTypeReferenceOptions.GenericTypeParameter;
			}
			else if (baseType.IsGenericTypeDefinition)
				this.baseType = baseType.FullName;
			else if (baseType.IsGenericType) {
				this.baseType = baseType.GetGenericTypeDefinition ().FullName;
				foreach (Type arg in baseType.GetGenericArguments ()) {
					if (arg.IsGenericParameter)
						TypeArguments.Add (new CodeTypeReference (new CodeTypeParameter (arg.Name)));
					else
						TypeArguments.Add (new CodeTypeReference (arg));
				}
			}
			else
#endif
			if (baseType.IsArray) {
				this.arrayRank = baseType.GetArrayRank ();
				this.arrayElementType = new CodeTypeReference (baseType.GetElementType ());
				this.baseType = arrayElementType.BaseType;
			} else {
				Parse (baseType.FullName);
			}
			this.isInterface = baseType.IsInterface;
		}
 internal CoordinatorScratchpad(Type elementType)
 {
     _elementType = elementType;
     _nestedCoordinatorScratchpads = new List<CoordinatorScratchpad>();
     _expressionWithErrorHandlingMap = new Dictionary<Expression, Expression>();
     _inlineDelegates = new HashSet<LambdaExpression>();
 }
示例#9
1
    /// <summary>
    /// Gets the smart part info.
    /// </summary>
    /// <param name="smartPartInfoType">Type of the smart part info.</param>
    /// <returns></returns>
    public override ISmartPartInfo GetSmartPartInfo(Type smartPartInfoType)
    {
        ToolsSmartPartInfo tinfo = new ToolsSmartPartInfo();
        if (BindingSource != null)
        {
            if (BindingSource.Current != null)
            {
                tinfo.Title = _stage.Id != null
                                  ? (_mode == "Complete"
                                         ? GetLocalResourceObject("DialogTitleComplete").ToString()
                                         : GetLocalResourceObject("DialogTitleEdit").ToString())
                                  : GetLocalResourceObject("DialogTitleAdd").ToString();
            }
        }

        foreach (Control c in Form_LTools.Controls)
        {
            tinfo.LeftTools.Add(c);
        }
        foreach (Control c in Form_CTools.Controls)
        {
            tinfo.CenterTools.Add(c);
        }
        foreach (Control c in Form_RTools.Controls)
        {
            tinfo.RightTools.Add(c);
        }
        return tinfo;
    }
示例#10
1
        internal VarEnumSelector(Type[] explicitArgTypes) {
            _variantBuilders = new VariantBuilder[explicitArgTypes.Length];

            for (int i = 0; i < explicitArgTypes.Length; i++) {
                _variantBuilders[i] = GetVariantBuilder(explicitArgTypes[i]);
            }
        }
示例#11
1
 internal static InternalPrimitiveTypeE ToCode(Type type) =>
         type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) :
         type.GetTypeInfo().IsPrimitive ? ToPrimitiveTypeEnum(type.GetTypeCode()) :
         ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime :
         ReferenceEquals(type, s_typeofTimeSpan) ? InternalPrimitiveTypeE.TimeSpan :
         ReferenceEquals(type, s_typeofDecimal) ? InternalPrimitiveTypeE.Decimal :
         InternalPrimitiveTypeE.Invalid;
示例#12
0
        static CXXOperatorKind CheckMissingOperatorOverloadPair(Class @class, out int index,
            CXXOperatorKind op1, CXXOperatorKind op2, Type typeLeft, Type typeRight)
        {
            var first = @class.Operators.FirstOrDefault(o => o.OperatorKind == op1 &&
                o.Parameters.First().Type.Equals(typeLeft) && o.Parameters.Last().Type.Equals(typeRight));
            var second = @class.Operators.FirstOrDefault(o => o.OperatorKind == op2 &&
                o.Parameters.First().Type.Equals(typeLeft) && o.Parameters.Last().Type.Equals(typeRight));

            var hasFirst = first != null;
            var hasSecond = second != null;

            if (hasFirst && (!hasSecond || !second.IsGenerated))
            {
                index = @class.Methods.IndexOf(first);
                return op2;
            }

            if (hasSecond && (!hasFirst || !first.IsGenerated))
            {
                index = @class.Methods.IndexOf(second);
                return op1;
            }

            index = 0;
            return CXXOperatorKind.None;
        }
示例#13
0
        public IEnumerable<PropertyInfo> GetProperties(
            Type type,
            bool declaredOnly,
            IEnumerable<PropertyInfo> explicitlyMappedProperties = null,
            IEnumerable<Type> knownTypes = null,
            bool includePrivate = false)
        {
            DebugCheck.NotNull(type);

            explicitlyMappedProperties = explicitlyMappedProperties ?? Enumerable.Empty<PropertyInfo>();
            knownTypes = knownTypes ?? Enumerable.Empty<Type>();

            ValidatePropertiesForModelVersion(type, explicitlyMappedProperties);

            var propertyInfos
                = from p in declaredOnly ? type.GetDeclaredProperties() : type.GetNonHiddenProperties()
                  where !p.IsStatic() && p.IsValidStructuralProperty()
                  let m = p.Getter()
                  where (includePrivate || (m.IsPublic || explicitlyMappedProperties.Contains(p) || knownTypes.Contains(p.PropertyType)))
                        && (!declaredOnly || type.BaseType().GetInstanceProperties().All(bp => bp.Name != p.Name))
                        && (EdmV3FeaturesSupported || (!IsEnumType(p.PropertyType) && !IsSpatialType(p.PropertyType)))
                        && (Ef6FeaturesSupported || !p.PropertyType.IsNested)
                  select p;

            return propertyInfos;
        }
示例#14
0
    static void Main(string[] args)
    {
        AssemblyName an = new AssemblyName();
        an.Name = "HelloWorld";
        AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder module = ab.DefineDynamicModule("b.dll");
        TypeBuilder tb = module.DefineType("type", TypeAttributes.Public | TypeAttributes.Class);
        MethodBuilder mb = tb.DefineMethod("test",
					   MethodAttributes.HideBySig | MethodAttributes.Static |
					   MethodAttributes.Public, typeof(void), null);
        ILGenerator ig = mb.GetILGenerator();

	//
	// This is the actual test:
	//   Generate a method signature that contains modopts and modreqs
	//   and call that.  It has no name or anything, not sure how this
	//   is actually used, but we at least generate the stuff
	//
	SignatureHelper sh = SignatureHelper.GetMethodSigHelper (module, CallingConventions.HasThis, typeof(int));
	sh.AddArgument (typeof (bool));
	Type [] req = new Type [] { typeof (System.Runtime.CompilerServices.IsBoxed) };
	sh.AddArgument (typeof (string), req, null);
	Type [] opt = new Type [] { typeof (System.Runtime.CompilerServices.IsConst) };
	sh.AddArgument (typeof (byte), null, opt);
	sh.AddArgument (typeof (int), null, opt);
	sh.AddArgument (typeof (long), null, opt);
	ig.Emit (OpCodes.Call, sh);

        ig.Emit(OpCodes.Ret);

        tb.CreateType();

	ab.Save ("b.dll");
     }
示例#15
0
文件: Lexer.cs 项目: Profit0004/mono
		public Token (Type type, int startPosition, int endPosition)
			: this ()
		{
			this.type = type;
			StartPosition = startPosition;
			EndPosition = endPosition;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumTypeConfiguration"/> class.
        /// </summary>
        public EnumTypeConfiguration(ODataModelBuilder builder, Type clrType)
        {
            if (builder == null)
            {
                throw Error.ArgumentNull("builder");
            }
            if (clrType == null)
            {
                throw Error.ArgumentNull("clrType");
            }

            if (!clrType.IsEnum)
            {
                throw Error.Argument("clrType", SRResources.TypeCannotBeEnum, clrType.FullName);
            }

            ClrType = clrType;
            IsFlags = clrType.GetCustomAttributes(typeof(FlagsAttribute), false).Any();
            UnderlyingType = Enum.GetUnderlyingType(clrType);
            ModelBuilder = builder;
            _name = clrType.EdmName();
            _namespace = clrType.Namespace ?? DefaultNamespace;
            ExplicitMembers = new Dictionary<Enum, EnumMemberConfiguration>();
            RemovedMembers = new List<Enum>();
        }
示例#17
0
	public JSONObject(Dictionary<string, string> dic) {
		type = Type.OBJECT;
		foreach(KeyValuePair<string, string> kvp in dic){
			keys.Add(kvp.Key);
			list.Add(new JSONObject { type = Type.STRING, str = kvp.Value });
		}
	}
示例#18
0
        private static bool IsValid(Type type, TypeInfo typeInfo)
        {
            if (!ReferenceEquals(null, type))
            {
                if (typeInfo.IsArray)
                {
                    type = type.GetElementType();
                }

                if (typeInfo.IsAnonymousType || type.IsAnonymousType())
                {
                    var properties = type.GetProperties().Select(x => x.Name).ToList();
                    var propertyNames = typeInfo.Properties.Select(x => x.Name).ToList();

                    var match =
                        type.IsAnonymousType() &&
                        typeInfo.IsAnonymousType &&
                        properties.Count == propertyNames.Count &&
                        propertyNames.All(x => properties.Contains(x));

                    if (!match)
                    {
                        return false;
                    }
                }

                return true;
            }

            return false;
        }
        private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
        {
            if (type.IsGenericType)
            {
                Type openGenericType = type.GetGenericTypeDefinition();
                if (openGenericType == typeof(PageResult<>))
                {
                    // Get the T in PageResult<T>
                    Type[] typeParameters = type.GetGenericArguments();
                    Debug.Assert(typeParameters.Length == 1);

                    // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
                    object items = sampleGenerator.GetSampleObject(itemsType);

                    // Fill in the other information needed to invoke the PageResult<T> constuctor
                    Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
                    object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };

                    // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
                    ConstructorInfo constructor = type.GetConstructor(parameterTypes);
                    return constructor.Invoke(parameters);
                }
            }

            return null;
        }
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;

            return base.CanConvertTo(context, destinationType);
        }
示例#21
0
 public void setType(Type t)
 {
     
     type = t;
     InitType();
     changeChild();
 }
示例#22
0
 public CreateShelfService(string serviceName, ShelfType shelfType, Type bootstrapperType, AssemblyName[] assemblyNames)
 {
     ServiceName = serviceName;
     ShelfType = shelfType;
     BootstrapperType = bootstrapperType;
     AssemblyNames = assemblyNames;
 }
        private void AddressOf(BinaryExpression node, Type type)
        {
            Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method == null);

            if (TypeUtils.AreEquivalent(type, node.Type))
            {
                EmitExpression(node.Left);
                EmitExpression(node.Right);
                Type rightType = node.Right.Type;
                if (TypeUtils.IsNullableType(rightType))
                {
                    LocalBuilder loc = GetLocal(rightType);
                    _ilg.Emit(OpCodes.Stloc, loc);
                    _ilg.Emit(OpCodes.Ldloca, loc);
                    _ilg.EmitGetValue(rightType);
                    FreeLocal(loc);
                }
                Type indexType = TypeUtils.GetNonNullableType(rightType);
                if (indexType != typeof(int))
                {
                    _ilg.EmitConvertToType(indexType, typeof(int), isChecked: true);
                }
                _ilg.Emit(OpCodes.Ldelema, node.Type);
            }
            else
            {
                EmitExpressionAddress(node, type);
            }
        }
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }
示例#25
0
        // Maps a URI to an Object containing the actual resource.
        public override Object GetEntity(Uri uri, string role, Type typeOfObjectToReturn)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (typeOfObjectToReturn != null && typeOfObjectToReturn != typeof(Stream) && typeOfObjectToReturn != typeof(Object))
            {
                throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
            }

            string filePath = uri.OriginalString;
            if (uri.IsAbsoluteUri)
            {
                if (!uri.IsFile)
                    throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()));

                filePath = uri.LocalPath;
            }

            try
            {
                return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (ArgumentException e)
            {
                throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()), e);
            }
        }
示例#26
0
 internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) {
     _type = type;
     _body = body;
     _handlers = handlers;
     _finally = @finally;
     _fault = fault;
 }
        private static bool CanUpdateReadOnlyProperty(Type propertyType)
        {
            // Value types have copy-by-value semantics, which prevents us from updating
            // properties that are marked readonly.
            if (propertyType.IsValueType)
            {
                return false;
            }

            // Arrays are strange beasts since their contents are mutable but their sizes aren't.
            // Therefore we shouldn't even try to update these. Further reading:
            // http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
            if (propertyType.IsArray)
            {
                return false;
            }

            // Special-case known immutable reference types
            if (propertyType == typeof(string))
            {
                return false;
            }

            return true;
        }
示例#28
0
		public XmlFormatExtensionAttribute (string elementName, string ns, Type[] extensionPoints)
			: this ()
		{
			this.elementName = elementName;
			this.ns = ns;
			this.extensionPoints = extensionPoints;
		}
        static Type[] ProcessDescriptionForMsmqIntegration(ServiceEndpoint endpoint, Type[] existingSerializationTypes)
        {
            List<Type> targetSerializationTypes;
            if (existingSerializationTypes == null)
            {
                targetSerializationTypes = new List<Type>();
            }
            else
            {
                targetSerializationTypes = new List<Type>(existingSerializationTypes);
            }

            foreach (OperationDescription operationDesc in endpoint.Contract.Operations)
            {
                foreach (Type type in operationDesc.KnownTypes)
                {
                    // add contract known types to targetSerializationTypes
                    if (!targetSerializationTypes.Contains(type))
                    {
                        targetSerializationTypes.Add(type);
                    }
                }
                // Default document style doesn't work for Integration Transport
                // because messages that SFx layer deals with are not wrapped
                // We need to change style for each operation
                foreach (MessageDescription messageDescription in operationDesc.Messages)
                {
                    messageDescription.Body.WrapperName = messageDescription.Body.WrapperNamespace = null;
                }
            }
            return targetSerializationTypes.ToArray();
        }
        /// <inheritdoc />
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter,
            ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            IEdmNavigationSource navigationSource = writeContext.NavigationSource;
            if (navigationSource == null)
            {
                throw new SerializationException(SRResources.NavigationSourceMissingDuringSerialization);
            }

            var path = writeContext.Path;
            if (path == null)
            {
                throw new SerializationException(SRResources.ODataPathMissing);
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter(navigationSource, path.EdmType as IEdmEntityType);
            WriteObjectInline(graph, navigationSource.EntityType().ToEdmTypeReference(isNullable: false), writer, writeContext);
        }
示例#31
0
 public Variable(string name, Type type)
 {
     Name = name;
     Type = type;
 }
示例#32
0
 public override bool CanConvertFrom(ITypeDescriptorContext context, Type type)
 {
     throw new NotImplementedException();
 }
示例#33
0
 /// <summary>
 /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
 /// The help page will use this information to produce more accurate request samples.
 /// </summary>
 /// <param name="config">The <see cref="HttpConfiguration"/>.</param>
 /// <param name="type">The type.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
 {
     config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
 }
示例#34
0
 internal DateTimeArgBuilder(Type parameterType)
     : base(parameterType)
 {
     Debug.Assert(parameterType == typeof(DateTime));
 }
示例#35
0
 public object GenerateObject(Type type)
 {
     return(DefaultGenerators[type](++_index));
 }
示例#36
0
 public object ConvertBack(object value, Type targetType, object parameter, string language)
 {
     return !(value is bool && (bool)value);
 }
示例#37
0
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(Enum.ToObject(targetType, (int)value));
 }
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     throw new NotImplementedException();
 }
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return((ViewDirection)value == ViewDirection.BackView ? Visibility.Visible : Visibility.Collapsed);
 }
示例#40
0
        public string GetDocumentation(Type type)
        {
            XPathNavigator typeNode = GetTypeNode(type);

            return(GetTagValue(typeNode, "summary"));
        }
示例#41
0
        private object GenerateObject(Type type, Dictionary <Type, object> createdObjectReferences)
        {
            try
            {
                if (SimpleTypeObjectGenerator.CanGenerateObject(type))
                {
                    return(SimpleObjectGenerator.GenerateObject(type));
                }

                if (type.IsArray)
                {
                    return(GenerateArray(type, DefaultCollectionSize, createdObjectReferences));
                }

                if (type.IsGenericType)
                {
                    return(GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences));
                }

                if (type == typeof(IDictionary))
                {
                    return(GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences));
                }

                if (typeof(IDictionary).IsAssignableFrom(type))
                {
                    return(GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences));
                }

                if (type == typeof(IList) ||
                    type == typeof(IEnumerable) ||
                    type == typeof(ICollection))
                {
                    return(GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences));
                }

                if (typeof(IList).IsAssignableFrom(type))
                {
                    return(GenerateCollection(type, DefaultCollectionSize, createdObjectReferences));
                }

                if (type == typeof(IQueryable))
                {
                    return(GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences));
                }

                if (type.IsEnum)
                {
                    return(GenerateEnum(type));
                }

                if (type.IsPublic || type.IsNestedPublic)
                {
                    return(GenerateComplexObject(type, createdObjectReferences));
                }
            }
            catch
            {
                // Returns null if anything fails
                return(null);
            }

            return(null);
        }
示例#42
0
        private static object GenerateGenericType(Type type, int collectionSize, Dictionary <Type, object> createdObjectReferences)
        {
            Type genericTypeDefinition = type.GetGenericTypeDefinition();

            if (genericTypeDefinition == typeof(Nullable <>))
            {
                return(GenerateNullable(type, createdObjectReferences));
            }

            if (genericTypeDefinition == typeof(KeyValuePair <,>))
            {
                return(GenerateKeyValuePair(type, createdObjectReferences));
            }

            if (IsTuple(genericTypeDefinition))
            {
                return(GenerateTuple(type, createdObjectReferences));
            }

            Type[] genericArguments = type.GetGenericArguments();
            if (genericArguments.Length == 1)
            {
                if (genericTypeDefinition == typeof(IList <>) ||
                    genericTypeDefinition == typeof(IEnumerable <>) ||
                    genericTypeDefinition == typeof(ICollection <>))
                {
                    Type collectionType = typeof(List <>).MakeGenericType(genericArguments);
                    return(GenerateCollection(collectionType, collectionSize, createdObjectReferences));
                }

                if (genericTypeDefinition == typeof(IQueryable <>))
                {
                    return(GenerateQueryable(type, collectionSize, createdObjectReferences));
                }

                Type closedCollectionType = typeof(ICollection <>).MakeGenericType(genericArguments[0]);
                if (closedCollectionType.IsAssignableFrom(type))
                {
                    return(GenerateCollection(type, collectionSize, createdObjectReferences));
                }
            }

            if (genericArguments.Length == 2)
            {
                if (genericTypeDefinition == typeof(IDictionary <,>))
                {
                    Type dictionaryType = typeof(Dictionary <,>).MakeGenericType(genericArguments);
                    return(GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences));
                }

                Type closedDictionaryType = typeof(IDictionary <,>).MakeGenericType(genericArguments[0], genericArguments[1]);
                if (closedDictionaryType.IsAssignableFrom(type))
                {
                    return(GenerateDictionary(type, collectionSize, createdObjectReferences));
                }
            }

            if (type.IsPublic || type.IsNestedPublic)
            {
                return(GenerateComplexObject(type, createdObjectReferences));
            }

            return(null);
        }
示例#43
0
 /// <summary>
 /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
 /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
 /// Complex types: POCO types.
 /// Nullables: <see cref="Nullable{T}"/>.
 /// Arrays: arrays of simple types or complex types.
 /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
 /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
 /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
 /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
 /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <returns>An object of the given type.</returns>
 public object GenerateObject(Type type)
 {
     return(GenerateObject(type, new Dictionary <Type, object>()));
 }
示例#44
0
 public static bool CanGenerateObject(Type type)
 {
     return(DefaultGenerators.ContainsKey(type));
 }
示例#45
0
 public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
 {
     return(new Version((string)reader.Value));
 }
示例#46
0
 public ComponentResourceManager(Type t) : base(t)
 {
 }
示例#47
0
 public void GetTypeFromProgID_ReturnsExpected()
 {
     AssertExtensions.Throws <ArgumentNullException>("progID", () => Type.GetTypeFromProgID(null));
 }
示例#48
0
        /// <summary>
        ///     This method examines all the resources for the provided culture.
        ///     When it finds a resource with a key in the format of 
        ///     &quot[objectName].[property name]&quot; it will apply that resource's value
        ///     to the corresponding property on the object.  If there is no matching
        ///     property the resource will be ignored.
        /// </summary>
        public virtual void ApplyResources(object value, string objectName, CultureInfo culture)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (objectName == null)
            {
                throw new ArgumentNullException(nameof(objectName));
            }
            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }

            // The general case here will be to always use the same culture, so optimize for
            // that.  The resourceSets hashtable uses culture as a key.  It's value is
            // a sorted dictionary that contains ALL the culture values (so it traverses up
            // the parent culture chain) for that culture.  This means that if ApplyResources
            // is called with different cultures there could be some redundancy in the
            // table, but it allows the normal case of calling with a single culture to 
            // be much faster.
            //

            // The reason we use a SortedDictionary here is to ensure the resources are applied
            // in an order consistent with codedom deserialization. 
            SortedList<string, object> resources;

            if (_resourceSets == null)
            {
                ResourceSet dummy;
                _resourceSets = new Hashtable();
                resources = FillResources(culture, out dummy);
                _resourceSets[culture] = resources;
            }
            else
            {
                resources = (SortedList<string, object>)_resourceSets[culture];
                if (resources == null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase))
                {
                    ResourceSet dummy;
                    resources = FillResources(culture, out dummy);
                    _resourceSets[culture] = resources;
                }
            }

            BindingFlags flags = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance;
            if (IgnoreCase)
            {
                flags |= BindingFlags.IgnoreCase;
            }

            bool componentReflect = false;
            if (value is IComponent)
            {
                ISite site = ((IComponent)value).Site;
                if (site != null && site.DesignMode)
                {
                    componentReflect = true;
                }
            }

            foreach (KeyValuePair<string, object> kvp in resources)
            {
                // See if this key matches our object.
                //
                string key = kvp.Key;
                if (key == null)
                {
                    continue;
                }

                if (IgnoreCase)
                {
                    if (string.Compare(key, 0, objectName, 0, objectName.Length, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        continue;
                    }
                }
                else
                {
                    if (string.CompareOrdinal(key, 0, objectName, 0, objectName.Length) != 0)
                    {
                        continue;
                    }
                }

                // Character after objectName.Length should be a ".", or else we should continue.
                //
                int idx = objectName.Length;
                if (key.Length <= idx || key[idx] != '.')
                {
                    continue;
                }

                // Bypass type descriptor if we are not in design mode.  TypeDescriptor does an attribute
                // scan which is quite expensive.
                //
                string propName = key.Substring(idx + 1);

                if (componentReflect)
                {
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(value).Find(propName, IgnoreCase);

                    if (prop != null && !prop.IsReadOnly && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value)))
                    {
                        prop.SetValue(value, kvp.Value);
                    }
                }
                else
                {
                    PropertyInfo prop = null;

                    try
                    {
                        prop = value.GetType().GetProperty(propName, flags);
                    }
                    catch (AmbiguousMatchException)
                    {
                        // Looks like we ran into a conflict between a declared property and an inherited one.
                        // In such cases, we choose the most declared one.
                        Type t = value.GetType();
                        do
                        {
                            prop = t.GetProperty(propName, flags | BindingFlags.DeclaredOnly);
                            t = t.BaseType;
                        } while (prop == null && t != null && t != typeof(object));
                    }

                    if (prop != null && prop.CanWrite && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value)))
                    {
                        prop.SetValue(value, kvp.Value, null);
                    }
                }
            }
        }
示例#49
0
 public void GetTypeFromProgID_Unix()
 {
     Assert.Null(Type.GetTypeFromProgID(TestProgID, throwOnError: false));
     Assert.Throws <PlatformNotSupportedException>(() => Type.GetTypeFromProgID(TestProgID, throwOnError: true));
 }
 public override bool CanConvert(Type objectType)
 {
     return objectType == typeof(byte[]);
 }
示例#51
0
 public void GetTypeFromCLSID_Unix()
 {
     Assert.Null(Marshal.GetTypeFromCLSID(Guid.Empty));
     Assert.Null(Type.GetTypeFromCLSID(Guid.Empty, throwOnError: false));
     Assert.Throws <PlatformNotSupportedException>(() => Type.GetTypeFromCLSID(Guid.Empty, throwOnError: true));
 }
示例#52
0
        private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
        {
            ApiDescription apiDescription = apiModel.ApiDescription;

            foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
            {
                if (apiParameter.Source == ApiParameterSource.FromUri)
                {
                    HttpParameterDescriptor parameterDescriptor        = apiParameter.ParameterDescriptor;
                    Type                        parameterType          = null;
                    ModelDescription            typeDescription        = null;
                    ComplexTypeModelDescription complexTypeDescription = null;
                    if (parameterDescriptor != null)
                    {
                        parameterType          = parameterDescriptor.ParameterType;
                        typeDescription        = modelGenerator.GetOrCreateModelDescription(parameterType);
                        complexTypeDescription = typeDescription as ComplexTypeModelDescription;
                    }

                    // Example:
                    // [TypeConverter(typeof(PointConverter))]
                    // public class Point
                    // {
                    //     public Point(int x, int y)
                    //     {
                    //         X = x;
                    //         Y = y;
                    //     }
                    //     public int X { get; set; }
                    //     public int Y { get; set; }
                    // }
                    // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
                    //
                    // public class Point
                    // {
                    //     public int X { get; set; }
                    //     public int Y { get; set; }
                    // }
                    // Regular complex class Point will have properties X and Y added to UriParameters collection.
                    if (complexTypeDescription != null &&
                        !IsBindableWithTypeConverter(parameterType))
                    {
                        foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
                        {
                            apiModel.UriParameters.Add(uriParameter);
                        }
                    }
                    else if (parameterDescriptor != null)
                    {
                        ParameterDescription uriParameter =
                            AddParameterDescription(apiModel, apiParameter, typeDescription);

                        if (!parameterDescriptor.IsOptional)
                        {
                            uriParameter.Annotations.Add(new ParameterAnnotation()
                            {
                                Documentation = "Required"
                            });
                        }

                        object defaultValue = parameterDescriptor.DefaultValue;
                        if (defaultValue != null)
                        {
                            uriParameter.Annotations.Add(new ParameterAnnotation()
                            {
                                Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture)
                            });
                        }
                    }
                    else
                    {
                        Debug.Assert(parameterDescriptor == null);

                        // If parameterDescriptor is null, this is an undeclared route parameter which only occurs
                        // when source is FromUri. Ignored in request model and among resource parameters but listed
                        // as a simple string here.
                        ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
                        AddParameterDescription(apiModel, apiParameter, modelDescription);
                    }
                }
            }
        }
 protected AspectAttribute(Type interceptorType)
 {
     InterceptorType = interceptorType;
 }
示例#54
0
        private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
        {
            parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
                p => p.Source == ApiParameterSource.FromBody ||
                (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));

            if (parameterDescription == null)
            {
                resourceType = null;
                return(false);
            }

            resourceType = parameterDescription.ParameterDescriptor.ParameterType;

            if (resourceType == typeof(HttpRequestMessage))
            {
                HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
                resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
            }

            if (resourceType == null)
            {
                parameterDescription = null;
                return(false);
            }

            return(true);
        }
示例#55
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return((int)value);
 }
示例#56
0
 /// <summary>
 /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
 /// The help page will use this information to produce more accurate response samples.
 /// </summary>
 /// <param name="config">The <see cref="HttpConfiguration"/>.</param>
 /// <param name="type">The type.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 /// <param name="parameterNames">The parameter names.</param>
 public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
 {
     config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
 }
示例#57
0
 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
 {
     throw new NotImplementedException();
 }
示例#58
0
 public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
 {
     throw new NotImplementedException();
 }
		protected override string Convert (int value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			return value > 0 ? $"{value} min" : "None" ;
		}
示例#60
0
 /// <summary>
 /// Sets the sample directly for all actions with the specified type and media type.
 /// </summary>
 /// <param name="config">The <see cref="HttpConfiguration"/>.</param>
 /// <param name="sample">The sample.</param>
 /// <param name="mediaType">The media type.</param>
 /// <param name="type">The parameter type or return type of an action.</param>
 public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
 {
     config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
 }