I am a decades-old C programmer. Unity is my first foray into modern C and I find myself pleasantly surprised - but some of the subtleties of the language have escaped me.
First a technical question: What is the right way to store a Unity Object in a generic class? In the example below I get the following error:
Assets/scripts/MediaTest.cs(49,44): error CS0030: Cannot convert type `UnityEngine.Texture2D' to `T'
Second the real question: What is a better approach to loading a set of textures?
Thanks in advance for your help
/*
* MediaTest.cs
*
* Pared down generic class test
*
*/
using System.Collections; // Load IEnumerable
using System.Collections.Generic; // Load Dictionary
using System.Text.RegularExpressions; // Load Regex
using UnityEngine; // Load UnityEngine.Object
public class MediaTest<T> : IEnumerable where T : UnityEngine.Object {
private Dictionary<string, MediaContent> _dict =
new Dictionary<string, MediaContent>();
private class MediaContent {
public string path { get; set; }
public T item { get; set; }
public MediaContent(string path, T item) {
this.path = path;
this.item = item;
}
}
// Indexer to return a UnityEngine.Object by filename
public T this[string name] {
get { return (T)_dict[name].item; }
}
// Convert a path to just the filename
public string Basename(string path) {
return new Regex(#"^.*/").Replace(path, "");
}
// Iterate through the filenames (keys) to the stored objects
public IEnumerator GetEnumerator() {
foreach (string name in _dict.Keys) {
yield return name;
}
}
// Read in the Resource at the specified path into a UnityEngine.Object
public void Load(string path, bool load=false) {
string name = Basename(path);
if (this.GetType() == typeof(Media<Texture2D>) && IsStill(name)) {
T item = (load) ? (T)Resources.Load<Texture2D>(path) : null;
_dict[name] = new MediaContent(path, item);
return;
}
if (this.GetType() == typeof(Media<AudioClip>) && IsAudio(name)) {
T item = (load) ? (T)Resources.Load<AudioClip>(path) : null;
_dict[name] = new MediaContent(path, item);
return;
}
}
// The real code uses Regex.Match on the file extension for supported types
public bool IsStill(string name) { return true; }
public bool IsAudio(string name) { return true; }
}
Here is the working code with updates from the comments. Thanks derHugo!
public void Load(string path, bool load=false) {
// Translate the filesystem path to a Resources relative path by removing both
// The */Resources prefix and the filename extention
Regex re_path = new Regex(#".*/Resources/");
Regex re_ext = new Regex(#"\.\w+$");
string relpath = re_ext.Replace(re_path.Replace(path, ""), "");
// Create an asset name from the path
string name = System.IO.Path.GetFileName(relpath);
// Skip this file if it doesn't match our type
if ( (typeof(T) == typeof(Texture2D) && IsStill(path)) ||
// (typeof(T) == typeof(Video) && IsVideo(path)) ||
(typeof(T) == typeof(AudioClip) && IsAudio(name))) {
T item = (load) ? Resources.Load(relpath) as T : null;
_dict[name] = new MediaContent(path, item);
}
}
Related
I've started rewriting my Curve tool to deal with problem of drawing it in array and other reasons. All was well till I tried to click between editors in array and list elements. Sometimes Previously edited element retains its height until other element of that collection gets edited or curve field gets edited. I have no idea how to tell Unity it should refresh field heights. I've tried EditorUtility.SetDirty(targetObject); with or without EditorGUI.BeginChangeCheck(); EditorGUI.EndChangeCheck();
Number on left is OtherCurve.z, it's a way to deferenciate which PropertyDrawer you are debugging in code. Labels are temporal.
public class OtherTestScript : MonoBehaviour
{
public OtherCurve curve;
public OtherCurve[] curveArray;
public List<OtherCurve> curveList;
}
Curve tool repository at last commit with the issue
To test download this commit code and put it in Assets/Plugins/ and add these to your Packages/manifest.json:
"st.one-line": "https://github.com/slavniyteo/one-line.git#master",
"st.rect-ex": "https://github.com/slavniyteo/rect-ex.git#master",
This code stays there, I'm not going to hide it from public or rewrite history of the repository.
After trying to recreate this behaviour on a simpler example I've found out that my technique works...
Edited: Appears that using GUI.Label(..) to draw label in Editor and not using any other EditorGUI components caused GetPropertyHeight not being called. So If I wouldn't stop at this bug, it would disappear when I replaced that GUI.Label placeholder with actually meaningful code. I feel empty for wasting that much time to figure this out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
using System.Reflection;
using System.Linq;
using System.Text.RegularExpressions;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
public class PropertyThing : MonoBehaviour
{
public CustomThing thing;
public List<CustomThing> thingList;
public CustomThing[] thingArray;
[Serializable]
public class CustomThing
{
#if UNITY_EDITOR
public bool _isEdited;
#endif
public string field;
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(CustomThing))]
public class CustomThingInspector : PropertyDrawer
{
private UnityEngine.Object targetObject;
private CustomThing value;
private static Action FinishCurrentEditorAction;
private static void FinishCurrentEditor() => FinishCurrentEditorAction();
private static void FinishCurrentEditor(Scene s) => FinishCurrentEditorAction();
private string EditButtonText(bool editing) => editing ? "Stop Edit" : "Edit";
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
GetObjects(property);
return value._isEdited ? 38 : 18;
}
private void GetObjects(SerializedProperty property)
{
targetObject = property.serializedObject.targetObject;
value = property.GetValue<CustomThing>();
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var c = GUI.color;
GetObjects(property);
EditorGUI.BeginProperty(position, label, property);
var firstline = new Rect(position.x, position.y, position.width, 18);
var editor = new Rect(position.x, position.y + 20, position.width, position.height - 20);
var brect = EditorGUI.PrefixLabel(firstline, label);
if (value._isEdited) GUI.color = Color.red * .6666f + Color.white * .3333f;
if (GUI.Button(brect, EditButtonText(value._isEdited)))
{
EditPressed();
}
GUI.color = c;
if (value._isEdited)
EditorGUI.PropertyField(editor, property.FindPropertyRelative("field"));
EditorGUI.EndProperty();
GUI.color = c;
}
private void EditPressed()
{
value._isEdited = !value._isEdited;
if (value._isEdited)
StartEditor(value);
else
FinishEditor(value);
}
private void StartEditor(CustomThing thing)
{
var capturedThing = thing;
FinishCurrentEditorAction?.Invoke();
FinishCurrentEditorAction = () => {
FinishEditor(capturedThing);
EditorUtility.SetDirty(targetObject);
FinishCurrentEditorAction = null;
};
capturedThing._isEdited = true;
SceneView.duringSceneGui += OnEditorSceneView;
}
private void FinishEditor(CustomThing thing)
{
Selection.selectionChanged -= FinishCurrentEditor;
EditorSceneManager.sceneClosed -= FinishCurrentEditor;
AssemblyReloadEvents.beforeAssemblyReload -= FinishCurrentEditor;
SceneView.duringSceneGui -= OnEditorSceneView;
thing._isEdited = false;
FinishCurrentEditorAction = null;
}
private void OnEditorSceneView(SceneView obj)
{
if (targetObject is Component c)
Handles.Label(c.transform.position, c.gameObject.name);
else
Handles.Label(Vector3.zero, targetObject.name);
}
}
#endif
}
public static class SerializedUtility
{
public static T GetValue<T>(this SerializedProperty property) where T : class
{
object obj = property.serializedObject.targetObject;
string path = property.propertyPath.Replace(".Array.data", "");
string[] fieldStructure = path.Split('.');
Regex rgx = new Regex(#"\[\d+\]");
for (int i = 0; i < fieldStructure.Length; i++)
{
if (fieldStructure[i].Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldStructure[i].Where(c => char.IsDigit(c)).ToArray()));
obj = GetFieldValueWithIndex(rgx.Replace(fieldStructure[i], ""), obj, index);
}
else
{
obj = GetFieldValue(fieldStructure[i], obj);
}
}
return (T)obj;
}
public static bool SetValue<T>(this SerializedProperty property, T value) where T : class
{
object obj = property.serializedObject.targetObject;
string path = property.propertyPath.Replace(".Array.data", "");
string[] fieldStructure = path.Split('.');
Regex rgx = new Regex(#"\[\d+\]");
for (int i = 0; i < fieldStructure.Length - 1; i++)
{
if (fieldStructure[i].Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldStructure[i].Where(c => char.IsDigit(c)).ToArray()));
obj = GetFieldValueWithIndex(rgx.Replace(fieldStructure[i], ""), obj, index);
}
else
{
obj = GetFieldValue(fieldStructure[i], obj);
}
}
string fieldName = fieldStructure.Last();
if (fieldName.Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldName.Where(c => char.IsDigit(c)).ToArray()));
return SetFieldValueWithIndex(rgx.Replace(fieldName, ""), obj, index, value);
}
else
{
Debug.Log(value);
return SetFieldValue(fieldName, obj, value);
}
}
private static object GetFieldValue(string fieldName, object obj, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
return field.GetValue(obj);
}
return default(object);
}
private static object GetFieldValueWithIndex(string fieldName, object obj, int index, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
object list = field.GetValue(obj);
if (list.GetType().IsArray)
{
return ((object[])list)[index];
}
else if (list is IEnumerable)
{
return ((IList)list)[index];
}
}
return default(object);
}
public static bool SetFieldValue(string fieldName, object obj, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
field.SetValue(obj, value);
return true;
}
return false;
}
public static bool SetFieldValueWithIndex(string fieldName, object obj, int index, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
object list = field.GetValue(obj);
if (list.GetType().IsArray)
{
((object[])list)[index] = value;
return true;
}
else if (value is IEnumerable)
{
((IList)list)[index] = value;
return true;
}
}
return false;
}
}
I'm experiencing a problem when D&D a custom object from Swing to JavaFX and I'm wondering if I'm doing something wrong or its probably a Java FX bug.
My Transferable has been defined as the following:
public class TransferableEmployee implements Transferable {
public static final DataFlavor EMPLOYEE_FLAVOR = new DataFlavor(Employee[].class, "Employee");
public static final DataFlavor DEFINITION_FLAVOR = new DataFlavor(PropertyDefinition[].class, "Definition");
private static final DataFlavor FFLAVORS [] = {EMPLOYEE_FLAVOR, DEFINITION_FLAVOR};
private Employee[] employees;
private PropertyDefinition[] propertyDefinitions;
public MintTransferableEmployee(Employee[] employees, PropertyDefinition[] propertyDefinitions) {
this.employees = employees != null ? employees.clone() : null;
this.propertyDefinitions = propertyDefinitions != null ? propertyDefinitions.clone() : null;
}
public DataFlavor[] getTransferDataFlavors() {
return FFLAVORS.clone();
}
public Object getTransferData(DataFlavor aFlavor) throws UnsupportedFlavorException {
Object returnObject = null;
if (aFlavor.equals(EMPLOYEE_FLAVOR)) {
returnObject = employees;
}
else if(aFlavor.equals(DEFINITION_FLAVOR)){
returnObject = propertyDefinitions;
}
else{
throw new UnsupportedFlavorException(aFlavor);
}
return returnObject;
}
public boolean isDataFlavorSupported(DataFlavor aFlavor) {
boolean lReturnValue = false;
for (int i=0, n=FFLAVORS.length; i<n; i++) {
if (aFlavor.equals(FFLAVORS[i])) {
lReturnValue = true;
break;
}
}
return lReturnValue;
}
}
I've created an imageView (FX Component) where I added the setOnDragOver just as the following:
employeePhotoImageView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
System.out.println("dragOver");
event.getDragboard().getContentTypes();
event.getDragboard().getContent(DataFormat.lookupMimeType("application/x-java-serialized-object"));
}
});
The getContentTypes() returns a Map with [[application/x-java-serialized-object]], so now I try to get the Content, and this only returns the List of PropertyDefinition but no Employee at all (which in this case, is the one I need).
If I remove the data of the PropertyDefinition in the transferable, the employee is returned in the getContent(DataFormat) method.
For me, this means that JavaFX only works with 1 DataFlavor or somehow it is only returning the last flavor found in the Transferable.
Any clues on this?
Thanks in advanced...
Trying to remove or place items on a property grid by changing the Browsable attribute.
But unless browsable is set on object creation my code to change Browsable doesn't work. Now I can manually add browsable, but when I make a change to my entity (still developing project so lots of changes to entity) any additional attributes I add go away.
I attempted to set [Browsable(true)] two ways other ways: http://ardalis.com/adding-attributes-to-generated-classes and http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/617ebfca-0f68-4b90-83fd-0da758fadbd0/
Both seem to actually set the Browsable correctly, but when I loop thru the Attributes in Property Descriptor it is not there (for me to change).
String fieldname = "browsable"; // I also edit "description"
PropertyDescriptor pd = TypeDescriptor.GetProperties(o.GetType())[propertyName];
object attrib = null;
AttributeCollection attribs = pd.Attributes;
foreach (Attribute a in attribs)
{
if (a.GetType() == attributeType)
{
attrib = a;
break;
}
}
// The microsoft documentation leads one to believe the following line of code would find the desired attribute,
// negating the need for the more complete foreach statement above.
// However, it appears to find attribute even when it does not exist. Setting value for "found" attribute
// will result in random memory being changed, which results in very unpredictable behavior.
// attrib = pd.Attributes[t];
if (attrib != null)
{
// locate field that contains value
FieldInfo field = attrib.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
if (field.FieldType == value.GetType())
{
// set field to desired value
field.SetValue(attrib, value);
}
}
}
else
{
throw new Exception("Attribute (" + attributeType.Name + ") does not exist for Property(" + propertyName + ")");
}
So I keep getting the Exception that I throw if it doesn't find "browsable" - but only if not set in Model.Designer.cs first.
Below is what my Model.Designer.cs looks like.
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
[Browsable(false)] // this works, but goes away if change my entity
public Nullable<global::System.TimeSpan> SignoutAfter
{
get
{
return _SignoutAfter;
}
set
{
OnSignoutAfterChanging(value);
ReportPropertyChanging("SignoutAfter");
_SignoutAfter = StructuralObject.SetValidValue(value);
ReportPropertyChanged("SignoutAfter");
OnSignoutAfterChanged();
}
}
private Nullable<global::System.TimeSpan> _SignoutAfter;
partial void OnSignoutAfterChanging(Nullable<global::System.TimeSpan> value);
partial void OnSignoutAfterChanged();
So I need a way to either 1. add browsable to entity when I edit them so it is always on perhaps editing the t4, but I don't even know where to begin with that or 2. Another way to add or remove (and edit) the properties (see I might edit the description based on some logic) or 3 find the hole in my code so I can find and edit browsable (description and displayname).
Update The second link above, http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/617ebfca-0f68-4b90-83fd-0da758fadbd0/ , has a lot of what I need, I think. Adding a Attribute array variable to the class and some code to see if that is set seems to have the effect that I am looking for. But leaving this open to find a better answer.
partial class Client : ICustomTypeDescriptor
{
public Attribute[] SignOutAttributes; // added this
#region ICustomTypeDescriptor Members
... // see the link for the other code
public PropertyDescriptorCollection GetProperties (Attribute[] attributes)
{
var propsColl = TypeDescriptor.GetProperties (this, attributes, true);
var props = new List<PropertyDescriptor> ();
foreach (PropertyDescriptor prop in propsColl)
{
String strUPPERCaseName = prop.Name.ToUpper (); // for my thick fingers
// make sure case values are upper case
switch (strUPPERCaseName)
{
case "SIGNOUTAFTER":
if (SignOutAttributes != null)
{
props.Add(new CustomPropertyDescriptor(prop, SignOutAttributes));
}
else
{
props.Add (new CustomPropertyDescriptor (prop, new Attribute[]
{
new CategoryAttribute("Settings"),
new DisplayNameAttribute("Signout After"),
new BrowsableAttribute(true),
new ReadOnlyAttribute(false)
}));
}
break;
default:
props.Add (prop);
break;
}
}
return new PropertyDescriptorCollection (props.ToArray ());
}
In my code I can change the Attribute Array to have what Attribute values I want.
_client.SignOutAttributes = new Attribute[]
{
new CategoryAttribute ("My Category"),
new DisplayNameAttribute("Signout After"),
new BrowsableAttribute(true),
new ReadOnlyAttribute(false)
};
I'm not 100% happy with this. I have to write code for each Property.
Using ICustomTypeDescriptor is definitely the good solution when you want dynamic (set at runtime) properties. Here is generic ICustomTypeDescriptor utility class that I've been using for this sort of property grid hacking, it's pretty straightforward to use:
public sealed class DynamicTypeDescriptor: ICustomTypeDescriptor, INotifyPropertyChanged
{
private Type _type;
private AttributeCollection _attributes;
private TypeConverter _typeConverter;
private Dictionary<Type, object> _editors;
private EventDescriptor _defaultEvent;
private PropertyDescriptor _defaultProperty;
private EventDescriptorCollection _events;
public event PropertyChangedEventHandler PropertyChanged;
private DynamicTypeDescriptor()
{
}
public DynamicTypeDescriptor(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
_type = type;
_typeConverter = TypeDescriptor.GetConverter(type);
_defaultEvent = TypeDescriptor.GetDefaultEvent(type);
_defaultProperty = TypeDescriptor.GetDefaultProperty(type);
_events = TypeDescriptor.GetEvents(type);
List<PropertyDescriptor> normalProperties = new List<PropertyDescriptor>();
OriginalProperties = TypeDescriptor.GetProperties(type);
foreach (PropertyDescriptor property in OriginalProperties)
{
if (!property.IsBrowsable)
continue;
normalProperties.Add(property);
}
Properties = new PropertyDescriptorCollection(normalProperties.ToArray());
_attributes = TypeDescriptor.GetAttributes(type);
_editors = new Dictionary<Type, object>();
object editor = TypeDescriptor.GetEditor(type, typeof(UITypeEditor));
if (editor != null)
{
_editors.Add(typeof(UITypeEditor), editor);
}
editor = TypeDescriptor.GetEditor(type, typeof(ComponentEditor));
if (editor != null)
{
_editors.Add(typeof(ComponentEditor), editor);
}
editor = TypeDescriptor.GetEditor(type, typeof(InstanceCreationEditor));
if (editor != null)
{
_editors.Add(typeof(InstanceCreationEditor), editor);
}
}
public T GetPropertyValue<T>(string name, T defaultValue)
{
if (name == null)
throw new ArgumentNullException("name");
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
try
{
return (T)Convert.ChangeType(pd.GetValue(Component), typeof(T));
}
catch
{
return defaultValue;
}
}
}
return defaultValue;
}
public void SetPropertyValue(string name, object value)
{
if (name == null)
throw new ArgumentNullException("name");
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
pd.SetValue(Component, value);
break;
}
}
}
internal void OnValueChanged(PropertyDescriptor prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop.Name));
}
}
internal static T GetAttribute<T>(AttributeCollection attributes) where T : Attribute
{
if (attributes == null)
return null;
foreach (Attribute att in attributes)
{
if (typeof(T).IsAssignableFrom(att.GetType()))
return (T)att;
}
return null;
}
public sealed class DynamicProperty: PropertyDescriptor, INotifyPropertyChanged
{
private readonly Type _type;
private readonly bool _hasDefaultValue;
private readonly object _defaultValue;
private readonly PropertyDescriptor _existing;
private readonly DynamicTypeDescriptor _descriptor;
private Dictionary<Type, object> _editors;
private bool? _readOnly;
private bool? _browsable;
private string _displayName;
private string _description;
private string _category;
private List<Attribute> _attributes = new List<Attribute>();
public event PropertyChangedEventHandler PropertyChanged;
internal DynamicProperty(DynamicTypeDescriptor descriptor, Type type, object value, string name, Attribute[] attrs)
: base(name, attrs)
{
_descriptor = descriptor;
_type = type;
Value = value;
DefaultValueAttribute def = DynamicTypeDescriptor.GetAttribute<DefaultValueAttribute>(Attributes);
if (def == null)
{
_hasDefaultValue = false;
}
else
{
_hasDefaultValue = true;
_defaultValue = def.Value;
}
if (attrs != null)
{
foreach (Attribute att in attrs)
{
_attributes.Add(att);
}
}
}
internal static Attribute[] GetAttributes(PropertyDescriptor existing)
{
List<Attribute> atts = new List<Attribute>();
foreach (Attribute a in existing.Attributes)
{
atts.Add(a);
}
return atts.ToArray();
}
internal DynamicProperty(DynamicTypeDescriptor descriptor, PropertyDescriptor existing, object component)
: this(descriptor, existing.PropertyType, existing.GetValue(component), existing.Name, GetAttributes(existing))
{
_existing = existing;
}
public void RemoveAttributesOfType<T>() where T : Attribute
{
List<Attribute> remove = new List<Attribute>();
foreach (Attribute att in _attributes)
{
if (typeof(T).IsAssignableFrom(att.GetType()))
{
remove.Add(att);
}
}
foreach (Attribute att in remove)
{
_attributes.Remove(att);
}
}
public IList<Attribute> AttributesList
{
get
{
return _attributes;
}
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(_attributes.ToArray());
}
}
public object Value { get; set; }
public override bool CanResetValue(object component)
{
if (_existing != null)
return _existing.CanResetValue(component);
return _hasDefaultValue;
}
public override Type ComponentType
{
get
{
if (_existing != null)
return _existing.ComponentType;
return typeof(object);
}
}
public override object GetValue(object component)
{
if (_existing != null)
return _existing.GetValue(component);
return Value;
}
public override string Category
{
get
{
if (_category != null)
return _category;
return base.Category;
}
}
public void SetCategory(string category)
{
_category = category;
}
public override string Description
{
get
{
if (_description != null)
return _description;
return base.Description;
}
}
public void SetDescription(string description)
{
_description = description;
}
public override string DisplayName
{
get
{
if (_displayName != null)
return _displayName;
if (_existing != null)
return _existing.DisplayName;
return base.DisplayName;
}
}
public void SetDisplayName(string displayName)
{
_displayName = displayName;
}
public override bool IsBrowsable
{
get
{
if (_browsable.HasValue)
return _browsable.Value;
return base.IsBrowsable;
}
}
public void SetBrowsable(bool browsable)
{
_browsable = browsable;
}
public override bool IsReadOnly
{
get
{
if (_readOnly.HasValue)
return _readOnly.Value;
if (_existing != null)
return _existing.IsReadOnly;
ReadOnlyAttribute att = DynamicTypeDescriptor.GetAttribute<ReadOnlyAttribute>(Attributes);
if (att == null)
return false;
return att.IsReadOnly;
}
}
public void SetIsReadOnly(bool readOnly)
{
_readOnly = readOnly;
}
public override Type PropertyType
{
get
{
if (_existing != null)
return _existing.PropertyType;
return _type;
}
}
public override void ResetValue(object component)
{
if (_existing != null)
{
_existing.ResetValue(component);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(Name));
}
_descriptor.OnValueChanged(this);
return;
}
if (CanResetValue(component))
{
Value = _defaultValue;
_descriptor.OnValueChanged(this);
}
}
public override void SetValue(object component, object value)
{
if (_existing != null)
{
_existing.SetValue(component, value);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(Name));
}
_descriptor.OnValueChanged(this);
return;
}
Value = value;
_descriptor.OnValueChanged(this);
}
public override bool ShouldSerializeValue(object component)
{
if (_existing != null)
return _existing.ShouldSerializeValue(component);
return false;
}
public override object GetEditor(Type editorBaseType)
{
if (editorBaseType == null)
throw new ArgumentNullException("editorBaseType");
if (_editors != null)
{
object type;
if ((_editors.TryGetValue(editorBaseType, out type)) && (type != null))
return type;
}
return base.GetEditor(editorBaseType);
}
public void SetEditor(Type editorBaseType, object obj)
{
if (editorBaseType == null)
throw new ArgumentNullException("editorBaseType");
if (_editors == null)
{
if (obj == null)
return;
_editors = new Dictionary<Type, object>();
}
if (obj == null)
{
_editors.Remove(editorBaseType);
}
else
{
_editors[editorBaseType] = obj;
}
}
}
public PropertyDescriptor AddProperty(Type type, string name, object value, string displayName, string description, string category, bool hasDefaultValue, object defaultValue, bool readOnly)
{
return AddProperty(type, name, value, displayName, description, category, hasDefaultValue, defaultValue, readOnly, null);
}
public PropertyDescriptor AddProperty(
Type type,
string name,
object value,
string displayName,
string description,
string category,
bool hasDefaultValue,
object defaultValue,
bool readOnly,
Type uiTypeEditor)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
List<Attribute> atts = new List<Attribute>();
if (!string.IsNullOrEmpty(displayName))
{
atts.Add(new DisplayNameAttribute(displayName));
}
if (!string.IsNullOrEmpty(description))
{
atts.Add(new DescriptionAttribute(description));
}
if (!string.IsNullOrEmpty(category))
{
atts.Add(new CategoryAttribute(category));
}
if (hasDefaultValue)
{
atts.Add(new DefaultValueAttribute(defaultValue));
}
if (uiTypeEditor != null)
{
atts.Add(new EditorAttribute(uiTypeEditor, typeof(UITypeEditor)));
}
if (readOnly)
{
atts.Add(new ReadOnlyAttribute(true));
}
DynamicProperty property = new DynamicProperty(this, type, value, name, atts.ToArray());
AddProperty(property);
return property;
}
public void RemoveProperty(string name)
{
if (name == null)
throw new ArgumentNullException("name");
List<PropertyDescriptor> remove = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
remove.Add(pd);
}
}
foreach (PropertyDescriptor pd in remove)
{
Properties.Remove(pd);
}
}
public void AddProperty(PropertyDescriptor property)
{
if (property == null)
throw new ArgumentNullException("property");
Properties.Add(property);
}
public override string ToString()
{
return base.ToString() + " (" + Component + ")";
}
public PropertyDescriptorCollection OriginalProperties { get; private set; }
public PropertyDescriptorCollection Properties { get; private set; }
public DynamicTypeDescriptor FromComponent(object component)
{
if (component == null)
throw new ArgumentNullException("component");
if (!_type.IsAssignableFrom(component.GetType()))
throw new ArgumentException(null, "component");
DynamicTypeDescriptor desc = new DynamicTypeDescriptor();
desc._type = _type;
desc.Component = component;
// shallow copy on purpose
desc._typeConverter = _typeConverter;
desc._editors = _editors;
desc._defaultEvent = _defaultEvent;
desc._defaultProperty = _defaultProperty;
desc._attributes = _attributes;
desc._events = _events;
desc.OriginalProperties = OriginalProperties;
// track values
List<PropertyDescriptor> properties = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in Properties)
{
DynamicProperty ap = new DynamicProperty(desc, pd, component);
properties.Add(ap);
}
desc.Properties = new PropertyDescriptorCollection(properties.ToArray());
return desc;
}
public object Component { get; private set; }
public string ClassName { get; set; }
public string ComponentName { get; set; }
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return _attributes;
}
string ICustomTypeDescriptor.GetClassName()
{
if (ClassName != null)
return ClassName;
if (Component != null)
return Component.GetType().Name;
if (_type != null)
return _type.Name;
return null;
}
string ICustomTypeDescriptor.GetComponentName()
{
if (ComponentName != null)
return ComponentName;
return Component != null ? Component.ToString() : null;
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return _typeConverter;
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return _defaultEvent;
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return _defaultProperty;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
object editor;
if (_editors.TryGetValue(editorBaseType, out editor))
return editor;
return null;
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return _events;
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return _events;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return Properties;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return Properties;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return Component;
}
}
I am trying to understand this example from a MSDN article, to my understanding with the IEnumberable interface, we will be able to use Foreach to loop through the class collection, I am confused at the Main method, why don't we just use:
foreach (Person p in peopleArray)
Console.WriteLine(p.firstName + " " + p.lastName);
instead of
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
Example:
using System;
using System.Collections;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
You're right, you could simply use the first version because arrays implement IEnumerable.
The reason they chose to iterate over People is simply for academic purposes; to demonstrate how iterators work (and how to implement IEnumerable). If they simply iterated over peoplearray, they wouldn't be using the People class, which is the main focus of that example.
Hi I was wondering if EntityReference.Load method includes
If Not ref.IsLoaded Then ref.Load()
My question is basically:
Dim person = Context.Persons.FirstOrDefault
person.AddressReference.Load()
person.AddressReference.Load() 'Does it do anything?
It does Load again. I verified this by Profiler and it shown two queries. Default merge option is MergeOption.AppendOnly and it doesn't prevent from querying again. Code from Reflector:
public override void Load(MergeOption mergeOption)
{
base.CheckOwnerNull();
ObjectQuery<TEntity> query = base.ValidateLoad<TEntity>(mergeOption, "EntityReference");
base._suppressEvents = true;
try
{
List<TEntity> collection = new List<TEntity>(RelatedEnd.GetResults<TEntity>(query));
if (collection.Count > 1)
{
throw EntityUtil.MoreThanExpectedRelatedEntitiesFound();
}
if (collection.Count == 0)
{
if (base.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
{
throw EntityUtil.LessThanExpectedRelatedEntitiesFound();
}
if ((mergeOption == MergeOption.OverwriteChanges) || (mergeOption == MergeOption.PreserveChanges))
{
EntityKey entityKey = ObjectStateManager.FindKeyOnEntityWithRelationships(base.Owner);
EntityUtil.CheckEntityKeyNull(entityKey);
ObjectStateManager.RemoveRelationships(base.ObjectContext, mergeOption, (AssociationSet) base.RelationshipSet, entityKey, (AssociationEndMember) base.FromEndProperty);
}
base._isLoaded = true;
}
else
{
base.Merge<TEntity>(collection, mergeOption, true);
}
}
finally
{
base._suppressEvents = false;
}
this.OnAssociationChanged(CollectionChangeAction.Refresh, null);
}
Just for reference for anyone else finding the accepted answer, here is the extension method I created for my current project.
using System.Data.Objects.DataClasses;
namespace ProjectName
{
public static class EntityFrameworkExtensions
{
public static void EnsureLoaded<TEntity>(this EntityReference<TEntity> reference)
where TEntity : class, IEntityWithRelationships
{
if (!reference.IsLoaded)
reference.Load();
}
}
}
And usage:
Patient patient = // get patient
patient.ClinicReference.EnsureLoaded();
patient.Clinic.DoStuff();