Results 1 to 16 of 16

Thread: Clone Objects with Sub-Objects !?

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2021
    Posts
    59

    Clone Objects with Sub-Objects !?

    Hello everyone!

    My question is the one posed in the title ...

    I wanted to know:
    There is a quick method to be able to 'Clone' an object (I mean a Picturebox in this case), but considering that this in turn contains other objects (in this specific case: 5 TextBoxes), in full, as it is present !?

    (Reworded in a reduced way:

    Can you copy -to RunTime, you mean- an Object and its sub-objects !?)

  2. #2
    PowerPoster
    Join Date
    Jan 2020
    Posts
    3,746

    Re: Clone Objects with Sub-Objects !?

    You can learn to dynamically create controls, handle the relationship between upper and lower layers, Z order, coordinate position, and control size

  3. #3
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Clone Objects with Sub-Objects !?

    What you're describing is called deep cloning. The general consensus when it comes to deep cloning is that special care must be taken with objects where any of it's fields are non primitive types or arrays/collections. When deep cloning such objects the common practice is to write code specifically to handle such fields and avoid any temptation to write more generalized code that attempts to handle objects and arrays/collections of ANY type. In you example, you want code to specifically handle collections of TextBoxes and specific code for collections of each of whatever control type you expect to be contained in the PictureBox.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  4. #4
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Clone Objects with Sub-Objects !?

    Calling controls "objects" obscures the reality a bit. We have two words for a reason. Controls must implement additional interfaces, and that's what makes them controls.

    The PictureBox is a pretty poor container control. Usually it is the wrong choice.

    Instead create a proper UserControl that persists its design-time properties. Once you have that it is a simple matter to use a control array as a mechanism for loading additional instances. New instances will inherit the design time property settings of the lowest indexed design-time instance. Contained controls get duplicated for free.

  5. #5

    Thread Starter
    Member
    Join Date
    Mar 2021
    Posts
    59

    Re: Clone Objects with Sub-Objects !?

    Hello everybody!


    Thanks for the replies !!

    I have chosen to create a routine to do this.

    But in fact, I didn't want to do anything in particular; I was just wondering, if what I needed, it was possible to 'accelerate' everything in a different way.

    Like an instant 'cloning', as it happens in Design-mode !!

  6. #6
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,120

    Re: Clone Objects with Sub-Objects !?

    The easiest way to implement deep-copy is to implement serialization of your classes. This is like copy/paste through the clipboard in the design-time form editor i.e. copy will serialize the heirachy to a string (in clipboard) and paste will parse the string (from clipboard) into a separate object heirarchy.

    For instance you can (quickly) serialize to JSON format and then de-serialize from this JSON string again all in memory. This will allow creating deep-copies of the structure as a by-product.

    cheers,
    </wqw>

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Clone Objects with Sub-Objects !?

    Quote Originally Posted by ProgyReloaded View Post
    Hello everybody!


    Thanks for the replies !!

    I have chosen to create a routine to do this.

    But in fact, I didn't want to do anything in particular; I was just wondering, if what I needed, it was possible to 'accelerate' everything in a different way.

    Like an instant 'cloning', as it happens in Design-mode !!
    The simple answer is: No, there is no simple way to do this.

    People often look for some kind of generic method that will perform a deep copy of an object, and such a generic method not only doesn't exist, it can't. There are just too many 'options' as to what pieces need to be copied and which should not be copied, for it to be possible to write a generic method to do this. It ALWAYS comes down to doing it yourself, one way or another. The simplest approach is what wqweto suggested...when it works for the object you are trying to clone. What Niya and Dilettante mentioned are other common solutions, but the bottom line is still the same: You aren't missing anything, there is no canned, generic, solution to this problem. You always have to roll your own.
    My usual boring signature: Nothing

  8. #8
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: Clone Objects with Sub-Objects !?

    Personally, I'd have to second what Dil said.

    Progy, I don't know the specifics of what you're trying to do, but it does sound like you're after a custom user control. And (as Dil stated) those provide the advantage of automatically cloning all your sub-controls, and also all the details of all your events (even after cloning) are also worked out.

    There is a bit of a learning curve to get good at custom user controls. But, in their simplest form, it's just about learning how to use the module level Event declarations, how to use RaiseEvent to raise those events, how to use Property Get and Property Let/Set for your user control's properties, and how to use the UserControl_ReadProperties/UserControl_WriteProperties procedures to make sure your properties get saved at design-time.

    Here is some sample source code for the simplest possible custom user control (which I left as the default name of UserControl1). I just placed a single label on this user control (and left it named Label1). I'll let you work out the details of actually doing that (as it's very simple). And here's the code I wrote for inside of this user control:

    Code:
    
    Option Explicit
    '
    Event Click()
    '
    
    Private Sub UserControl_Initialize()
        ' Just some initialization when the user control loads (design-time or run-time).
        Label1.Top = 0
        Label1.Left = 0
        MakeSameSize
    End Sub
    
    Private Sub UserControl_Resize()
        MakeSameSize
    End Sub
    
    Private Sub MakeSameSize()
        ' This just keeps the label the same size as the user control, if we want.
        Label1.Height = UserControl.Height
        Label1.Width = UserControl.Width
    End Sub
    
    Public Property Get Caption() As String
        ' This just gets the user control's caption when/if it's needed.
        Caption = Label1.Caption
    End Property
    
    Public Property Let Caption(ByVal s As String)
        ' Sets the caption, and, in design-time tells it to save these changes with the source code.
        Label1.Caption = s
        UserControl.Refresh
        PropertyChanged "Caption"
    End Property
    
    Private Sub Label1_Click()
        ' Raises the "Click" event when this user control is placed on a regular form when the label sees a click.
        RaiseEvent Click
    End Sub
    
    Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
        ' IDE takes care of this.  It just reads our caption from the source code.
        Label1.Caption = PropBag.ReadProperty("Caption", "Default Caption")
    End Sub
    
    Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
        ' IDE takes care of this.  It just saves our caption with the source code.
        PropBag.WriteProperty "Caption", Label1.Caption, "Default Caption"
    End Sub
    
    
    
    And then, I just drag/dropped a copy of this new UserControl1 onto Form1 (from the toolbox), which the IDE named (by default) as UserControl11. I then placed this code in Form1:

    Code:
    
    Option Explicit
    
    Private Sub Form_Load()
        UserControl11.Caption = "testing"
    End Sub
    
    
    You could also set this user control's caption from the Properties Window in the IDE, as all public Get/Let/Set properties in the user control will appear on the Properties Window.

    So, as Dil suggested, using this approach just does everything for you.

    Also, just to say it, you could put a PictureBox on your custom user control, and have all kinds of nested controls on this PictureBox (nested to whatever level you like), and they would all be "cloned" whenever you used this user control (or cloned it during runtime).

    Good Luck,
    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  9. #9
    Frenzied Member
    Join Date
    Aug 2020
    Posts
    1,421

    Re: Clone Objects with Sub-Objects !?

    Deep copying of objects can be achieved in JavaScript (the speed of copying is much faster than serialization/deserialization), I don't know how it is done. Studying deep copying of objects in JavaScript should be helpful to our discussion.

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Clone Objects with Sub-Objects !?

    Probably not. JS is a weird language, and not terribly efficient by design, but there are fundamental reasons why deep copies can't be generalized. What I've seen of JS deep clones (and I admit that I haven't looked extensively), they tend to just wrap a serialization/deserialization, or walk the object tree cloning in what might be a recursive fashion (that type of deep clone would fail on circular references, and some of the JS deep clone solutions DO fail in that way).

    All of those are just saying, "I don't care about the potential problems, do it anyways." Consider the case where you have a class that opens a gigabyte file, such as an image, but does it read only. A blind clone of that object would require that same gigabyte file be opened for the clone, even though they could readily share the memory. That would gobble memory pretty fast for no good reason.

    Further consider a class that wrapped, in some fashion, a database connection. What should the clone do?

    There are probably more complex scenarios, too. The simple fact is that it is easy to find scenarios where any blind, generic, copy will do something that is arguably bad. For that reason, deep copies tend not to be generalized, and when they are, there are cases where they don't work well.
    My usual boring signature: Nothing

  11. #11
    Frenzied Member
    Join Date
    Aug 2020
    Posts
    1,421

    Re: Clone Objects with Sub-Objects !?

    Maybe we can find a balanced solution based on the "2-8" principle. We all know that there is a "2-8" principle in software design, that is, 80% of the commonly used features only cost 20% of workload, but the remaining 20% of the infrequent (or special) features cost 80% workload.

    If we could find a solution that only takes a small amount of workload (20%) to meet 80% of the deep copy situation, then the remaining 20% of the special deep-copy cases can be completed by the developer's own code.

    JavaScript does a good job in this regard. JavaScript's object-clone can meet 90% of the needs, and the remaining 10% of special cases require programmers to figure out their own solutions.

  12. #12
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Clone Objects with Sub-Objects !?

    The 80% already covers objects who's fields are made of only primitive types. Such objects are easily serializable in most frameworks without much work.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Clone Objects with Sub-Objects !?

    That 20-80 only really makes sense if you can identify whether or not YOUR case is in the 80 or the 20.

    Suppose some language added a DeepClone feature which only worked 80% of the time. Most people would just call DeepClone when they wanted a copy. Hopefully, they would only call it when they wanted a deep copy, but there's no guarantee that they would. In any case, it would occasionally fail. Would it tell them that it failed, or would they have to discover that? Would it be able to tell them at compile time, or only at runtime? If it failed, would they understand why it failed?

    What would you do if assigning a to B with A = B only occasionally put B into A, and sometimes it left A unchanged?

    We assume that when we do X, the result will be predictable. By adding a deep copy mechanism that only worked in certain cases, we would be violating that principle by adding a feature such that when we do X, the result might not be predictable at all...unless you fully understood what X did such that you knew the limitations of X and when it would fail. If you understand X to that detail, you can write your own X, and you might as well.
    My usual boring signature: Nothing

  14. #14
    Frenzied Member
    Join Date
    Aug 2020
    Posts
    1,421

    Re: Clone Objects with Sub-Objects !?

    IMO, 80% means to include the following:
    (1) Primitive data types
    (2) Array type
    (3) Collection (or other enumerable object) type
    (4) Objects with ToString method
    (5) Provide serialization and deserialization events (or allow developers to execute some personalized code during deep-copy through function-pointers/call-back)

  15. #15
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Clone Objects with Sub-Objects !?

    Quote Originally Posted by SearchingDataOnly View Post
    IMO, 80% means to include the following:
    (1) Primitive data types
    (2) Array type
    (3) Collection (or other enumerable object) type
    (4) Objects with ToString method
    (5) Provide serialization and deserialization events (or allow developers to execute some personalized code during deep-copy through function-pointers/call-back)
    I'd further specify that arrays and collections must be of primitive types too. Arrays/Collections of other complex objects would fall into the 20% you'd spend all day working on.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  16. #16
    PowerPoster
    Join Date
    Feb 2017
    Posts
    4,995

    Re: Clone Objects with Sub-Objects !?

    You cannot know what should be cloned and what should not be cloned in an automated process based only on data types.

    Suppose an object cParent that has three other contained objects, of class cChild.
    And the parent has also a property/variable array that has a pointers to each of these child objects.
    You cannot just copy those numbers in the cloning process.

    I think that more than the 80%, possibly 95% can be automated in the cloning process.
    And the fact that there are some special cases that cannot be automated it does not mean (IMO) that the process cannot be automated at all.
    The cloning function should work as a helper, not something that guarantees (always) a correct cloning.
    Someone understanding the object should be able to predict what would be correct and what would be wrong.
    So the programmer using the clone function should understand the object, to know what can be automatically cloned and what cannot.
    You should be able to tell to the cloner procedure what properties (or whatever) not to clone, and later handle those properties particularly.


    Some approach is; if we cannot do it always 100% right, then don't do it at all.
    Other approach would be: we cannot do it always 100% right, but we can help by doing 95% and let the programmer correct/handle the other 5%

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width