示例#1
0
 private static void CloneMe( ICloneable c )
 {
     // Clone whatever we get and print out the name.
     object theClone = c.Clone();
     Console.WriteLine("Your clone is a: {0}",
       theClone.GetType().Name);
 }
 /// <summary>
 /// Protected constructor; the command is assumed to be a prototype
 /// that will be cloned on CreateCommand, and the cloned command will be executed.
 /// </summary>
 protected DbCommandDefinition(DbCommand prototype) {
     EntityUtil.CheckArgumentNull(prototype, "prototype");
     _prototype = prototype as ICloneable;
     if (null == _prototype) {
         throw EntityUtil.CannotCloneStoreProvider();
     }
 }
示例#3
0
 //END OF MAIN
 //accepts objects implementing ICloneable
 //if not and still you send them to this method then you will get a compile time error
 public static void ICloneableDemo(ICloneable ic)
 {
     //Clone() creates a new independent instance
     Object _ic = ic.Clone();
     //((Program)_ic).i = 100;
     Console.WriteLine(@"Underlying Type ""{0}""", _ic.GetType().Name);
 }
示例#4
0
 // dependencies will be automatically resolved when Get<T>
 // is called on AutoScopeTest.  In this case, T would
 // be TestDependencyInjection
 public TestDependencyInjection(
     ICloneable cloneable,
     // unused dependency, but here just for show
     IComparable unusedComparable)
 {
     _cloneable = cloneable;
 }
 internal InitializedTranslationProfile(ICloneable<TranslationProfile> profile)
 {
     var clone = profile.DeepClone();
     this.ColumnNamePrefix = clone.ColumnNamePrefix;
     this.ColumnNameSuffix = clone.ColumnNameSuffix;
     this.ProfileName = clone.ProfileName;
 }
示例#6
0
 public Playlist(long id, string title, List<Song> songs, ICloneable serviceInfo)
 {
     Id = id;
     Title = title;
     Songs = songs;
     ServiceInfo = serviceInfo;
     _currentPosition = -1;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Common.DbCommandDefinition" /> class using the supplied
 ///     <see
 ///         cref="T:System.Data.Common.DbCommand" />
 ///     .
 /// </summary>
 /// <param name="prototype">
 ///     The supplied <see cref="T:System.Data.Common.DbCommand" />.
 /// </param>
 protected DbCommandDefinition(DbCommand prototype)
 {
     Check.NotNull(prototype, "prototype");
     _prototype = prototype as ICloneable;
     if (null == _prototype)
     {
         throw new ProviderIncompatibleException(Strings.EntityClient_CannotCloneStoreProvider);
     }
 }
 /// <summary>
 /// Protected constructor; the command is assumed to be a prototype
 /// that will be cloned on CreateCommand, and the cloned command will be executed.
 /// </summary>
 protected DbCommandDefinition(DbCommand prototype)
 {
     //Contract.Requires(prototype != null);
     _prototype = prototype as ICloneable;
     if (null == _prototype)
     {
         throw new ProviderIncompatibleException(Strings.EntityClient_CannotCloneStoreProvider);
     }
 }
 private InitializedTranslation(ICloneable<TranslationBase> translation)
 {
     var clone = translation.DeepClone();
     this.TranslationUniqueIdentifier = clone.TranslationUniqueIdentifier;
     this.TraversedGenericArguments = clone.TraversedGenericArguments;
     this.TranslationProfile = clone.TranslationProfile;
     this.TranslationSettings = clone.TranslationSettings;
     this.ColumnConfigurations = clone.ColumnConfigurations;
 }
示例#10
0
        public static IntPtr NativeClone(ICloneable @object)
        {
            CloneHandler clone;
            var type = @object.GetType();

            lock (cloneHandlers)
                if (!cloneHandlers.TryGetValue(type, out clone))
                    cloneHandlers.Add(type, clone = GetHandler(type));

            return clone(@object); // This code may have side effects and should not be run from the lock
        }
示例#11
0
 public void CopyFrom(PathSegment other)
 {
   this.WaitTimeOnStart = other.WaitTimeOnStart;
   this.WaitTimeOnFinish = other.WaitTimeOnFinish;
   this.Duration = other.Duration;
   this.Acceleration = other.Acceleration;
   this.Deceleration = other.Deceleration;
   this.JitterFactor = other.JitterFactor;
   this.Destination = other.Destination;
   this.Orientation = other.Orientation;
   this.CustomData = other.CustomData == null ? (ICloneable) null : other.CustomData.Clone() as ICloneable;
 }
示例#12
0
 private static TreeNode CreateNode(ICloneable c)
 {
     TreeNode node = new TreeNode("" + c);
     if (c == null) return node;
     node.Tag = c;
     foreach (PropertyInfo pi in c.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
     {
         MethodInfo getter = pi.GetGetMethod();
         if (getter == null) continue;
         if (pi.PropertyType.IsSubclassOf(typeof(OptionSet)))
         {
             OptionSet ic = getter.Invoke(c, new object[0]) as OptionSet;
             TreeNode subNode = CreateNode(ic);
             if (subNode.Tag != null)
             {
                 Console.WriteLine("Tag: (" + subNode.Tag + ")");
                 node.Nodes.Add(CreateNode(ic));
             }
         }
     }
     return node;
 }
示例#13
0
        public override DictionaryStorage Clone()
        {
            lock (this) {
                IDictionary <string, object> dict;
                ICloneable cloneable = _dict as ICloneable;
                if (cloneable != null)
                {
                    dict = (IDictionary <string, object>)cloneable.Clone();
                }
                else
                {
                    dict = new Dictionary <string, object>(_dict, StringComparer.Ordinal);
                }

                Dictionary <object, object> objDict = null;
                if (_objDict != null)
                {
                    objDict = new Dictionary <object, object>(_objDict, DefaultContext.DefaultPythonContext.EqualityComparer);
                }

                return(new StringDictionaryStorage(dict, objDict));
            }
        }
        private static void DeepClone()
        {
            IMailEx mail = ProtoTypeFactory.Create <IMailEx>();

            mail.From    = "*****@*****.**";
            mail.Content = "This is prototype pattern demo mail.";

            List <string> lstMainAddress = new List <string>
            {
                "*****@*****.**",
                "*****@*****.**"
            };

            mail.Tos = lstMainAddress;


            ICloneable originallMail = mail as ICloneable;

            if (originallMail == null)
            {
                Console.WriteLine("Main cannot clone");
                return;
            }

            IMailEx newMail = originallMail.Clone() as IMailEx;

            lstMainAddress.Add("*****@*****.**");
            if (newMail != null)
            {
                Console.WriteLine(string.Format("From : {0}", newMail.From));
                Console.WriteLine(string.Format("Content : {0}", newMail.Content));
                foreach (var strMailAddress in newMail.Tos)
                {
                    Console.WriteLine(string.Format("To : {0}", strMailAddress));
                }
            }
        }
        /// <summary>
        /// Saves the Model, first committing changes
        /// if ManagedObjectLifetime is true.
        /// </summary>
        protected virtual T DoSave()
        {
            T result = (T)Model;

            Error = null;
            try
            {
                var savable = Model as ISavable;
                if (ManageObjectLifetime)
                {
                    // clone the object if possible
                    ICloneable clonable = Model as ICloneable;
                    if (clonable != null)
                    {
                        savable = (ISavable)clonable.Clone();
                    }

                    //apply changes
                    var undoable = savable as ISupportUndo;
                    if (undoable != null)
                    {
                        undoable.ApplyEdit();
                    }
                }

                result = (T)savable.Save();

                Model = result;
                OnSaved();
            }
            catch (Exception ex)
            {
                Error = ex;
                OnSaved();
            }
            return(result);
        }
示例#16
0
    static void Main(string[] args)
    {
        Person p1 = new Person();

        p1.Age       = 42;
        p1.BirthDate = Convert.ToDateTime("1977-01-01");
        p1.Name      = "Jack";
        // p1.SecondName = "Daniels";
        p1.IdInfo = new IdInfo(666);
        // p1.Address = new Address("Kings Road", 15);

        ICloneable p2 = p1.ShallowCopy();
        ICloneable p3 = p1.DeepCopy();

        Console.WriteLine("Original values of p1, p2, p3:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values:");
        DisplayValues((Person)p2);
        Console.WriteLine("   p3 instance values:");
        DisplayValues((Person)p3);

        p1.Age       = 32;
        p1.BirthDate = Convert.ToDateTime("1900-01-01");
        p1.Name      = "Frank";
        // p1.SecondName = "Simpson"
        p1.IdInfo.IdNumber = 7878;
        // p1.Address = new Address("Wall street", 10);
        Console.WriteLine("\nValues of p1, p2 and p3 after changes to p1:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values (reference values have changed):");
        DisplayValues((Person)p2);
        Console.WriteLine("   p3 instance values (everything was kept the same):");
        DisplayValues((Person)p3);
    }
        internal static IDictionary CloneDictionary(IDictionary source)
        {
            if (source == null)
            {
                return(null);
            }
            if (source is ICloneable)
            {
                return((IDictionary)((ICloneable)source).Clone());
            }
            IDictionary           dictionary = (IDictionary)Activator.CreateInstance(source.GetType());
            IDictionaryEnumerator enumerator = source.GetEnumerator();

            while (enumerator.MoveNext())
            {
                ICloneable key        = enumerator.Key as ICloneable;
                ICloneable cloneable2 = enumerator.Value as ICloneable;
                if ((key != null) && (cloneable2 != null))
                {
                    dictionary.Add(key.Clone(), cloneable2.Clone());
                }
            }
            return(dictionary);
        }
示例#18
0
        /// <summary>
        /// Converts the parameter object provided by the
        /// <see cref="AlgorithmDefinition"/> containing the properties
        /// to persist.
        /// </summary>
        /// <param name="parameterObject">The value of the algorithms
        /// parameter object</param>
        /// <returns>The <see cref="XElement"/> describing the properties
        /// within the object.</returns>
        public XElement CreateXml(ICloneable parameterObject)
        {
            if (parameterObject == null)
            {
                return(new XElement("properties"));
            }

            MatlabProperties       p             = parameterObject as MatlabProperties;
            string                 path          = p.ScriptFile;
            string                 contentsAsStr = System.Convert.ToBase64String(p.SerializedFile);
            ICollection <XElement> paramElements = new List <XElement>();

            foreach (MatlabParameter parameter in p.Parameters)
            {
                XElement paramXml = parameter.CreateXml();
                paramElements.Add(paramXml);
            }

            return(new XElement("properties",
                                new XAttribute("script-path", path),
                                new XElement("script-copy",
                                             new XCData(contentsAsStr)),
                                new XElement("parameters", paramElements)));
        }
        public void CloneEnumerator_MatchesOriginal(int count)
        {
            IEnumerator e1 = NonGenericIEnumerableFactory(count).GetEnumerator();

            ICloneable c1 = e1 as ICloneable;

            if (c1 == null)
            {
                Assert.False(SupportsEnumeratorCloning, "Enumerator is not cloneable");
                return;
            }
            Assert.True(SupportsEnumeratorCloning, "Enumerator is cloneable");

            // Walk the enumerator, and at each step of the way, clone it.
            // For all cloned enumerators, make sure they match the original
            // for the remainder of the iteration.
            var enumerators = new List <IEnumerator>();

            while (e1.MoveNext())
            {
                foreach (IEnumerator e2 in enumerators)
                {
                    Assert.True(e2.MoveNext(), "Could not MoveNext the enumerator");
                    Assert.Equal(e1.Current, e2.Current);
                }

                if (enumerators.Count < 10) // arbitrary limit to time-consuming N^2 behavior
                {
                    enumerators.Add((IEnumerator)c1.Clone());
                }
            }
            foreach (IEnumerator e2 in enumerators)
            {
                Assert.False(e2.MoveNext(), "Expected to not be able to MoveNext the enumerator");
            }
        }
示例#20
0
        /// <summary>
        /// Creates a deep copy of the <see cref="StackEx{T}"/>.</summary>
        /// <returns>
        /// A deep copy of the <see cref="StackEx{T}"/>.</returns>
        /// <exception cref="InvalidCastException">
        /// <typeparamref name="T"/> does not implement <see cref="ICloneable"/>.</exception>
        /// <remarks>
        /// <b>Copy</b> is similar to <see cref="Clone"/> but creates a deep copy the <see
        /// cref="StackEx{T}"/> by invoking <see cref="ICloneable.Clone"/> on all <typeparamref
        /// name="T"/> elements.</remarks>

        public StackEx <T> Copy()
        {
            StackEx <T> copy = new StackEx <T>(Count);

            // reverse enumeration order
            T[] array = ToArray();
            Array.Reverse(array);

            foreach (T item in array)
            {
                ICloneable cloneable = (ICloneable)item;

                if (cloneable != null)
                {
                    copy.Push((T)cloneable.Clone());
                }
                else
                {
                    copy.Push(item);
                }
            }

            return(copy);
        }
示例#21
0
        public void Paste()
        {
            IDataObject dataObject = Clipboard.GetDataObject();

            if (dataObject.GetDataPresent(typeof(Hashtable).FullName))
            {
                Hashtable dictionary = (Hashtable)dataObject.GetData(typeof(Hashtable));

                foreach (DictionaryEntry n in dictionary)
                {
                    if (!this.ContainsName((string)n.Key))
                    {
                        ICloneable   cloneable = (ICloneable)n.Value;
                        object       value     = cloneable.Clone();
                        ResourceItem item      = this.AddResource((string)n.Key, value);
                        item.Selected = true;
                    }
                    else
                    {
                        MessageBox.Show(this, "Resource \'" + n.Key + "\' already exists.", StringTable.GetString("ApplicationName"));
                    }
                }
            }
        }
        private static void CanCreateAStrictMultiMockFromClassAndTwoInterfacesCommon(XmlReader reader)
        {
            reader.Expect(x => x.AttributeCount).Return(3);

            ICloneable cloneable = reader as ICloneable;

            Assert.NotNull(cloneable);
            cloneable.Expect(x => x.Clone()).Return(reader);

            IHasXmlNode hasXmlNode = reader as IHasXmlNode;

            Assert.NotNull(hasXmlNode);

            XmlNode node = new XmlDocument();

            hasXmlNode.Expect(x => x.GetNode()).Return(node);

            Assert.Equal(3, reader.AttributeCount);
            Assert.Equal(node, hasXmlNode.GetNode());

            Assert.Same(cloneable, cloneable.Clone());

            reader.VerifyAllExpectations();
        }
示例#23
0
        public void Clone()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3),
                    new JObject(
                        new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
                        new JProperty("Second", 1),
                        new JProperty("Third", null),
                        new JProperty("Fourth", new JConstructor("Date", 12345)),
                        new JProperty("Fifth", double.PositiveInfinity),
                        new JProperty("Sixth", double.NaN)
                        )
                    );

            ICloneable c = a;

            JArray a2 = (JArray)c.Clone();

            Assert.IsTrue(a.DeepEquals(a2));
        }
示例#24
0
        /// <summary>
        /// Creates a new instance of the <see cref="T:Northwoods.Go.Xml.GoXmlSimpleData" />-inheriting class
        /// and copies all of the property values -- copying <see cref="T:Northwoods.Go.GoObject" />s
        /// and cloning <c>ICloneable</c>s.
        /// </summary>
        /// <returns>an instance of this same <see cref="T:Northwoods.Go.Xml.GoXmlSimpleData" />-inheriting type</returns>
        public object Clone()
        {
            GoXmlSimpleData             goXmlSimpleData  = (GoXmlSimpleData)Activator.CreateInstance(GetType());
            Dictionary <string, object> dictionary       = goXmlSimpleData.myTable;
            GoCopyDictionary            goCopyDictionary = new GoCopyDictionary();

            foreach (KeyValuePair <string, object> item in myTable)
            {
                GoObject goObject = item.Value as GoObject;
                if (goObject != null)
                {
                    dictionary[item.Key] = goCopyDictionary.CopyComplete(goObject);
                }
                else
                {
                    ICloneable cloneable = goObject as ICloneable;
                    if (cloneable != null)
                    {
                        dictionary[item.Key] = cloneable.Clone();
                    }
                }
            }
            return(goXmlSimpleData);
        }
示例#25
0
        public object Clone()
        {
            RmAttributeValue newValue = new RmAttributeValue();

            newValue.values = new List <IComparable>();
            foreach (IComparable value in this.values)
            {
                ICloneable cloneValue = value as ICloneable;
                if (cloneValue == null)
                {
                    newValue.values.Add(value);
                }
                else
                {
                    IComparable cloneInsert = cloneValue.Clone() as IComparable;
                    if (cloneInsert == null)
                    {
                        throw new InvalidOperationException("A comparable, when cloned, returned a non-comparable: " + cloneValue.ToString());
                    }
                    newValue.values.Add(cloneInsert);
                }
            }
            return(newValue);
        }
示例#26
0
        private void Paste_Click(object Sender, EventArgs e)
        {
            IDataObject d = Clipboard.GetDataObject();

            if (d.GetDataPresent(typeof(Hashtable).FullName))
            {
                Hashtable h = (Hashtable)d.GetData(typeof(Hashtable));
                MainFrame.StatusBar.Text = h.Count + " object(s) added from clipboard.";
                foreach (DictionaryEntry n in h)
                {
                    if (!Resource.ContainsKey(n.Key))
                    {
                        ICloneable c = (ICloneable)n.Value;
                        object     o = c.Clone();
                        Resource.Add(n.Key, o);
                    }
                    else
                    {
                        MainFrame.StatusBar.Text = "Paste partially failed. Resource name already exists.";
                    }
                }
                Initialize();
            }
        }
示例#27
0
        public void CloneObjectTest()
        {
            Assert.AreEqual(0, referenceDictionary.Count);

            for (int i = 1; i <= 25; i++)
            {
                referenceDictionary.Add(new CloneableInt(i), new CloneableInt(i * 1000));
            }

            Assert.AreEqual(25, referenceDictionary.Count);

            ICloneable cloneable = (ICloneable)referenceDictionary;
            IDictionary <CloneableInt, CloneableInt> cloned = (IDictionary <CloneableInt, CloneableInt>)cloneable.Clone();

            // Make sure of the basics... that they aren't pointing to the same references
            Assert.IsFalse(object.ReferenceEquals(referenceDictionary, cloned));

            // Check that the sizes match... duh
            Assert.AreEqual(referenceDictionary.Count, cloned.Count);

            // Go through all the elements in the list and make sure they are equal
            // but that they point to different physical objects
            IEnumerator <KeyValuePair <CloneableInt, CloneableInt> > enumOrig  = referenceDictionary.GetEnumerator();
            IEnumerator <KeyValuePair <CloneableInt, CloneableInt> > enumClone = cloned.GetEnumerator();

            while (enumOrig.MoveNext() && enumClone.MoveNext())
            {
                // Keys point to different objects but are equal
                Assert.IsFalse(object.ReferenceEquals(enumOrig.Current.Key, enumClone.Current.Key));
                Assert.AreEqual(enumOrig.Current.Key, enumClone.Current.Key);

                // Values point to different objects but are equal
                Assert.IsFalse(object.ReferenceEquals(enumOrig.Current.Value, enumClone.Current.Value));
                Assert.AreEqual(enumOrig.Current.Value, enumClone.Current.Value);
            }
        }
示例#28
0
        public override object CopyNativeAs(Schema.IDataType dataType)
        {
            if (IsNative)
            {
                ICloneable cloneable = Value as ICloneable;
                if (cloneable != null)
                {
                    return(cloneable.Clone());
                }

                if (DataType.IsCompound)
                {
                    return(DataValue.CopyNative(Manager, DataType.CompoundRowType, Value));
                }

                return(Value);
            }

            if (StreamID == StreamID.Null)
            {
                return(StreamID);
            }
            return(Manager.StreamManager.Reference(StreamID));
        }
示例#29
0
        public static int RegisterType <T>()
        {
            string      className;
            Destructor  dtorHandler;
            Constructor ctorHandler;

            if (SmokeMarshallers.IsSmokeClass(typeof(T)))
            {
                className   = SmokeMarshallers.SmokeClassName(typeof(T));
                dtorHandler = delegate(IntPtr obj) { DestroyObject(className, obj); };
                ctorHandler = delegate(IntPtr copy) { return(CreateObject(className, copy)); };
            }
            else
            {
                className   = typeof(T).ToString();
                dtorHandler = delegate(IntPtr obj) { ((GCHandle)obj).SynchronizedFree(); };
                ctorHandler = delegate(IntPtr copy) {
                    if (copy != IntPtr.Zero)
                    {
                        object o = (T)((GCHandle)copy).Target;    // create a copy if this is a valuetype

                        ICloneable cloneable = o as ICloneable;
                        if (cloneable != null)
                        {
                            o = cloneable.Clone();
                        }
                        return((IntPtr)GCHandle.Alloc(o));
                    }
                    return((IntPtr)GCHandle.Alloc(default(T)));
                };
            }
            GCHandle.Alloc(className); // prevent collection
            GCHandle.Alloc(dtorHandler);
            GCHandle.Alloc(ctorHandler);
            return(QMetaTypeRegisterType(className, dtorHandler, ctorHandler));
        }
示例#30
0
 private static void CloneMe(ICloneable c)
 {
     object theClone = c.Clone();
     Console.WriteLine("Your clone is a: {0}", theClone.GetType().Name);
 }
示例#31
0
 public  Node(ICloneable d, Node p, Node n)
 {
     Data = d;
     Prev = p;
     Next = n;
 }
示例#32
0
		public ExpressionOwner()
		{
			this.InstanceB = new ArrayList();
			this.InstanceA = this.InstanceB;
			this.NullField = null;
			this.DecimalA = 100;
			this.DecimalB = 0.25M;
			this.KeyboardA = new Keyboard();
			this.KeyboardA.StructA = new Mouse("mouse", 123);
			this.KeyboardA.ClassA = new Monitor();
			this.EncodingA = System.Text.Encoding.ASCII;
			this.DelegateA = DoAction;
			this.ICloneableArray = new string[] {};
			this.ArrayA = new string[] {};
			this.DelegateANull = null;
			this.IComparableNull = null;
			this.IComparableString = "string";
			this.ExceptionA = new ArgumentException();
			this.ExceptionNull = null;
			this.ValueTypeStructA = new TestStruct();
			this.ObjectStringA = "string";
			this.ObjectIntA = 100;
			this.IComparableA = 100.25;
			this.StructA = new TestStruct();
			this.VersionA = new System.Version(1, 1, 1, 1);
			this.ICloneableA = "abc";
			this.GuidA = Guid.NewGuid();
			this.List = new ArrayList();
			this.List.Add("a");
			this.List.Add(100);
			this.StringDict = new System.Collections.Specialized.StringDictionary();
			this.StringDict.Add("key", "value");
			this.DoubleA = 100.25;
			this.SingleA = 100.25f;
			this.Int32A = 100000;
			this.StringA = "string";
			this.BoolA = true;
			this.TypeA = typeof(string);
			this.ByteA = 50;
			this.ByteB = 2;
			this.SByteA = -10;
			this.Int16A = -10;
			this.UInt16A = 100;
			this.DateTimeA = new DateTime(2007, 7, 1);
			this.GenericDict = new Dictionary<string, int>();
			this.GenericDict.Add("a", 100);
			this.GenericDict.Add("b", 100);

			this.Dict = new Hashtable();
			this.Dict.Add(100, null);
			this.Dict.Add("abc", null);

			DataTable dt = new DataTable();
			dt.Columns.Add("ColumnA", typeof(int));

			dt.Rows.Add(100);

			this.Row = dt.Rows[0];
		}
 public D(IConvertible dep1, IDisposable dep2, ICloneable dep3)
 {
 }
示例#34
0
        public override void RunSub(ICloneable _threadParameter)
        {
            JudgeTaskCancelFlag();
            DirectoryInfo originalFold = new DirectoryInfo(((NameConflictParameter)_threadParameter).OriginalDirectory);

            log.Log("Analyzing [" + originalFold.FullName + "]");

            var originalfiles = originalFold.GetFiles().Where(s => {
                bool rtn          = false;
                var extensionlist = ((NameConflictParameter)_threadParameter).OriginalExtension.Split(';');
                foreach (string item in extensionlist)
                {
                    rtn = rtn || s.Name.ToLower().EndsWith("." + item.ToLower());
                }

                return(rtn);
                //s.Name.EndsWith(".exe") || s.Name.EndsWith(".doc") || s.Name.EndsWith(".docx")
            }
                                                              );
            List <NameConflictResult> listNameConflictResult = new List <NameConflictResult>();
            IEnumerable <FileInfo>    ListAllFile            = (IEnumerable <FileInfo>)originalfiles.Where <FileInfo>(s => { return(true); });


            // Check OrigLinal First
            foreach (FileInfo file in originalfiles)
            {
                JudgeTaskCancelFlag();
                //Thread.Sleep(1000);
                // remove self first
                ListAllFile = (IEnumerable <FileInfo>)ListAllFile.Except(new FileInfo[] { file });
                var conflictList = ListAllFile.Where(item => { return(Path.GetFileNameWithoutExtension(file.Name) == Path.GetFileNameWithoutExtension(item.Name)); });
                if (conflictList.Count() > 0)
                {
                    NameConflictResult conflictresult = new NameConflictResult();
                    conflictresult.OriginalFileName = file.Name;
                    conflictresult.Path             = ((NameConflictParameter)_threadParameter).OriginalDirectory;
                    conflictresult.ExtensionName    = Path.GetExtension(file.Name);
                    foreach (FileInfo s in conflictList)
                    {
                        conflictresult.NameConflictFileName += s.Name + " ; ";
                        // remove conflict file
                        ListAllFile = (IEnumerable <FileInfo>)ListAllFile.Except(new FileInfo[] { s });
                    }
                    listNameConflictResult.Add(conflictresult);
                }
            }
            if (((NameConflictParameter)_threadParameter).IsShowFolder)
            {
                if (listNameConflictResult.Count() == 0)
                {
                    // none conflict files under this folder
                    NameConflictResult conflictresult = new NameConflictResult();
                    conflictresult.OriginalFileName     = "OK";
                    conflictresult.Path                 = ((NameConflictParameter)_threadParameter).OriginalDirectory;
                    conflictresult.NameConflictFileName = "none conflicts";
                    listNameConflictResult.Add(conflictresult);
                }
            }
            log.DeleteLog(2);
            LogConflictResult(listNameConflictResult);
            foreach (DirectoryInfo dir in originalFold.GetDirectories())
            {
                NameConflictParameter paramSub = (NameConflictParameter)((NameConflictParameter)_threadParameter).Clone();
                paramSub.OriginalDirectory = dir.FullName;

                RunSub(paramSub);
            }
        }
        /// <summary>
        /// Builds an exception message for the given list of invalid properties.
        /// </summary>
        /// <param name="invalidProperties">The list of names of invalid properties.</param>
        /// <param name="objectName">Name of the object.</param>
        /// <returns>The exception message</returns>
        private string BuildExceptionMessage(string[] invalidProperties, ICloneable objectName)
        {
            int size = invalidProperties.Length;
            StringBuilder sb = new StringBuilder();
            sb.Append(size == 1 ? "Property" : "Properties");
            for (int i=0; i < size; i++)
            {
                string propName = invalidProperties[i];
                if (i > 0)
                {
                    if (i == (size -1 ))
                    {
                        sb.Append(" and");
                    }
                    else
                    {
                        sb.Append(", ");
                    }
                }
                sb.Append(" '").Append(propName).Append("'");
            }
            sb.Append(" required for object '").Append(objectName).Append("'");
            return sb.ToString();

        }
示例#36
0
        static private VistaDBParameter CloneParameter(VistaDBParameter p)
        {
            ICloneable param = p as ICloneable;

            return(param.Clone() as VistaDBParameter);
        }
示例#37
0
        /// <summary>
        /// This occurs while copying properties from the specified source, and
        /// is the default handling for subclasses.
        /// </summary>
        /// <param name="source">Source to copy properties from.</param>
        protected virtual void OnCopyProperties(object source)
        {
            Type original = GetType();
            Type copy     = source.GetType();

            PropertyInfo[] originalProperties = DistinctNames(original.GetProperties(BindingFlags.Public | BindingFlags.Instance));
            PropertyInfo[] copyProperties     = DistinctNames(copy.GetProperties(BindingFlags.Public | BindingFlags.Instance));
            foreach (PropertyInfo originalProperty in originalProperties)
            {
                if (originalProperty.CanWrite == false)
                {
                    continue;
                }
                if (copyProperties.Contains(originalProperty.Name) == false)
                {
                    continue;
                }

                PropertyInfo copyProperty = copyProperties.GetFirst(originalProperty.Name);
                if (copyProperty == null)
                {
                    // The name of the property was not found on the other object
                    continue;
                }

                object copyValue = copyProperty.GetValue(source, null);
                if (copyProperty.GetCustomAttributes(typeof(ShallowCopy), true).Length == 0)
                {
                    ICloneable cloneable = copyValue as ICloneable;
                    if (cloneable != null)
                    {
                        originalProperty.SetValue(this, cloneable.Clone(), null);
                        continue;
                    }
                }

                // Use a shallow copy where ICloneable is not specifically defined.
                originalProperty.SetValue(this, copyValue, null);
            }

            // Public Fields
            FieldInfo[] originalFields = original.GetFields(BindingFlags.Public | BindingFlags.Instance);
            FieldInfo[] copyFields     = copy.GetFields(BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo originalField in originalFields)
            {
                FieldInfo copyField = copyFields.GetFirst(originalField.Name);
                if (copyFields.Contains(originalField.Name) == false)
                {
                    continue;
                }
                if (copyField == null)
                {
                    continue;
                }

                // If it can be cloned, clone it instead of using a reference copy
                object copyValue = copyField.GetValue(source);
                if (copyField.GetCustomAttributes(typeof(ShallowCopy), true).Length == 0)
                {
                    ICloneable cloneable = copyValue as ICloneable;
                    if (cloneable != null)
                    {
                        originalField.SetValue(this, cloneable.Clone());
                        continue;
                    }
                }

                // Use a reference copy only when there is no other alternative.
                originalField.SetValue(this, copyValue);
            }
        }
        object Clone(ICloneable cloned)
        {
            var t = cloned.GetType();
            var clone = Activator.CreateInstance(t);

            foreach (var v in t.GetProperties())
            {
                if (v.CanWrite)
                {
                    var val = v.GetValue(cloned, null);
                    var c = val as ICloneable;
                    if (c != null && !(c is string))
                        val = Clone(c);
                    v.SetValue(clone, val, null);
                }
            }

            return clone;
        }
		public override void CopyFrom (ItemConfiguration configuration)
		{
			base.CopyFrom (configuration);
			ValaProjectConfiguration conf = (ValaProjectConfiguration)configuration;
			
			output = conf.output;
			target = conf.target;
			includes = conf.includes;
			libs = conf.libs;
			source_directory_path = conf.source_directory_path;
			
			if (conf.CompilationParameters == null) {
				compilationParameters = null;
			} else {
				compilationParameters = (ICloneable)conf.compilationParameters.Clone ();
			}
		}
示例#40
0
        private void RedispatchKeyEvent(IEventDispatcher targetComponent, ICloneable systemManagerKeyEvent)
        {
            _keyEvent = (KeyboardEvent)systemManagerKeyEvent.Clone();
            _keyEvent.Target = targetComponent;
            
            /**
             * 1) Dispatch from here
             * */
            DispatchEvent(_keyEvent);

            // the event might be canceled
            if (_keyEvent.Canceled)
                return;

            /**
             * 2) Dispatch from the component
             * */
            targetComponent.DispatchEvent(_keyEvent);
        }
示例#41
0
        private static bool IsHitCollision(Obj_AI_Base collision, ICloneable input, Vector3 pos, float extraRadius)
        {
            var inputSub = input.Clone() as PredictionInput;

            if (inputSub == null)
            {
                return false;
            }

            inputSub.Unit = collision;
            var radius = inputSub.Unit.BoundingRadius;
            var predPos = Movement.GetPrediction(inputSub, false, false).UnitPosition.ToVector2();

            return (collision is Obj_AI_Minion
                    && (predPos.Distance(inputSub.From) < 10 + radius || predPos.Distance(pos) < radius))
                   || predPos.LSDistanceSquared(inputSub.From.ToVector2(), pos.ToVector2(), true)
                   <= Math.Pow(inputSub.Radius + radius + extraRadius, 2);
        }
 internal static InitializedTranslation CreateInstance(ICloneable<TranslationBase> translation, IEnumerable<TranslationEngine> engines)
 {
     var initializedTranslation = new InitializedTranslation(translation);
     engines.ToList().ForEach(e => initializedTranslation.Structures.Add(e.Name, e.BuildDataTableStructure(initializedTranslation)));
     return initializedTranslation;
 }
示例#43
0
 private static IntPtr CloneRegular(ICloneable @object)
 {
     return ObjectiveC.GetNativeObject(@object.Clone());
 }
示例#44
0
        private static IntPtr CloneWrapperImpl(ICloneable @object)
        {
            var clone = @object.Clone();

            return (IntPtr)clone.GetType().InvokeMember("NativePointer", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, Type.DefaultBinder, clone, null);
        }
示例#45
0
        private static void CloneMe(ICloneable c)
        {
            object theClone = c.Clone();

            Console.WriteLine($"Your clone is a: {theClone.GetType().Name}");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ReturnCloneAction"/> class.
 /// </summary>
 /// <param name="prototype">The prototype.</param>
 public ReturnCloneAction(ICloneable prototype)
 {
     this.prototype = prototype;
 }
示例#47
0
        internal void Append(SqlCommand command)
        {
            ADP.CheckArgumentNull(command, nameof(command));

            string cmdText = command.CommandText;

            if (string.IsNullOrEmpty(cmdText))
            {
                throw ADP.CommandTextRequired(nameof(Append));
            }

            CommandType commandType = command.CommandType;

            switch (commandType)
            {
            case CommandType.Text:
            case CommandType.StoredProcedure:
                break;

            case CommandType.TableDirect:
                throw SQL.NotSupportedCommandType(commandType);

            default:
                throw ADP.InvalidCommandType(commandType);
            }

            SqlParameterCollection parameters = null;

            SqlParameterCollection collection = command.Parameters;

            if (0 < collection.Count)
            {
                parameters = new SqlParameterCollection();

                // clone parameters so they aren't destroyed
                for (int i = 0; i < collection.Count; ++i)
                {
                    SqlParameter p = new SqlParameter();
                    collection[i].CopyTo(p);
                    parameters.Add(p);

                    // SQL Injection awareness
                    if (!s_sqlIdentifierParser.IsMatch(p.ParameterName))
                    {
                        throw ADP.BadParameterName(p.ParameterName);
                    }
                }

                foreach (SqlParameter p in parameters)
                {
                    // deep clone the parameter value if byte[] or char[]
                    object obj        = p.Value;
                    byte[] byteValues = (obj as byte[]);
                    if (null != byteValues)
                    {
                        int offset       = p.Offset;
                        int size         = p.Size;
                        int countOfBytes = byteValues.Length - offset;
                        if ((0 != size) && (size < countOfBytes))
                        {
                            countOfBytes = size;
                        }
                        byte[] copy = new byte[Math.Max(countOfBytes, 0)];
                        Buffer.BlockCopy(byteValues, offset, copy, 0, copy.Length);
                        p.Offset = 0;
                        p.Value  = copy;
                    }
                    else
                    {
                        char[] charValues = (obj as char[]);
                        if (null != charValues)
                        {
                            int offset       = p.Offset;
                            int size         = p.Size;
                            int countOfChars = charValues.Length - offset;
                            if ((0 != size) && (size < countOfChars))
                            {
                                countOfChars = size;
                            }
                            char[] copy = new char[Math.Max(countOfChars, 0)];
                            Buffer.BlockCopy(charValues, offset, copy, 0, copy.Length * 2);
                            p.Offset = 0;
                            p.Value  = copy;
                        }
                        else
                        {
                            ICloneable cloneable = (obj as ICloneable);
                            if (null != cloneable)
                            {
                                p.Value = cloneable.Clone();
                            }
                        }
                    }
                }
            }

            int returnParameterIndex = -1;

            if (null != parameters)
            {
                for (int i = 0; i < parameters.Count; ++i)
                {
                    if (ParameterDirection.ReturnValue == parameters[i].Direction)
                    {
                        returnParameterIndex = i;
                        break;
                    }
                }
            }
            LocalCommand cmd = new LocalCommand(cmdText, parameters, returnParameterIndex, command.CommandType, command.ColumnEncryptionSetting);

            CommandList.Add(cmd);
        }
示例#48
0
文件: objects.cs 项目: kumpera/mono
	public static int test_0_cast_iface_array () {
		object o = new ICloneable [0];
		object o2 = new Duper [0];
		object t;
		bool ok;

		if (!(o is object[]))
			return 1;
		if (!(o2 is ICloneable[]))
			return 2;

		try {
			ok = true;
			t = (object[])o;
		} catch {
			ok = false;
		}
		if (!ok)
			return 3;
	
		try {
			ok = true;
			t = (ICloneable[])o2;
		} catch {
			ok = false;
		}
		if (!ok)
			return 4;

		try {
			ok = true;
			t = (ICloneable[])o;
		} catch {
			ok = false;
		}
		if (!ok)
			return 5;

		if (!(o is ICloneable[]))
			return 6;

		/* add tests for interfaces that 'inherit' interfaces */
		return 0;
	}
示例#49
0
 public NameConflict(CustomizedLog _log, CancellationTokenSource _tokenSource, ICloneable _threadParameter) : base(_log, _tokenSource, _threadParameter)
 {
     //param = (CopyFileParameter)ThreadParameter;
 }
示例#50
0
        /// <summary>
        /// 接受数据完成处理函数,异步的特性就体现在这个函数中,
        /// 收到数据后,会自动解析为字符串报文
        /// </summary>
        /// <param name="iar">目标客户端Socket</param>
        protected virtual void ReceiveData(IAsyncResult iar)
        {
            Session session = (Session)iar.AsyncState;
            Socket  client  = session.ClientSocket;

            try
            {
                //如果两次开始了异步的接收,所以当客户端退出的时候
                //会两次执行EndReceive

                int recv = client.EndReceive(iar);

                if (recv == 0)
                {
                    //正常的关闭
                    CloseClient(session.ID, Session.ExitType.NormalExit);
                    return;
                }

                string receivedData = _coder.GetEncodingString(_recvDataBuffer, recv);

                //发布收到数据的事件
                if (RecvData != null)
                {
                    Session sendDataSession = FindSession(session.ID);

                    Debug.Assert(sendDataSession != null);

                    //如果定义了报文的尾标记,需要处理报文的多种情况
                    if (_resolver != null)
                    {
                        if (sendDataSession.Datagram != null &&
                            sendDataSession.Datagram.Length != 0)
                        {
                            //加上最后一次通讯剩余的报文片断
                            receivedData = sendDataSession.Datagram + receivedData;
                        }

                        string[] recvDatagrams = _resolver.Resolve(ref receivedData);


                        foreach (string newDatagram in recvDatagrams)
                        {
                            //深拷贝,为了保持Datagram的对立性
                            ICloneable copySession = (ICloneable)sendDataSession;

                            Session clientSession = (Session)copySession.Clone();

                            clientSession.Datagram = newDatagram;
                            //发布一个报文消息
                            RecvData(this, new NetEventArgs(clientSession));
                        }

                        //剩余的代码片断,下次接收的时候使用
                        sendDataSession.Datagram = receivedData;

                        if (sendDataSession.Datagram.Length > MaxDatagramSize)
                        {
                            sendDataSession.Datagram = null;
                        }
                    }
                    //没有定义报文的尾标记,直接交给消息订阅者使用
                    else
                    {
                        ICloneable copySession = (ICloneable)sendDataSession;

                        Session clientSession = (Session)copySession.Clone();

                        clientSession.Datagram = receivedData;

                        RecvData(this, new NetEventArgs(clientSession));
                    }
                }//end of if(RecvData!=null)

                //继续接收来自来客户端的数据
                client.BeginReceive(_recvDataBuffer, 0, _recvDataBuffer.Length, SocketFlags.None,
                                    new AsyncCallback(ReceiveData), session);
            }
            catch (SocketException ex)
            {
                //客户端退出
                if (10054 == ex.ErrorCode)
                {
                    //客户端强制关闭
                    CloseClient(session.ID, Session.ExitType.ExceptionExit);
                }
            }
            catch (ObjectDisposedException ex)
            {
                if (ex != null)
                {
                    ex = null;
                    //DoNothing;
                }
            }
        }
示例#51
0
        public static void CloneMe(ICloneable c)
        {
            object theClone = c.Clone();

            Console.WriteLine("Your clone is a : {0} ", theClone.GetType().Name);
        }
		public virtual void SetOptions (ICloneable ops, string configuration)
		{
			if (options == null)
				options = new Hashtable ();
				
			Hashtable configOptions = (Hashtable) options [configuration];
			if (configOptions == null) {
				configOptions = new Hashtable ();
				options [configuration] = configOptions;
			}
			
			configOptions [ops.GetType ()] = ops.Clone ();
			SaveOptions ();
		}
示例#53
0
        /// <summary>
        /// 数据接收处理函数
        /// </summary>
        /// <param name="iar">异步Socket</param>
        protected virtual void RecvData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;

            try
            {
                int recv = remote.EndReceive(iar);

                //正常的退出
                if (recv == 0)
                {
                    _session.TypeOfExit = Session.ExitType.NormalExit;

                    if (DisConnectedServer != null)
                    {
                        DisConnectedServer(this, new NetEventArgs(_session));
                    }
                    Close();

                    return;
                }

                string receivedData = _coder.GetEncodingString(_recvDataBuffer, recv);

                //通过事件发布收到的报文
                if (ReceivedDatagram != null)
                {
                    //通过报文解析器分析出报文
                    //如果定义了报文的尾标记,需要处理报文的多种情况
                    if (_resolver != null)
                    {
                        if (_session.Datagram != null &&
                            _session.Datagram.Length != 0)
                        {
                            //加上最后一次通讯剩余的报文片断
                            receivedData = _session.Datagram + receivedData;
                        }

                        string[] recvDatagrams = _resolver.Resolve(ref receivedData);


                        foreach (string newDatagram in recvDatagrams)
                        {
                            //Need Deep Copy.因为需要保证多个不同报文独立存在
                            ICloneable copySession = (ICloneable)_session;

                            Session clientSession = (Session)copySession.Clone();

                            clientSession.Datagram = newDatagram;

                            //发布一个报文消息
                            ReceivedDatagram(this, new NetEventArgs(clientSession));
                        }

                        //剩余的代码片断,下次接收的时候使用
                        _session.Datagram = receivedData;
                    }
                    //没有定义报文的尾标记,直接交给消息订阅者使用
                    else
                    {
                        ICloneable copySession = (ICloneable)_session;

                        Session clientSession = (Session)copySession.Clone();

                        clientSession.Datagram = receivedData;

                        ReceivedDatagram(this, new NetEventArgs(clientSession));
                    }
                }//end of if(ReceivedDatagram != null)

                //继续接收数据
                _session.ClientSocket.BeginReceive(_recvDataBuffer, 0, DefaultBufferSize, SocketFlags.None,
                                                   new AsyncCallback(RecvData), _session.ClientSocket);
            }
            catch (SocketException ex)
            {
                //客户端退出
                if (10054 == ex.ErrorCode)
                {
                    //服务器强制的关闭连接,强制退出
                    _session.TypeOfExit = Session.ExitType.ExceptionExit;

                    if (DisConnectedServer != null)
                    {
                        DisConnectedServer(this, new NetEventArgs(_session));
                    }
                    Close();
                }
                else
                {
                    //服务器强制的关闭连接,强制退出
                    if (CannotConnectedServer != null)
                    {
                        CannotConnectedServer(this, new NetEventArgs());
                    }
                    Close();
                }
            }
            catch (ObjectDisposedException ex)
            {
                if (ex != null)
                {
                    ex = null;
                    //DoNothing;
                }
            }
        }
示例#54
0
        /// <summary>
        /// Called by the business object's Save() method to
        /// insert, update or delete an object in the database.
        /// </summary>
        /// <remarks>
        /// Note that this method returns a reference to the updated business object.
        /// If the server-side DataPortal is running remotely, this will be a new and
        /// different object from the original, and all object references MUST be updated
        /// to use this new object.
        /// </remarks>
        /// <param name="obj">A reference to the business object to be updated.</param>
        /// <returns>A reference to the updated business object.</returns>
        public static object Update(object obj)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            DataPortalOperations     operation = DataPortalOperations.Update;
            Type objectType = obj.GetType();

            try
            {
                OnDataPortalInitInvoke(null);
                DataPortalMethodInfo method;
                var factoryInfo = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
                if (factoryInfo != null)
                {
                    var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);
                    var bbase       = obj as Core.BusinessBase;
                    if (bbase != null && bbase.IsDeleted)
                    {
                        if (!YYT.Security.AuthorizationRules.CanDeleteObject(objectType))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "delete",
                                                                                      objectType.Name));
                        }
                        method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.DeleteMethodName, new object[] { obj });
                    }
                    else
                    {
                        if (!YYT.Security.AuthorizationRules.CanEditObject(objectType))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "save",
                                                                                      objectType.Name));
                        }
                        method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName, new object[] { obj });
                    }
                }
                else
                {
                    string methodName;
                    if (obj is CommandBase)
                    {
                        methodName = "DataPortal_Execute";
                        operation  = DataPortalOperations.Execute;
                        if (!YYT.Security.AuthorizationRules.CanEditObject(objectType))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "execute",
                                                                                      objectType.Name));
                        }
                    }
                    else
                    {
                        var bbase = obj as Core.BusinessBase;
                        if (bbase != null)
                        {
                            if (bbase.IsDeleted)
                            {
                                methodName = "DataPortal_DeleteSelf";
                                if (!YYT.Security.AuthorizationRules.CanDeleteObject(objectType))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "delete",
                                                                                              objectType.Name));
                                }
                            }
                            else
                            if (bbase.IsNew)
                            {
                                methodName = "DataPortal_Insert";
                                if (!YYT.Security.AuthorizationRules.CanCreateObject(objectType))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "create",
                                                                                              objectType.Name));
                                }
                            }
                            else
                            {
                                methodName = "DataPortal_Update";
                                if (!YYT.Security.AuthorizationRules.CanEditObject(objectType))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "save",
                                                                                              objectType.Name));
                                }
                            }
                        }
                        else
                        {
                            methodName = "DataPortal_Update";
                            if (!YYT.Security.AuthorizationRules.CanEditObject(objectType))
                            {
                                throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                          "save",
                                                                                          objectType.Name));
                            }
                        }
                    }
                    method = Server.DataPortalMethodCache.GetMethodInfo(obj.GetType(), methodName);
                }

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(method.RunLocal);

                dpContext =
                    new Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, operation));

                try
                {
                    if (!proxy.IsServerRemote && ApplicationContext.AutoCloneOnUpdate)
                    {
                        // when using local data portal, automatically
                        // clone original object before saving
                        ICloneable cloneable = obj as ICloneable;
                        if (cloneable != null)
                        {
                            obj = cloneable.Clone();
                        }
                    }
                    result = proxy.Update(obj, dpContext);
                }
                catch (Server.DataPortalException ex)
                {
                    result = ex.Result;
                    if (proxy.IsServerRemote)
                    {
                        ApplicationContext.SetGlobalContext(result.GlobalContext);
                    }
                    throw new DataPortalException(
                              String.Format("DataPortal.Update {0} ({1})", Resources.Failed, ex.InnerException.InnerException),
                              ex.InnerException, result.ReturnObject);
                }

                if (proxy.IsServerRemote)
                {
                    ApplicationContext.SetGlobalContext(result.GlobalContext);
                }

                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, operation));
            }
            catch (Exception ex)
            {
                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, operation, ex));
                throw;
            }
            return(result.ReturnObject);
        }
示例#55
0
 public Pair(STMObject stmObject, ICloneable snapshot)
 {
     this.stmObject = stmObject;
     this.snapshot  = snapshot;
 }
示例#56
0
 /// <summary>
 /// Returns a clone as method return value.
 /// </summary>
 /// <param name="prototype">The prototype to clone.</param>
 /// <returns>Action defining the return value of a method.</returns>
 public static IAction CloneOf(ICloneable prototype)
 {
     return new ReturnCloneAction(prototype);
 }
示例#57
0
 /// <summary>
 /// Called when VisualTemplate property has changed.
 /// </summary>
 /// <param name="oldValue">Old property value</param>
 /// <param name="newValue">New property value</param>
 protected virtual void OnVisualTemplateChanged(ICloneable oldValue, ICloneable newValue)
 {
     //OnPropertyChanged(new PropertyChangedEventArgs("VisualTemplate"));
 }
示例#58
0
 public abstract void RunSub(ICloneable _threadParameter);
示例#59
0
文件: Cil.cs 项目: pusp/o2platform
        public static void CopyTo(object target, ICloneable aspect) {
            bool preconditions = target != null && aspect != null;

            if (preconditions && target == Cil.TargetMainModule && aspect is TypeDefinition) {
                TypeDefinition aspectTypeDef = (TypeDefinition)aspect;
                if (Cil.TargetMainModule.Types[aspectTypeDef.FullName] == null)
                    Cil.TargetMainModule.Types.Add(TargetMainModule.Inject(aspectTypeDef));
            } else if (target is TypeDefinition) {
                TypeDefinition targetType = (TypeDefinition)target;

                // Only insert members on classes or structs
                preconditions = !targetType.FullName.StartsWith("<")
                    && !targetType.IsEnum
                    && !targetType.IsInterface
                    && !(targetType.BaseType != null && targetType.BaseType.Name == "Delegate");

                if (preconditions) {
                    if (aspect is FieldDefinition) {
                        FieldDefinition aspectFieldDef = (FieldDefinition)aspect;
                        bool contains = false;
                        foreach(FieldDefinition fieldDef in targetType.Fields)
                            if (fieldDef.Name == aspectFieldDef.Name){
                                contains = true;
                                break;
                            }
                        if (! contains) 
                            targetType.Fields.Add(TargetMainModule.Inject(aspectFieldDef));
                    } else if (aspect is MethodDefinition) {
                        MethodDefinition aspectMethodDef = (MethodDefinition)aspect;
                        bool contains = false;
                        foreach (MethodDefinition methodDef in targetType.Methods)
                            if (methodDef.Name == aspectMethodDef.Name) {
                                contains = true;
                                break;
                            }
                        if (!contains) {
                            MethodDefinition clone = TargetMainModule.Inject(aspectMethodDef);
                            targetType.Methods.Add(clone);

                            // Update field, method or type references in the instructions of the copied method
                            if (clone.Body != null) {
                                clone.Body.InitLocals = true;

                                MethodReference aspectMethod = (MethodReference)aspect;

                                foreach (Instruction instr in clone.Body.Instructions)
                                    if (instr.Operand is FieldReference) {
                                        FieldReference fieldRef = (FieldReference)instr.Operand;
                                        if (fieldRef.DeclaringType.FullName == aspectMethod.DeclaringType.FullName)
                                            instr.Operand = targetType.Fields.GetField(fieldRef.Name);
                                    } else if (instr.Operand is MethodReference) {
                                        MethodReference methodRef = (MethodReference)instr.Operand;
                                        if (methodRef.DeclaringType.FullName == aspectMethod.DeclaringType.FullName)
                                            instr.Operand = targetType.Methods.GetMethod(methodRef.Name, methodRef.Parameters);
                                    } else if (instr.Operand is TypeReference) {
                                        TypeReference typeRef = (TypeReference)instr.Operand;
                                        if (typeRef.FullName == aspectMethod.DeclaringType.FullName)
                                            instr.Operand = targetType;
                                    }
                            }
                        }
                    } else if (aspect is TypeDefinition) {
                        TypeDefinition clone = Cil.TargetMainModule.Inject((TypeDefinition)aspect);
                        targetType.NestedTypes.Add(clone);
                    }
                }
            }
        }
示例#60
0
		public ItemWithCloneable(ICloneable c)
		{
			value = c;
		}