public static TypeHelper GetHelperForType(Type type) { TypeHelper helper; if (!_cachedTypeLookup.TryGetValue(type, out helper)) { helper = new TypeHelper(type); _cachedTypeLookup[type] = helper; } return helper; }
public NetworkCommandViewModel() { TypeHelp = new TypeHelper(); CppTypeMapping = new ObservableCollection<TypeMap>(); CSharpTypeMapping = new ObservableCollection<TypeMap>(); NetworkCommands = new ObservableCollection<NetworkCommandTreeItemModel>(); }
public override object Read(ref ProtoReader.State state, object value) { return(state.ReadBaseType <TBase, T>(TypeHelper <T> .FromObject(value))); }
public override object Read(ref ProtoReader.State state, object value) { return(deserializer(ref state, TypeHelper <T> .FromObject(value))); }
/// <summary> /// Generate remote method on client side /// </summary> /// <param name="contractType">Type of the contract.</param> /// <param name="method">The method.</param> /// <param name="stream">The stream.</param> public static void GenerateServiceMethod(Type contractType, MethodInfo method, FileStream stream) { if (contractType == null) { ThrowHelper.ThrowArgumentNullException("contractType"); } if (method == null) { ThrowHelper.ThrowArgumentNullException("method"); } if (stream == null) { ThrowHelper.ThrowArgumentNullException("stream"); } OperationContractAttribute ocAnnotation = TypeHelper.GetAttribute <OperationContractAttribute>(method); Write(stream, NEW_LINE_BYTES); Write(stream, CODE_DEBUGGER_STEP_THROUGH_ATTRIBUTE); Write(stream, CODE_PUBLIC_METHOD); // visszatérési érték if (method.ReturnType.Equals(typeof(void))) { Write(stream, VOID); } else { Write(stream, method.ReturnType.FullName); } Write(stream, SPACE); // metódus neve Write(stream, method.Name); Write(stream, BRACKET_LEFT); // paraméterlista if (method.GetParameters().Length > 0) { for (int paramIndex = 0; paramIndex < method.GetParameters().Length; paramIndex++) { // ha több paraméter van, akkor vesszővel és space-el elválasztom őket if (paramIndex > 0) { Write(stream, COMMA); Write(stream, SPACE); } // paraméter typusa Write(stream, method.GetParameters()[paramIndex].ParameterType.FullName); Write(stream, SPACE); // paraméter neve string pName = string.Format("{0}{1}", method.GetParameters()[paramIndex].ParameterType.Name.Substring(0, 1).ToLower(), method.GetParameters()[paramIndex].ParameterType.Name.Substring(1)); Write(stream, String.Format("{0}{1}", pName, paramIndex)); } } Write(stream, BRACKET_RIGHT); Write(stream, NEW_LINE_BYTES); Write(stream, TAB_SPACE_BYTES); Write(stream, TAB_SPACE_BYTES); Write(stream, LEFT_CURLY_BRACE); // metódustörzs kezdete Write(stream, NEW_LINE_BYTES); Write(stream, CODE_DISPOSECHECK); // doDisposeCheck if (!ocAnnotation.IsOneWay) { Write(stream, CODE_RESPONSEMESSAGE_VARIABLE); // ResponseMessage variable declaration } Write(stream, CODE_BEGIN_TRY_BLOCK); // try Write(stream, CODE_CHECK_PROXY_REGISTERED); // proxy registration check Write(stream, NEW_LINE_BYTES); Write(stream, CODE_METHOD_PARAMETER_DECLARATION); // _mps declaration Write(stream, NEW_LINE_BYTES); // paraméter lista: _mpx sorozat if (method.GetParameters().Length > 0) { // paraméterek átadása for (int i = 0; i < method.GetParameters().Length; i++) { Write(stream, String.Format(CODE_METHOD_PARAMETER_ITEM, i, i, method.GetParameters()[i].ParameterType.FullName, i)); // declaration } StringBuilder sb = new StringBuilder(); for (int i = 0; i < method.GetParameters().Length; i++) { if (i > 0) { sb.Append(", "); } sb.Append("_mp"); sb.Append(i); } Write(stream, String.Format(CODE_METHOD_PARAMETER_ARRAY, sb.ToString()).Replace("<REPLACELEFT>", "{").Replace("<REPLACERIGHT>", "}")); Write(stream, NEW_LINE_BYTES); } // message declaration Write(stream, String.Format(CODE_MESSAGE_DECLARATION, ocAnnotation.IsOneWay ? (ocAnnotation.IsReliable ? MessageTypeEnum.Datagram.ToString() : MessageTypeEnum.DatagramOneway.ToString()) : MessageTypeEnum.Request.ToString(), MessageInvokeModeEnum.RequestCallback.ToString(), contractType.FullName, method.Name, ocAnnotation.AllowParallelExecution.ToString().ToLower())); Write(stream, CODE_CONTEXT_FILL_SERVICESIDE); // fill proxyid Write(stream, NEW_LINE_BYTES); // timeout Write(stream, String.Format(CODE_TIMEOUT, contractType.FullName, method.Name)); Write(stream, NEW_LINE_BYTES); // send message and optionally receive response if (ocAnnotation.IsOneWay) { Write(stream, TAB_SPACE_BYTES); // TABs Write(stream, TAB_SPACE_BYTES); Write(stream, TAB_SPACE_BYTES); Write(stream, TAB_SPACE_BYTES); } else { Write(stream, CODE_RESPONSE_MESSAGE_ASSIGN); } Write(stream, CODE_SEND_MESSAGE); WriteEndTryBlock(stream); // try block vége catch ággal if (!ocAnnotation.IsOneWay) { // return value or exception WriteReturnValueAndExceptions(method, stream); } // metódus törzs vége Write(stream, TAB_SPACE_BYTES); Write(stream, TAB_SPACE_BYTES); Write(stream, RIGHT_CURLY_BRACE); Write(stream, NEW_LINE_BYTES); }
private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters?parms) { if (testMethod.Method.IsAbstract) { return(MarkAsNotRunnable(testMethod, "Method is abstract")); } if (!testMethod.Method.IsPublic) { return(MarkAsNotRunnable(testMethod, "Method is not public")); } IParameterInfo[] parameters; parameters = testMethod.Method.GetParameters(); int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) { minArgsNeeded++; } } int maxArgsNeeded = parameters.Length; object?[]? arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) { argsProvided = arglist.Length; } if (testMethod.RunState != RunState.Runnable) { return(false); } } var returnType = testMethod.Method.ReturnType.Type; if (AsyncToSyncAdapter.IsAsyncOperation(testMethod.Method.MethodInfo)) { if (returnType == typeof(void)) { return(MarkAsNotRunnable(testMethod, "Async test method must have non-void return type")); } var voidResult = Reflect.IsVoidOrUnit(AwaitAdapter.GetResultType(returnType)); if (!voidResult && (parms == null || !parms.HasExpectedResult)) { return(MarkAsNotRunnable(testMethod, "Async test method must return an awaitable with a void result when no result is expected")); } if (voidResult && parms != null && parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Async test method must return an awaitable with a non-void result when a result is expected")); } } else if (Reflect.IsVoidOrUnit(returnType)) { if (parms != null && parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result")); } } else if (parms == null || !parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected")); } if (argsProvided > 0 && maxArgsNeeded == 0) { return(MarkAsNotRunnable(testMethod, "Arguments provided for method with no parameters")); } if (argsProvided == 0 && minArgsNeeded > 0) { return(MarkAsNotRunnable(testMethod, "No arguments were provided")); } if (argsProvided < minArgsNeeded) { return(MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded))); } if (argsProvided > maxArgsNeeded) { return(MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded))); } if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { if (!new GenericMethodHelper(testMethod.Method.MethodInfo).TryGetTypeArguments(arglist, out var typeArguments)) { return(MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method")); } testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (parms != null && parms.TestName != null && parms.TestName.Trim() == "") { return(MarkAsNotRunnable(testMethod, "Test name cannot be all white-space or empty.")); } if (arglist != null && parameters != null) { TypeHelper.ConvertArgumentList(arglist, parameters); } return(true); }
/// <summary> /// Executes an instance method with parameters. Returns a dynamic object. /// </summary> /// <param name="obj">Instance which will be instanciated to call the method.</param> /// <param name="parameters">Anonymous object with properties matching the parameter names of the method.</param> /// <returns></returns> public static dynamic ExecuteMethod(object obj, dynamic parameters) { WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); #if NET45 WindowsImpersonationContext impersonatedUser = windowsIdentity.Impersonate(); #endif #if NETSTANDARD20 return WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () => #endif { var frame = new StackTrace().GetFrames().Skip(1).First(x => x.GetMethod().DeclaringType.Namespace != "System.Dynamic"); string methodName = frame.GetMethod().Name; ManagementClass genericClass = new ManagementClass(TypeHelper.GetNamespace(obj), TypeHelper.GetClassName(obj), null); ManagementObject instance = TypeHelper.GetManagementObject(genericClass, obj); ManagementBaseObject inParams = genericClass.GetMethodParameters(methodName); foreach (PropertyInfo p in parameters.GetType().GetProperties()) { inParams[p.Name] = p.GetValue(parameters); } ManagementBaseObject result = instance.InvokeMethod(methodName, inParams, null); return result == null ? null : TypeHelper.LoadDynamicObject(result); } #if NETSTANDARD20 ); #endif }
private static IEdmType GetEdmType(IEdmModel edmModel, Type clrType, bool testCollections) { Contract.Assert(edmModel != null); Contract.Assert(clrType != null); IEdmPrimitiveType primitiveType = GetEdmPrimitiveTypeOrNull(clrType); if (primitiveType != null) { return(primitiveType); } else { if (testCollections) { Type enumerableOfT = ExtractGenericInterface(clrType, typeof(IEnumerable <>)); if (enumerableOfT != null) { Type elementClrType = enumerableOfT.GetGenericArguments()[0]; // IEnumerable<SelectExpandWrapper<T>> is a collection of T. Type entityType; if (IsSelectExpandWrapper(elementClrType, out entityType)) { elementClrType = entityType; } IEdmType elementType = GetEdmType(edmModel, elementClrType, testCollections: false); if (elementType != null) { return(new EdmCollectionType(elementType.ToEdmTypeReference(IsNullable(elementClrType)))); } } } Type underlyingType = TypeHelper.GetUnderlyingTypeOrSelf(clrType); if (underlyingType.IsEnum) { clrType = underlyingType; } // search for the ClrTypeAnnotation and return it if present IEdmType returnType = edmModel .SchemaElements .OfType <IEdmType>() .Select(edmType => new { EdmType = edmType, Annotation = edmModel.GetAnnotationValue <ClrTypeAnnotation>(edmType) }) .Where(tuple => tuple.Annotation != null && tuple.Annotation.ClrType == clrType) .Select(tuple => tuple.EdmType) .SingleOrDefault(); // default to the EdmType with the same name as the ClrType name returnType = returnType ?? edmModel.FindType(clrType.EdmFullName()); if (clrType.BaseType != null) { // go up the inheritance tree to see if we have a mapping defined for the base type. returnType = returnType ?? GetEdmType(edmModel, clrType.BaseType, testCollections); } return(returnType); } }
/// <summary> /// Creates the ISample's implementation with the specified name. /// </summary> /// <returns>The sample implementation instance.</returns> /// <param name="name">The sample name.</param> /// <param name="constructorArgs">Constructor arguments.</param> public static ISampleController CreateSampleControllerByName(string name, params object[] constructorArgs) { return(TypeHelper.CreateInstanceByName <ISampleController>(name, constructorArgs)); }
/// <summary> /// Gets the available sample names. /// </summary> /// <returns>The sample names.</returns> public static IList <string> GetSampleControllerNames() { return(TypeHelper.GetDisplayNamesByInterface <ISampleController>()); }
/// <summary> /// Gets available sample types. /// </summary> /// <returns>All available sample types.</returns> public static IList <Type> GetSampleControllerTypes() { return(TypeHelper.GetTypesByInterface <ISampleController>()); }
/// <summary> /// Discovers fields from configuration properties marked with the field attribute. /// </summary> private static List <ConfigurationField> DiscoverFields() { var fields = new List <ConfigurationField>(); var properties = TypeHelper.CachedDiscoverableProperties(typeof(TConfiguration)); foreach (var property in properties) { var attribute = property.GetCustomAttribute <ConfigurationFieldAttribute>(false); if (attribute == null) { continue; } ConfigurationField field; // if the field does not have its own type, use the base type if (attribute.Type == null) { field = new ConfigurationField { // if the key is empty then use the property name Key = string.IsNullOrWhiteSpace(attribute.Key) ? property.Name : attribute.Key, Name = attribute.Name, PropertyName = property.Name, PropertyType = property.PropertyType, Description = attribute.Description, HideLabel = attribute.HideLabel, View = attribute.View }; fields.Add(field); continue; } // if the field has its own type, instantiate it try { field = (ConfigurationField)Activator.CreateInstance(attribute.Type); } catch (Exception ex) { throw new Exception($"Failed to create an instance of type \"{attribute.Type}\" for property \"{property.Name}\" of configuration \"{typeof(TConfiguration).Name}\" (see inner exception).", ex); } // then add it, and overwrite values if they are assigned in the attribute fields.Add(field); field.PropertyName = property.Name; field.PropertyType = property.PropertyType; if (!string.IsNullOrWhiteSpace(attribute.Key)) { field.Key = attribute.Key; } // if the key is still empty then use the property name if (string.IsNullOrWhiteSpace(field.Key)) { field.Key = property.Name; } if (!string.IsNullOrWhiteSpace(attribute.Name)) { field.Name = attribute.Name; } if (!string.IsNullOrWhiteSpace(attribute.View)) { field.View = attribute.View; } if (!string.IsNullOrWhiteSpace(attribute.Description)) { field.Description = attribute.Description; } if (attribute.HideLabelSettable.HasValue) { field.HideLabel = attribute.HideLabel; } } return(fields); }
private void Generate <T>(Action <T> action) where T : class, new() { //获取内部自定义属性 CustomerSectionAttribute sectionAttribute = AttributeHelper.GetCustomerAttribute <CustomerSectionAttribute>(typeof(T)); if (sectionAttribute == null) { LoadFailedHandler(null); throw new Exception("无法获取配置项,因为该配置节点没有标记CustomerSectionAttribute属性。"); } T section = new T(); List <FieldWithAttribute <CustomerFieldAttribute> > fields = TypeHelper.GetFields <CustomerFieldAttribute>(section.GetType()); if (fields == null || fields.Count == 0) { return; } var checkResult = fields.Where(attribute => attribute.Attribute.IsList && (String.IsNullOrEmpty(attribute.Attribute.ElementName) || attribute.Attribute.ElementType == null)); if (checkResult.Count() > 0) { LoadFailedHandler(null); throw new Exception("无法加载本地配置文件,因为如果将一个CustomerFieldAttribute的IsList = true, 则必须标记该属性的ElementName以及ElementType字段值。"); } //获取指定配置节 XmlNode spNode = _xmlDocument.ChildNodes[0].ChildNodes[1].ChildNodes.Cast <XmlNode>().Where(child => child.Name == sectionAttribute.Name).First(); if (spNode == null) { return; } List <InnerXmlNodeInfomation> nodes = XmlHelper.GetNodes(spNode.ChildNodes); if (nodes == null || nodes.Count == 0) { return; } var items = nodes.Where(node => node.Name != "#comment").GroupBy(node => node.Name); var result = items.Select( node => new { GroupInfomation = node, FieldAttribute = fields.Where(field => node.Key == (field.Attribute.IsList ? field.Attribute.ElementName : field.Attribute.Name)).FirstOrDefault() }); var last = result.Where(res => res.FieldAttribute != null); if (last.Count() > 0) { foreach (var item in last) { //不是列表形式的 if (!item.FieldAttribute.Attribute.IsList) { InnerGetSingelConfiguration(section, item.FieldAttribute, item.GroupInfomation.First()); } else if (item.FieldAttribute.Attribute.IsList) { InnerGetListConfiguration(section, item.FieldAttribute, item.GroupInfomation); } } } action(section); LoadSuccessfullyHandler(null); }
/// <summary> /// Compare a single property of a class /// </summary> /// <param name="parms"></param> /// <param name="info"></param> /// <param name="object2Properties"></param> private void CompareProperty(CompareParms parms, PropertyEntity object1Property, PropertyEntity object2Property) { //If we can't read it, skip it if (object1Property?.CanRead == false || object2Property.CanRead == false) { return; } //Skip if this is a shallow compare if (!parms.Config.CompareChildren && TypeHelper.CanHaveChildren(object1Property?.PropertyType) || !parms.Config.CompareChildren && TypeHelper.CanHaveChildren(object2Property.PropertyType)) { return; } //Skip if it should be excluded based on the configuration if (object1Property?.PropertyInfo != null && ExcludeLogic.ShouldExcludeMember(parms.Config, object1Property.PropertyInfo) || object2Property.PropertyInfo != null && ExcludeLogic.ShouldExcludeMember(parms.Config, object2Property.PropertyInfo)) { return; } //If we should ignore read only, skip it if (!parms.Config.CompareReadOnly && object1Property?.CanWrite == false || !parms.Config.CompareReadOnly && object2Property.CanWrite == false) { return; } //If the property does not exist, and we are ignoring the object types, skip it //We need to disscus this!!!! //if (parms.Config.IgnoreObjectTypes && secondObjectInfo == null) // return; object objectValue1 = object1Property?.Value; object objectValue2 = object2Property?.Value; /* * //need deep investigation about indexerComparer!!! * if (!IsValidIndexer(parms.Config, object1Property, parms.BreadCrumb)) * { * objectValue1 = object1Property.Value; * objectValue2 = object2Property != null ? object2Property.Value : null; * } * else * { * _indexerComparer.CompareIndexer(parms, object1Property); * return; * } * //need deep investigation about indexerComparer!!! */ bool object1IsParent = objectValue1 != null && (objectValue1 == parms.Object1 || parms.Object1.GetHashCode().Equals(objectValue1.GetHashCode())); bool object2IsParent = objectValue2 != null && (objectValue2 == parms.Object2 || parms.Object2.GetHashCode().Equals(objectValue2.GetHashCode())); //Skip properties where both point to the corresponding parent if ((TypeHelper.IsClass(object1Property?.PropertyType) || TypeHelper.IsInterface(object1Property?.PropertyType) || TypeHelper.IsStruct(object1Property?.PropertyType) || TypeHelper.IsClass(object2Property.PropertyType) || TypeHelper.IsInterface(object2Property.PropertyType) || TypeHelper.IsStruct(object2Property.PropertyType)) && (object1IsParent && object2IsParent)) { return; } string currentBreadCrumb = AddBreadCrumb(parms.Config, parms.BreadCrumb, object1Property.Name); CompareParms childParms = new CompareParms { Result = parms.Result, Config = parms.Config, ParentObject1 = parms.Object1, ParentObject2 = parms.Object2, Object1 = objectValue1, Object2 = objectValue2, BreadCrumb = currentBreadCrumb }; _rootComparer.Compare(childParms); }
private static IEnumerable <Type> GetMatchingTypes(string edmFullName, IAssembliesResolver assembliesResolver) { return(TypeHelper.GetLoadedTypes(assembliesResolver).Where(t => t.IsPublic && t.EdmFullName() == edmFullName)); }
void LoadParameterOrNull(ParameterInfo pi, Type type) { EmitHelper emit = Context.MethodBuilder.Emitter; object[] attrs = pi.GetCustomAttributes(typeof(ParamNullValueAttribute), true); object nullValue = attrs.Length == 0 ? null : ((ParamNullValueAttribute)attrs[0]).Value; Label labelNull = emit.DefineLabel(); Label labelEndIf = emit.DefineLabel(); if (pi.Attributes == ParameterAttributes.Out) { emit .ldnull .end() ; return; } if (nullValue != null) { Type nullValueType = type; bool isNullable = TypeHelper.IsNullable(type); if (type.IsEnum) { nullValueType = Enum.GetUnderlyingType(type); nullValue = System.Convert.ChangeType(nullValue, nullValueType); } else if (isNullable) { nullValueType = type.GetGenericArguments()[0]; emit .ldarga(pi) .call(type, "get_HasValue") .brfalse(labelNull) ; } if (nullValueType == nullValue.GetType() && emit.LoadWellKnownValue(nullValue)) { if (nullValueType == typeof(string)) emit .ldargEx(pi, false) .call(nullValueType, "Equals", nullValueType) .brtrue(labelNull) ; else if (isNullable) emit .ldarga(pi) .call(type, "get_Value") .beq(labelNull) ; else emit .ldargEx(pi, false) .beq(labelNull) ; } else { string nullString = TypeDescriptor.GetConverter(nullValue).ConvertToInvariantString(nullValue); FieldBuilder staticField = CreateNullValueField(nullValueType, nullString); MethodInfo miEquals = new TypeHelper(nullValueType).GetPublicMethod("Equals", nullValueType); if (miEquals == null) { // Is it possible? // throw new TypeBuilderException(string.Format( Resources.DataAccessorBuilder_EqualsMethodIsNotPublic, type.FullName)); } if (isNullable) emit .ldsflda(staticField) .ldarga(pi) .call(pi.ParameterType, "get_Value") ; else emit .ldsflda(staticField) .ldarg(pi) ; if (miEquals.GetParameters()[0].ParameterType.IsClass) emit .boxIfValueType(nullValueType) ; emit .call(miEquals) .brtrue(labelNull) ; } } if (type.IsEnum) emit .ldloc(_locManager) .callvirt(typeof(DbManager).GetProperty("MappingSchema").GetGetMethod()) ; emit .ldargEx(pi, true) ; if (type.IsEnum) emit .ldc_i4_1 .callvirt(typeof(MappingSchema), "MapEnumToValue", typeof(object), typeof(bool)) ; if (nullValue != null) { emit .br(labelEndIf) .MarkLabel(labelNull) .ldnull .MarkLabel(labelEndIf) ; } }
private void TraverseClassFieldTree(XmlDocument xmlDocument, XmlElement xmlElement, ClassField classField) { var fieldLabel = classField.FieldName; if (!string.IsNullOrEmpty(fieldLabel)) { var splitted = fieldLabel.Split(new char[] { '.' }); fieldLabel = splitted[splitted.Count() - 1]; } var element = xmlDocument.CreateElement(fieldLabel); if (xmlElement == null) { xmlDocument.AppendChild(element); } else { xmlElement.AppendChild(element); } if (classField.IsBasicType() || classField.FieldType.IsEnum) { var htmlEncoding = new HtmlEncoding(); element.InnerText = classField.FieldValue == null ? "" : htmlEncoding.HtmlEncode(classField.FieldValue.ToString()); return; } var traverseFields = true; if ((classField.FieldType.IsArray || classField.FieldType.GetGenericArguments().Count() > 0) && classField.FieldValue != null) { traverseFields = false; var typeHelper = new TypeHelper(); var childFieldValues = (IList)classField.FieldValue; foreach (var childFieldValue in childFieldValues) { var isBasicType = typeHelper.IsBasicType(childFieldValue.GetType()); if (!isBasicType) { traverseFields = true; break; } var subChildField = new ClassField(childFieldValue.GetType().Name, classField.Fields[0].FieldType, childFieldValue); TraverseClassFieldTree(xmlDocument, element, subChildField); } } if (!traverseFields) { return; } foreach (var field in classField.Fields) { TraverseClassFieldTree(xmlDocument, element, field); } }
/// <summary> /// Gets the sample type by the name. /// </summary> /// <returns>The sample type.</returns> /// <param name="name">The name of sample.</param> public static Type GetSampleControllerTypeByName(string name) { return(TypeHelper.GetTypeByName <ISampleController>(name)); }
/// <summary> /// Executes WMI instance method with no parameter. Returns an object of specified type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj">Instance which will be instanciated to call the method.</param> /// <returns></returns> public static T ExecuteMethod<T>(object obj) { WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); #if NET45 WindowsImpersonationContext impersonatedUser = windowsIdentity.Impersonate(); #endif #if NETSTANDARD20 return WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () => #endif { var mth = new StackTrace().GetFrame(1).GetMethod(); string methodName = mth.Name; ManagementClass genericClass = new ManagementClass(TypeHelper.GetNamespace(obj), TypeHelper.GetClassName(obj), null); ManagementObject instance = TypeHelper.GetManagementObject(genericClass, obj); ManagementBaseObject result = instance.InvokeMethod(methodName, null, null); return (T)TypeHelper.LoadObject(result, typeof(T)); } #if NETSTANDARD20 ); #endif }
/// <summary> /// Returns true if both objects are an IP End Point /// </summary> /// <param name="type1">The type of the first object</param> /// <param name="type2">The type of the second object</param> /// <returns></returns> public override bool IsTypeMatch(Type type1, Type type2) { return(TypeHelper.IsIpEndPoint(type1) && TypeHelper.IsIpEndPoint(type2)); }
protected override IList <Type> GetActionTypes() { return(_actionTypeCache.GetOrAdd(typeof(EventPipelineActionBase), t => TypeHelper.GetDerivedTypes <EventPipelineActionBase>(new[] { typeof(EventPipeline).Assembly }).SortByPriority())); }
public bool CanHandleType(Type t) { return(serializer.CanHandleType(t) || serializer.CanHandleType(TypeHelper.GetUnderlyingNullableType(t))); }
public override ExpressionSyntax Visit(ConversionContext context, TypeExpr expr) { return(SyntaxFactory.ParseTypeName(TypeHelper.ConvertType(expr.getType().toString()))); }
/// <summary> /// Returns true if the both objects are a class /// </summary> /// <param name="type1">The type of the first object</param> /// <param name="type2">The type of the second object</param> /// <returns></returns> public override bool IsTypeMatch(Type type1, Type type2) { return((TypeHelper.IsClass(type1) && TypeHelper.IsClass(type2)) || (TypeHelper.IsInterface(type1) && TypeHelper.IsInterface(type2))); }
private void btn_confirm_Click(object sender, RoutedEventArgs e) { int temp = 0; if (!string.IsNullOrEmpty(tb_next.Text) && !int.TryParse(tb_next_value.Text, out temp)) { MsgBox.Show("前节点权值必须为整数"); tb_next_value.Focus(); return; } if (!string.IsNullOrEmpty(tb_left.Text) && !int.TryParse(tb_left_value.Text, out temp)) { MsgBox.Show("左节点权值必须为整数"); tb_left_value.Focus(); return; } if (!string.IsNullOrEmpty(tb_right.Text) && !int.TryParse(tb_right_value.Text, out temp)) { MsgBox.Show("右节点权值必须为整数"); tb_right_value.Focus(); return; } if (!string.IsNullOrEmpty(tb_back.Text) && !int.TryParse(tb_back_value.Text, out temp)) { MsgBox.Show("后节点权值必须为整数"); tb_back_value.Focus(); return; } if (!string.IsNullOrEmpty(tb_x.Text) && !int.TryParse(tb_x.Text, out temp)) { MsgBox.Show("坐标必须为整数"); tb_x.Focus(); return; } if (!string.IsNullOrEmpty(tb_y.Text) && !int.TryParse(tb_y.Text, out temp)) { MsgBox.Show("坐标必须为整数"); tb_y.Focus(); return; } RouteInfo myInfo = new RouteInfo(); myInfo.Routecode = tb_routecode.Text; myInfo.Isstart = 0; int way = 0; myInfo.Nextroutecode = tb_next.Text; myInfo.Nextroutevalue = TypeHelper.StrToInt(tb_next_value.Text); if (!string.IsNullOrEmpty(myInfo.Nextroutecode)) { way++; } myInfo.Leftroutecode = tb_left.Text; myInfo.Leftroutevalue = TypeHelper.StrToInt(tb_left_value.Text); if (!string.IsNullOrEmpty(myInfo.Leftroutecode)) { way++; } myInfo.Rightroutecode = tb_right.Text; myInfo.Rightroutevalue = TypeHelper.StrToInt(tb_right_value.Text); if (!string.IsNullOrEmpty(myInfo.Rightroutecode)) { way++; } myInfo.Backroutecode = tb_back.Text; myInfo.Backroutevalue = TypeHelper.StrToInt(tb_back_value.Text); if (!string.IsNullOrEmpty(myInfo.Backroutecode)) { way++; } myInfo.Routewaycount = way; myInfo.Createtime = DateTime.Now; myInfo.Updatetime = DateTime.Now; myInfo.IsValid = 1; myInfo.X = TypeHelper.StrToInt(tb_x.Text); myInfo.Y = TypeHelper.StrToInt(tb_y.Text); myInfo.HouseId = houseId; RouteService x_rService = new RouteService(); if (MyRoute != null) { } else { x_rService.Insert(myInfo); } MyRoute = null; IndexView.InitData(); this.Close(); }
// consolidate "val != 3 and val != 4 and val != 5" // to "val not in (3, 4, 5)" private static void HandleConsolidateNotEqual(IList <FilterSpecParam> parameters, FilterParamExprMap filterParamExprMap, string statementName) { IList <FilterSpecParamInValue> values = new List <FilterSpecParamInValue>(); ExprNode lastNotEqualsExprNode = null; foreach (var param in parameters) { if (param is FilterSpecParamConstant) { var constantParam = (FilterSpecParamConstant)param; var constant = constantParam.FilterConstant; values.Add(new FilterForEvalConstantAnyType(constant)); } else if (param is FilterSpecParamEventProp) { var eventProp = (FilterSpecParamEventProp)param; values.Add(new FilterForEvalEventPropMayCoerce(eventProp.ResultEventAsName, eventProp.ResultEventProperty, eventProp.IsMustCoerce, TypeHelper.GetBoxedType(eventProp.CoercionType))); } else if (param is FilterSpecParamEventPropIndexed) { var eventProp = (FilterSpecParamEventPropIndexed)param; values.Add(new FilterForEvalEventPropIndexedMayCoerce(eventProp.ResultEventAsName, eventProp.ResultEventIndex, eventProp.ResultEventProperty, eventProp.IsMustCoerce, TypeHelper.GetBoxedType(eventProp.CoercionType), statementName)); } else { throw new ArgumentException("Unknown filter parameter:" + param.ToString()); } lastNotEqualsExprNode = filterParamExprMap.RemoveEntry(param); } var paramIn = new FilterSpecParamIn(parameters[0].Lookupable, FilterOperator.NOT_IN_LIST_OF_VALUES, values); filterParamExprMap.Put(lastNotEqualsExprNode, paramIn); }
public override void Write(ref ProtoWriter.State state, object value) { serializer(ref state, TypeHelper <T> .FromObject(value)); }
private List <string> GetMatchingSpec(ComparisonResult result, Type type) { //The user defined a key for the order if (result.Config.CollectionMatchingSpec.Keys.Contains(type)) { return(result.Config.CollectionMatchingSpec.First(p => p.Key == type).Value.ToList()); } Type[] typeInterfaces = type.GetInterfaces(); bool matchingInterfacePresent = result.Config.CollectionMatchingSpec.Keys.Any(k => typeInterfaces.Any(t => t == k)); if (matchingInterfacePresent) { return(result.Config.CollectionMatchingSpec.First(p => typeInterfaces.Contains(p.Key)).Value.ToList()); } //Make a key out of primative types, date, decimal, string, guid, and enum of the class List <string> list = Cache.GetPropertyInfo(result, type) .Where(o => o.CanWrite && (TypeHelper.IsSimpleType(o.PropertyType) || TypeHelper.IsEnum(o.PropertyType))) .Select(o => o.Name).ToList(); //Remove members to ignore in the key foreach (var member in result.Config.MembersToIgnore) { list.Remove(member); } return(list); }
public override void Write(ref ProtoWriter.State state, object value) { state.WriteBaseType <TBase>(TypeHelper <T> .FromObject(value)); }
/// <summary> /// PP02전문통신(전화번호) 완료 이벤트 /// </summary> /// <param name="responseData"></param> void pp02_TaskCompleted(WSWD.WmallPos.FX.Shared.NetComm.Response.TaskResponseData responseData) { ChildManager.ShowProgress(false); if (responseData.Response.ResponseState == SocketTrxnResType.Success) { var data = responseData.DataRecords.ToDataRecords <PP02RespData>(); if (data.Length > 0) { if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate() { if (TypeHelper.ToInt32(data[0].CustCount) > 1) { DataTable dtCust = new DataTable(); dtCust.Columns.Add("Col01"); dtCust.Columns.Add("Col02"); for (int i = 0; i < TypeHelper.ToInt32(data[0].CustCount); i++) { dtCust.Rows.Add(new object[] { data[0].CustList[i].CustCardNo.ToString(), data[0].CustList[i].CustName.ToString() }); } //동일 전화번호가 두명이상이면 선택팝업 open if (dtCust.Rows.Count > 0) { using (var pop = ChildManager.ShowPopup(strMsg12, "WSWD.WmallPos.POS.PT.dll", "WSWD.WmallPos.POS.PT.VC.POS_PT_P003", dtCust)) { if (pop.ShowDialog(this) == DialogResult.OK) { if (pop.ReturnResult != null && pop.ReturnResult.Count > 0) { foreach (var item in pop.ReturnResult) { GetServerRegister("1", item.Value.ToString()); break; } } } } } SetControlDisable(false); } if (TypeHelper.ToInt32(data[0].CustCount) <= 1) { GetServerRegister("1", data[0].CustList[0].CustCardNo.ToString()); } }); } else { if (TypeHelper.ToInt32(data[0].CustCount) > 1) { DataTable dtCust = new DataTable(); dtCust.Columns.Add("Col01"); dtCust.Columns.Add("Col02"); for (int i = 0; i < TypeHelper.ToInt32(data[0].CustCount); i++) { dtCust.Rows.Add(new object[] { data[0].CustList[i].CustCardNo.ToString(), data[0].CustList[i].CustName.ToString() }); } //동일 전화번호가 두명이상이면 선택팝업 open if (dtCust.Rows.Count > 0) { using (var pop = ChildManager.ShowPopup(strMsg12, "WSWD.WmallPos.POS.PT.dll", "WSWD.WmallPos.POS.PT.VC.POS_PT_P003", dtCust)) { if (pop.ShowDialog(this) == DialogResult.OK) { if (pop.ReturnResult != null && pop.ReturnResult.Count > 0) { foreach (var item in pop.ReturnResult) { GetServerRegister("1", item.Value.ToString()); break; } } } } } SetControlDisable(false); } if (TypeHelper.ToInt32(data[0].CustCount) <= 1) { GetServerRegister("1", data[0].CustList[0].CustCardNo.ToString()); } } } } else if (responseData.Response.ResponseState == WSWD.WmallPos.FX.Shared.NetComm.SocketTrxnResType.NoInfo) { if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate() { POSDeviceManager.SignPad.RequestPinData(strMsg06, "", "", "", 1, 13); _returnData = null; txtCardNo.Text = ""; txtCustName.Text = ""; txtGradeName.Text = ""; txtDelayPoint.Text = ""; txtAbtyPoint.Text = ""; txtCltePoint.Text = ""; txtRemark.Text = ""; strCustNo = ""; msgBar.Text = responseData.Response.ErrorMessage.ToString(); SetControlDisable(false); }); } else { POSDeviceManager.SignPad.RequestPinData(strMsg06, "", "", "", 1, 13); _returnData = null; txtCardNo.Text = ""; txtCustName.Text = ""; txtGradeName.Text = ""; txtDelayPoint.Text = ""; txtAbtyPoint.Text = ""; txtCltePoint.Text = ""; txtRemark.Text = ""; strCustNo = ""; msgBar.Text = responseData.Response.ErrorMessage.ToString(); SetControlDisable(false); } } else { if (this.InvokeRequired) { this.BeginInvoke((MethodInvoker) delegate() { POSDeviceManager.SignPad.RequestPinData(strMsg06, "", "", "", 1, 13); _returnData = null; txtCardNo.Text = ""; txtCustName.Text = ""; txtGradeName.Text = ""; txtDelayPoint.Text = ""; txtAbtyPoint.Text = ""; txtCltePoint.Text = ""; txtRemark.Text = ""; strCustNo = ""; msgBar.Text = responseData.Response.ErrorMessage.ToString(); SetControlDisable(false); }); } else { POSDeviceManager.SignPad.RequestPinData(strMsg06, "", "", "", 1, 13); _returnData = null; txtCardNo.Text = ""; txtCustName.Text = ""; txtGradeName.Text = ""; txtDelayPoint.Text = ""; txtAbtyPoint.Text = ""; txtCltePoint.Text = ""; txtRemark.Text = ""; strCustNo = ""; msgBar.Text = responseData.Response.ErrorMessage.ToString(); SetControlDisable(false); } } }
CellAlignment CalcAlignment(CellAlignment a, TypeHelper th) { if (th!=null && a == CellAlignment.Auto) if (th.IsNumericType) return CellAlignment.Right; return a; }
private void HandleBundle(IExpression outer, object definition, IExpression instance) { Contract.Requires(outer != null); Contract.Requires(definition != null); if (definition is IParameterDefinition) { var name = ((IParameterDefinition)definition).Name.Value; if (!string.IsNullOrEmpty(name)) { TryAdd(outer, name); } else { // NO OP: implicit this of superclass is not named (e.g., for default ctor of subclass) } } else if (definition is IPropertyDefinition) { var name = ((IPropertyDefinition)definition).Name.Value; Contract.Assume(!string.IsNullOrWhiteSpace(name), Context()); TryAdd(outer, name); } else if (definition is IFieldReference) { var field = ((IFieldReference)definition).ResolvedField; if (!(field is Dummy) && !field.Attributes.Any(a => TypeManager.IsCompilerGenerated(field))) { if (field.IsStatic) { var container = field.ContainingType.ResolvedType; // Celeriac uses reflection-style names for inner types, need to be consistent here var name = string.Join(".", TypeHelper.GetTypeName(container, NameFormattingOptions.UseReflectionStyleForNestedTypeNames), field.Name.Value); TryAdd(outer, name); AddInstanceExpr(container, outer); StaticNames.Add(outer); } else { Contract.Assume(instance != null, "Non-static field reference '" + field.Name + "' has no provided instance; " + Context()); if (instance != null && NameTable.ContainsKey(instance)) { var name = NameTable[instance] + "." + field.Name; TryAdd(outer, name); AddInstanceExpr(Type, outer); } else { // NO OP (we aren't tracking the name of the instance) } } } } else if (definition is IArrayIndexer) { var def = (IArrayIndexer)definition; if (NameTable.ContainsKey(def.IndexedObject)) { TryAdd(outer, FormElementsExpression(NameTable[def.IndexedObject])); // propogate instance expression information if (InstanceExpressionsReferredTypes.ContainsKey(def.IndexedObject)) { AddInstanceExpr(InstanceExpressionsReferredTypes[def.IndexedObject], outer); } } else { // NO OP (we aren't tracking the name of the instance) } } else if (definition is ILocalDefinition) { var def = (ILocalDefinition)definition; TryAdd(outer, "<local>" + def.Name.Value); } else if (definition is IAddressDereference) { // NO OP } else { throw new NotSupportedException("Comparability: Unexpected bundled type " + definition.GetType().Name); } }
private void FillInterfaceMethods(ClassField childField, object underLyingObject, MethodInfo classMethodName) { var result = underLyingObject.GetType().InvokeMember(classMethodName.Name, BindingFlags.InvokeMethod, null, underLyingObject, null); var subChildItem = new ClassField(classMethodName.Name, classMethodName.ReturnType, result); childField.Fields.Add(subChildItem); var typeHelper = new TypeHelper(); if (typeHelper.IsArrayType(result)) { FillClassFieldTree(subChildItem); return; } var resultlist = (IList)result; foreach (var resultItem in resultlist) { var subsubChildItem = new ClassField(resultItem.GetType().ToString(), resultItem.GetType(), resultItem); subChildItem.Fields.Add(subsubChildItem); FillClassFieldTree(subsubChildItem); } }
public override void Visit(IMethodCall call) { var receiver = call.ThisArgument; var callee = call.MethodToCall.ResolvedMethod; if (callee is Dummy || callee.Name is Dummy) { return; } else if (NameTable.ContainsKey(call)) { // TODO ##: can call occur more than once / be referentially equal? return; } var calleeName = callee.Name.Value; Contract.Assume(!string.IsNullOrWhiteSpace(calleeName)); string name = null; if (!call.IsStaticCall && NameTable.ContainsKey(receiver)) { if (callee.ParameterCount == 0) { name = NameTable[call.ThisArgument] + "." + (IsGetter(callee) ? calleeName.Substring("get_".Length) : calleeName + "()"); } else if (IsSetter(callee)) { name = NameTable[call.ThisArgument] + "." + calleeName.Substring("set_".Length); } Parent.Add(call, call.ThisArgument); // propogate the instance information if (InstanceExpressionsReferredTypes.ContainsKey(receiver)) { AddInstanceExpr(InstanceExpressionsReferredTypes[receiver], call); } } // Check for indexes into a List if (!call.IsStaticCall && NameTable.ContainsKey(receiver)) { foreach (var m in MemberHelper.GetImplicitlyImplementedInterfaceMethods(call.MethodToCall.ResolvedMethod)) { var genericDef = TypeHelper.UninstantiateAndUnspecialize(m.ContainingTypeDefinition); if (TypeHelper.TypesAreEquivalent(genericDef, Host.PlatformType.SystemCollectionsGenericIList, true)) { if (m.Name.Value.OneOf("get_Item")) { name = FormElementsExpression(NameTable[call.ThisArgument]); } } } } // Check for indexes into a Dictionary if (!call.IsStaticCall && NameTable.ContainsKey(receiver)) { var genericDef = TypeHelper.UninstantiateAndUnspecialize(receiver.Type); if (TypeHelper.TypesAreEquivalent(genericDef, Host.PlatformType.SystemCollectionsGenericDictionary, true)) { if (callee.Name.Value.OneOf("get_Item")) { // ISSUE #91: this supports the dictionary[..].Value collection; does not support dictionary.Values name = FormElementsExpression(NameTable[call.ThisArgument]) + ".Value"; } } } if (name == null) { // Assign a unique generated name (required for return value comparability) name = "<method>" + calleeName + "__" + methodCallCnt; methodCallCnt++; } TryAdd(call, name); }
public static object BuildObject(IObjectService objectService, IObjectDescription description, IDictionary items, params object[] args) { if (description == null) { return(null); } var objectType = description.ObjectType; if (objectType.IsInterface) { throw new Exception("无法创建接口的实例"); } object instance = null; if (args != null && args.Length > 0) { instance = TypeHelper.CreateObject(objectType, null, true, args); } if (instance == null) { var parameters = description.ConstructorParameters; if (parameters != null) { var length = parameters.Length; if (length > 0) { var types = new Type[length]; var values = new object[length]; for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; types[i] = parameter.Type; values[i] = GetValueFromValueDescription(parameter, objectService); } instance = TypeHelper.CreateObject(objectType, null, true, types, values); } } } if (instance == null) { instance = TypeHelper.CreateObject(objectType, null, true); } //尝试进行属性注入 var properties = description.Properties; if (instance != null && properties != null && properties.Length > 0) { foreach (var property in properties) { var name = property.Name; var value = GetValueFromValueDescription(property, objectService); if (value == null && property.ValueRequired) { throw new Exception($"value of {description.ObjectType}.{property.Name} cannot be resolved."); } if (instance is IPropertyDescriptor descriptor) { descriptor.SetValue(name, value); } else { TypeHelper.SetPropertyValue(instance, name, value); } } } return(instance); }
/// <summary> /// This calls a generic where method.. more explaining to follow /// /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="source"></param> /// <param name="filter"></param> /// <returns></returns> private static IQueryable <TSource> CallGenericWhereMethod <TSource>(IQueryable <TSource> source, BaseFilterQuery filter) { var op = filter.FilterOperation; var concreteType = typeof(TSource); PropertyInfo relationProperty = null; PropertyInfo property = null; MemberExpression left; ConstantExpression right; // {model} var parameter = Expression.Parameter(concreteType, "model"); // Is relationship attribute if (filter.IsAttributeOfRelationship) { relationProperty = concreteType.GetProperty(filter.Relationship.InternalRelationshipName); if (relationProperty == null) { throw new ArgumentException($"'{filter.Relationship.InternalRelationshipName}' is not a valid relationship of '{concreteType}'"); } var relatedType = filter.Relationship.DependentType; property = relatedType.GetProperty(filter.Attribute.InternalAttributeName); if (property == null) { throw new ArgumentException($"'{filter.Attribute.InternalAttributeName}' is not a valid attribute of '{filter.Relationship.InternalRelationshipName}'"); } var leftRelationship = Expression.PropertyOrField(parameter, filter.Relationship.InternalRelationshipName); // Intercept the call if the relationship is type of "HasMany" if (typeof(IEnumerable).IsAssignableFrom(leftRelationship.Type)) { // Create the lambda using "Any" extension method var callExpr = BuildAnyCall(leftRelationship, relatedType, filter); var lambda = Expression.Lambda <Func <TSource, bool> >(callExpr, parameter); return(source.Where(lambda)); } // {model.Relationship} left = Expression.PropertyOrField(leftRelationship, property.Name); } // Is standalone attribute else { property = concreteType.GetProperty(filter.Attribute.InternalAttributeName); if (property == null) { throw new ArgumentException($"'{filter.Attribute.InternalAttributeName}' is not a valid property of '{concreteType}'"); } // {model.Id} left = Expression.PropertyOrField(parameter, property.Name); } try { if (op == FilterOperations.isnotnull || op == FilterOperations.isnull) { right = Expression.Constant(null); } else { // "Like" or "StartWith" or "EndWith" only apply on "string" values if (op == FilterOperations.like || op == FilterOperations.sw || op == FilterOperations.ew) { right = Expression.Constant(filter.PropertyValue, typeof(string)); source = source.Where(Expression.Lambda <Func <TSource, bool> >( GetFilterExpressionLambda(left, right, FilterOperations.isnotnull), parameter) ); } else { // convert the incoming value to the target value type // "1" -> 1 var convertedValue = TypeHelper.ConvertType(filter.PropertyValue, property.PropertyType); // {1} right = Expression.Constant(convertedValue, property.PropertyType); } } var body = GetFilterExpressionLambda(left, right, filter.FilterOperation); var lambda = Expression.Lambda <Func <TSource, bool> >(body, parameter); return(source.Where(lambda)); } catch (FormatException) { throw new JsonApiException(400, $"Could not cast {filter.PropertyValue} to {property.PropertyType.Name}"); } }