Exemple #1
0
        /// <summary>
        /// Save the current state of the object so that you can revert to it if necessary.
        /// </summary>
        public void CreateSnapshot()
        {
            Type      currentType;
            Hashtable state = new Hashtable();

            FieldInfo[] fields;
            string      fieldName;

            _bindingEdit = true;

            currentType = this.GetType();

            do
            {
                // Get the member-fields of this type
                fields = currentType.GetFields(BindingFlags.Public |
                                               BindingFlags.NonPublic |
                                               BindingFlags.Instance);

                foreach (FieldInfo field in fields)
                {
                    // If this field is declared in the current-type, and, it is
                    // a field that is undoable, then keep track of its state.
                    if (field.DeclaringType == currentType &&
                        this.IsUndoableField(field))
                    {
                        object fieldValue = field.GetValue(this);

                        // If the field is an IUndoable type, cascade the call.
                        IUndoable uf = fieldValue as IUndoable;

                        if (uf != null)
                        {
                            uf.CreateSnapshot();
                        }
                        else
                        {
                            fieldName = currentType.Name + "." + field.Name;
                            state.Add(fieldName, fieldValue);
                        }
                    }
                }

                currentType = currentType.BaseType;
            } while(currentType != typeof(BusinessObject));

            // Now we have saved the complete state of the object in the
            // hashtable.  We need to stack it into the state-stack.
            MemoryStream    buffer = new MemoryStream();
            BinaryFormatter fmt    = new BinaryFormatter();

            fmt.Serialize(buffer, state);
            _stateStack.Push(buffer.ToArray());   // Stack it as a byte-array
        }