protected override void OnEnable() { base.OnEnable(); _propertyToType = new Dictionary<string, TypeData>(); Type targetType = typeof(InteractionMaterial); var it = serializedObject.GetIterator(); while (it.NextVisible(true)) { if (it.propertyType == SerializedPropertyType.ObjectReference) { FieldInfo fieldInfo = targetType.GetField(it.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (fieldInfo == null) { continue; } Type propertyType = fieldInfo.FieldType; var attributeObj = fieldInfo.GetCustomAttributes(typeof(InteractionMaterial.ControllerAttribute), true).FirstOrDefault(); if (attributeObj == null) { continue; } TypeData data = new TypeData(); data.controllerAttribute = attributeObj as InteractionMaterial.ControllerAttribute; data.types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => p.IsSubclassOf(propertyType)) .OrderBy(t => t.Name) .ToList(); if (data.controllerAttribute.AllowNone) { data.types.Insert(0, typeof(void)); } data.dropdownNames = data.types.Select(t => { if (t == typeof(void)) { return "None"; } else { return t.Name; } }).ToArray(); _propertyToType[it.name] = data; } } SerializedProperty prop = serializedObject.FindProperty("_physicMaterialMode"); specifyConditionalDrawing(() => prop.intValue == (int)InteractionMaterial.PhysicMaterialModeEnum.Replace, "_replacementMaterial"); specifyConditionalDrawing("_warpingEnabled", "_warpCurve", "_graphicalReturnTime"); specifyCustomDrawer("_holdingPoseController", controllerDrawer); specifyCustomDrawer("_moveToController", controllerDrawer); specifyCustomDrawer("_suspensionController", controllerDrawer); specifyCustomDrawer("_throwingController", controllerDrawer); specifyCustomDrawer("_layerController", controllerDrawer); }
public void ConstructorArgChecking() { var typeData = new TypeData(context, new TypeDataCache(context), typeof(SimpleTestClass), FudgeFieldNameConvention.Identity); var badTypeData = new TypeData(context, new TypeDataCache(context), GetType(), FudgeFieldNameConvention.Identity); Assert.Throws<ArgumentNullException>(() => new DataContractSurrogate(null, typeData)); Assert.Throws<ArgumentNullException>(() => new DataContractSurrogate(context, null)); Assert.Throws<ArgumentOutOfRangeException>(() => new DataContractSurrogate(context, badTypeData)); }
internal void RegisterTypeData(TypeData data) { lock (cache) { Debug.Assert(!cache.ContainsKey(data.Type)); cache.Add(data.Type, data); } }
public void Setup() { DllExtractor = new DllExtractor(); MockExtractorCollector = new Mock<IExtractorCollector>(); MockExtractorCollector.Setup(x => x.AddProperty(It.IsAny<TypeData>(), It.IsAny<PropertyData>())); BasicTypeData = new TypeData(""); }
/// <summary> /// extract the generic parameters for a type /// </summary> /// <param name="context"></param> /// <param name="typeInfo"></param> /// <param name="type"></param> private void ExtractGenericArguments(IExtractorCollector context, TypeData typeInfo, Type type) { if (!type.IsGenericTypeDefinition) return; foreach (Type parameter in type.GetGenericArguments()) { typeInfo.GenericArguments.Add(new GenericArgumentData { Name = parameter.Name }); } }
public IterLocalVariable(string name, TypeData localType, bool isTypecaseVariable, TypeBuilder enumerator, int index) : base(name, localType, isTypecaseVariable) { this.enumerator = enumerator; this.index = index; fieldBuilder = null; }
private void LoadMemberMap(TypeData type, AnalysisContext context) { this.Members = new Dictionary<IMemberData, IMemberData>(); var map = type.Inner.GetInterfaceMap(this.Interface.Inner); for (int i = 0; i < map.InterfaceMethods.Length; i++) { var source = context.Resolver.Resolve(map.InterfaceMethods[i]); var target = context.Resolver.Resolve(map.TargetMethods[i]); this.Members.Add(source, target); } }
/// <summary> /// Constructs a new <see cref="DotNetSerializableSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public DotNetSerializableSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "DotNetSerializableSurrogate cannot handle " + typeData.Type.FullName); this.context = context; this.type = typeData.Type; this.constructor = FindConstructor(typeData); helper = new SerializationInfoMixin(context, typeData.Type, new BeforeAfterSerializationMixin(context, typeData)); }
/// <summary> /// Constructs a new <see cref="DotNetSerializationSurrogateSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> /// <param name="surrogate">Surrogate that maps the object to or from a <see cref="SerializationInfo"/>.</param> /// <param name="selector">Selector that produced the surrogate.</param> public DotNetSerializationSurrogateSurrogate(FudgeContext context, TypeData typeData, ISerializationSurrogate surrogate, ISurrogateSelector selector) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (surrogate == null) throw new ArgumentNullException("surrogate"); // Don't care if selector is null this.helper = new SerializationInfoMixin(context, typeData.Type, new BeforeAfterSerializationMixin(context, typeData)); this.surrogate = surrogate; this.selector = selector; }
/// <summary> /// Constructs a new <see cref="PropertyBasedSerializationSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public PropertyBasedSerializationSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "PropertyBasedSerializationSurrogate cannot handle " + typeData.Type.FullName); Debug.Assert(typeData.DefaultConstructor != null); // Should have been caught in CanHandle() var constructor = typeData.DefaultConstructor; this.memberSerializer = new MemberSerializerMixin(context, typeData, typeData.Properties, new BeforeAfterSerializationMixin(context, typeData), () => constructor.Invoke(null)); }
/// <summary> /// Constructs a new <see cref="ImmutableSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public ImmutableSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "ImmutableSurrogate cannot handle " + typeData.Type.FullName); this.context = context; this.type = typeData.Type; this.constructor = FindConstructor(typeData.Constructors, typeData.Properties, out constructorParams); Debug.Assert(constructor != null); // Else how did it pass CanHandle? this.helper = new PropertyBasedSerializationSurrogate.PropertySerializerMixin(context, typeData, typeData.Properties, new DotNetSerializableSurrogate.BeforeAfterMethodMixin(context, typeData)); }
/// <summary> /// Constructs a new <see cref="ToFromFudgeMsgSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public ToFromFudgeMsgSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "ToFromFudgeMsgSurrogate cannot handle " + typeData.Type.FullName); this.context = context; this.toFudgeMsgMethod = GetToMsg(typeData); this.fromFudgeMsgMethod = GetFromMsg(typeData); Debug.Assert(toFudgeMsgMethod != null); Debug.Assert(fromFudgeMsgMethod != null); }
/// <summary> /// Gets the type data for a given type, constructing if necessary. /// </summary> /// <param name="type">Type for which to get data.</param> /// <param name="fieldNameConvention">Convention for mapping .net property names to serialized field names.</param> /// <returns><see cref="TypeData"/> for the given type.</returns> public TypeData GetTypeData(Type type, FudgeFieldNameConvention fieldNameConvention) { if (type == null) throw new ArgumentNullException("type"); TypeData result; lock (cache) { if (!cache.TryGetValue(type, out result)) { result = new TypeData(context, this, type, fieldNameConvention); Debug.Assert(cache.ContainsKey(type)); // TypeData registers itself during construction } } return result; }
/// <summary> /// Constructs a new <see cref="SerializableAttributeSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public SerializableAttributeSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "SerializableAttributeSurrogate cannot handle " + typeData.Type.FullName); this.type = typeData.Type; var fields = from field in typeData.Fields where field.GetCustomAttribute<NonSerializedAttribute>() == null select field; var beforeAfterMixin = new DotNetSerializableSurrogate.BeforeAfterMethodMixin(context, typeData); this.serializerMixin = new PropertyBasedSerializationSurrogate.PropertySerializerMixin(context, typeData, fields, beforeAfterMixin); }
/// <summary> /// Constructs a new <see cref="SerializableAttributeSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> public SerializableAttributeSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "SerializableAttributeSurrogate cannot handle " + typeData.Type.FullName); this.type = typeData.Type; var fields = from field in typeData.Fields where field.GetCustomAttribute<NonSerializedAttribute>() == null select field; var type = typeData.Type; // So the closure in the lambda below is as tight as possible var beforeAfterMixin = new BeforeAfterSerializationMixin(context, typeData); this.memberSerializer = new MemberSerializerMixin(context, typeData, fields, beforeAfterMixin, () => FormatterServices.GetUninitializedObject(type)); }
/// <summary> /// Constructs a new instance for a specific type /// </summary> /// <param name="context"><see cref="FudgeContext"/> for this surrogate.</param> /// <param name="typeData"><see cref="TypeData"/> describing the type to serialize.</param> public DataContractSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "ImmutableSurrogate cannot handle " + typeData.Type.FullName); this.context = context; this.type = typeData.Type; Debug.Assert(typeData.DefaultConstructor != null); // Should have been caught in CanHandle() var properties = from prop in typeData.Properties.Concat(typeData.Fields) where prop.GetCustomAttribute<DataMemberAttribute>() != null select prop; this.helper = new PropertyBasedSerializationSurrogate.PropertySerializerMixin(context, typeData, properties, new DotNetSerializableSurrogate.BeforeAfterMethodMixin(context, typeData)); }
/// <summary> /// Constructs a new instance for a specific type /// </summary> /// <param name="context"><see cref="FudgeContext"/> for this surrogate.</param> /// <param name="typeData"><see cref="TypeData"/> describing the type to serialize.</param> public DataContractSurrogate(FudgeContext context, TypeData typeData) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (!CanHandle(typeData)) throw new ArgumentOutOfRangeException("typeData", "ImmutableSurrogate cannot handle " + typeData.Type.FullName); this.context = context; this.type = typeData.Type; Debug.Assert(typeData.DefaultConstructor != null); // Should have been caught in CanHandle() var properties = from prop in typeData.Properties.Concat(typeData.Fields) where prop.GetCustomAttribute<DataMemberAttribute>() != null select prop; var type = typeData.Type; // So the closure in the lambda below is as tight as possible var beforeAfterMixin = new BeforeAfterSerializationMixin(context, typeData); this.memberSerializer = new MemberSerializerMixin(context, typeData, properties, beforeAfterMixin, () => FormatterServices.GetUninitializedObject(type)); }
/// <summary> /// Extract the properties for a type. /// </summary> /// <param name="context"></param> /// <param name="typeInfo"></param> /// <param name="type"></param> public void ExtractProperties(IExtractorCollector context, TypeData typeInfo, Type type) { //this should only get properties either directly on the type or ovverriden on the type. Properties of base classes should not be added PropertyInfo[] properties = type.GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); foreach (PropertyInfo property in properties) { PropertyData propertyData = new PropertyData() { Name = property.Name, TypeName = property.PropertyType.AssemblyQualifiedName, }; AccessType getAccessType = AccessType.None; AccessType setAccessType = AccessType.Private; MethodInfo getMethod = property.GetGetMethod(true); MethodInfo setMethod = property.GetSetMethod(true); MethodInfo anyAccessor = getMethod ?? setMethod; if (getMethod != null) { if (getMethod.IsFamily) getAccessType = AccessType.Protected; else if (getMethod.IsPublic) getAccessType = AccessType.Public; else getAccessType = AccessType.Private; } if (setMethod != null) { if (setMethod.IsFamily) setAccessType = AccessType.Protected; else if (setMethod.IsPublic) setAccessType = AccessType.Public; } propertyData.GetAccessType = getAccessType; propertyData.SetAccessType = setAccessType; propertyData.IsStatic = anyAccessor.IsStatic; propertyData.IsVirtual = anyAccessor.IsVirtual; propertyData.IsAbstract = anyAccessor.IsAbstract; context.AddProperty(typeInfo, propertyData); } }
public async static Task <T> ConvertAsync <T>(ReadOnlyMemory <byte> memory) { var typeData = TypeData.GetTypeData(typeof(T)); var instance = typeData.GetInstance(); var objectStack = new Stack(); objectStack.Push(instance); var currentObject = instance; var unclosedNodes = 0; MemberData member = null; await foreach (var item in FileDBSerializer.EnumerateTreeAsync(memory)) { switch (item.serializingType) { // Node case SerializingType.OpenNode: //Handle non serialized trees if (unclosedNodes != 0) { unclosedNodes++; } //Check data required by member else { currentObject = objectStack.Peek(); typeData = TypeData.GetTypeData(currentObject.GetType()); //Find matching member typeData.UnorderedNodes.TryGetValue(item.Name, out member); //Not required if (member == null) { unclosedNodes++; } //Serialize data else { var memberTypeData = TypeData.GetTypeData(member.Type); object memberObject = null; object value = null; var elementType = member.Type.GetFirstUnderlayingType(); if (elementType == null) { memberObject = memberTypeData.GetInstance(); member.MemberInfo.SetMemberValue(currentObject, memberObject); } else if (member.Type.IsGenericType) { var existingObject = member.MemberInfo.GetMemberValue(currentObject); if (existingObject == null) { existingObject = memberTypeData.GetInstance(); member.MemberInfo.SetMemberValue(currentObject, existingObject); } if (existingObject is IList list) { memberObject = TypeData.GetTypeData(elementType).GetInstance(); list.Add(memberObject); } else { throw new NotImplementedException( $"Type {member.Type} is not supported by the serializer."); } } else { throw new NotImplementedException( $"Type {member.Type} is not supported by the serializer."); } objectStack.Push(memberObject); } } break; // Close Node case SerializingType.CloseNode: if (unclosedNodes > 0) { unclosedNodes--; } else { objectStack.Pop(); } break; // Attribute case SerializingType.Content: currentObject = objectStack.Peek(); typeData = TypeData.GetTypeData(currentObject.GetType()); //Find matching member typeData.UnorderedAttributes.TryGetValue(item.Name, out member); if (member != null) { ReadMember(currentObject, member, in item.Content); break; } break; default: break; } } return((T)instance); }
private static object Union(TypeData thisType, TypeData thatType) { thisType.Instance = (MemberData)Union(thisType.Instance, thatType.Instance); thisType.Static = (MemberData)Union(thisType.Static, thatType.Static); return(thisType); }
public void NonGenericClassTest5() { var expectedTypeData = new TypeData("Namespace1.Class1"); ValidateSuccessfulParseResult(" Namespace1.Class1 ", expectedTypeData); }
protected override String Visit(ExpNode caller, ExpNode node) { if (node is ProjectExpression) { ProjectExpression e = (ProjectExpression)node; if (e.Projections.Count == 0) { return(String.Format("{0}", this.Visit(e, e.Input) )); } else if (e.Projections.Count == 1) { if (e.Projections[0] is PropertyExpression) { return(String.Format("{0}/{1}", this.Visit(e, e.Input), this.Visit(e, e.Projections[0]) )); } } else { throw new Exception("More than 1 projection, invalid"); } } else if (node is ServiceOperationExpression) { AstoriaTestLog.WriteLine("Calling Service Operation"); ServiceOperationExpression e = (ServiceOperationExpression)node; string serviceOp = this.Visit(e, e.Input); AstoriaTestLog.WriteLine(serviceOp); StringBuilder sbParametersString = new StringBuilder(); if (!serviceOp.Contains("?")) { sbParametersString.Append("?"); } for (int index = 0; index < e.Arguments.Length; index++) { ServiceOperationParameterExpression parameter = e.Arguments[index]; if (index > 0) { sbParametersString.Append("&"); } string strLiteralString = CreateKeyStringValue(parameter.ParameterValue); sbParametersString.AppendFormat("{0}={1}", parameter.ParameterName, strLiteralString); } return(String.Format("{0}{1}", serviceOp, sbParametersString.ToString())); } else if (node is ScanExpression) { ScanExpression e = (ScanExpression)node; if (e.Input is VariableExpression && ((VariableExpression)e.Input).Variable is ResourceContainer) { return(String.Format("{0}", this.Visit(e, e.Input) )); } throw new Exception("Unsupported on in scan expression"); } else if (node is PredicateExpression) { PredicateExpression e = (PredicateExpression)node; KeyExpression key = e.Predicate as KeyExpression; if (key != null) { return(String.Format("{0}({1})", this.Visit(e, e.Input), this.Visit(e, e.Predicate) )); } else { return(String.Format("{0}?$filter={1}", this.Visit(e, e.Input), this.Visit(e, e.Predicate) )); } } else if (node is CountExpression) { CountExpression e = (CountExpression)node; string sCount = ""; string visit = ""; if (!e.IsInline) { visit = this.Visit(e, e.Input); sCount = string.Format("{0}/$count", visit); } else { visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) { sCount = string.Format("{0}?$inlinecount={1}", visit, e.CountKind); } else { sCount = string.Format("{0}&$inlinecount={1}", visit, e.CountKind); } } return(sCount); } else if (node is NewExpression) { NewExpression e = (NewExpression)node; string uri = this.Visit(e, e.Input); ExpNode[] pe = new ExpNode[] { }; List <ExpNode> nodes = new List <ExpNode>(); foreach (ExpNode parameter in e.Arguments) { nodes.Add(parameter as ExpNode); } pe = nodes.ToArray(); string _select = String.Format("{0}", this.Visit(e, pe[0])); if (nodes.Count > 1) { for (int j = 1; j < nodes.Count; j++) { _select = String.Format("{0},{1}", _select, this.Visit(e, pe[j])); } } if (uri.IndexOf("?$") == -1) { return(string.Format("{0}?$select={1}", uri, _select)); } else { return(string.Format("{0}&$select={1}", uri, _select)); } } else if (node is MemberBindExpression) { return(this.Visit(node, ((MemberBindExpression)node).SourceProperty)); } else if (node is TopExpression) { TopExpression e = (TopExpression)node; string visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) { return(string.Format("{0}?$top={1}", visit, e.Predicate)); } else { return(string.Format("{0}&$top={1}", visit, e.Predicate)); } } else if (node is SkipExpression) { SkipExpression e = (SkipExpression)node; string visit = this.Visit(e, e.Input); if (visit.IndexOf("?$") == -1) { return(string.Format("{0}?$skip={1}", visit, e.Predicate)); } else { return(string.Format("{0}&$skip={1}", visit, e.Predicate)); } } else if (node is OrderByExpression) { OrderByExpression e = (OrderByExpression)node; string ordervalue = String.Empty; int i = 0; string visit = this.Visit(e, e.Input); if (e.ExcludeFromUri) { return(visit); } string propVisit = this.Visit(e, e.PropertiesExp[0]); switch (e.AscDesc) { case true: if (visit.IndexOf("?$") == -1) { ordervalue = String.Format("{0}?$orderby={1}", visit, propVisit); } else { ordervalue = String.Format("{0}&$orderby={1}", visit, propVisit); } break; case false: if (visit.IndexOf("?$") == -1) { ordervalue = String.Format("{0}?$orderby={1} desc", visit, propVisit); } else { ordervalue = String.Format("{0}&$orderby={1} desc", visit, propVisit); } break; } ; if (e.PropertiesExp.Length > 0) { for (i++; i < e.PropertiesExp.Length; i++) { String nextValue = this.Visit(e, e.PropertiesExp[i]); nextValue = String.Format("{0}", nextValue); switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", ordervalue, nextValue); break; case false: ordervalue = String.Format("{0},{1} desc", ordervalue, nextValue); break; } } } return(ordervalue); } else if (node is ThenByExpression) { ThenByExpression e = (ThenByExpression)node; string ordervalue = String.Empty; int i = 0; string visit = this.Visit(e, e.Input); if (e.ExcludeFromUri) { return(visit); } switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", visit, e.Properties[0].Name); break; case false: ordervalue = String.Format("{0},{1} desc", visit, e.Properties[0].Name); break; } if (e.Properties.Length > 0) { for (i++; i < e.Properties.Length; i++) { String nextValue = e.Properties[i].Name; nextValue = String.Format("{0}", nextValue); switch (e.AscDesc) { case true: ordervalue = String.Format("{0},{1}", ordervalue, nextValue); break; case false: ordervalue = String.Format("{0},{1} desc", ordervalue, nextValue); break; } } } return(ordervalue); } else if (node is ExpandExpression) { ExpandExpression e = (ExpandExpression)node; string uri = this.Visit(e, e.Input); string expand = String.Format("{0}", this.Visit(e, e.PropertiesExp[0])); if (e.Properties.Length > 1) { for (int i = 1; i < e.Properties.Length; i++) { expand = String.Format("{0},{1}", expand, this.Visit(e, e.PropertiesExp[i])); } } if (uri.IndexOf("?$") == -1) { return(string.Format("{0}?$expand={1}", uri, expand)); } else { return(string.Format("{0}&$expand={1}", uri, expand)); } } else if (node is NavigationExpression) { NavigationExpression e = (NavigationExpression)node; if (!e.IsLink) { return(String.Format("{0}/{1}", this.Visit(e, e.Input), this.Visit(e, e.PropertyExp))); } else { return(String.Format("{0}/{1}/$ref", this.Visit(e, e.Input), this.Visit(e, e.PropertyExp))); } } else if (node is KeyExpression) { KeyExpression key = node as KeyExpression; return(CreateKeyString(key)); } else if (node is NestedPropertyExpression) { NestedPropertyExpression e = (NestedPropertyExpression)node; string enitySetname = e.Name; string nestedProperty = ""; foreach (PropertyExpression p in e.PropertyExpressions) { string interim = this.Visit(e, p); //AstoriaTestLog.WriteLine(interim); if (p.ValueOnly) { nestedProperty = String.Format("{0}/{1}/{2},", nestedProperty, enitySetname, interim + "/$value").TrimStart('/'); } else { nestedProperty = String.Format("{0}/{1}/{2},", nestedProperty, enitySetname, interim).TrimStart('/'); } } return(nestedProperty.TrimEnd(',').Replace(",/", ",")); } else if (node is PropertyExpression) { PropertyExpression e = (PropertyExpression)node; if (e.ValueOnly) { return(e.Property.Name + "/$value"); } else { return(e.Property.Name); } } else if (node is VariableExpression) { VariableExpression e = (VariableExpression)node; return(e.Variable.Name); } if (node is LogicalExpression) { LogicalExpression e = (LogicalExpression)node; string left = this.Visit(e, e.Left); string right = null; if (e.Operator != LogicalOperator.Not) { right = this.Visit(e, e.Right); } string logical; switch (e.Operator) { case LogicalOperator.And: logical = string.Format("{0} and {1}", left, right); break; case LogicalOperator.Or: logical = string.Format("{0} or {1}", left, right); break; case LogicalOperator.Not: logical = string.Format("not {0}", left); break; default: throw new Exception("Unhandled Comparison Type: " + e.Operator); } return(logical); } else if (node is ComparisonExpression) { ComparisonExpression e = (ComparisonExpression)node; String left = this.Visit(e, e.Left); String right = this.Visit(e, e.Right); switch (e.Operator) { case ComparisonOperator.Equal: return(String.Format("{0} eq {1}", left, right)); case ComparisonOperator.NotEqual: return(String.Format("{0} ne {1}", left, right)); case ComparisonOperator.GreaterThan: return(String.Format("{0} gt {1}", left, right)); case ComparisonOperator.GreaterThanOrEqual: return(String.Format("{0} ge {1}", left, right)); case ComparisonOperator.LessThan: return(String.Format("{0} lt {1}", left, right)); case ComparisonOperator.LessThanOrEqual: return(String.Format("{0} le {1}", left, right)); default: throw new Exception("Unhandled Comparison Type: " + e.Operator); } ; } else if (node is IsOfExpression || node is CastExpression) { ExpNode target; NodeType targetType; string operation; if (node is IsOfExpression) { IsOfExpression e = (IsOfExpression)node; operation = "isof"; target = e.Target; targetType = e.TargetType; } else { CastExpression e = (CastExpression)node; operation = "cast"; target = e.Target; targetType = e.TargetType; } string targetTypeName = targetType.FullName; if (targetType is PrimitiveType) { targetTypeName = TypeData.FindForType(targetType.ClrType).GetEdmTypeName(); } if (target == null) { return(String.Format("{0}('{1}')", operation, targetTypeName)); } else { return(String.Format("{0}({1}, '{2}')", operation, this.Visit(node, target), targetTypeName)); } } else if (node is ArithmeticExpression) { ArithmeticExpression e = (ArithmeticExpression)node; String left = this.Visit(e, e.Left); String right = this.Visit(e, e.Right); switch (e.Operator) { case ArithmeticOperator.Add: return(String.Format("{0} add {1}", left, right)); case ArithmeticOperator.Div: return(String.Format("{0} div {1}", left, right)); case ArithmeticOperator.Mod: return(String.Format("{0} mod {1}", left, right)); case ArithmeticOperator.Mult: return(String.Format("{0} mul {1}", left, right)); case ArithmeticOperator.Sub: return(String.Format("{0} sub {1}", left, right)); default: throw new Exception("Unhandled Arithmetic Type: " + e.Operator); } ; } else if (node is MethodExpression) { MethodExpression e = (MethodExpression)node; return(BuildMemberOrMethodExpression(node, e.Caller, e.Arguments, e.Name)); } else if (node is MemberExpression) { MemberExpression e = (MemberExpression)node; return(BuildMemberOrMethodExpression(node, e.Caller, e.Arguments, e.Name)); } else if (node is ConstantExpression) { ConstantExpression e = (ConstantExpression)node; object value = e.Value.ClrValue; string val = TypeData.FormatForKey(value, this.UseSmallCasing, false); if (this.EscapeUriValues) { // FormatForKey already does this for doubles that don't have the D if (!(value is double) || Versioning.Server.SupportsV2Features) { val = Uri.EscapeDataString(val); } } if (value == null) { val = "null"; } else if (!(value is String)) { val = val.Replace("+", "").Replace("%2B", ""); } return(val); } else if (node is NegateExpression) { NegateExpression e = (NegateExpression)node; return("-(" + this.Visit(e, e.Argument) + ")"); } else if (node is FirstExpression) { FirstExpression first = node as FirstExpression; return(this.Visit(first, first.Input)); } else if (node is FirstOrDefaultExpression) { FirstOrDefaultExpression first = node as FirstOrDefaultExpression; return(this.Visit(first, first.Input)); } else if (node is SingleExpression) { SingleExpression first = node as SingleExpression; return(this.Visit(first, first.Input)); } else if (node is SingleOrDefaultExpression) { SingleOrDefaultExpression first = node as SingleOrDefaultExpression; return(this.Visit(first, first.Input)); } else { throw new Exception(this.GetType().Name + " Unhandled Node: " + node.GetType().Name); } }
/// <summary> /// Detects whether a given type can be serialized with this class. /// </summary> /// <param /// name="typeData">Type to test.</param> /// <returns><c>true</c> if this class can handle the type.</returns> public static bool CanHandle(TypeData typeData) { return typeof(ISerializable).IsAssignableFrom(typeData.Type) && FindConstructor(typeData) != null; }
public void RequestUriNamedKeyTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("TypeData", TypeData.Values), new Dimension("UseSmallCasing", new bool[] { true, false }), new Dimension("UseDoublePostfix", new bool[] { true, false })); bool syntaxErrorTested = false; TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { TypeData typeData = (TypeData)values["TypeData"]; if (!typeData.IsTypeSupportedAsKey) { return; } // TODO: when System.Uri handles '/' correctly, re-enable. if (typeData.ClrType == typeof(System.Xml.Linq.XElement)) { return; } Type entityType = typeof(DoubleKeyTypedEntity <, ,>).MakeGenericType(typeData.ClrType, typeData.ClrType, typeof(int)); CustomDataContextSetup setup = new CustomDataContextSetup(entityType); object idValue = typeData.NonNullValue; if (idValue is byte[]) { // idValue = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; return; } bool useSmallCasing = (bool)values["UseSmallCasing"]; bool useDoublePostFix = (bool)values["UseDoublePostfix"]; if (!(idValue is double) && useDoublePostFix) { return; } string valueAsString = TypeData.FormatForKey(idValue, useSmallCasing, useDoublePostFix); TestUtil.ClearMetadataCache(); using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess)) { Trace.WriteLine("Running with value: [" + valueAsString + "] for [" + typeData.ToString() + "]"); setup.Id = idValue; setup.SecondId = idValue; setup.MemberValue = 1; request.DataServiceType = setup.DataServiceType; request.Accept = "application/json"; request.RequestUriString = "/Values(FirstKey=" + valueAsString + ",SecondKey=" + valueAsString + ")"; request.SendRequest(); string response = request.GetResponseStreamAsText(); TestUtil.AssertContains(response, "\"FirstKey\":"); TestUtil.AssertContains(response, "\"SecondKey\":"); if (!syntaxErrorTested) { syntaxErrorTested = true; VerifyRequestSyntaxError(request, "/Values(" + valueAsString + "," + valueAsString + ")"); VerifyRequestSyntaxError(request, "/Values(SecondKey == " + valueAsString + " , FirstKey = " + valueAsString + " )"); VerifyRequestSyntaxError(request, "/Values(ASecondKey = " + valueAsString + " , FirstKey = " + valueAsString + " )"); VerifyRequestSyntaxError(request, "/Values(SecondKey = " + valueAsString + ")"); VerifyRequestSyntaxError(request, "/Values(SecondKey = " + valueAsString + ",,FirstKey=" + valueAsString + ")"); VerifyRequestSyntaxError(request, "/Values(SecondKey)"); VerifyRequestSyntaxError(request, "/Values(SecondKey=,FirstKey=)"); VerifyRequestSyntaxError(request, "/Values(SecondKey = " + valueAsString + ",FirstKey=" + valueAsString + ",ThirdKey=" + valueAsString + ")"); } } setup.Cleanup(); }); }
public Command(TypeData typeData) { TypeData = typeData; }
public static string RenderMessage( PBS.Battle.View.Events.MessageParameterized message, PBS.Battle.View.Model myModel, int myPlayerID = 0, PBS.Battle.View.WifiFriendly.Trainer myTrainer = null, PBS.Battle.View.WifiFriendly.Team myTeamPerspective = null) { GameTextData textData = GameTextDatabase.instance.GetGameTextData(message.messageCode); if (textData == null) { return(""); } string baseString = textData.languageDict[GameSettings.language]; string newString = baseString; PBS.Battle.View.WifiFriendly.Trainer trainerPerspective = (myTrainer == null)? myModel.GetMatchingTrainer(message.playerPerspectiveID) : myTrainer; PBS.Battle.View.WifiFriendly.Team teamPerspective = (myTeamPerspective == null)? myModel.GetMatchingTeam(message.teamPerspectiveID) : myTeamPerspective; // player newString = newString.Replace("{{-player-name-}}", PlayerSave.instance.name); if (!string.IsNullOrEmpty(message.pokemonID)) { PBS.Battle.View.WifiFriendly.Pokemon pokemon = myModel.GetMatchingPokemon(message.pokemonID); PokemonData pokemonData = PokemonDatabase.instance.GetPokemonData(pokemon.pokemonID); newString = newString.Replace("{{-pokemon-}}", pokemon.nickname); newString = newString.Replace("{{-pokemon-form-}}", pokemonData.formName); newString = newString.Replace("{{-pokemon-poss-}}", pokemon.nickname + ((pokemon.nickname.EndsWith("s")) ? "'" : "'s") ); } if (!string.IsNullOrEmpty(message.pokemonUserID)) { PBS.Battle.View.WifiFriendly.Pokemon pokemon = myModel.GetMatchingPokemon(message.pokemonUserID); PokemonData pokemonData = PokemonDatabase.instance.GetPokemonData(pokemon.pokemonID); newString = newString.Replace("{{-user-pokemon-}}", pokemon.nickname); newString = newString.Replace("{{-user-pokemon-form-}}", pokemonData.formName); newString = newString.Replace("{{-user-pokemon-poss-}}", pokemon.nickname + ((pokemon.nickname.EndsWith("s")) ? "'" : "'s") ); } if (!string.IsNullOrEmpty(message.pokemonTargetID)) { PBS.Battle.View.WifiFriendly.Pokemon pokemon = myModel.GetMatchingPokemon(message.pokemonTargetID); PokemonData pokemonData = PokemonDatabase.instance.GetPokemonData(pokemon.pokemonID); newString = newString.Replace("{{-target-pokemon-}}", pokemon.nickname); newString = newString.Replace("{{-target-pokemon-form-}}", pokemonData.formName); newString = newString.Replace("{{-target-pokemon-poss-}}", pokemon.nickname + ((pokemon.nickname.EndsWith("s")) ? "'" : "'s") ); } if (message.pokemonListIDs.Count > 0) { List <PBS.Battle.View.WifiFriendly.Pokemon> pokemonList = new List <Battle.View.WifiFriendly.Pokemon>(); for (int i = 0; i < message.pokemonListIDs.Count; i++) { pokemonList.Add(myModel.GetMatchingPokemon(message.pokemonListIDs[i])); } string pokemonNameList = GetPokemonNames(pokemonList, myModel); newString = newString.Replace("{{-pokemon-list-}}", pokemonNameList); } if (message.trainerID != 0) { newString = RenderMessageTrainer( message.trainerID, myModel, teamPerspective.teamID, newString, myPlayerID: myPlayerID, myTrainer: myTrainer, myTeamPerspective: myTeamPerspective); } if (message.teamID != 0) { newString = RenderMessageTeam( teamID: message.teamID, teamPerspectiveID: teamPerspective.teamID, baseString: newString, myPlayerID: myPlayerID, myTrainer: myTrainer, myTeamPerspective: myTeamPerspective); } if (!string.IsNullOrEmpty(message.typeID)) { TypeData typeData = TypeDatabase.instance.GetTypeData(message.typeID); newString = newString.Replace("{{-type-name-}}", typeData.typeName + "-type"); } if (message.typeIDs.Count > 0) { newString = newString.Replace("{{-type-list-}}", GameTextDatabase.ConvertTypesToString(message.typeIDs.ToArray())); } if (!string.IsNullOrEmpty(message.moveID)) { MoveData moveData = MoveDatabase.instance.GetMoveData(message.moveID); newString = newString.Replace("{{-move-name-}}", moveData.moveName); } if (message.moveIDs.Count > 0) { for (int i = 0; i < message.moveIDs.Count; i++) { MoveData moveXData = MoveDatabase.instance.GetMoveData(message.moveIDs[i]); string partToReplace = "{{-move-name-" + i + "-}}"; newString = newString.Replace(partToReplace, moveXData.moveName); } } if (!string.IsNullOrEmpty(message.abilityID)) { AbilityData abilityData = AbilityDatabase.instance.GetAbilityData(message.abilityID); newString = newString.Replace("{{-ability-name-}}", abilityData.abilityName); } if (message.abilityIDs.Count > 0) { for (int i = 0; i < message.abilityIDs.Count; i++) { AbilityData abilityXData = AbilityDatabase.instance.GetAbilityData(message.abilityIDs[i]); string partToReplace = "{{-ability-name-" + i + "-}}"; newString = newString.Replace(partToReplace, abilityXData.abilityName); } } if (!string.IsNullOrEmpty(message.itemID)) { ItemData itemData = ItemDatabase.instance.GetItemData(message.itemID); newString = newString.Replace("{{-item-name-}}", itemData.itemName); } if (!string.IsNullOrEmpty(message.statusID)) { StatusPKData statusData = StatusPKDatabase.instance.GetStatusData(message.statusID); newString = newString.Replace("{{-status-name-}}", statusData.conditionName); } if (!string.IsNullOrEmpty(message.statusTeamID)) { StatusTEData statusData = StatusTEDatabase.instance.GetStatusData(message.statusTeamID); newString = newString.Replace("{{-team-status-name-}}", statusData.conditionName); } if (!string.IsNullOrEmpty(message.statusEnvironmentID)) { StatusBTLData statusData = StatusBTLDatabase.instance.GetStatusData(message.statusEnvironmentID); newString = newString.Replace("{{-battle-status-name-}}", statusData.conditionName); } // swapping substrings for (int i = 0; i < message.intArgs.Count; i++) { string partToReplace = "{{-int-" + i + "-}}"; newString = newString.Replace(partToReplace, message.intArgs[i].ToString()); } if (message.statList.Count > 0) { newString = newString.Replace("{{-stat-types-}}", ConvertStatsToString(message.statList.ToArray())); if (GameSettings.language == GameLanguages.English) { newString = newString.Replace("{{-stat-types-was-}}", (message.statList.Count == 1)? "was" : "were"); } else { newString = newString.Replace("{{-stat-types-was-}}", ""); } newString = newString.Replace("{{-stat-types-LC-}}", ConvertStatsToString(message.statList.ToArray(), false)); } return(newString); }
public static TypeData RegisterClass(Type t) { int fieldCount; List <TypeSortedField> sortFields = SortFields(t.GetFields(), out fieldCount); if (sortFields == null) { return(null); } TypeData td = new TypeData(); td.ClassType = t; td.HashCode = Utility.GetHash(td.ClassType.ToString()); td.Handle = null; td.Size = 0; td.ArrayCount = 1; td.Fields = new TypeData[fieldCount]; int idx = 0; for (int n = 0; n < sortFields.Count; ++n) { for (int i = 0; i < sortFields[n].Fields.Count; ++i) { TypeFiledPack field = sortFields[n].Fields[i]; FieldInfo fi = field.Field; TypeData curData = null; if (fi.FieldType.IsPrimitive) { curData = new TypeData(); curData.Handle = fi; curData.ArrayCount = 1; curData.ClassType = fi.FieldType; curData.HashCode = Utility.GetHash(curData.ClassType.ToString()); curData.OrgSize = curData.Size = TypeReaderMapping.GetReaderFromHash(curData.HashCode).TypeSize(); } else if (fi.FieldType.IsArray) { //获取原始类型 string strType = fi.FieldType.ToString(); strType = strType.Remove(strType.Length - 2, 2); Type orgType = Type.GetType(strType); if (orgType == null) { LogMgr.Log("未知的数组类型:" + strType); return(null); } if (field.Count < 1 && field.VarType == false) { LogMgr.Log("数组的特性TypeInfo必须大于0,或者是变长的数组"); return(null); } if (orgType.IsPrimitive) { curData = new TypeData(); curData.ClassType = orgType; curData.HashCode = Utility.GetHash(curData.ClassType.ToString()); curData.ArrayCount = field.Count; curData.VarType = field.VarType; curData.OrgSize = curData.Size = TypeReaderMapping.GetReaderFromHash(curData.HashCode).TypeSize(); if (curData.VarType) { curData.Size = 0; } else { curData.Size = (short)(curData.Size * field.Count); } curData.Handle = fi; } else if (orgType.IsClass /* || orgType.IsValueType*/) { curData = RegisterClass(orgType); if (curData == null) { return(null); } curData.ArrayCount = field.Count; curData.VarType = field.VarType; if (curData.VarType) { curData.Size = 0; } else { curData.Size = (short)(curData.Size * field.Count); } curData.Handle = fi; } else { LogMgr.Log("未知的数组原始类型:" + strType); return(null); } } else if (fi.FieldType == typeof(string)) { curData = new TypeData(); curData.ArrayCount = field.Count; curData.OrgSize = (short)sizeof(char); curData.VarType = field.VarType; if (curData.VarType) { curData.Size = 0; } else { curData.Size = (short)(sizeof(char) * field.Count); } curData.ClassType = fi.FieldType; curData.HashCode = STRING_HASH; curData.Handle = fi; } else if (fi.FieldType.IsClass /*|| fi.FieldType.IsValueType*/) { curData = RegisterClass(fi.FieldType); if (curData == null) { return(null); } curData.Handle = fi; } else { LogMgr.Log("未知的类型:" + fi.FieldType.ToString()); return(null); } td.Fields[idx++] = curData; td.Size += curData.Size; } } td.OrgSize = td.Size; return(td); }
public ConcreteObject(Type type) { Type = type; _data = type; }
private static bool IsConstructedGenericType(TypeData typeBase) => typeBase is ConstructedGenericTypeData;
private static Type DeserializeType(TypeData typeData) => s_typeCache.GetOrAdd( typeData, td => AssemblyLoader.LoadAssembly( td.AssemblyName, td.AssemblyFileName).GetType(td.Name));
public void SweepLoop2Test() { var plan = new TestPlan(); var sweep = new SweepParameterStep(); var step = new ScopeTestStep(); plan.ChildTestSteps.Add(sweep); sweep.ChildTestSteps.Add(step); sweep.SweepValues.Add(new SweepRow()); sweep.SweepValues.Add(new SweepRow()); TypeData.GetTypeData(step).GetMember(nameof(ScopeTestStep.A)).Parameterize(sweep, step, "Parameters \\ A"); TypeData.GetTypeData(step).GetMember(nameof(ScopeTestStep.EnabledTest)).Parameterize(sweep, step, nameof(ScopeTestStep.EnabledTest)); var td1 = TypeData.GetTypeData(sweep.SweepValues[0]); var memberA = td1.GetMember("Parameters \\ A"); memberA.SetValue(sweep.SweepValues[0], 10); memberA.SetValue(sweep.SweepValues[1], 20); { // verify Enabled<T> works with SweepParameterStep. var annotation = AnnotationCollection.Annotate(sweep); var col = annotation.GetMember(nameof(SweepParameterStep.SelectedParameters)).Get <IStringReadOnlyValueAnnotation>().Value; Assert.AreEqual("A, EnabledTest", col); var elements = annotation.GetMember(nameof(SweepParameterStep.SweepValues)) .Get <ICollectionAnnotation>().AnnotatedElements .Select(elem => elem.GetMember(nameof(ScopeTestStep.EnabledTest))) .ToArray(); annotation.Write(); Assert.IsFalse((bool)elements[0].GetMember("IsEnabled").Get <IObjectValueAnnotation>().Value); elements[0].GetMember("IsEnabled").Get <IObjectValueAnnotation>().Value = true; annotation.Write(); Assert.IsFalse((bool)elements[1].GetMember("IsEnabled").Get <IObjectValueAnnotation>().Value); Assert.IsTrue((bool)elements[0].GetMember("IsEnabled").Get <IObjectValueAnnotation>().Value); } var str = new TapSerializer().SerializeToString(plan); var plan2 = (TestPlan) new TapSerializer().DeserializeFromString(str); var sweep2 = (SweepParameterStep)plan2.Steps[0]; var td2 = TypeData.GetTypeData(sweep2); var members2 = td2.GetMembers(); var rows = sweep2.SweepValues; Assert.AreEqual(2, rows.Count); var msgmem = TypeData.GetTypeData(rows[0]).GetMember("Parameters \\ A"); Assert.AreEqual(10, msgmem.GetValue(rows[0])); // this feature was disabled. //var annotated = AnnotationCollection.Annotate(sweep2); //var messageMember = annotated.GetMember(nameof(ScopeTestStep.A)); //Assert.IsFalse(messageMember.Get<IEnabledAnnotation>().IsEnabled); var run = plan2.Execute(); Assert.AreEqual(Verdict.Pass, run.Verdict); Assert.IsTrue(((ScopeTestStep)sweep2.ChildTestSteps[0]).Collection.SequenceEqual(new[] { 10, 20 })); var name = sweep.GetFormattedName(); Assert.AreEqual("Sweep A, EnabledTest", name); }
private static void TestAssignability(Type a, Type b) { var aData = a.IsGenericParameter ? GenericTypeParameterData.FromType(a) : TypeData.FromType(a); var bData = b.IsGenericParameter ? GenericTypeParameterData.FromType(b) : TypeData.FromType(b); if (aData == null || bData == null) { Assert.Inconclusive("Unable to get one of the types"); } if (a.IsImplicitlyAssignableFrom(b)) { Assert.IsTrue(aData.IsAssignableFromNew(bData), string.Format("The type should be assignable: {0} <- {1}", aData.Name, bData.Name)); } else { Assert.IsFalse(aData.IsAssignableFromNew(bData), string.Format("The type should not be assignable: {0} <- {1}", aData.Name, bData.Name)); } if (b.IsImplicitlyAssignableFrom(a)) { Assert.IsTrue(bData.IsAssignableFromNew(aData), string.Format("The type should be assignable: {0} <- {1}", bData.Name, aData.Name)); } else { Assert.IsFalse(bData.IsAssignableFromNew(aData), string.Format("The type should not be assignable: {0} <- {1}", bData.Name, aData.Name)); } }
/// <summary> /// Create a TypeSpec from a type and data with generic arguments. /// from deserialized data to an existing type. /// </summary> /// <param name="type">Existing type</param> /// <param name="data">Deserialized data with generic types</param> /// <returns>GenericInstSig</returns> TypeSpec ApplyGenerics(ITypeDefOrRef type, TypeData data) { List<TypeSig> generics = new List<TypeSig>(); foreach (var g in data.GenericTypes) { var gtype = this.ResolveType_NoLock(g.Position); generics.Add(gtype.ToTypeSig()); } return ApplyGenerics(type, generics); //List<TypeSig> types = new List<TypeSig>(); //foreach (var g in data.GenericTypes) //{ // var gtype = this.ResolveType_NoLock(g.Position); // types.Add(gtype.ToTypeSig()); //} // //ClassOrValueTypeSig typeSig = type.ToTypeSig().ToClassOrValueTypeSig(); //// return new GenericInstSig(typeSig, types).ToTypeDefOrRef(); // //GenericInstSig genericSig = new GenericInstSig(typeSig, types); //TypeSpec typeSpec = new TypeSpecUser(genericSig); //return typeSpec; }
/// <summary> /// Determines whether a given type can be serialized with this class. /// </summary> /// <param /// name="typeData">Type to test.</param> /// <returns><c>true</c> if this class can handle the type.</returns> public static bool CanHandle(TypeData typeData) { return (typeData.GetCustomAttribute<DataContractAttribute>() != null); }
public static TCSymbol NewVariable(TypeData type, ESIR_Expression expr, SymbolFlags flags = 0) => new (new (type, expr), flags);
private IFudgeSerializationSurrogate SurrogateFromDotNetSurrogateSelector(FudgeContext context, TypeData typeData) { if (DotNetSurrogateSelector == null) return null; ISurrogateSelector selector; StreamingContext sc = new StreamingContext(StreamingContextStates.Persistence); ISerializationSurrogate dotNetSurrogate = DotNetSurrogateSelector.GetSurrogate(typeData.Type, sc, out selector); if (dotNetSurrogate == null) return null; return new DotNetSerializationSurrogateSurrogate(context, typeData, dotNetSurrogate, selector); }
public ConverterUtil(Type forType, SerializationContext context) { _handler = context.GetTypeHandler(forType); }
private static IconAccess GetAccess(TypeData type) { if (type.Inner.IsNestedPrivate) return IconAccess.Private; if (type.Inner.IsNestedFamily ) return IconAccess.Protected; if (type.Inner.IsNestedAssembly || type.Inner.IsNestedFamORAssem || type.Inner.IsNotPublic) return IconAccess.Internal; return IconAccess.Public; }
public static void Create() { TypeData.Start(); ThreadJobsPrinting = 0; ThreadJobsDone = 0; if (Directory.Exists("dump")) { Directory.Delete("dump", true); } Directory.CreateDirectory("dump"); Directory.CreateDirectory("dump/sobjects"); Directory.CreateDirectory("dump/uobjects"); Directory.CreateDirectory("dump/statics"); using (var logger = new StreamWriter("dump/memory.csv")) { Dictionary <Assembly, List <StructOrClass> > assemblyResults = new Dictionary <Assembly, List <StructOrClass> >(); Dictionary <Assembly, int> assemblySizes = new Dictionary <Assembly, int>(); List <KeyValuePair <Type, Exception> > parseErrors = new List <KeyValuePair <Type, Exception> >(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { string assemblyFolder; if (assembly.FullName.Contains("Assembly-CSharp")) { assemblyFolder = string.Format("dump/statics/{0}/", assembly.FullName.Replace("<", "(").Replace(">", ")").Replace(".", "_")); } else { assemblyFolder = "dump/statics/misc/"; } Directory.CreateDirectory(assemblyFolder); List <StructOrClass> types = new List <StructOrClass>(); foreach (var type in assembly.GetTypes()) { if (type.IsEnum || type.IsGenericType) { continue; } try { types.Add(new StructOrClass(type, assemblyFolder)); } catch (Exception e) { parseErrors.Add(new KeyValuePair <Type, Exception>(type, e)); } } assemblyResults[assembly] = types; } List <StructOrClass> unityComponents = new List <StructOrClass>(); foreach (var go in Resources.FindObjectsOfTypeAll <GameObject>()) { foreach (var component in go.GetComponents <Component>()) { if (component == null) { continue; } try { unityComponents.Add(new StructOrClass(component)); } catch (Exception e) { parseErrors.Add(new KeyValuePair <Type, Exception>(component.GetType(), e)); } } } List <StructOrClass> unityScriptableObjects = new List <StructOrClass>(); foreach (ScriptableObject scriptableObject in Resources.FindObjectsOfTypeAll <ScriptableObject>()) { if (scriptableObject == null) { continue; } try { unityScriptableObjects.Add(new StructOrClass(scriptableObject)); } catch (Exception e) { parseErrors.Add(new KeyValuePair <Type, Exception>(scriptableObject.GetType(), e)); } } foreach (var genericType in genericTypes.ToList()) { try { assemblyResults[genericType.Assembly].Add(new StructOrClass(genericType, "dump/statics/misc/")); } catch (Exception e) { parseErrors.Add(new KeyValuePair <Type, Exception>(genericType, e)); } } foreach (var pair in assemblyResults) { assemblySizes[pair.Key] = pair.Value.Sum(a => a.Size); pair.Value.Sort((a, b) => b.Size - a.Size); } TypeData.Clear(); var assemblySizesList = assemblySizes.ToList(); assemblySizesList.Sort((a, b) => (b.Value - a.Value)); unityComponents.Sort((a, b) => (b.Size - a.Size)); int unityComponentsSize = unityComponents.Sum(a => a.Size); bool printedUnityComponents = false; unityScriptableObjects.Sort((a, b) => (b.Size - a.Size)); int unityScriptableObjectsSize = unityScriptableObjects.Sum(a => a.Size); bool printedUnityScriptableObjects = false; //logger.WriteLine("Total tracked memory (including duplicates, so too high) = {0}", assemblySizesList.Sum(a => a.Value) + unityComponentsSize + unityScriptableObjectsSize); foreach (var pair in assemblySizesList) { var assembly = pair.Key; var size = pair.Value; if (!printedUnityComponents && size < unityComponentsSize) { printedUnityComponents = true; //logger.WriteLine("Unity components of total size: {0}", unityComponentsSize); foreach (var instance in unityComponents) { if (instance.Size >= TYPE_MIN_SIZE_TO_PRINT) { logger.WriteLine("\"{0}\",\"{1}\",{2},{3}", "Unity Components", instance.ParsedType.FullName, instance.InstanceID, instance.Size); } } } if (!printedUnityScriptableObjects && size < unityScriptableObjectsSize) { printedUnityScriptableObjects = true; //logger.WriteLine("Unity scriptableobjects of total size: {0}", unityScriptableObjectsSize); foreach (var instance in unityScriptableObjects) { if (instance.Size >= TYPE_MIN_SIZE_TO_PRINT) { logger.WriteLine("\"{0}\",\"{1}\",{2},{3}", "Unity ScriptableObjects", instance.ParsedType.FullName, instance.InstanceID, instance.Size); } } } //logger.WriteLine("Assembly: {0} of total size: {1}", assembly, size); foreach (var type in assemblyResults[assembly]) { if (type.Size >= TYPE_MIN_SIZE_TO_PRINT) { logger.WriteLine("\"{0}\",\"{1}\",,{2}", assembly, type.ParsedType.FullName, type.Size); } } } foreach (var error in parseErrors) { //logger.WriteLine(error); } } while (ThreadJobsDone < ThreadJobsPrinting) { System.Threading.Thread.Sleep(1); } }
public void CustomConstructionTest() { var type = TypeDefinitionData.FromType(typeof(List <>)); var addMethod = type.GetMethod("Add"); Assert.AreEqual("T", addMethod.Parameters[0].Type.Name); var constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>() }); addMethod = constructedType.GetMethod("Add"); Assert.AreEqual("TestTypeArgument", addMethod.Parameters[0].Type.Name); type = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <>)); constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>() }); var constructor = (ConstructorData)constructedType.GetMember(".ctor"); Assert.AreEqual("TestTypeArgument?", constructor.Parameters[0].Type.GetDisplayName(fullyQualify: false)); var _event = (EventData)constructedType.GetMember("Event"); Assert.AreEqual("EventHandler<TestTypeArgument>", _event.Type.GetDisplayName(fullyQualify: false)); var field = (FieldData)constructedType.GetMember("Field"); Assert.AreEqual("TestTypeArgument[]", field.Type.GetDisplayName(fullyQualify: false)); var indexer = (IndexerData)constructedType.GetMember("Item"); Assert.AreEqual("IList<TestTypeArgument>", indexer.Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("TestTypeArgument[]", indexer.Parameters[0].Type.GetDisplayName(fullyQualify: false)); var method = (MethodData)constructedType.GetMember("Method"); Assert.AreEqual("TestTypeArgument?", method.Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("TestTypeArgument", method.Parameters[0].Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("U", method.Parameters[1].Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("Dictionary<TestTypeArgument[], U[]>", method.Parameters[2].Type.GetDisplayName(fullyQualify: false)); var _operator = (OperatorData)constructedType.GetMember("op_Addition"); Assert.AreEqual("KeyValuePair<TestTypeArgument, object>", _operator.Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("TestGenericTypeDefinition<TestTypeArgument>", _operator.Parameters[0].Type.GetDisplayName(fullyQualify: false)); Assert.AreEqual("TestTypeArgument", _operator.Parameters[1].Type.GetDisplayName(fullyQualify: false)); var property = (PropertyData)constructedType.GetMember("Property"); Assert.AreEqual("IComparer<TestTypeArgument>", property.Type.GetDisplayName(fullyQualify: false)); var nestedType = (ConstructedGenericTypeData)constructedType.GetMember("NestedType`1"); Assert.IsNull(nestedType); type = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <> .NestedType <>)); constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>(), TypeData.FromType <double>() }); Assert.AreEqual("NestedType<double>", constructedType.GetDisplayName(fullyQualify: false)); Assert.AreEqual("BreakingChangesDetector.UnitTests.MetadataTypesTests.ConstructedGenericTypeDataTests.TestGenericTypeDefinition<TestTypeArgument>.NestedType<double>", constructedType.GetDisplayName()); Assert.AreEqual("Tuple<int, TestTypeArgument[], double>", constructedType.BaseType.GetDisplayName(fullyQualify: false)); type = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <> .NestedType <> .FurtherNestedType <>)); constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <int>(), TypeData.FromType <TestTypeArgument>(), TypeData.FromType <double>() }); Assert.AreEqual("FurtherNestedType<double>", constructedType.GetDisplayName(fullyQualify: false)); Assert.AreEqual("BreakingChangesDetector.UnitTests.MetadataTypesTests.ConstructedGenericTypeDataTests.TestGenericTypeDefinition<int>.NestedType<TestTypeArgument>.FurtherNestedType<double>", constructedType.GetDisplayName()); Assert.AreEqual("Dictionary<int, Tuple<TestTypeArgument, double>>", constructedType.BaseType.GetDisplayName(fullyQualify: false)); }
public void PlainSerializersBasicTest() { CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("ValidMime", new object[] { true, false }), new Dimension("SpecificMime", new object[] { true, false }), new Dimension("TypeData", TypeData.Values)); Hashtable table = new Hashtable(); while (engine.Next(table)) { bool validMime = (bool)table["ValidMime"]; bool specificMime = (bool)table["SpecificMime"]; TypeData typeData = (TypeData)table["TypeData"]; // If ValidMime is false, whether it's specific or not doesn't matter. if (!validMime && specificMime) { continue; } if (!typeData.IsTypeSupported) { continue; } using (TestWebRequest request = TestWebRequest.CreateForLocation(WebServerLocation.InProcess)) { Type valueType = typeData.ClrType; Type entityType = typeof(TypedEntity <,>).MakeGenericType(typeof(int), valueType); CustomDataContextSetup dataContextSetup = new CustomDataContextSetup(entityType); dataContextSetup.Id = 1; dataContextSetup.MemberValue = typeData.NonNullValue; Type serviceType = dataContextSetup.DataServiceType; request.DataServiceType = serviceType; request.RequestUriString = "/Values(1)/Member/$value"; if (validMime) { request.Accept = TypeData.FindForType(valueType).DefaultContentType; } else { request.Accept = "application/unexpected"; } try { request.SendRequest(); if (!validMime) { Assert.Fail("Request should have failed."); } } catch (WebException) { if (!validMime) { continue; } throw; } string expectedType = request.Accept; Assert.AreEqual(expectedType, TestUtil.GetMediaType(request.ResponseContentType)); Stream stream = request.GetResponseStream(); if (valueType == typeof(byte[])) { byte[] bytes = (byte[])dataContextSetup.MemberValue; for (int i = 0; i < bytes.Length; i++) { Assert.AreEqual(bytes[i], (byte)stream.ReadByte()); } } else { using (StreamReader reader = new StreamReader(stream)) { typeData.VerifyAreEqual(dataContextSetup.MemberValue, typeData.ValueFromXmlText(reader.ReadToEnd(), request.Accept), request.Accept); } } } } }
public void SetValuesTest() { var delayStep1 = new DelayStep(); var delayStep2 = new DelayStep(); var logStep = new LogStep(); var logStep2 = new LogStep(); var fileStep = new MacroFilePathTestStep(); var fileStep2 = new MacroFilePathTestStep(); var ifstep = new IfStep(); fileStep.PathToThing.Text = "<TESTPLANDIR>\\asdasd"; TestPlan plan = new TestPlan(); plan.ChildTestSteps.Add(delayStep1); plan.ChildTestSteps.Add(delayStep2); plan.ChildTestSteps.Add(logStep); plan.ChildTestSteps.Add(logStep2); plan.ChildTestSteps.Add(fileStep); plan.ChildTestSteps.Add(fileStep2); plan.ChildTestSteps.Add(ifstep); ifstep.InputVerdict.Step = delayStep2; ifstep.InputVerdict.Property = TypeData.GetTypeData(delayStep1).GetMember("Verdict"); var delayInfo = TypeData.GetTypeData(delayStep1); var logInfo = TypeData.GetTypeData(logStep); var fileStepInfo = TypeData.GetTypeData(fileStep); plan.ExternalParameters.Add(delayStep1, delayInfo.GetMember("DelaySecs")); plan.ExternalParameters.Add(delayStep2, delayInfo.GetMember("DelaySecs"), "Time Delay"); plan.ExternalParameters.Add(logStep, logInfo.GetMember("Severity"), Name: "Severity"); plan.ExternalParameters.Add(logStep2, logInfo.GetMember("Severity"), Name: "Severity"); plan.ExternalParameters.Add(fileStep, fileStepInfo.GetMember("PathToThing"), Name: "Path1"); plan.ExternalParameters.Add(fileStep2, fileStepInfo.GetMember("PathToThing"), Name: "Path1"); plan.ExternalParameters.Add(ifstep, TypeData.GetTypeData(ifstep).GetMember(nameof(IfStep.InputVerdict)), Name: "InputVerdict"); for (int j = 0; j < 5; j++) { for (double x = 0.01; x < 10; x += 3.14) { plan.ExternalParameters.Get("Time Delay").Value = x; Assert.AreEqual(x, delayStep1.DelaySecs); Assert.AreEqual(x, delayStep2.DelaySecs); } plan.ExternalParameters.Get("Severity").Value = LogSeverity.Error; Assert.AreEqual(LogSeverity.Error, logStep.Severity); Assert.AreEqual(LogSeverity.Error, logStep2.Severity); plan.ExternalParameters.Get("Path1").Value = plan.ExternalParameters.Get("Path1").Value; string planstr = null; using (var memstream = new MemoryStream()) { plan.Save(memstream); planstr = Encoding.UTF8.GetString(memstream.ToArray()); } Assert.IsTrue(planstr.Contains(@"Parameter=""Time Delay""")); Assert.IsTrue(planstr.Contains(@"Parameter=""Severity""")); Assert.IsTrue(planstr.Contains(@"Parameter=""Path1""")); using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(planstr))) plan = TestPlan.Load(memstream, planstr); delayStep1 = (DelayStep)plan.ChildTestSteps[0]; delayStep2 = (DelayStep)plan.ChildTestSteps[1]; logStep = (LogStep)plan.ChildTestSteps[2]; logStep2 = (LogStep)plan.ChildTestSteps[3]; fileStep = (MacroFilePathTestStep)plan.ChildTestSteps[4]; fileStep2 = (MacroFilePathTestStep)plan.ChildTestSteps[5]; ifstep = (IfStep)plan.ChildTestSteps[6]; Assert.IsTrue(fileStep2.PathToThing.Context == fileStep2); Assert.AreEqual(fileStep2.PathToThing.Text, fileStep.PathToThing.Text); Assert.AreEqual(delayStep2, ifstep.InputVerdict.Step); } }
public InterfaceImplementation(TypeData type, TypeData @interface, AnalysisContext context) { this.Interface = @interface; this.LoadMemberMap(type, context); }
internal static bool CanHandle(TypeData typeData) { if (typeData.DefaultConstructor == null) return false; foreach (var prop in typeData.Properties) { switch (prop.Kind) { case TypeData.TypeKind.FudgePrimitive: case TypeData.TypeKind.Inline: case TypeData.TypeKind.Reference: // OK break; default: // Unknown return false; } if (!prop.HasPublicSetter && !ListSurrogate.IsList(prop.Type)) // Special case for lists, which we can just append to if no setter present { // Not bean-style return false; } } return true; }
public void NonGenericClassTest7() { var expectedTypeData = new TypeData("_Namespace1_._Class1_"); ValidateSuccessfulParseResult(" _Namespace1_._Class1_ ", expectedTypeData); }
/// <summary> /// Detects whether a given type can be serialized with this class. /// </summary> /// <param /// name="typeData">Type to test.</param> /// <returns><c>true</c> if this class can handle the type.</returns> public static bool CanHandle(TypeData typeData) { return typeData.GetCustomAttribute<SerializableAttribute>() != null; }
/// <summary> /// Ignore a property to keep from being serialized, same as if the JsonExIgnore attribute had been set /// </summary> /// <param name="objectType">the type that contains the property</param> /// <param name="propertyName">the name of the property</param> public void IgnoreProperty(Type objectType, string propertyName) { TypeData handler = GetTypeHandler(objectType); handler.IgnoreProperty(propertyName); }
internal TCVariable(TypeData type, ESIR_Expression irExpr) { Type = type; IRExpression = irExpr; }
public void AddBoxSurfaces(Vector3 origin, Vector3 size, TypeData type, ref Dictionary <int, SurfaceData> surfaces) { for (int i = 0; i < 6; i++) { if (!surfaces.ContainsKey(type.materials[i])) { surfaces.Add(type.materials[i], new SurfaceData()); } } AddSurface( origin + new Vector3(0, 0, size.z), origin + new Vector3(0, size.y, size.z), origin + new Vector3(size.x, size.y, size.z), origin + new Vector3(size.x, 0, size.z), (int)size.x, (int)size.y, Direction.SOUTH, surfaces[type.materials[0]] ); AddSurface( origin, origin + new Vector3(0, size.y, 0), origin + new Vector3(size.x, size.y, 0), origin + new Vector3(size.x, 0, 0), (int)size.x, (int)size.y, Direction.NORTH, surfaces[type.materials[1]] ); AddSurface( origin, origin + new Vector3(0, size.y, 0), origin + new Vector3(0, size.y, size.z), origin + new Vector3(0, 0, size.z), (int)size.z, (int)size.y, Direction.WEST, surfaces[type.materials[2]] ); AddSurface( origin + new Vector3(size.x, 0, 0), origin + new Vector3(size.x, size.y, 0), origin + new Vector3(size.x, size.y, size.z), origin + new Vector3(size.x, 0, size.z), (int)size.z, (int)size.y, Direction.EAST, surfaces[type.materials[3]] ); AddSurface( origin, origin + new Vector3(0, 0, size.z), origin + new Vector3(size.x, 0, size.z), origin + new Vector3(size.x, 0, 0), (int)size.x, (int)size.z, Direction.BOTTOM, surfaces[type.materials[4]] ); AddSurface( origin + new Vector3(0, size.y, 0), origin + new Vector3(0, size.y, size.z), origin + new Vector3(size.x, size.y, size.z), origin + new Vector3(size.x, size.y, 0), (int)size.x, (int)size.z, Direction.TOP, surfaces[type.materials[5]] ); }
public ExprJsTypeData(Ctx ctx, TypeData typeData) : base(ctx) { this.TypeData = typeData; }
/// <summary> /// Registers a type with a serialization surrogate. /// </summary> /// <param name="type">Type that the surrogate is for.</param> /// <param name="surrogate">Surrogate to serialize and deserialize the type.</param> public int RegisterType(Type type, IFudgeSerializationSurrogate surrogate) { int id = typeDataList.Count; var entry = new TypeData { Surrogate = surrogate, Type = type }; typeDataList.Add(entry); typeMap.Add(type, id); return id; }
private void ScanForTypeMissingAsyncMethods(TypeData typeData) { var documentData = typeData.NamespaceData.DocumentData; var syncMethods = typeData.Node.Members .OfType <MethodDeclarationSyntax>() .Where(o => !o.Identifier.ValueText.EndsWith("Async")) .Select(o => new { Node = (SyntaxNode)o, Symbol = documentData.SemanticModel.GetDeclaredSymbol(o) }) // Expression properties .Concat( typeData.Node.Members .OfType <PropertyDeclarationSyntax>() .Where(o => o.ExpressionBody != null) .Select(o => new { Node = (SyntaxNode)o.ExpressionBody, Symbol = documentData.SemanticModel.GetDeclaredSymbol(o).GetMethod }) ) // Non expression properties .Concat( typeData.Node.Members .OfType <PropertyDeclarationSyntax>() .Where(o => o.ExpressionBody == null) .SelectMany(o => o.AccessorList.Accessors) .Select(o => new { Node = (SyntaxNode)o, Symbol = documentData.SemanticModel.GetDeclaredSymbol(o) }) ) .ToLookup(o => o.Symbol.GetAsyncName()); var asyncMethods = typeData.Node.Members .OfType <MethodDeclarationSyntax>() .Where(o => o.Identifier.ValueText.EndsWith("Async")) .Select(o => new { Node = (SyntaxNode)o, Symbol = documentData.SemanticModel.GetDeclaredSymbol(o) }) .ToLookup(o => o.Symbol.Name); foreach (var asyncMember in typeData.Symbol.AllInterfaces .SelectMany(o => o.GetMembers().OfType <IMethodSymbol>() .Where(m => m.Name.EndsWith("Async")))) { // Skip if there is already an implementation defined var impl = typeData.Symbol.FindImplementationForInterfaceMember(asyncMember); if (impl != null) { continue; } if (!syncMethods.Contains(asyncMember.Name)) { // Try to find if there is a property with that name documentData.AddDiagnostic($"Sync counterpart of async member {asyncMember} not found", DiagnosticSeverity.Hidden); continue; } var nonAsyncMember = syncMethods[asyncMember.Name].First(o => o.Symbol.IsAsyncCounterpart(null, asyncMember, true, true, false)); // TODO: what to do if there are more than one? var methodData = documentData.GetMethodOrAccessorData(nonAsyncMember.Node); if (methodData.Conversion == MethodConversion.Ignore) { methodData.AddDiagnostic("Overriding conversion from Ignore to ToAsync in order to avoid having an invalid code generated.", DiagnosticSeverity.Hidden); } methodData.ToAsync(); methodData.Missing = true; // We have to generate the cancellation token parameter if the async member has more parameters that the sync counterpart if (asyncMember.Parameters.Length > nonAsyncMember.Symbol.Parameters.Length) { methodData.CancellationTokenRequired = true; // We suppose that the cancellation token is the last parameter methodData.MethodCancellationToken = asyncMember.Parameters.Last().HasExplicitDefaultValue ? MethodCancellationToken.Optional : MethodCancellationToken.Required; } } // Find all abstract and virtual non implemented async methods in all descend base types. var baseType = typeData.Symbol.BaseType; while (baseType != null) { foreach (var asyncMember in baseType.GetMembers() .OfType <IMethodSymbol>() .Where(o => (o.IsAbstract || o.IsVirtual) && o.Name.EndsWith("Async"))) { if (!syncMethods.Contains(asyncMember.Name)) { documentData.AddDiagnostic($"Abstract sync counterpart of async member {asyncMember} not found", DiagnosticSeverity.Hidden); continue; } var nonAsyncMember = syncMethods[asyncMember.Name].FirstOrDefault(o => o.Symbol.IsAsyncCounterpart(null, asyncMember, true, true, false)); if (nonAsyncMember == null) { documentData.AddDiagnostic($"Abstract sync counterpart of async member {asyncMember} not found", DiagnosticSeverity.Hidden); continue; } // Skip if the type already implements the method if (asyncMethods[asyncMember.Name].Any(o => o.Symbol.MatchesDefinition(asyncMember))) { continue; } var methodData = documentData.GetMethodOrAccessorData(nonAsyncMember.Node); if (methodData.Conversion == MethodConversion.Ignore) { // An ignored virtual method can be ignored as it will not produce a compilation error if (!asyncMember.IsAbstract) { continue; } methodData.AddDiagnostic("Overriding conversion from Ignore to ToAsync in order to avoid having an invalid code generated.", DiagnosticSeverity.Hidden); } methodData.ToAsync(); methodData.Missing = true; // We have to generate the cancellation token parameter if the async member has more parameters that the sync counterpart if (asyncMember.Parameters.Length > nonAsyncMember.Symbol.Parameters.Length) { methodData.CancellationTokenRequired = true; // We suppose that the cancellation token is the last parameter methodData.MethodCancellationToken = asyncMember.Parameters.Last().HasExplicitDefaultValue ? MethodCancellationToken.Optional : MethodCancellationToken.Required; } } baseType = baseType.BaseType; } }
/// <summary> Creates a Key and a Value node in the XML.</summary> public override bool Serialize(XElement node, object obj, ITypeData _expectedType) { if (obj == null || false == obj.GetType().DescendsTo(typeof(KeyValuePair <,>))) { return(false); } if (_expectedType is TypeData expectedType2 && expectedType2.Type is Type expectedType) { var key = new XElement("Key"); var value = new XElement("Value"); bool keyok = Serializer.Serialize(key, _expectedType.GetMember("Key").GetValue(obj), TypeData.FromType(expectedType.GetGenericArguments()[0])); bool valueok = Serializer.Serialize(value, _expectedType.GetMember("Value").GetValue(obj), TypeData.FromType(expectedType.GetGenericArguments()[1])); if (!keyok || !valueok) { return(false); } node.Add(key); node.Add(value); return(true); } return(false); }
private static Type DeserializeType(TypeData typeData) => s_typeCache.GetOrAdd(typeData, td => LoadAssembly(typeData.ManifestModuleName).GetType(typeData.Name));
private IFudgeSerializationSurrogate SurrogateFromAttribute(FudgeContext context, TypeData typeData) { var surrogateAttribute = typeData.CustomAttributes.FirstOrDefault(attrib => attrib is FudgeSurrogateAttribute); if (surrogateAttribute != null) { return BuildSurrogate(typeData.Type, (FudgeSurrogateAttribute)surrogateAttribute); } return null; }
ITypeDefOrRef ResolveType_NoLock(Int32 position) { this.Stream.Position = position; InlineOperand operand = new InlineOperand(this.Reader); if (operand.IsToken) { MDToken token = new MDToken(operand.Token); if (token.Table == Table.TypeDef) { return(this.Module.ResolveTypeDef(token.Rid)); } else if (token.Table == Table.TypeRef) { return(this.Module.ResolveTypeRef(token.Rid)); } else if (token.Table == Table.TypeSpec) { return(this.Module.ResolveTypeSpec(token.Rid)); } throw new Exception("Unable to resolve type: bad MDToken table"); } else { TypeData data = operand.Data as TypeData; // Resolve via name TypeName typeName = new TypeName(data.Name); NameResolver nameResolver = new NameResolver(this.Module); ITypeDefOrRef typeDefOrRef = nameResolver.ResolveTypeDefOrRef(typeName); if (typeDefOrRef == null) { throw new Exception(String.Format( "Unable to resolve ITypeDefOrRef from given name: {0}", typeName.FullName)); } // Apply generics, if any (resulting in a TypeSpec) if (data.GenericTypes.Length > 0) { typeDefOrRef = ApplyGenerics(typeDefOrRef, data); } if (typeDefOrRef == null) { throw new Exception(String.Format( "Unable to apply generic types: {0}", typeName.FullName )); } // Apply [], *, & typeDefOrRef = SigUtil.FromBaseSig(typeDefOrRef.ToTypeSig(), typeName.Modifiers) .ToTypeDefOrRef(); return(typeDefOrRef); } }
/// <summary> /// Creates the command. /// </summary> /// <param name="operationType">Type of the operation.</param> /// <param name="config">The configuration.</param> /// <returns></returns> internal AsyncOperationCommand CreateCommand(Guid operationType, IOrganizationConfiguration config) { TypeData typeData = new TypeData(System.Type.GetType(ConfigurationManager.AppSettings[operationType.ToString().ToUpper()]), operationType); if (typeData != null) { MyTrace.Write(TraceCategory.AsyncService, Mysoft.MAP2.Common.Trace.TraceLevel.Info, "为作业类型{0}创建AsyncOperationCommand {1}。", operationType, typeData.Value); return System.Activator.CreateInstance(typeData.Value, this, config) as AsyncOperationCommand; } MyTrace.Write(TraceCategory.AsyncService, Mysoft.MAP2.Common.Trace.TraceLevel.Warning, "未找到作业类型{0}对应AsyncOperationCommand类型。", operationType); return new UnrecognizedOperationTypeCommand(this, config); }
public void RequestQueryParserOperatorsReferences() { // AllTypesWithReferences var referenceTypes = new Type[] { typeof(object), // an open property null // a null literal }; CombinatorialEngine engine = CombinatorialEngine.FromDimensions( new Dimension("Operator", OperatorData.Values), new Dimension("LeftType", referenceTypes), new Dimension("RightType", TypeData.Values)); OpenTypeContextWithReflection <AllTypesWithReferences> .ClearHandlers(); try { OpenTypeContextWithReflection <AllTypesWithReferences> .ValuesRequested += (x, y) => { ((OpenTypeContextWithReflection <AllTypesWithReferences>)x).SetValues(new object[] { new AllTypesWithReferences() }); }; using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(OpenTypeContextWithReflection <AllTypesWithReferences>); TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values) { Type left = (Type)values["LeftType"]; TypeData right = (TypeData)values["RightType"]; if (!right.IsTypeSupported) { return; } string leftName = AllTypesWithReferences.PropertyNameForReferenceType(left); string rightName = AllTypesWithReferences.PropertyNameForType(right.ClrType); OperatorData o = (OperatorData)values["Operator"]; string requestText = "/Values?$filter=" + leftName + "%20" + o.Token + "%20" + rightName; request.RequestUriString = requestText; Trace.WriteLine("Sending request " + requestText); Exception exception = TestUtil.RunCatching(request.SendRequest); if (left == null) { // Anything can be compared to null (but only for equality, no ordering supported). TestUtil.AssertExceptionExpected(exception, !o.IsEqualityComparison); } else if (left == typeof(object)) { // Anything can be compared to an open property for anything at parse time. // At execution time, ordering will only be supported for types which can be // ordered as well. // // NOTE: because the sample values are null, reference checks will succeed at runtime. // (we normally would just fail this at parse time, but because these are reference // types and provides the open type comparer, it passes; that's probably OK, in case // a back-end does provider order for these types) TestUtil.AssertExceptionExpected(exception, !o.IsEqualityComparison && !right.IsOrderComparableTo(right) && right.ClrType != typeof(byte[]) && right.ClrType != typeof(System.Data.Linq.Binary) && right.ClrType != typeof(System.Xml.Linq.XElement) && !(null != Nullable.GetUnderlyingType(right.ClrType))); } }); } } finally { OpenTypeContextWithReflection <AllTypesWithReferences> .ClearHandlers(); } }
private static IconType GetIconType(TypeData type) { if (type.Inner.IsEnum) return IconType.Enum; if (type.Inner.IsInterface) return IconType.Interface; return type.Inner.IsClass ? IconType.Class : IconType.Struct; }
public void SaveAndLoadTestPlanReference() { double defaultValue = 0.7; //seconds //double tolerance = Math.Abs(newValue * .0000001); // The tolerance for variation in their delay double values int stepsCount = 1; // how many delay steps should be generated and tested string externalParameterName = "External Delay"; string externalParamaterNameEncoded = "External_x0020_Delay"; string externalParamaterNameLegacy = "prop0"; string filePath1 = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".TapPlan"; string filePath2 = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".TapPlan"; string filePath3 = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".TapPlan"; try { // Save the test plan to be referenced GenerateTestPlanWithNDelaySteps(stepsCount, filePath1, defaultValue, externalParameterName); // Scope for separating the test Serialization (Save) from Deserialization (Load) { // Create a test plan TestPlan testPlan = new TestPlan(); // Create a ReferencePlanStep and add it to the test plan TestPlanReference tpr = new TestPlanReference(); MacroString ms = new MacroString(tpr) { Text = filePath1 }; tpr.Filepath = ms; // automatically calls LoadTesPlan testPlan.ChildTestSteps.Add(tpr); // Save the new test plan testPlan.Save(filePath2); // The output should be something like this, remark the "External Delay" has been encoded as "External_x0020_Delay" //<?xml version=\"1.0\" encoding=\"utf-8\"?> //<TestPlan type=\"OpenTap.TestPlan\" Locked=\"false\"> // <Steps> // <TestStep type=\"[email protected]\" Version=\"9.0.0-Development\" Id=\"ae56d9d6-e077-4524-bd14-cb0c9f2d4ced\"> // <External_x0020_Delay>0.7</External_x0020_Delay> // <Filepath>%TEMP%\\e7563ab3-d5e2-4e27-bc77-1f9b76feb37c.TapPlan</Filepath> // <StepMapping /> // <Enabled>true</Enabled> // <Name>Test Plan Reference</Name> // </TestStep> // </Steps> // <Package.Dependencies> // <Package Name=\"OpenTAP\" Version=\"9.0.0+15a61e86\" /> // </Package.Dependencies> //</TestPlan> // Verify that the saved file contains the encoded elements using (var str = File.Open(filePath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var read = new StreamReader(str)) { string content = read.ReadToEnd(); Assert.IsTrue(content.Contains($"<{externalParamaterNameEncoded}>")); Assert.IsTrue(content.Contains($"</{externalParamaterNameEncoded}>")); Assert.IsFalse(content.Contains($"<{externalParameterName}>")); Assert.IsFalse(content.Contains($"</{externalParameterName}>")); Assert.IsFalse(content.Contains($"<{externalParamaterNameLegacy}>")); Assert.IsFalse(content.Contains($"</{externalParamaterNameLegacy}>")); } } } // Scope for separating the test Deserialization (Load) from Serialization (Save) { TestPlan testPlan = TestPlan.Load(filePath2); Assert.AreEqual(1, testPlan.ChildTestSteps.Count); TestPlanReference tpr = testPlan.ChildTestSteps[0] as TestPlanReference; Assert.IsNotNull(tpr); ITypeData ti = TypeData.GetTypeData(tpr); // ensure there is a property "External Delay" IMemberData mi = ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParameterName)); Assert.IsNotNull(mi); Assert.AreEqual(defaultValue, mi.GetValue(tpr)); // ensure there is no property "External_x0020_Delay" Assert.IsNull(ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParamaterNameEncoded))); // ensure there is no property "prop0" Assert.IsNull(ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParamaterNameLegacy))); } // Scope for separating the test Deserialization legacy (Load) from Serialization (Save) { // Replace string content = ""; using (var str = File.Open(filePath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var read = new StreamReader(str)) { content = read.ReadToEnd(); } } Assert.IsTrue(content.Contains($"<{externalParamaterNameEncoded}>")); Assert.IsTrue(content.Contains($"</{externalParamaterNameEncoded}>")); Assert.IsFalse(content.Contains($"<{externalParameterName}>")); Assert.IsFalse(content.Contains($"</{externalParameterName}>")); Assert.IsFalse(content.Contains($"<{externalParamaterNameLegacy}>")); Assert.IsFalse(content.Contains($"</{externalParamaterNameLegacy}>")); content = content.Replace(externalParamaterNameEncoded, externalParamaterNameLegacy); Assert.IsFalse(content.Contains($"<{externalParamaterNameEncoded}>")); Assert.IsFalse(content.Contains($"</{externalParamaterNameEncoded}>")); Assert.IsFalse(content.Contains($"<{externalParameterName}>")); Assert.IsFalse(content.Contains($"</{externalParameterName}>")); Assert.IsTrue(content.Contains($"<{externalParamaterNameLegacy}>")); Assert.IsTrue(content.Contains($"</{externalParamaterNameLegacy}>")); Assert.IsFalse(File.Exists(filePath3)); using (var str = File.Open(filePath3, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { using (var write = new StreamWriter(str)) { write.Write(content); } } Assert.IsTrue(File.Exists(filePath3)); // Load the test case and its test ref TestPlan testPlan = TestPlan.Load(filePath3); Assert.AreEqual(1, testPlan.ChildTestSteps.Count); TestPlanReference tpr = testPlan.ChildTestSteps[0] as TestPlanReference; Assert.IsNotNull(tpr); ITypeData ti = TypeData.GetTypeData(tpr); // ensure there is a property "External Delay" IMemberData mi = ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParameterName)); Assert.IsNotNull(mi); Assert.AreEqual(defaultValue, mi.GetValue(tpr)); // ensure there is no property "External_x0020_Delay" Assert.IsNull(ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParamaterNameEncoded))); // ensure there is no property "prop0" Assert.IsNull(ti.GetMembers().FirstOrDefault(m => m.Attributes.Any(xa => (xa as DisplayAttribute)?.Name == externalParamaterNameLegacy))); } } finally { if (File.Exists(filePath1)) { File.Delete(filePath1); } if (File.Exists(filePath2)) { File.Delete(filePath2); } if (File.Exists(filePath3)) { File.Delete(filePath3); } } }