/// <summary> /// Gets or sets the record of the given name /// </summary> /// <param name="record">The name of the record</param> /// <returns>The record item</returns> public object this[string record] { get { lock (_lock) { var item = _dict[record]; /* * If the item is a persist records collection then it's because * the item was an IPersist-aware type and now it needs * creating and loading with the values */ if (item is PersistRecords) { var pr = (PersistRecords)item; IPersist inst; try { inst = (IPersist)Activator.CreateInstance(pr._iPersistParentType); } catch (Exception ex) { throw new ApplicationException( string.Format("Failed to create instance of type '{0}' to load persisted data", pr._iPersistParentType), ex); } try { inst.LoadFromPersisted(pr); } catch (Exception ex) { throw new ApplicationException("Failed to get the instance to load from persisted records", ex); } return inst; } else { return item; } } } set { if (_readonly) { throw new InvalidOperationException("Readonly"); } lock (_lock) { if (value != null) { if (!Attribute.IsDefined(value.GetType(), typeof(SerializableAttribute)) && value.GetType().GetInterface(typeof(IPersist).FullName) == null) { throw new ArgumentException("Value must either be serializable or support 'IPersist'", "value"); } /* * If the value is an IPerist-aware type build up a new records * and get the instance to persist to it, store the records instead * of the instance */ if (value.GetType().GetInterface(typeof(IPersist).FullName) != null) { try { var pr = new PersistRecords(Guid.NewGuid().ToString(), false, new Dictionary<string, object>()); pr._iPersistParentType = value.GetType(); ((IPersist)value).PersistRecords(pr); _dict[record] = pr; return; } catch (Exception ex) { throw new ApplicationException( string.Format("Failed to turn record item of type '{0}' into persist records " + "collection as it is IPersist-aware", value.GetType()), ex); } } _dict[record] = value; } else { _dict[record] = null; } } } }
/// <summary> /// Generates <see cref="PersistRecords"/> and gets <paramref name="persistable"/> to persist data to it /// </summary> /// <param name="persistable">The <see cref="IPersist"/>-aware instance</param> /// <returns>The <see cref="PersistRecords"/></returns> public static PersistRecords GetRecordsFromPersistable(IPersist persistable) { var pr = new PersistRecords(); persistable.PersistRecords(pr); return pr; }