C# (CSharp) Class System. Type Code Examples

C# (CSharp) System.Type - 30 examples found. These are the top rated real world C# (CSharp) examples of class System.Type extracted from open source projects. You can rate examples to help us improve the quality of examples
Represents type declarations: class types, interface types, array types, value types, and enumeration types.
Inheritance: System.Reflection.MemberInfo
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(double));
            var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options);

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Double:
                    return bsonReader.ReadDouble();
                case BsonType.Int32:
                    return representationSerializationOptions.ToDouble(bsonReader.ReadInt32());
                case BsonType.Int64:
                    return representationSerializationOptions.ToDouble(bsonReader.ReadInt64());
                case BsonType.String:
                    return XmlConvert.ToDouble(bsonReader.ReadString());
                default:
                    var message = string.Format("Cannot deserialize Double from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
        public override bool CanConvert(Type objectType)
        {
#if !DNX
            useInternal = base.CanConvert(objectType);
#endif
            return useInternal || objectType == typeof(byte[]);
        }
 static string CreateMessage(Type modelType, Type propertyType)
 {
     return string.Format(
         "Model type '{0}' has invalid DebuggerDisplay return type '{1}'. Expected 'string'.",
         modelType.FullName,
         propertyType.Name);
 }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var parameterValue = parameter as String;
            bool toLower = false;
            bool toUpper = false;

            if (parameterValue != null)
            {
                toLower = parameterValue.ToLower().Equals("lower");
                toUpper = parameterValue.ToLower().Equals("upper");
            }

            var inputValue = value as String;
            String returnValue = inputValue;
            if (!String.IsNullOrWhiteSpace(inputValue))
            {
                if (toLower)
                {
                    returnValue = inputValue.ToLower();
                }
                else if (toUpper)
                {
                    returnValue = inputValue.ToUpper();
                }
            }

            return returnValue;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonDynamicContract"/> class.
        /// </summary>
        /// <param name="underlyingType">The underlying type for the contract.</param>
        public JsonDynamicContract(Type underlyingType)
            : base(underlyingType)
        {
            ContractType = JsonContractType.Dynamic;

            Properties = new JsonPropertyCollection(UnderlyingType);
        }
        public override List<ExplorerItem> GetSchema(IConnectionInfo connectionInfo, Type customType)
        {
            var indexDirectory = connectionInfo.DriverData.FromXElement<LuceneDriverData>().IndexDirectory;

            //TODO: Fields with configured delimiters should show up as a tree
            //TODO: Show Numeric and String fields with their types
            //TODO: If the directory selected contains sub-directories, maybe we should show them all...

            using (var directory = FSDirectory.Open(new DirectoryInfo(indexDirectory)))
            using (var indexReader = IndexReader.Open(directory, true))
            {
                return indexReader
                    .GetFieldNames(IndexReader.FieldOption.ALL)
                    .Select(fieldName =>
                    {
                        //var field = //TODO: Get the first document with this field and get its types.
                        return new ExplorerItem(fieldName, ExplorerItemKind.QueryableObject, ExplorerIcon.Column)
                        {
                            IsEnumerable = false,       //TODO: Should be true when its a multi-field
                            ToolTipText = "Cool tip"
                        };
                    })
                    .ToList();
            }
        }
Example #7
0
        public void DeleteById(Type type, string key, string value)
        {
            string sql = "delete from " + type.Name;
            sql += " where " + key + "=" + value;

            DBExtBase.ExeNonQueryBySqlText(this.dataCtx, sql);
        }
	public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
	{
		if (context == null)
			return false;
		var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
		return p != null && destinationType == typeof (string);
	}
	public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
	{
		if (context == null)
			return null;
		var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
		return p != null ? p.GetName (value) : null;
	}
        public object Convert(object[] values,
                              Type targetType,
                              object parameter,
                              System.Globalization.CultureInfo culture)
        {
            if (values == null ||
                values.Length != 2)
            {
                return Visibility.Collapsed;
            }

            if (values[0] is IEnumerable<string>)
            {
                var a = (IEnumerable<string>)values[0];
                var b = values[1];

                if (a.Contains(b) == true)
                {
                    return Visibility.Collapsed;
                }
            }
            else if (values[0] is ItemCollection)
            {
                var a = (ItemCollection)values[0];
                var b = values[1];

                if (a.Contains(b) == true)
                {
                    return Visibility.Collapsed;
                }
            }

            return Visibility.Visible;
        }
 public object[] ConvertBack(object value,
                             Type[] targetTypes,
                             object parameter,
                             System.Globalization.CultureInfo culture)
 {
     throw new NotSupportedException();
 }
	private IEnumerable<PluginWrapper> GetModule(string pFileName, Type pTypeInterface)
	{
		var plugins = new List<PluginWrapper>();
		try
		{
			var assembly = Assembly.LoadFrom(pFileName);
			foreach(var type in assembly.GetTypes())
			{
				try
				{
					if(!type.IsPublic || type.IsAbstract)
						continue;
					var typeInterface = type.GetInterface(pTypeInterface.ToString(), true);
					if(typeInterface == null)
						continue;
					var instance = Activator.CreateInstance(type) as IPlugin;
					if(instance != null)
						plugins.Add(new PluginWrapper(pFileName, instance));
				}
				catch(Exception ex)
				{
					Logger.WriteLine("Error Loading " + pFileName + ":\n" + ex, "PluginManager");
				}
			}
		}
		catch(Exception ex)
		{
			Logger.WriteLine("Error Loading " + pFileName + ":\n" + ex, "PluginManager");
		}
		return plugins;
	}
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new InvalidOperationException("The target must be boolean.");

            return !(bool)value;
        }
Example #14
0
	public ClassInfo(bool isAbstract, Type superClass, Db4objects.Db4o.Reflect.Self.FieldInfo
		[] fieldInfo)
	{
		_isAbstract = isAbstract;
		_superClass = superClass;
		_fieldInfo = fieldInfo;
	}
        private bool IsValidFixtureType(Type type, ref string reason)
        {
            if (type.IsAbstract)
            {
                reason = string.Format("{0} is an abstract class", type.FullName);
                return false;
            }

            if (Reflect.GetConstructor(type) == null)
            {
                reason = string.Format("{0} does not have a valid constructor", type.FullName);
                return false;
            }

            if (!NUnitFramework.CheckSetUpTearDownMethods(type, NUnitFramework.SetUpAttribute, ref reason) ||
                !NUnitFramework.CheckSetUpTearDownMethods(type, NUnitFramework.TearDownAttribute, ref reason) )
                    return false;

            if ( Reflect.HasMethodWithAttribute(type, NUnitFramework.FixtureSetUpAttribute, true) )
            {
                reason = "TestFixtureSetUp method not allowed on a SetUpFixture";
                return false;
            }

            if ( Reflect.HasMethodWithAttribute(type, NUnitFramework.FixtureTearDownAttribute, true) )
            {
                reason = "TestFixtureTearDown method not allowed on a SetUpFixture";
                return false;
            }

            return true;
        }
 public IEnumerable<Type> GetLoadableTypes(Assembly assembly, Type ofBaseType)
 {
     var types = GetLoadableTypes(assembly);
     return types != null
                ? types.Where(ofBaseType.IsAssignableFrom)
                : null;
 }
Example #17
0
 /// <summary>
 /// Displays help for the specified command.
 /// <param name="Command">Command type.</param>
 /// </summary>
 public static void Help(Type Command)
 {
     string Description;
     List<string> Params;
     GetTypeHelp(Command, out Description, out Params);
     LogHelp(Command, Description, Params);
 }
Example #18
0
 /// <summary>
 /// Compiles the specified template.
 /// </summary>
 /// <param name="key">The string template.</param>
 /// <param name="modelType">The model type.</param>
 public ICompiledTemplate Compile(ITemplateKey key, Type modelType)
 {
     Contract.Requires(key != null);
     var source = Resolve(key);
     var result = CreateTemplateType(source, modelType);
     return new CompiledTemplate(result.Item2, key, source, result.Item1, modelType);
 }
        private static Dictionary<string, AsyncMethodInfo> InternalGetAjaxMethods(Type type)
        {
            var ret = new Dictionary<string, AsyncMethodInfo>();
            var mis = CoreHelper.GetMethodsFromType(type);
            foreach (MethodInfo mi in mis)
            {
                string methodName = mi.Name;
                var method = CoreHelper.GetMemberAttribute<AjaxMethodAttribute>(mi);
                if (method != null)
                {
                    if (!string.IsNullOrEmpty(method.Name))
                    {
                        methodName = method.Name;
                    }

                    if (!ret.ContainsKey(methodName))
                    {
                        AsyncMethodInfo asyncMethod = new AsyncMethodInfo();
                        asyncMethod.Method = mi;
                        asyncMethod.Async = method.Async;
                        ret[methodName] = asyncMethod;
                    }
                }
            }

            return ret;
        }
 public TypePromptDocument Get(Type model, string propertyName)
 {
     return (from p in Prompts
             where p.TypeName == model.Name
                   && p.TextName == propertyName
             select p).FirstOrDefault();
 }
Example #21
0
	protected override Type[] CreateInOutParamTypes(Uiml.Param[] parameters, out Hashtable outputPlaceholder)
	{
		outputPlaceholder = null;
		Type[] tparamTypes =  new Type[parameters.Length]; 
		int i=0;
		try
		{
			for(i=0; i<parameters.Length; i++)
			{
				tparamTypes[i] = Type.GetType(parameters[i].Type);
				int j = 0;
				while(tparamTypes[i] == null)	
					tparamTypes[i] = ((Assembly)ExternalLibraries.Instance.Assemblies[j++]).GetType(parameters[i].Type);
				//also prepare a placeholder when this is an output parameter
				if(parameters[i].IsOut)
				{
					if(outputPlaceholder == null)
						outputPlaceholder = new Hashtable();
					outputPlaceholder.Add(parameters[i].Identifier, null);
				}
			}
			return tparamTypes;
		}
			catch(ArgumentOutOfRangeException aore)
			{
				Console.WriteLine("Can not resolve type {0} of parameter {1} while calling method {2}",parameters[i].Type ,i , Call.Name);
				Console.WriteLine("Trying to continue without executing {0}...", Call.Name);
				throw aore;					
			}
	}
        public void TestRoute(string url, string verb, Type type, string actionName)
        {
            //Arrange
            url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
            url = Host + url;

            //Act
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

            IHttpControllerSelector controller = this.GetControllerSelector();
            IHttpActionSelector action = this.GetActionSelector();

            IHttpRouteData route = this.Config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;

            HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);

            HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
            {
                ControllerDescriptor = controllerDescriptor
            };

            var actionDescriptor = action.SelectAction(context);

            //Assert
            Assert.NotNull(controllerDescriptor);
            Assert.NotNull(actionDescriptor);
            Assert.Equal(type, controllerDescriptor.ControllerType);
            Assert.Equal(actionName, actionDescriptor.ActionName);
        }
Example #23
0
        public static SlayerName GetLootSlayerType(Type type)
        {
            foreach (SlayerGroup grp in m_Groups)
            {
                Type[] foundOn = grp.FoundOn;

                bool inGroup = false;

                for (int j = 0; foundOn != null && !inGroup && j < foundOn.Length; ++j)
                {
                    inGroup = (foundOn[j] == type);
                }

                if (inGroup)
                {
                    int index = Utility.Random(1 + grp.Entries.Length);

                    if (index == 0)
                    {
                        return grp.Super.Name;
                    }

                    return grp.Entries[index - 1].Name;
                }
            }

            return SlayerName.Silver;
        }
        public static IBinding Create(string parameterName, Type parameterType)
        {
            if (parameterType.IsByRef)
            {
                return null;
            }

            if (parameterType.ContainsGenericParameters)
            { 
                return null; 
            }

            Type genericTypeDefinition;

            if (!parameterType.IsValueType)
            {
                genericTypeDefinition = typeof(ClassInvokeBinding<>);
            }
            else
            {
                genericTypeDefinition = typeof(StructInvokeBinding<>);
            }

            Type genericType = genericTypeDefinition.MakeGenericType(parameterType);
            return (IBinding)Activator.CreateInstance(genericType, parameterName);
        }
        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 static void sendMessage(Type nodeType) 
	{
		RawMessage msg = new RawMessage();
		msg.putInt("id", TypeIdGenerator.getMessageId( typeof(LUnlockNodeRequest) ));
		msg.putInt("tid",TypeIdGenerator.getScienceNodeIds (nodeType));
		Network.server.SendMessage(msg);
	}
Example #27
0
        internal IContentSerializer GetSerializer(Type storageType, Type objectType)
        {
            lock (contentSerializers)
            {
                // Process serializer attributes of objectType
                foreach (var contentSerializer in GetSerializers(objectType))
                {
                    if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && (storageType == null || contentSerializer.SerializationType == storageType))
                        return contentSerializer;
                }

                // Process serializer attributes of storageType
                if (storageType != null)
                {
                    foreach (var contentSerializer in GetSerializers(storageType))
                    {
                        if (objectType.GetTypeInfo().IsAssignableFrom(contentSerializer.ActualType.GetTypeInfo()) && contentSerializer.SerializationType == storageType)
                            return contentSerializer;
                    }
                }

                //foreach (var contentSerializerGroup in contentSerializers)
                //{
                //    if (contentSerializerGroup.Key.GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()))
                //    {
                //        return GetSerializer(contentSerializerGroup.Value, storageType);
                //    }
                //}
            }

            return null;
        }
Example #28
0
        public object[] GetParameters(IBuilderContext context, Type type, string id, ConstructorInfo constructor)
        {
            ParameterInfo[] parms = constructor.GetParameters();
            object[] parmsValueArray = new object[parms.Length];

            for (int i = 0; i < parms.Length; ++i)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parms[i].ParameterType))
                {
                    Type genericList = typeof(List<>);
                    Type fullType = genericList.MakeGenericType(parms[i].ParameterType.GetGenericArguments()[0]);
                    parmsValueArray[i] = Activator.CreateInstance(fullType);

                    foreach (object o in Core.Objects.ObjectFactory.BuildAll(parms[i].ParameterType.GetGenericArguments()[0]))
                    {
                        ((IList)parmsValueArray[i]).Add(o);
                    }
                }
                else
                {
                    parmsValueArray[i] = Core.Objects.ObjectFactory.BuildUp(parms[i].ParameterType);
                }
            }
            return parmsValueArray;
        }
 protected override bool IsValidStruct(Type type, string structName)
 {
     switch (structName) {
     case "ccArray":
         return type.Name == "CCArray";
     case "_ccBezierConfig":
         return type.Name == "CCBezierConfig";
     case "_ccBlendFunc":
         return type.Name == "CCBlendFunc";
     case "_ccColor3B":
         return type.Name == "CCColor3B";
     case "ccColor4F":
         return type.Name == "CCColor4F";
     case "_ccGridSize": // =ii
         return type.Name == "Size" || type.Name == "Point";
     case "sCCParticle":
         return type.Name == "CCParticle";
     case "_ccQuad3":
         return type.Name == "CCQuad3";
     case "_ccVertex3F": // =fff
         return type.Name == "Vector3";
     case "_ccV2F_C4B_T2F":
         return type.Name == "CCV2F_C4B_T2F";
     case "_ccV3F_C4B_T2F_Quad":
         return type.Name == "CCV3F_C4B_T2F_Quad";
     default:
         return base.IsValidStruct (type, structName);
     }
 }
Example #30
0
 public RunescapeSpell(int id, string name, int level, int air, int water, int earth, int fire, int mind,
     int body, int cosmic, int chaos, int astral, int nature, int death, int law, int blood, int soul, double exp,
     SpellCategory category, SpellType spellGroup, string description, Type requiredItem, params Type[] ingredients)
 {
     ID = id;
     Name = name;
     Level = level;
     Air = air;
     Water = water;
     Earth = earth;
     Fire = fire;
     Mind = mind;
     Body = body;
     Cosmic = cosmic;
     Chaos = chaos;
     Astral = astral;
     Nature = nature;
     Death = death;
     Law = law;
     Blood = blood;
     Soul = soul;
     Exp = exp;
     Category = category;
     SpellGroup = spellGroup;
     Description = description;
     RequiredItem = requiredItem;
     Ingredients = ingredients;
 }