public void CreateGetter_ValueTypeWithValidPropertyName_ReturnsGetter() { var data = TimeSpan.FromDays(1); var getter = PropertyAccessors.CreateGetter(nameof(TimeSpan.TotalMilliseconds), data); Assert.IsNotNull(getter); }
public void CreateGetterT_GetterCalled_ReturnsReferenceType() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter <string>("Name", data); Assert.AreSame(data.Name, getter(data)); }
public void CreateGetterT_InvalidReturnType_ReturnsNull() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter <string>("Value", data); Assert.IsNull(getter); }
public void CreateGetter_InvalidProperty_ReturnsNull() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter("Invalid", data); Assert.IsNull(getter); }
public void CreateGetter_GetterCalledWithInvalidObjectType_ThrowsArgumentException() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter("Value", data); getter(new object()); }
/// <summary> /// Replaces all placeholders (e.g. {$ip_address}, {$session_id} in the specified text for the specified obj. /// Since ip_address can take several values over different Networks, this method returns a list of Uri for /// each of the different IP addresses. /// </summary> /// <param name="text">The text that contains the placeholders to be replaced.</param> /// <param name="obj">The object that the placeholder replacements are for.</param> /// <returns>A List of Uris.</returns> public static List <Uri> SubstituteUri(string uri, IXenObject obj) { Util.ThrowIfParameterNull(uri, "uri"); string ipAddressName = Enum.GetName(typeof(PropertyNames), PropertyNames.ip_address); try { if (!uri.Contains(string.Format(PlaceholderFormat, ipAddressName))) { return(new List <Uri> { new Uri(Substitute(uri, obj)) }); } string u = Substitute(uri, obj, s => s != ipAddressName); var ips = (List <ComparableAddress>)PropertyAccessors.Get(PropertyNames.ip_address)(obj); if (ips == null || ips.Count == 0) { return(new List <Uri> { new Uri(u) }); } return(ips.ConvertAll(ip => new Uri(u.Replace(string.Format(PlaceholderFormat, ipAddressName), ip.ToString())))); } catch (UriFormatException) { log.Warn(string.Format("Failed to parse url {0}", uri)); return(new List <Uri> { new Uri("about:blank") }); } }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SimpleNullablePrincipalDependentKeyValueFactory( [NotNull] IProperty property, [NotNull] PropertyAccessors propertyAccessors) { _propertyAccessors = propertyAccessors; EqualityComparer = property.CreateKeyEqualityComparer <TKey>(); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SimpleNonNullableDependentKeyValueFactory( IProperty property, PropertyAccessors propertyAccessors) { _propertyAccessors = propertyAccessors; EqualityComparer = property.CreateKeyEqualityComparer <TKey>(); }
public void CreateGetter_ReferenceTypeWithValidPropertyName_ReturnsGetter() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter("Name", data); Assert.IsNotNull(getter); }
/// <summary> /// Gets the replacement for the specified placeholder for the specified object. /// </summary> /// <param name="placeholder">The placeholder to be replaced.</param> /// <param name="objs">The objects that the placeholder replacements are for.</param> /// <param name="match">A predicate indicating whether the specified placeholder should be replaced.</param> /// <returns>The replacement for the specified placeholder.</returns> private static string GetPlaceholderReplacement(string placeholder, IList <IXenObject> objs, Predicate <string> match) { if (match(placeholder)) { if (objs == null || objs.Count == 0) { return(NULL_PLACEHOLDER_KEY); } if (objs.Count > 1) { return(MULTI_TARGET_PLACEHOLDER_KEY); } if (placeholder == "session_id") { if (objs[0].Connection == null || objs[0].Connection.Session == null) { return(NULL_PLACEHOLDER_KEY); } return(objs[0].Connection.Session.uuid); } else { // otherwise update url with the latest info PropertyNames property = (PropertyNames)Enum.Parse(typeof(PropertyNames), placeholder); object val = PropertyAccessors.Get(property)(objs[0]); return(val != null?val.ToString() : NULL_PLACEHOLDER_KEY); } } return(null); }
/// <summary> /// Sets the value to the property of the target object /// </summary> /// <param name="target">The object to set the property</param> /// <param name="propertyName">The name of the property to set</param> /// <param name="value">The value to set</param> public void SetValue(object target, string propertyName, object value) { if (propertyName.Contains(".")) // Support nested properties { var propertyNames = propertyName.Split('.'); var typeAccessor = this; // The type accessor needs to change for each new target foreach (var name in propertyNames) { if (!typeAccessor.PropertyAccessors.ContainsKey(name)) { throw new InvalidOperationException($"Property: '{name}' not found for object of type: '{target.GetType().FullName}'"); } var propertyAccessor = typeAccessor.PropertyAccessors[name]; if (!propertyAccessor.CanSet) { throw new InvalidOperationException($"Can not set the value of property: '{propertyAccessor.PropertyName}'.Verify that the declaring type is not a value type(such as struct)"); } if (name == propertyNames.Last()) // Assume the last property as a scalar (primitive) value { propertyAccessor.SetValue(target, value); } else { var t = propertyAccessor.GetValue(target); if (t == null) // Nested property instance does not exist { t = Activator.CreateInstance(propertyAccessor.PropertyType); propertyAccessor.SetValue(target, t); } target = t; typeAccessor = t.GetTypeAccessor(); } } } else { if (!PropertyAccessors.ContainsKey(propertyName)) { throw new InvalidOperationException($"Property: '{propertyName}' not found for object of type: '{target.GetType().FullName}'"); } var propertyAccessor = PropertyAccessors[propertyName]; if (!propertyAccessor.CanSet) { throw new InvalidOperationException($"Can not set the value of property: '{propertyAccessor.PropertyName}'.Verify that the declaring type is not a value type(such as struct)"); } propertyAccessor.SetValue(target, value); } }
public SimplePrincipalKeyValueFactory([NotNull] PropertyAccessors propertyAccessors) { _propertyAccessors = propertyAccessors; EqualityComparer = typeof(IStructuralEquatable).GetTypeInfo().IsAssignableFrom(typeof(TKey).GetTypeInfo()) ? (IEqualityComparer <TKey>) new NoNullsStructuralEqualityComparer() : new NoNullsEqualityComparer(); }
protected sealed override RuntimeNamedMethodInfo GetPropertyMethod(PropertyMethodSemantics whichMethod) { MethodDefinitionHandle methodHandle; PropertyAccessors propertyAccessors = _property.GetAccessors(); switch (whichMethod) { case PropertyMethodSemantics.Getter: methodHandle = propertyAccessors.Getter; break; case PropertyMethodSemantics.Setter: methodHandle = propertyAccessors.Setter; break; default: return(null); } bool inherited = !_reflectedType.Equals(ContextTypeInfo); if (inherited) { MethodAttributes flags = _reader.GetMethodDefinition(methodHandle).Attributes; if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) { return(null); } } return(RuntimeNamedMethodInfo <EcmaFormatMethodCommon> .GetRuntimeNamedMethodInfo(new EcmaFormatMethodCommon(methodHandle, _definingTypeInfo, ContextTypeInfo), _reflectedType)); }
public void CreateGetterT_GetterCalled_ReturnsValueType() { var data = new TestData <int>("Test", 5); var getter = PropertyAccessors.CreateGetter <int>("Value", data); Assert.AreEqual(5, getter(data)); }
public void CreateGetter_GetterCalled_ReturnsRefferenceType() { var data = new TestData <object>("Test", null); var getter = PropertyAccessors.CreateGetter("Name", data); Assert.AreSame(data.Name, getter(data)); }
/// <summary> /// Initializes a new instance of the PropertyName class. /// </summary> public PropertyName(string name, NameVisibilityRestriction getVisibility, NameVisibilityRestriction setVisibility, Scope scope, PropertyAccessors accessors, Context context) : base(name, getVisibility, scope, context) { this.accessors = accessors; this.setVisibility = setVisibility; }
public static MethodDefinitionHandle GetAny(this PropertyAccessors accessors) { if (!accessors.Getter.IsNil) { return(accessors.Getter); } return(accessors.Setter); }
/// <summary> /// Retrieves a value /// </summary> /// <param name="target">The object to retrieve the value from</param> /// <param name="propertyName">The name of the property to get the value from</param> /// <returns>The value of the property</returns> public object GetValue(object target, string propertyName) { if (propertyName.Contains(".")) // Support nested properties { var propertyNames = propertyName.Split('.'); var typeAccessor = this; // The type accessor needs to change for each new target PropertyAccessor propertyAccessor = null; foreach (var name in propertyNames) { if (!typeAccessor.PropertyAccessors.ContainsKey(name)) { throw new InvalidOperationException($"Property: '{name}' not found for object of type: '{target.GetType().FullName}'"); } propertyAccessor = typeAccessor.PropertyAccessors[name]; if (!propertyAccessor.CanGet) { throw new InvalidOperationException($"Can not get the value of property: '{propertyAccessor.PropertyName}'"); } if (name != propertyNames.Last()) // Assume the last property as a scalar (primitive) value { var t = propertyAccessor.GetValue(target); if (t == null) // Nested property instance does not exist { return(null); } target = t; typeAccessor = t.GetTypeAccessor(); } } return(propertyAccessor.GetValue(target)); } else { if (!PropertyAccessors.ContainsKey(propertyName)) { throw new InvalidOperationException($"Property: '{propertyName}' not found for object of type: '{target.GetType().FullName}'"); } PropertyAccessor propertyAccessor = PropertyAccessors[propertyName]; if (!propertyAccessor.CanGet) { throw new InvalidOperationException($"Can not get the value of property: '{propertyAccessor.PropertyName}'"); } return(propertyAccessor.GetValue(target)); } }
public static void AddDependenciesDueToCustomAttributes(ref DependencyList dependencies, NodeFactory factory, EcmaMethod method) { MetadataReader reader = method.MetadataReader; MethodDefinitionHandle methodHandle = method.Handle; MethodDefinition methodDef = reader.GetMethodDefinition(methodHandle); // Handle custom attributes on the method AddDependenciesDueToCustomAttributes(ref dependencies, factory, method.Module, methodDef.GetCustomAttributes()); // Handle custom attributes on method parameters foreach (ParameterHandle parameterHandle in methodDef.GetParameters()) { Parameter parameter = reader.GetParameter(parameterHandle); AddDependenciesDueToCustomAttributes(ref dependencies, factory, method.Module, parameter.GetCustomAttributes()); } // Handle custom attributes on generic method parameters foreach (GenericParameterHandle genericParameterHandle in methodDef.GetGenericParameters()) { GenericParameter parameter = reader.GetGenericParameter(genericParameterHandle); AddDependenciesDueToCustomAttributes(ref dependencies, factory, method.Module, parameter.GetCustomAttributes()); } // We don't model properties and events as separate entities within the compiler, so ensuring // we can generate custom attributes for the associated events and properties from here // is as good as any other place. // // As a performance optimization, we look for associated events and properties only // if the method is SpecialName. This is required for CLS compliance and compilers we // care about emit accessors like this. if ((methodDef.Attributes & MethodAttributes.SpecialName) != 0) { TypeDefinition declaringType = reader.GetTypeDefinition(methodDef.GetDeclaringType()); foreach (PropertyDefinitionHandle propertyHandle in declaringType.GetProperties()) { PropertyDefinition property = reader.GetPropertyDefinition(propertyHandle); PropertyAccessors accessors = property.GetAccessors(); if (accessors.Getter == methodHandle || accessors.Setter == methodHandle) { AddDependenciesDueToCustomAttributes(ref dependencies, factory, method.Module, property.GetCustomAttributes()); } } foreach (EventDefinitionHandle eventHandle in declaringType.GetEvents()) { EventDefinition @event = reader.GetEventDefinition(eventHandle); EventAccessors accessors = @event.GetAccessors(); if (accessors.Adder == methodHandle || accessors.Remover == methodHandle || accessors.Raiser == methodHandle) { AddDependenciesDueToCustomAttributes(ref dependencies, factory, method.Module, @event.GetCustomAttributes()); } } } }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public SimplePrincipalKeyValueFactory([NotNull] IProperty property) { _property = property; _propertyAccessors = _property.GetPropertyAccessors(); EqualityComparer = typeof(IStructuralEquatable).GetTypeInfo().IsAssignableFrom(typeof(TKey).GetTypeInfo()) ? (IEqualityComparer <TKey>) new NoNullsStructuralEqualityComparer() : EqualityComparer <TKey> .Default; }
public void TestVirtStatusIsNot(string filter, string[] expectedVmNames) { var dict = PropertyAccessors.Geti18nFor(PropertyNames.virtualisation_status) as Dictionary <string, VM.VirtualisationStatus>; Assert.NotNull(dict, "Did not find i18n for VM.VirtualisationStatus"); Assert.IsTrue(dict.TryGetValue(filter, out var status), $"Did not find i18n for {filter}"); var query = new EnumPropertyQuery <VM.VirtualisationStatus>(PropertyNames.virtualisation_status, status, false); CheckMatch(query, expectedVmNames); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SimplePrincipalKeyValueFactory([NotNull] IProperty property) { _property = property; _propertyAccessors = _property.GetPropertyAccessors(); var comparer = property.GetKeyValueComparer(); EqualityComparer = comparer != null ? new NoNullsCustomEqualityComparer(comparer) : typeof(IStructuralEquatable).IsAssignableFrom(typeof(TKey)) ? (IEqualityComparer <TKey>) new NoNullsStructuralEqualityComparer() : EqualityComparer <TKey> .Default; }
protected override void OnPropertyChanged(string name) { base.OnPropertyChanged(name); if (PropertyAccessors.TryGetValue(name, out var accessor) && accessor != null) { if (!accessor.HasGetter) { return; } if (accessor.IsSystem) { return; } TestLog.Info("Changed: {0}, {1} = {2}", this, name, GetProperty(name)); } }
private static bool AddDependenciesFromPropertySetter(DependencyList dependencies, NodeFactory factory, TypeDesc attributeType, string propertyName) { EcmaType attributeTypeDefinition = (EcmaType)attributeType.GetTypeDefinition(); MetadataReader reader = attributeTypeDefinition.MetadataReader; var typeDefinition = reader.GetTypeDefinition(attributeTypeDefinition.Handle); foreach (PropertyDefinitionHandle propDefHandle in typeDefinition.GetProperties()) { PropertyDefinition propDef = reader.GetPropertyDefinition(propDefHandle); if (reader.StringComparer.Equals(propDef.Name, propertyName)) { PropertyAccessors accessors = propDef.GetAccessors(); if (!accessors.Setter.IsNil) { MethodDesc setterMethod = (MethodDesc)attributeTypeDefinition.EcmaModule.GetObject(accessors.Setter); if (factory.MetadataManager.IsReflectionBlocked(setterMethod)) { return(false); } // Method on a generic attribute if (attributeType != attributeTypeDefinition) { setterMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(setterMethod, (InstantiatedType)attributeType); } // TODO: what if the setter is virtual/abstract? dependencies.Add(factory.CanonicalEntrypoint(setterMethod), "Custom attribute blob"); } return(true); } } // Haven't found it in current type. Check the base type. TypeDesc baseType = attributeType.BaseType; if (baseType != null) { return(AddDependenciesFromPropertySetter(dependencies, factory, baseType, propertyName)); } // Not found. This is bad metadata that will result in a runtime failure, but we shouldn't fail the compilation. return(true); }
internal static void CheckPropertyAccessors(this PropertyInfo @this, PropertyAccessors accessors) { if (accessors == PropertyAccessors.Get || accessors == PropertyAccessors.GetAndSet) { if ([email protected]) { throw new PropertyNotFoundException($"Property {@this.Name} on type {@this.DeclaringType.Name} cannot be read from."); } } if (accessors == PropertyAccessors.Set || accessors == PropertyAccessors.GetAndSet) { if ([email protected]) { throw new PropertyNotFoundException($"Property {@this.Name} on type {@this.DeclaringType.Name} cannot be written to."); } } }
/// <summary> /// Replaces all placeholders (e.g. {$ip_address}, {$session_id} in the specified text for the specified obj. /// Since ip_address can take several values over different Networks, this method returns a list of Uri for /// each of the different IP addresses. /// </summary> /// <param name="uri">The text that contains the placeholders to be replaced.</param> /// <param name="obj">The object that the placeholder replacements are for.</param> /// <returns>A List of Uris.</returns> public static List <Uri> SubstituteUri(string uri, IXenObject obj) { Util.ThrowIfParameterNull(uri, "uri"); string ipAddressName = Enum.GetName(typeof(PropertyNames), PropertyNames.ip_address); try { if (!uri.Contains(string.Format(PlaceholderFormat, ipAddressName))) { return new List <Uri> { new Uri(Substitute(uri, obj)) } } ; var ips = (List <ComparableAddress>)PropertyAccessors.Get(PropertyNames.ip_address)(obj); if (ips == null || ips.Count == 0) { log.DebugFormat("Object {0} (opaque_ref {1}) has no IPs.", obj.Name(), obj.opaque_ref); return(new List <Uri> { new Uri("about:blank") }); } string u = Substitute(uri, obj, s => s != ipAddressName); return(ips.ConvertAll(ip => { var ipstring = ip.AddressIP != null && ip.AddressIP.AddressFamily == AddressFamily.InterNetworkV6 ? string.Format("[{0}]", ip) : ip.ToString(); return new Uri(u.Replace(string.Format(PlaceholderFormat, ipAddressName), ipstring)); })); } catch (UriFormatException ex) { log.Warn("Failed to parse url.", ex); return(new List <Uri> { new Uri("about:blank") }); } }
private void InitializeDictionaries() { // add all single types, names and images Dictionary <String, ObjectTypes> dict = (Dictionary <String, ObjectTypes>)PropertyAccessors.Geti18nFor(PropertyNames.type); ImageDelegate <ObjectTypes> images = (ImageDelegate <ObjectTypes>)PropertyAccessors.GetImagesFor(PropertyNames.type); foreach (KeyValuePair <String, ObjectTypes> kvp in dict) { typeNames[kvp.Value] = kvp.Key; typeImages[kvp.Value] = Images.GetImage16For(images(kvp.Value)); } // add all combo types, mostly names only typeNames[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Messages.ALL_SRS; typeImages[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Images.GetImage16For(images(ObjectTypes.LocalSR | ObjectTypes.RemoteSR)); typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM] = Messages.SERVERS_AND_VMS; typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_REMOTE_SRS; typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_ALL_SRS; typeNames[ObjectTypes.AllExcFolders] = Messages.ALL_TYPES; typeNames[ObjectTypes.AllIncFolders] = Messages.ALL_TYPES_AND_FOLDERS; }
public void Run() { IPHostEntry thisMachine = null; // Network on the GUI thread!!! try { thisMachine = Dns.GetHostEntry(""); } catch { Assert.Fail("Couldn't resolve this machine's IP address"); } PropertyAccessor ipAddress = PropertyAccessors.Get(PropertyNames.ip_address); foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy) { foreach (IXenObject o in connection.Cache.XenSearchableObjects) { // We want this to error if the cast fails ComparableList <ComparableAddress> addresses = (ComparableList <ComparableAddress>)ipAddress(o); if (addresses == null) { continue; } foreach (ComparableAddress address in addresses) { foreach (IPAddress hostAddress in thisMachine.AddressList) { Assert.False(address.Equals(hostAddress), String.Format("XenCenter address ({0}) appears on object '{1}'!", address, Helpers.GetName(o))); } } } } }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SimpleFullyNullableDependentKeyValueFactory([NotNull] PropertyAccessors propertyAccessors) { _propertyAccessors = propertyAccessors; }
internal static PropertyInfo FindProperty(this Type @this, string name, PropertyAccessors accessors) { var property = @this.FindProperty(name); TypeExtensions.CheckPropertyAccessors(property, accessors); return property; }
private static void CheckPropertyAccessors(PropertyInfo property, PropertyAccessors accessors) { if (accessors == PropertyAccessors.Get || accessors == PropertyAccessors.GetAndSet) { if (!property.CanRead) { throw new PropertyNotFoundException($"Property {property.Name} on type {property.DeclaringType.Name} cannot be read from."); } } if (accessors == PropertyAccessors.Set || accessors == PropertyAccessors.GetAndSet) { if (!property.CanWrite) { throw new PropertyNotFoundException($"Property {property.Name} on type {property.DeclaringType.Name} cannot be written to."); } } }
internal PropertyMockableResult(PropertyInfo value, RequiresExplicitInterfaceImplementation requiresExplicitInterfaceImplementation, PropertyAccessors accessors) : base(value, requiresExplicitInterfaceImplementation) => this.Accessors = accessors;
internal static PropertyInfo FindProperty(this Type @this, Type[] indexers, PropertyAccessors accessors) { var property = @this.FindProperty(indexers); TypeExtensions.CheckPropertyAccessors(property, accessors); return property; }
public IndexerName(NameVisibilityRestriction getVisibility, NameVisibilityRestriction setVisibility, Scope scope, PropertyAccessors accessors, Context context) : base("Items", getVisibility, setVisibility, scope, accessors, context) { }