/// <summary> /// Gets the set of <see cref="IWebHookHandler"/> instances discovered by a default /// discovery mechanism which is used if none are registered with the Dependency Injection engine. /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> containing the discovered instances.</returns> public static IEnumerable <IWebHookHandler> GetHandlers() { if (_handlers != null) { return(_handlers); } IAssembliesResolver assembliesResolver = WebHooksConfig.Config.Services.GetAssembliesResolver(); ICollection <Assembly> assemblies = assembliesResolver.GetAssemblies(); IEnumerable <IWebHookHandler> instances = TypeUtilities.GetInstances <IWebHookHandler>(assemblies, t => TypeUtilities.IsType <IWebHookHandler>(t)); Interlocked.CompareExchange(ref _handlers, instances, null); return(_handlers); }
public void GetValueFromEnum() { Assert.AreEqual(System.UriKind.RelativeOrAbsolute, TypeUtilities.InvokeTypeMember(typeof(System.UriKind), "RelativeOrAbsolute", null)); }
private object GetValue(object target) { var typeInfo = target.GetType().GetTypeInfo(); var list = target as IList; var dictionary = target as IDictionary; var indexerProperty = GetIndexer(typeInfo); var indexerParameters = indexerProperty?.GetIndexParameters(); if (indexerProperty != null && indexerParameters.Length == Arguments.Count) { var convertedObjectArray = new object[indexerParameters.Length]; for (int i = 0; i < Arguments.Count; i++) { object temp = null; if (!TypeUtilities.TryConvert(indexerParameters[i].ParameterType, Arguments[i], CultureInfo.InvariantCulture, out temp)) { return(AvaloniaProperty.UnsetValue); } convertedObjectArray[i] = temp; } var intArgs = convertedObjectArray.OfType <int>().ToArray(); // Try special cases where we can validate indicies if (typeInfo.IsArray) { return(GetValueFromArray((Array)target, intArgs)); } else if (Arguments.Count == 1) { if (list != null) { if (intArgs.Length == Arguments.Count && intArgs[0] >= 0 && intArgs[0] < list.Count) { return(list[intArgs[0]]); } return(AvaloniaProperty.UnsetValue); } else if (dictionary != null) { if (dictionary.Contains(convertedObjectArray[0])) { return(dictionary[convertedObjectArray[0]]); } return(AvaloniaProperty.UnsetValue); } else { // Fallback to unchecked access return(indexerProperty.GetValue(target, convertedObjectArray)); } } else { // Fallback to unchecked access return(indexerProperty.GetValue(target, convertedObjectArray)); } } // Multidimensional arrays end up here because the indexer search picks up the IList indexer instead of the // multidimensional indexer, which doesn't take the same number of arguments else if (typeInfo.IsArray) { return(GetValueFromArray((Array)target)); } return(AvaloniaProperty.UnsetValue); }
public void RaiseIfUnknownType() { TypeUtilities.GetType(new BindingEnvironment(), "Foo.Bar"); }
public void GetValueFromType() { Assert.IsFalse((bool)TypeUtilities.InvokeTypeMember(typeof(System.IO.File), "Exists", new object[] { "unknown.txt" })); }
private static ObjectInstance __STUB__Construct(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is DataViewConstructor)) { throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'Construct' is not generic."); } switch (args.Length) { case 0: return(((DataViewConstructor)thisObj).Construct(null, 0, null)); case 1: return(((DataViewConstructor)thisObj).Construct(TypeUtilities.IsUndefined(args[0]) ? null : TypeConverter.ToObject <ArrayBufferInstance>(engine, args[0]), 0, null)); case 2: return(((DataViewConstructor)thisObj).Construct(TypeUtilities.IsUndefined(args[0]) ? null : TypeConverter.ToObject <ArrayBufferInstance>(engine, args[0]), TypeUtilities.IsUndefined(args[1]) ? 0 : TypeConverter.ToInteger(args[1]), null)); default: return(((DataViewConstructor)thisObj).Construct(TypeUtilities.IsUndefined(args[0]) ? null : TypeConverter.ToObject <ArrayBufferInstance>(engine, args[0]), TypeUtilities.IsUndefined(args[1]) ? 0 : TypeConverter.ToInteger(args[1]), TypeUtilities.IsUndefined(args[2]) ? (int?)null : TypeConverter.ToInteger(args[2]))); } }
private bool TestRequirementInternal() { // This requirement will only ever be checked once in the event the containing assembly does not exist. return(requiredTypeNames.All(typeName => TypeUtilities.TypeExists(typeName))); }
/// <summary> /// Casts a strongly typed match function to a weakly typed one. /// </summary> /// <param name="f">The strongly typed function.</param> /// <returns>The weakly typed function.</returns> private static Func <object, bool> CastMatch(Func <T, bool> f) { return(o => TypeUtilities.CanCast <T>(o) && f((T)o)); }
public EditResourceModel(DesignerContext designerContext, DictionaryEntryNode resourceEntryNode, IPropertyInspector transactionContext) { this.designerContext = designerContext; this.resourceEntryNode = resourceEntryNode; object key = resourceEntryNode.Key; DocumentNode expression; if ((expression = key as DocumentNode) != null) { this.keyString = XamlExpressionSerializer.GetStringFromExpression(expression, resourceEntryNode.DocumentNode); } else if ((this.keyString = key as string) == null) { this.keyString = key.ToString(); } this.keyStringIsValid = true; ResourceEntryItem resource = (ResourceEntryItem)this.designerContext.ResourceManager.GetResourceItem((DocumentCompositeNode)resourceEntryNode.DocumentNode); this.resourceObjectSet = new ResourceValueObjectSet(resource, designerContext, transactionContext); this.standInProperty = this.resourceObjectSet.CreateProperty(new PropertyReference((ReferenceStep)this.resourceObjectSet.ProjectContext.ResolveProperty(DictionaryEntryNode.ValueProperty)), TypeUtilities.GetAttributes(resource.EffectiveType)); this.standInProperty.PropertyValue.PropertyValueException += new EventHandler <PropertyValueExceptionEventArgs>(this.OnPropertyValueException); this.standInProperty.PropertyValue.PropertyChanged += new PropertyChangedEventHandler(this.OnValuePropertyChanged); }
public virtual void UpdateResponseWithJavaScriptExceptionDetails(IScriptEngine engine, JavaScriptException exception, BrewResponse response) { if (exception == null) { throw new ArgumentNullException("exception"); } if (response == null) { throw new ArgumentNullException("response"); } string message; var stack = String.Empty; var rawStack = String.Empty; var javascriptExceptionMessage = JavaScriptExceptionMessage; if (TypeUtilities.IsString(exception.ErrorObject)) { message = TypeConverter.ToString(exception.ErrorObject); } else if (exception.ErrorObject is ObjectInstance) { var errorObject = exception.ErrorObject as ObjectInstance; message = errorObject.GetPropertyValue("message") as string; if (message == null || message.IsNullOrWhiteSpace()) { message = engine.Stringify(exception.ErrorObject, null, 4); } else { stack = errorObject.GetPropertyValue("stack") as string; rawStack = stack; if (stack != null && stack.IsNullOrWhiteSpace() == false) { stack = stack.Replace("at ", "at<br/>"); javascriptExceptionMessage = JavaScriptExceptionMessageWithStackTrace; } } } else { message = exception.ErrorObject.ToString(); } response.StatusCode = HttpStatusCode.BadRequest; response.StatusDescription = message; response.ContentType = "text/html"; string exceptionName = exception.Name; if (exceptionName.IsNullOrWhiteSpace()) { exceptionName = "JavaScript Error"; } var resultMessage = String.Format(javascriptExceptionMessage, exceptionName, message, exception.FunctionName, exception.LineNumber, exception.SourcePath, stack); response.Content = Encoding.UTF8.GetBytes(resultMessage); response.ExtendedProperties.Add("Exception_Message", message); response.ExtendedProperties.Add("Exception_Name", exceptionName); response.ExtendedProperties.Add("Exception_FunctionName", exception.FunctionName); response.ExtendedProperties.Add("Exception_LineNumber", exception.LineNumber.ToString(CultureInfo.InvariantCulture)); response.ExtendedProperties.Add("Exception_SourcePath", exception.SourcePath); response.ExtendedProperties.Add("Exception_StackTrace", rawStack); }
/// <summary> /// Initializes a new instance of the <see cref="FuncDataTemplate{T}"/> class. /// </summary> /// <param name="build"> /// A function which when passed an object of <typeparamref name="T"/> returns a control. /// </param> /// <param name="supportsRecycling">Whether the control can be recycled.</param> public FuncDataTemplate(Func <T, INameScope, IControl> build, bool supportsRecycling = false) : base(o => TypeUtilities.CanCast <T>(o), CastBuild(build), supportsRecycling) { }
/// <summary> /// Generate all the necessary logic for serialization of payload types used by grain interfaces. /// </summary> internal static void GenerateSerializationForClass(Assembly grainAssembly, Type t, CodeNamespace container, HashSet <string> referencedNamespaces, Language language) { var generateSerializers = !CheckForCustomSerialization(t); var generateCopier = !CheckForCustomCopier(t); if (!generateSerializers && !generateCopier) { return; // If the class declares all custom implementations, then we don't need to do anything... } bool notVB = (language != Language.VisualBasic); var openGenerics = notVB ? "<" : "(Of "; var closeGenerics = notVB ? ">" : ")"; // Add the class's namespace to this namespace's imports, as well as some other imports we use container.Imports.Add(new CodeNamespaceImport("System")); container.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); container.Imports.Add(new CodeNamespaceImport("System.Reflection")); container.Imports.Add(new CodeNamespaceImport("Orleans.Serialization")); if (!String.IsNullOrEmpty(t.Namespace)) { container.Imports.Add(new CodeNamespaceImport(t.Namespace)); } // Create the class declaration, including any required generic parameters // At one time this was a struct, not a class, so all the variable names are "structFoo". Too bad. // Note that we need to replace any periods in the type name with _ to properly handle nested classes var className = TypeUtils.GetSimpleTypeName(TypeUtils.GetFullName(t)); var serializationClassName = className.Replace('.', '_') + SERIALIZER_CLASS_NAME_SUFFIX; var serializationClassOpenName = serializationClassName; var classDecl = new CodeTypeDeclaration(serializationClassName) { IsClass = true }; classDecl.Attributes = (classDecl.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; classDecl.TypeAttributes = TypeAttributes.NotPublic; CodeGeneratorBase.MarkAsGeneratedCode(classDecl); if (!t.IsGenericType) { classDecl.CustomAttributes.Add( new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference))); } if (t.IsGenericType) { className += openGenerics; serializationClassOpenName += openGenerics; bool first = true; foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments()) { var param = new CodeTypeParameter(genericParameter.Name); if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None) { param.Constraints.Add(" class"); } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None) { param.Constraints.Add(" struct"); } var constraints = genericParameter.GetGenericParameterConstraints(); foreach (var constraintType in constraints) { param.Constraints.Add(new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType))); } if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None) { param.HasConstructorConstraint = true; } classDecl.TypeParameters.Add(param); if (!first) { className += ", "; serializationClassOpenName += ","; } className += genericParameter.Name; first = false; } className += closeGenerics; serializationClassOpenName += closeGenerics; } // A couple of repeatedly-used CodeDom snippets var classType = new CodeTypeOfExpression(className); var classTypeReference = new CodeTypeReference(className); var objectTypeReference = new CodeTypeReference(typeof(object)); var serMgrRefExp = new CodeTypeReferenceExpression(typeof(SerializationManager)); var currentSerialzationContext = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(SerializationContext)), "Current"); // Static DeepCopyInner method: var copier = new CodeMemberMethod(); if (generateCopier) { classDecl.Members.Add(copier); } copier.Attributes = (copier.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; copier.Attributes = (copier.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; copier.Name = "DeepCopier"; copier.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "original")); bool shallowCopyable = t.IsOrleansShallowCopyable(); if (shallowCopyable) { copier.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("original"))); } else { copier.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input", new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("original")))); } copier.ReturnType = objectTypeReference; // Static serializer method: var serializer = new CodeMemberMethod(); if (generateSerializers) { classDecl.Members.Add(serializer); } serializer.Attributes = (serializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; serializer.Attributes = (serializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; serializer.Name = "Serializer"; serializer.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "untypedInput")); serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream")); serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); serializer.ReturnType = new CodeTypeReference(typeof(void)); serializer.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input", new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("untypedInput")))); // Static deserializer method; note that this will never get called for null values or back references var deserializer = new CodeMemberMethod(); if (generateSerializers) { classDecl.Members.Add(deserializer); } deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; deserializer.Name = "Deserializer"; deserializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); deserializer.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(BinaryTokenStreamReader), CodeTypeReferenceOptions.GlobalReference), "stream")); deserializer.ReturnType = objectTypeReference; // Static constructor, which just calls the Init method var staticConstructor = new CodeTypeConstructor(); classDecl.Members.Add(staticConstructor); staticConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, "Register"))); // Init method, which registers the type with the serialization manager, and later may get some static FieldInfo initializers var init = new CodeMemberMethod(); classDecl.Members.Add(init); init.Name = "Register"; init.Attributes = (init.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; init.Attributes = (init.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; if (generateCopier && generateSerializers) { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"), new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"), new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer"))); } else if (generateCopier) { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"), null, null)); } else { init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType, null, new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"), new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer"))); } CodeStatement constructor; var consInfo = t.GetConstructor(Type.EmptyTypes); if (consInfo != null) { if (!t.ContainsGenericParameters) { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(t)); } else { var typeName = TypeUtils.GetParameterizedTemplateName(t, tt => tt.Namespace != container.Name && !referencedNamespaces.Contains(tt.Namespace), true); if (language == Language.VisualBasic) { typeName = typeName.Replace("<", "(Of ").Replace(">", ")"); } constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(typeName)); } } else if (t.IsValueType) { constructor = !t.ContainsGenericParameters ? new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(t))) : new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(TypeUtils.GetTemplatedName(t)))); } else { if (!t.ContainsGenericParameters) { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)), "GetUninitializedObject", new CodeTypeOfExpression(t)))); } else { constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)), "GetUninitializedObject", new CodeTypeOfExpression(TypeUtils.GetTemplatedName(t))))); } } if (!shallowCopyable) { copier.Statements.Add(constructor); copier.Statements.Add(new CodeMethodInvokeExpression(currentSerialzationContext, "RecordObject", new CodeVariableReferenceExpression("original"), new CodeVariableReferenceExpression("result"))); } deserializer.Statements.Add(constructor); // For structs, once we encounter a field that we have to use reflection to set, we need to switch to a boxed representation and reflection // for the rest of the fields in the struct while setting. This flag indicates that we're in that mode. bool usingBoxedReflection = false; // For every field in the class: int counter = 0; List <FieldInfo> fields = GetAllFields(t).ToList(); fields.Sort(new FieldNameComparer()); foreach (var fld in fields) { if (fld.IsNotSerialized || fld.IsLiteral) { continue; } var fldType = fld.FieldType; if (TypeUtilities.IsTypeIsInaccessibleForSerialization(fldType, t.Module, grainAssembly)) { ConsoleText.WriteStatus("Skipping generation of serializer for {0} because one of it's field {1} is of a private/internal type.", t.FullName, fld.Name); return; // We cannot deserialize a class with a field of non-public type. Need to add a proper reporting here. } // Import the namespace for the field's type (and any of its parameters), just in case it's not already added ImportFieldNamespaces(fld.FieldType, container.Imports); SerializerGenerationManager.RecordTypeToGenerate(fld.FieldType); counter++; // Add the statements moving to and from a class instance, to the instance creation method and the non-default constructor // Getter and setter for this field's value from a class object CodeExpression getter = null; SetterGenerator setter = null; var name = fld.Name; // Normalize the field name -- strip trailing @ (F#) and look for automatic properties var normalizedName = name.TrimEnd('@'); if (name.StartsWith("<")) { // Backing field for an automatic property; see if it's public so we can use it var propertyName = name.Substring(1, name.IndexOf('>') - 1).TrimEnd('@'); var property = t.GetProperty(propertyName); // If the property is public and not hidden... if ((property != null) && property.DeclaringType == fld.DeclaringType) { if (property.GetGetMethod() != null) { getter = new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("input"), propertyName); } if (!usingBoxedReflection && (property.GetSetMethod() != null)) { setter = value => { var s = new CodeAssignStatement { Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("result"), propertyName), Right = value }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } } } var typeName = TypeUtils.GetTemplatedName(fld.FieldType, _ => !_.IsGenericParameter, language); // See if it's a public field if ((getter == null) || (setter == null)) { if (fld.Attributes.HasFlag(FieldAttributes.Public)) { if (getter == null) { getter = new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("input"), normalizedName); } if (!usingBoxedReflection && (setter == null) && !fld.IsInitOnly) { setter = value => { var s = new CodeAssignStatement { Left = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("result"), normalizedName), Right = value }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } } } // Have to use reflection if ((getter == null) || (setter == null)) { // Add a static field for the FieldInfo, and a static constructor string infoName = "fieldInfo" + counter; var info = new CodeMemberField(typeof(FieldInfo), infoName); info.Attributes |= MemberAttributes.Private | MemberAttributes.Static; classDecl.Members.Add(info); CodeTypeOfExpression fieldAccessType; if (fld.DeclaringType == t) { fieldAccessType = classType; } else { FieldInfo fld2 = t.GetField(fld.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((fld2 != null) && fld2.DeclaringType == fld.DeclaringType) { fieldAccessType = classType; } else { fieldAccessType = fld.DeclaringType.IsGenericType ? new CodeTypeOfExpression(TypeUtils.GetTemplatedName(fld.DeclaringType)) : new CodeTypeOfExpression(fld.DeclaringType); } } init.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(null, infoName), new CodeMethodInvokeExpression(fieldAccessType, "GetField", new CodePrimitiveExpression(name), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance"), CodeBinaryOperatorType.BitwiseOr, new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public"), CodeBinaryOperatorType.BitwiseOr, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic")))))); // Build the getter and setter if (getter == null) { getter = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeFieldReferenceExpression(null, infoName), "GetValue"), new CodeArgumentReferenceExpression("input")); } if (setter == null) { // If the type is a struct, then the setter becomes somewhat more complicated, so first treat non-structs if (t.IsByRef) { setter = value => { var s = new CodeExpressionStatement { Expression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeFieldReferenceExpression(null, infoName), "SetValue"), new CodeVariableReferenceExpression("result"), value) }; return(new CodeStatementCollection(new CodeStatement[] { s })); }; } else { // If this is the first field to use setting by reflection in a struct, we need to box the struct before we can continue if (!usingBoxedReflection) { usingBoxedReflection = true; // NOTE: object objResult = (object)result; if (!shallowCopyable) { copier.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult", new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result")))); } deserializer.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult", new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result")))); } var temp = "temp" + counter; setter = value => { var s1 = new CodeVariableDeclarationStatement(typeof(object), temp, value); var s2 = new CodeExpressionStatement { Expression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(null, infoName), "SetValue"), new CodeVariableReferenceExpression("objResult"), new CodeVariableReferenceExpression(temp)) }; return(new CodeStatementCollection(new CodeStatement[] { s1, s2 })); }; } } } // Copy this field, if needed if (!shallowCopyable) { if (fld.FieldType.IsOrleansShallowCopyable()) { copier.Statements.AddRange(setter(getter)); } else { copier.Statements.AddRange(fld.FieldType == typeof(object) ? setter(new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter)) : setter(new CodeCastExpression(typeName, new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter)))); } } // Serialize this field serializer.Statements.Add(new CodeMethodInvokeExpression(serMgrRefExp, "SerializeInner", getter, new CodeArgumentReferenceExpression("stream"), new CodeTypeOfExpression(typeName))); // Deserialize this field deserializer.Statements.AddRange(setter(new CodeCastExpression(typeName, new CodeMethodInvokeExpression(serMgrRefExp, "DeserializeInner", new CodeTypeOfExpression(typeName), new CodeArgumentReferenceExpression("stream"))))); } // Add return statements, as needed if (!shallowCopyable) { copier.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result"))); } deserializer.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result"))); // Special processing for generic types, necessary so that the appropriate closed types will get generated at run-time if (t.IsGenericType) { var masterClassName = TypeUtils.GetSimpleTypeName(t) + "GenericMaster"; var masterClass = new CodeTypeDeclaration(masterClassName); container.Types.Add(masterClass); masterClass.IsClass = true; masterClass.Attributes |= MemberAttributes.Static | MemberAttributes.Assembly | MemberAttributes.Final; masterClass.TypeAttributes = TypeAttributes.NotPublic; masterClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference))); var masterInit = AddInitMethod(masterClass); masterInit.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", new CodeTypeOfExpression(t), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericCopier"), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericSerializer"), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericDeserializer"))); var initClosed = new CodeMethodInvokeExpression { Method = new CodeMethodReferenceExpression { MethodName = "Invoke", TargetObject = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression ("closed"), "GetMethod", new CodePrimitiveExpression( "Register")) } }; initClosed.Parameters.Add(new CodePrimitiveExpression(null)); initClosed.Parameters.Add(new CodeArrayCreateExpression(typeof(object), 0)); var create = new CodeMemberMethod(); masterClass.Members.Add(create); create.Attributes = (create.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; create.Attributes = (create.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; create.Name = "CreateConcreteType"; create.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type[]), "typeParams")); create.ReturnType = new CodeTypeReference(typeof(Type)); create.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(serializationClassOpenName), "MakeGenericType", new CodeArgumentReferenceExpression("typeParams")))); var cop = new CodeMemberMethod(); masterClass.Members.Add(cop); cop.Attributes = (cop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cop.Attributes = (cop.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; cop.Name = "GenericCopier"; cop.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj")); cop.ReturnType = new CodeTypeReference(typeof(object)); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("obj"), "GetType"), "GetGenericArguments")))); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("DeepCopier")))); cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("obj") }))); cop.Statements.Add(new CodeMethodReturnStatement( new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args")))); var ser = new CodeMemberMethod(); masterClass.Members.Add(ser); ser.Attributes = (ser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; ser.Attributes = (ser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; ser.Name = "GenericSerializer"; ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "input")); ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream")); ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); ser.ReturnType = new CodeTypeReference(typeof(void)); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("input"), "GetType"), "GetGenericArguments")))); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Serializer")))); ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("input"), new CodeArgumentReferenceExpression("stream"), new CodeArgumentReferenceExpression("expected") }))); ser.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args"))); var deser = new CodeMemberMethod(); masterClass.Members.Add(deser); deser.Attributes = (deser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; deser.Attributes = (deser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static; deser.Name = "GenericDeserializer"; deser.ReturnType = new CodeTypeReference(typeof(object)); deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected")); deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamReader), "stream")); deser.ReturnType = new CodeTypeReference(typeof(object)); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType", new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("expected"), "GetGenericArguments")))); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f", new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Deserializer")))); deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args", new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("expected"), new CodeArgumentReferenceExpression("stream") }))); deser.Statements.Add(new CodeMethodReturnStatement( new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(), new CodeVariableReferenceExpression("args")))); } container.Types.Add(classDecl); }
/// <inheritdoc/> public void OnNext(object value) { if (value == BindingOperations.DoNothing) { return; } using (_inner.Subscribe(_ => { })) { var type = _inner.ResultType; if (type != null) { var converted = Converter.ConvertBack( value, type, ConverterParameter, CultureInfo.CurrentCulture); if (converted == BindingOperations.DoNothing) { return; } if (converted == AvaloniaProperty.UnsetValue) { converted = TypeUtilities.Default(type); _inner.SetValue(converted, _priority); } else if (converted is BindingNotification) { var notification = converted as BindingNotification; if (notification.ErrorType == BindingErrorType.None) { throw new AvaloniaInternalException( "IValueConverter should not return non-errored BindingNotification."); } PublishNext(notification); if (_fallbackValue != AvaloniaProperty.UnsetValue) { if (TypeUtilities.TryConvert( type, _fallbackValue, CultureInfo.InvariantCulture, out converted)) { _inner.SetValue(converted, _priority); } else { Logger.TryGet(LogEventLevel.Error)?.Log( LogArea.Binding, this, "Could not convert FallbackValue {FallbackValue} to {Type}", _fallbackValue, type); } } } else { _inner.SetValue(converted, _priority); } } } }
public DecisionsFramework.Design.Flow.FlowStep ConvertStep(ConversionData allConvertData, ConvertedStep stepToConvert) { CreateDataStep ps = new CreateDataStep(); FlowStep fs = new FlowStep(ps); List <PlaceholderData> allDataDefinitions = new List <PlaceholderData>(); foreach (OutcomeDefinition outcome in stepToConvert.OutcomeData) { foreach (DataDefinition outputData in outcome.OutcomeData) { Type t = TypeUtilities.FindTypeByFullName(outputData.FullTypeName); //Type t might be null if we aren't able to resolve the type of a custom type //so let's just set it to string. if (t == null) { t = typeof(string); } allDataDefinitions.Add( new PlaceholderData(new DecisionsNativeType(t), outputData.Name, outputData.IsList) ); } } ps.DataDefinitions = allDataDefinitions.ToArray(); // Now do the mapping. List <IOutputMapping> outputMapping = new List <IOutputMapping>(); foreach (OutcomeDefinition outcome in stepToConvert.OutcomeData) { foreach (DataDefinition outputData in outcome.OutcomeData) { RenameOutputMapping mapping = new RenameOutputMapping(); mapping.DataName = outputData.Name; mapping.OutputDataName = outputData.Name; outputMapping.Add(mapping); } } fs.OutputMapping = outputMapping.ToArray(); //string varName = (ConvertUtility.ConvertStepInputToInputMapping(stepToConvert.InputData.FirstOrDefault())).InputDataName; string varName = (stepToConvert.InputData.FirstOrDefault()).Name; Type type = Type.GetType(stepToConvert.InputData.FirstOrDefault().FullTypeName); object value = new bool(); //if (type == typeof(bool)) //{ // value = Convert.ToBoolean(stepToConvert.InputData.FirstOrDefault().ConstantValue); //} bool result; if (bool.TryParse(stepToConvert.InputData.FirstOrDefault().ConstantValue, out result)) { value = result; } //if (type == typeof(int)) //{ // value = Convert.ToInt32(stepToConvert.InputData.FirstOrDefault().ConstantValue); //} //else //{ // value = stepToConvert.InputData.FirstOrDefault().ConstantValue; //} //fs.AddInputMapping(new ConstantInputMapping() { InputDataName = varName, Value = stepToConvert.InputData.FirstOrDefault().ConstantValue }); fs.AddInputMapping(new ConstantInputMapping() { InputDataName = varName, Value = result }); return(fs); }
private static ReferenceExpression ReferenceExpressionFor(Type type) { return(ReferenceExpression.Lift(TypeUtilities.GetFullName(type))); }
private static object __STUB__Construct(ScriptEngine engine, object thisObj, object[] args) { switch (args.Length) { case 0: throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object"); case 1: throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object"); case 2: return(Construct(TypeConverter.ToObject <FunctionInstance>(engine, args[0]), TypeConverter.ToObject(engine, args[1]), null)); default: return(Construct(TypeConverter.ToObject <FunctionInstance>(engine, args[0]), TypeConverter.ToObject(engine, args[1]), TypeUtilities.IsUndefined(args[2]) ? null : TypeConverter.ToObject <FunctionInstance>(engine, args[2]))); } }
public int GetHashCode(object obj) { return(TypeUtilities.NormalizeValue(obj).GetHashCode()); }
internal bool RecordTypeToGenerate(Type t, Module module, Assembly targetAssembly) { if (!TypeUtilities.IsAccessibleFromAssembly(t, targetAssembly)) { return(false); } var typeInfo = t.GetTypeInfo(); if (typeInfo.IsGenericParameter || processedTypes.Contains(t) || typesToProcess.Contains(t) || typeof(Exception).GetTypeInfo().IsAssignableFrom(t) || typeof(Delegate).GetTypeInfo().IsAssignableFrom(t) || typeof(Task <>).GetTypeInfo().IsAssignableFrom(t)) { return(false); } if (typeInfo.IsArray) { RecordTypeToGenerate(typeInfo.GetElementType(), module, targetAssembly); return(false); } if (typeInfo.IsNestedFamily || typeInfo.IsNestedPrivate) { log.Warn( ErrorCode.CodeGenIgnoringTypes, "Skipping serializer generation for nested type {0}. If this type is used frequently, you may wish to consider making it non-nested.", t.Name); return(false); } if (t.IsConstructedGenericType) { var args = typeInfo.GetGenericArguments(); foreach (var arg in args) { RecordTypeToGenerate(arg, module, targetAssembly); } } if (typeInfo.IsInterface || typeInfo.IsAbstract || t == typeof(object) || t == typeof(void) || GrainInterfaceUtils.IsTaskType(t)) { return(false); } if (t.IsConstructedGenericType) { return(RecordTypeToGenerate(typeInfo.GetGenericTypeDefinition(), module, targetAssembly)); } if (typeInfo.IsOrleansPrimitive() || this.serializationManager.HasSerializer(t) || typeof(IAddressable).GetTypeInfo().IsAssignableFrom(t)) { return(false); } if (typeInfo.Namespace != null && (typeInfo.Namespace.Equals("System") || typeInfo.Namespace.StartsWith("System."))) { var message = "System type " + t.Name + " may require a custom serializer for optimal performance. " + "If you use arguments of this type a lot, consider submitting a pull request to https://github.com/dotnet/orleans/ to add a custom serializer for it."; log.Warn(ErrorCode.CodeGenSystemTypeRequiresSerializer, message); return(false); } if (TypeUtils.HasAllSerializationMethods(t)) { return(false); } // For every field which is not marked as [NonSerialized], check that it is accessible from code. // If any of those fields are not accessible, then a serializer cannot be generated for this type. var skipSerializerGeneration = t.GetAllFields().Where(field => !field.IsNotSerialized()) .Any(field => !TypeUtilities.IsAccessibleFromAssembly(field.FieldType, targetAssembly)); if (skipSerializerGeneration) { return(false); } typesToProcess.Add(t); return(true); }
private Selector?Create(IEnumerable <SelectorGrammar.ISyntax> syntax) { var result = default(Selector); var results = default(List <Selector>); foreach (var i in syntax) { switch (i) { case SelectorGrammar.OfTypeSyntax ofType: result = result.OfType(Resolve(ofType.Xmlns, ofType.TypeName)); break; case SelectorGrammar.IsSyntax @is: result = result.Is(Resolve(@is.Xmlns, @is.TypeName)); break; case SelectorGrammar.ClassSyntax @class: result = result.Class(@class.Class); break; case SelectorGrammar.NameSyntax name: result = result.Name(name.Name); break; case SelectorGrammar.PropertySyntax property: { var type = result?.TargetType; if (type == null) { throw new InvalidOperationException("Property selectors must be applied to a type."); } var targetProperty = AvaloniaPropertyRegistry.Instance.FindRegistered(type, property.Property); if (targetProperty == null) { throw new InvalidOperationException($"Cannot find '{property.Property}' on '{type}"); } object typedValue; if (TypeUtilities.TryConvert( targetProperty.PropertyType, property.Value, CultureInfo.InvariantCulture, out typedValue)) { result = result.PropertyEquals(targetProperty, typedValue); } else { throw new InvalidOperationException( $"Could not convert '{property.Value}' to '{targetProperty.PropertyType}"); } break; } case SelectorGrammar.ChildSyntax child: result = result.Child(); break; case SelectorGrammar.DescendantSyntax descendant: result = result.Descendant(); break; case SelectorGrammar.TemplateSyntax template: result = result.Template(); break; case SelectorGrammar.NotSyntax not: result = result.Not(x => Create(not.Argument)); break; case SelectorGrammar.CommaSyntax comma: if (results == null) { results = new List <Selector>(); } results.Add(result ?? throw new NotSupportedException("Invalid selector!")); result = null; break; default: throw new NotSupportedException($"Unsupported selector grammar '{i.GetType()}'."); } } if (results != null) { if (result != null) { results.Add(result); } result = results.Count > 1 ? Selectors.Or(results) : results[0]; } return(result); }
private static object __STUB__Contains(ScriptEngine engine, object thisObj, object[] args) { if (thisObj == null || thisObj == Undefined.Value || thisObj == Null.Value) { throw new JavaScriptException(ErrorType.TypeError, "Cannot convert undefined or null to object."); } switch (args.Length) { case 0: return(Contains(TypeConverter.ToString(thisObj), "undefined", 0)); case 1: return(Contains(TypeConverter.ToString(thisObj), TypeConverter.ToString(args[0]), 0)); default: return(Contains(TypeConverter.ToString(thisObj), TypeConverter.ToString(args[0]), TypeUtilities.IsUndefined(args[1]) ? 0 : TypeConverter.ToInteger(args[1]))); } }
public TypedArrayInstance Construct(object arg, int byteOffset = 0, int?length = null) { // new Int8Array(typedArray); // new Int8Array(object); // new Int8Array(buffer[, byteOffset[, length]]); if (arg is TypedArrayInstance) { // new %TypedArray%(typedArray); var typedArray = (TypedArrayInstance)arg; // Copy the items one by one. var result = new TypedArrayInstance(this.InstancePrototype, this.type, Engine.ArrayBuffer.Construct(typedArray.Length * BytesPerElement), 0, typedArray.Length); for (int i = 0; i < typedArray.Length; i++) { result[i] = typedArray[i]; } return(result); } else if (arg is ArrayBufferInstance) { // new %TypedArray%(buffer[, byteOffset[, length]]); var buffer = (ArrayBufferInstance)arg; int bytesPerElement = BytesPerElement; int actualLength; if (length == null) { if (byteOffset < 0) { throw new JavaScriptException(Engine, ErrorType.RangeError, "Invalid typed array offset"); } if ((byteOffset % BytesPerElement) != 0) { throw new JavaScriptException(Engine, ErrorType.RangeError, $"Start offset of {this.type} should be a multiple of {BytesPerElement}"); } if ((buffer.ByteLength % BytesPerElement) != 0) { throw new JavaScriptException(Engine, ErrorType.RangeError, $"Byte length of {this.type} should be a multiple of {BytesPerElement}"); } actualLength = (buffer.ByteLength - byteOffset) / bytesPerElement; if (actualLength < 0) { throw new JavaScriptException(Engine, ErrorType.RangeError, "Start offset is too large"); } } else { actualLength = length.Value; if (byteOffset + actualLength * bytesPerElement > buffer.ByteLength) { throw new JavaScriptException(Engine, ErrorType.RangeError, "Invalid typed array length"); } } return(new TypedArrayInstance(this.InstancePrototype, this.type, buffer, byteOffset, actualLength)); } else if (arg is ObjectInstance) { // new %TypedArray%(object); return(From(arg)); } else { // new %TypedArray%(length); if (TypeUtilities.IsUndefined(arg)) { throw new JavaScriptException(Engine, ErrorType.TypeError, "Argument cannot be undefined"); } int argLength = TypeConverter.ToInteger(arg); return(new TypedArrayInstance(this.InstancePrototype, this.type, Engine.ArrayBuffer.Construct(argLength * BytesPerElement), 0, argLength)); } }
public void RaiseIfUnknownType() { Assert.Throws <InvalidOperationException>(() => TypeUtilities.GetType(new Context(), "Foo.Bar"), "Unknown Type 'Foo.Bar'"); }
public void AsType() { Assert.IsNotNull(TypeUtilities.AsType("System.IO.File")); Assert.IsNull(TypeUtilities.AsType("Foo.Bar")); }
private SearchArguments CoerceSearchArguments(object query, object maxResults, object groupByFields) { var args = new Barista.Search.SearchArguments(); if (query == null || query == Null.Value || query == Undefined.Value) { args.Query = new MatchAllDocsQuery(); if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null) { args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults); } } else if (TypeUtilities.IsString(query)) { args.Query = new QueryParserQuery { Query = TypeConverter.ToString(query) }; if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null) { args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults); } if (groupByFields != null && groupByFields != Undefined.Value && groupByFields != Null.Value && groupByFields is ArrayInstance) { args.GroupByFields = ((ArrayInstance)groupByFields) .ElementValues .Select(t => TypeConverter.ToString(t)) .ToList(); } } else { var instance = query as SearchArgumentsInstance; if (instance != null) { var searchArgumentsInstance = instance; args = searchArgumentsInstance.GetSearchArguments(); } else if (query.GetType().IsAssignableFrom(typeof(IQuery <>))) { args = new SearchArguments(); var pi = typeof(IQuery <>).GetProperty("Query"); args.Query = (Query)pi.GetValue(query, null); } else { var obj = query as ObjectInstance; if (obj != null) { var argumentsObj = obj; args = new SearchArguments(); //Duck Type for the win if (argumentsObj.HasProperty("query")) { var queryObj = argumentsObj["query"]; var queryObjType = queryObj.GetType(); var queryProperty = queryObjType.GetProperty("Query", BindingFlags.Instance | BindingFlags.Public); if (queryProperty != null && typeof(Query).IsAssignableFrom(queryProperty.PropertyType)) { args.Query = queryProperty.GetValue(queryObj, null) as Query; } } else { var queryObjType = obj.GetType(); var queryProperty = queryObjType.GetProperty("Query", BindingFlags.Instance | BindingFlags.Public); if (queryProperty != null && typeof(Query).IsAssignableFrom(queryProperty.PropertyType)) { args.Query = queryProperty.GetValue(obj, null) as Query; } if (maxResults != Undefined.Value && maxResults != Null.Value && maxResults != null) { args.Take = JurassicHelper.GetTypedArgumentValue(Engine, maxResults, DefaultMaxResults); } } if (argumentsObj.HasProperty("filter")) { var filterObj = argumentsObj["filter"]; var filterObjType = filterObj.GetType(); var filterProperty = filterObjType.GetProperty("Filter", BindingFlags.Instance | BindingFlags.Public); if (filterProperty != null && typeof(Filter).IsAssignableFrom(filterProperty.PropertyType)) { args.Filter = filterProperty.GetValue(filterObj, null) as Filter; } } if (argumentsObj.HasProperty("groupByFields")) { var groupByFieldsValue = argumentsObj["groupByFields"] as ArrayInstance; if (groupByFieldsValue != null) { args.GroupByFields = groupByFieldsValue .ElementValues .Select(t => TypeConverter.ToString(t)) .ToList(); } } if (argumentsObj.HasProperty("sort") && argumentsObj["sort"] is SortInstance) { var sortValue = (SortInstance)argumentsObj["sort"]; args.Sort = sortValue.Sort; } if (argumentsObj.HasProperty("skip")) { var skipObj = argumentsObj["skip"]; args.Skip = TypeConverter.ToInteger(skipObj); } if (argumentsObj.HasProperty("take")) { var takeObj = argumentsObj["take"]; args.Take = TypeConverter.ToInteger(takeObj); } } else { throw new JavaScriptException(Engine, "Error", "Unable to determine the search arguments."); } } } return(args); }
public void GetMachineCurrent() { Machine machine = new Machine(); Assert.IsNotNull(TypeUtilities.InvokeTypeMember(typeof(Machine), "Current", null)); }
/// <summary> /// Generates a syntax tree for the provided assemblies. /// </summary> /// <param name="targetAssembly">The assemblies used for accessibility checks, or <see langword="null"/> during runtime code generation.</param> /// <param name="assemblies">The assemblies to generate code for.</param> /// <returns>The generated syntax tree.</returns> private GeneratedSyntax GenerateCode(Assembly targetAssembly, List <Assembly> assemblies) { var features = new FeatureDescriptions(); var members = new List <MemberDeclarationSyntax>(); // Expand the list of included assemblies and types. var knownAssemblies = new Dictionary <Assembly, KnownAssemblyAttribute>( assemblies.ToDictionary(k => k, k => default(KnownAssemblyAttribute))); foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes <KnownAssemblyAttribute>())) { knownAssemblies[attribute.Assembly] = attribute; } if (logger.IsEnabled(LogLevel.Information)) { logger.Info($"Generating code for assemblies: {string.Join(", ", knownAssemblies.Keys.Select(a => a.FullName))}"); } // Get types from assemblies which reference Orleans and are not generated assemblies. var grainClasses = new HashSet <Type>(); var grainInterfaces = new HashSet <Type>(); foreach (var pair in knownAssemblies) { var assembly = pair.Key; var treatTypesAsSerializable = pair.Value?.TreatTypesAsSerializable ?? false; foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger)) { if (treatTypesAsSerializable || type.IsSerializable || TypeHasKnownBase(type)) { string logContext = null; if (logger.IsEnabled(LogLevel.Trace)) { if (treatTypesAsSerializable) { logContext = $"known assembly {assembly.GetName().Name} where 'TreatTypesAsSerializable' = true"; } else if (type.IsSerializable) { logContext = $"known assembly {assembly.GetName().Name} where type is [Serializable]"; } else if (TypeHasKnownBase(type)) { logContext = $"known assembly {assembly.GetName().Name} where type has known base type."; } } serializableTypes.RecordType(type, targetAssembly, logContext); } // Include grain interfaces and classes. var isGrainInterface = GrainInterfaceUtils.IsGrainInterface(type); var isGrainClass = TypeUtils.IsConcreteGrainClass(type); if (isGrainInterface || isGrainClass) { // If code generation is being performed at runtime, the interface must be accessible to the generated code. if (!TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly)) { if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.Debug("Skipping inaccessible grain type, {0}", type.GetParseableName()); } continue; } // Attempt to generate serializers for grain state classes, i.e, T in Grain<T>. var baseType = type.BaseType; if (baseType != null && baseType.IsConstructedGenericType) { foreach (var arg in baseType.GetGenericArguments()) { string logContext = null; if (logger.IsEnabled(LogLevel.Trace)) { logContext = "generic base type of " + type.GetLogFormat(); } this.serializableTypes.RecordType(arg, targetAssembly, logContext); } } // Skip classes generated by this generator. if (IsOrleansGeneratedCode(type)) { if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.Debug("Skipping generated grain type, {0}", type.GetParseableName()); } continue; } if (this.knownGrainTypes.Contains(type)) { if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.Debug("Skipping grain type {0} since it already has generated code.", type.GetParseableName()); } continue; } if (isGrainClass) { if (this.logger.IsEnabled(LogLevel.Information)) { this.logger.Info("Found grain implementation class: {0}", type.GetParseableName()); } grainClasses.Add(type); } if (isGrainInterface) { if (this.logger.IsEnabled(LogLevel.Information)) { this.logger.Info("Found grain interface: {0}", type.GetParseableName()); } GrainInterfaceUtils.ValidateInterfaceRules(type); grainInterfaces.Add(type); } } } } // Group the types by namespace and generate the required code in each namespace. foreach (var groupedGrainInterfaces in grainInterfaces.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_))) { var namespaceName = groupedGrainInterfaces.Key; var namespaceMembers = new List <MemberDeclarationSyntax>(); foreach (var grainInterface in groupedGrainInterfaces) { var referenceTypeName = GrainReferenceGenerator.GetGeneratedClassName(grainInterface); var invokerTypeName = GrainMethodInvokerGenerator.GetGeneratedClassName(grainInterface); namespaceMembers.Add( GrainReferenceGenerator.GenerateClass( grainInterface, referenceTypeName, encounteredType => { string logContext = null; if (logger.IsEnabled(LogLevel.Trace)) { logContext = "used by grain type " + grainInterface.GetLogFormat(); } this.serializableTypes.RecordType(encounteredType, targetAssembly, logContext); })); namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(grainInterface, invokerTypeName)); var genericTypeSuffix = GetGenericTypeSuffix(grainInterface.GetGenericArguments().Length); features.GrainInterfaces.Add( new GrainInterfaceDescription { Interface = grainInterface.GetTypeSyntax(includeGenericParameters: false), Reference = SF.ParseTypeName(namespaceName + '.' + referenceTypeName + genericTypeSuffix), Invoker = SF.ParseTypeName(namespaceName + '.' + invokerTypeName + genericTypeSuffix), InterfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainInterface) }); } members.Add(CreateNamespace(namespaceName, namespaceMembers)); } foreach (var type in grainClasses) { features.GrainClasses.Add( new GrainClassDescription { ClassType = type.GetTypeSyntax(includeGenericParameters: false) }); } // Generate serializers into their own namespace. var serializerNamespace = this.GenerateSerializers(targetAssembly, features); members.Add(serializerNamespace); // Add serialization metadata for the types which were encountered. this.AddSerializationTypes(features.Serializers, targetAssembly, knownAssemblies.Keys.ToList()); foreach (var attribute in knownAssemblies.Keys.SelectMany(asm => asm.GetCustomAttributes <ConsiderForCodeGenerationAttribute>())) { this.serializableTypes.RecordType(attribute.Type, targetAssembly, "[ConsiderForCodeGeneration]"); if (attribute.ThrowOnFailure && !this.serializableTypes.IsTypeRecorded(attribute.Type) && !this.serializableTypes.IsTypeIgnored(attribute.Type)) { throw new CodeGenerationException( $"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code" + " could not be generated. Ensure that the type is accessible."); } } // Generate metadata directives for all of the relevant types. var(attributeDeclarations, memberDeclarations) = FeaturePopulatorGenerator.GenerateSyntax(targetAssembly, features); members.AddRange(memberDeclarations); var compilationUnit = SF.CompilationUnit().AddAttributeLists(attributeDeclarations.ToArray()).AddMembers(members.ToArray()); return(new GeneratedSyntax { SourceAssemblies = knownAssemblies.Keys.ToList(), Syntax = compilationUnit }); }
/// <summary> /// Checks whether the <paramref name="value"/> is valid for the property. /// </summary> /// <param name="value">The value.</param> /// <returns>True if the value is valid, otherwise false.</returns> public bool IsValidValue(object value) { return(TypeUtilities.TryConvertImplicit(PropertyType, value, out value)); }
/// <summary> /// Adds serialization type descriptions from <paramref name="targetAssembly"/> to <paramref name="serializationTypes"/>. /// </summary> /// <param name="serializationTypes">The serialization type descriptions.</param> /// <param name="targetAssembly">The target assembly for generated code.</param> /// <param name="assemblies"></param> private void AddSerializationTypes(SerializationTypeDescriptions serializationTypes, Assembly targetAssembly, List <Assembly> assemblies) { // Only types which exist in assemblies referenced by the target assembly can be referenced. var references = new HashSet <string>( assemblies.SelectMany(asm => asm.GetReferencedAssemblies() .Select(referenced => referenced.Name) .Concat(new[] { asm.GetName().Name }))); bool IsAssemblyReferenced(Type type) { // If the target doesn't reference this type's assembly, it cannot reference a type within that assembly. return(references.Contains(type.Assembly.GetName().Name)); } // Visit all types in other assemblies for serialization metadata. foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!references.Contains(assembly.GetName().Name)) { continue; } foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger)) { this.typeCollector.RecordEncounteredType(type); } } // Returns true if a type can be accessed from source and false otherwise. bool IsAccessibleType(Type type) => TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly); foreach (var type in this.typeCollector.EncounteredTypes) { // Skip types which can not or should not be referenced. if (type.IsGenericParameter) { continue; } if (!IsAssemblyReferenced(type)) { continue; } if (type.IsNestedPrivate) { continue; } if (type.GetCustomAttribute <CompilerGeneratedAttribute>() != null) { continue; } if (IsOrleansGeneratedCode(type)) { continue; } var qualifiedTypeName = RuntimeTypeNameFormatter.Format(type); if (this.knownTypes.Contains(qualifiedTypeName)) { continue; } var typeKeyString = type.OrleansTypeKeyString(); serializationTypes.KnownTypes.Add(new KnownTypeDescription { Type = qualifiedTypeName, TypeKey = typeKeyString }); if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.Debug( "Found type {0} with type key \"{1}\"", type.GetParseableName(), typeKeyString); } if (!IsAccessibleType(type)) { continue; } var typeSyntax = type.GetTypeSyntax(includeGenericParameters: false); var serializerAttributes = type.GetCustomAttributes <SerializerAttribute>().ToList(); if (serializerAttributes.Count > 0) { // Account for serializer types. foreach (var serializerAttribute in serializerAttributes) { if (!IsAccessibleType(serializerAttribute.TargetType)) { continue; } if (this.logger.IsEnabled(LogLevel.Information)) { this.logger.Info( "Found type {0} is a serializer for type {1}", type.GetParseableName(), serializerAttribute.TargetType.GetParseableName()); } serializationTypes.SerializerTypes.Add( new SerializerTypeDescription { Serializer = typeSyntax, Target = serializerAttribute.TargetType.GetTypeSyntax(includeGenericParameters: false) }); } } else { // Account for self-serializing types. SerializationManager.GetSerializationMethods(type, out var copier, out var serializer, out var deserializer); if (copier != null || serializer != null || deserializer != null) { if (this.logger.IsEnabled(LogLevel.Information)) { this.logger.Info( "Found type {0} is self-serializing.", type.GetParseableName()); } serializationTypes.SerializerTypes.Add( new SerializerTypeDescription { Serializer = typeSyntax, Target = typeSyntax }); } } } }
protected override bool SetTargetValueCore(object value, BindingPriority priority) { var typeInfo = Target.Target.GetType().GetTypeInfo(); var list = Target.Target as IList; var dictionary = Target.Target as IDictionary; var indexerProperty = GetIndexer(typeInfo); var indexerParameters = indexerProperty?.GetIndexParameters(); if (indexerProperty != null && indexerParameters.Length == Arguments.Count) { var convertedObjectArray = new object[indexerParameters.Length]; for (int i = 0; i < Arguments.Count; i++) { object temp = null; if (!TypeUtilities.TryConvert(indexerParameters[i].ParameterType, Arguments[i], CultureInfo.InvariantCulture, out temp)) { return(false); } convertedObjectArray[i] = temp; } var intArgs = convertedObjectArray.OfType <int>().ToArray(); // Try special cases where we can validate indicies if (typeInfo.IsArray) { return(SetValueInArray((Array)Target.Target, intArgs, value)); } else if (Arguments.Count == 1) { if (list != null) { if (intArgs.Length == Arguments.Count && intArgs[0] >= 0 && intArgs[0] < list.Count) { list[intArgs[0]] = value; return(true); } return(false); } else if (dictionary != null) { if (dictionary.Contains(convertedObjectArray[0])) { dictionary[convertedObjectArray[0]] = value; return(true); } else { dictionary.Add(convertedObjectArray[0], value); return(true); } } else { // Fallback to unchecked access indexerProperty.SetValue(Target.Target, value, convertedObjectArray); return(true); } } else { // Fallback to unchecked access indexerProperty.SetValue(Target.Target, value, convertedObjectArray); return(true); } } // Multidimensional arrays end up here because the indexer search picks up the IList indexer instead of the // multidimensional indexer, which doesn't take the same number of arguments else if (typeInfo.IsArray) { SetValueInArray((Array)Target.Target, value); return(true); } return(false); }
private string TypeName() { return(TypeUtilities.TypeName(_type)); }