Expandable Objects - Managed C++ - c++-cli

I try to develop custom control in managed c++, My custom cuntrol inherits from the Control class, As part of it i want to add custom properties to my custom control, to do that i created a class called ControlStyle, this class contains some properties like: colors, font etc.
Now i want to make a property of type ControlStyle in the CustomControl class, I'll explain myself: I want a property of type ControlStyle that will shown with the "+" sign in the properties window (called expandable properties), in the class CustomControl. so i did it, the problem is: that i drag and drop the custom control to a form and modify the values of the ControlStyle properties, and when i execute the application i see that any value of the ControlStyle properties that were changed by the user at the design time - not saved, and waht i get at runtime is the initial value of the ControlStyle properties, I understand that i'm not so clear, so lets talk code:
My ControlStyle class:
[TypeConverter(typeid(ExpandableObjectConverter))]
public ref class ControlStyle
{
// private variables
private: System::Drawing::Font^ font;
private: Color backColor1 = Color::Blue;
private: Color backColor2 = Color::Red;
// constructor
public: ControlStyle::ControlStyle()
{
font = gcnew System::Drawing::Font("Arial", 12);
}
// properties
public: property Color BackColor1
{
Color get() { retun backColor1; }
void set(Color value) { backColor1 = value; }
}
public: property Color BackColor2
{
Color get() { retun backColor2; }
void set(Color value) { backColor2 = value; }
}
public: virtual property System::Drawing::Font^ Font
{
virtual System::Drawing::Font^ get() override { return font; }
virtual void set(System::Drawing::Font^ value) override
{ font = value; }
}
}
My CustomControl class:
public ref class CustomControl : public System::Windows::Forms::Control
{
// private variables
private: ControlStyle^ controlStyle;
// constructor
public: CustomControl::CustomControl()
{
controlStyle = gcnew ControlStyle();
}
// properties
public: property ControlStyle^ Style
{
ControlStyle^ get() { return controlStyle; }
}
// methods like paint etc.
}
When i use the custom control on a form, (i see the first values of the ControlStyle properties like the initialization of them in the ControlStyle class), and i modify the values of the ControlStyle properties (Note: i modify the values of ControlStyle properties not by code, but manually by the properties window and i see the changes on the control - it works well), for example:
customControl1->Style->BackColor1 = Color::Green;
When i execute the program i see (at runtime) that the value of the customControl1->Style->BackColor1 property is Color::Blue that is the value of it's initial definition, and not Color::Green - which is the value that i put at design time.
To solve the issue i wrote the values that the customControl1->Style->BackColor1 property gets by the user at design time to a file and read it back when the DesignMode property change it's value to false, and additional attempts like this - and nothing...
I saw blogs says that it problem of serialization.
also applying the SerializableAttribute to the classes - does not work.
I think the reason for this problem is the initialization of the controlStyle variable in the CustomControl's constructor, i.e:
controlStyle = gcnew ControlStyle();
But this initialization must to be done for the control's function.
I will be very grateful for any help. Thanks alot!!

Related

Why documentt.data.getValue() gives empty string? [duplicate]

A custom object that takes a parameter of (DocumentSnapShot documentsnapShot). also is an inner object from Firebase that retrieves a snapshot and set the values to my custom model also have its argument (DocumentSnapShot documentsnapShot). However, I wish to get the data from Firebase and pass it to my custom argument because mine takes multiple data not only Firebase. And it's not possible to iterate Firestore without an override.
Here's the code:
public UserSettings getUserSettings(DocumentSnapshot documentSnapshot){
Log.d(TAG, "getUserSettings: retrieving user account settings from firestore");
DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID);
mSettings.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class);
settings.setDisplay_name(documentSnapshot.getString("display_name"));
settings.setUsername(documentSnapshot.getString("username"));
settings.setWebsite(documentSnapshot.getString("website"));
settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
settings.setPosts(documentSnapshot.getLong("posts"));
settings.setFollowers(documentSnapshot.getLong("followers"));
settings.setFollowing(documentSnapshot.getLong("following"));
}
});
}
You cannot return something now that hasn't been loaded yet. Firestore loads data asynchronously, since it may take some time for this. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available. If you want to pass settings object to another method, just call that method inside onSuccess() method and pass that object as an argument. So a quick fix would be this:
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class);
yourMethod(settings);
}
One more thing to mention is that you don't need to set the those values to object that already have them. You are already getting the data from the database as an object.
So remember, onSuccess() method has an asynchronous behaviour, which means that is called even before you are getting the data from your database. If you want to use the settings object outside that method, you need to create your own callback. To achieve this, first you need to create an interface like this:
public interface MyCallback {
void onCallback(UserAccountSettings settings);
}
Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID);
mSettings.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class);
myCallback.onCallback(settings);
}
});
}
In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:
readData(new MyCallback() {
#Override
public void onCallback(UserAccountSettings settings) {
Log.d("TAG", settings.getDisplay_name());
}
});
This is the only way in which you can use that object of UserAccountSettings class outside onSuccess() method. For more informations, you can take also a look at this video.
Use LiveData as return type and observe the changes of it's value to execute desired operation.
private MutableLiveData<UserAccountSettings> userSettingsMutableLiveData = new MutableLiveData<>();
public MutableLiveData<UserAccountSettings> getUserSettings(DocumentSnapshot documentSnapshot){
DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID);
mSettings.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class);
settings.setDisplay_name(documentSnapshot.getString("display_name"));
settings.setUsername(documentSnapshot.getString("username"));
settings.setWebsite(documentSnapshot.getString("website"));
settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
settings.setPosts(documentSnapshot.getLong("posts"));
settings.setFollowers(documentSnapshot.getLong("followers"));
settings.setFollowing(documentSnapshot.getLong("following"));
userSettingsMutableLiveData.setValue(settings);
}
});
return userSettingsMutableLiveData;
}
Then from your Activity/Fragment observe the LiveData and inside onChanged do your desired operation.
getUserSettings().observe(this, new Observer<UserAccountSettings>() {
#Override
public void onChanged(UserAccountSettings userAccountSettings) {
//here, do whatever you want on `userAccountSettings`
}
});

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

How to force MOXy to use the setter on a Collection property that is lazily initialized?

Given a bean like this:
public class MyBean {
private List<Something> things;
private List<Something> internalGetThings() {
if (things == null) {
things = new ArrayList<Something>();
}
return things;
}
public Iterable<Something> getThings() {
return <an immutable copy of internalGetThings()>;
}
public void setThings(List<Something> someThings) {
things.clear();
for (Something aThing : someThings) {
addThing(aThing);
}
}
public void addThing(Something aThing) {
things.add(aThing);
// Do some special stuff to aThing
}
}
Using external mapping file, when I map like this:
<xml-element java-attribute="things" name="thing" type="com.myco.Something" container-type="java.util.ArrayList" />
It seems that each individual Something is being added to the MyBean by calling getThings().add(). That's a problem because getThings() returns an immutable copy of the list, which is lazily initialized. How can I configure mapping (I'm using an external mapping file, not annotations) so that MOXy uses setThings() or addThing() instead?
Why Does JAXB/MOXy Check the Get Method for Collection First?
JAXB (JSR-222) implementations give you a chance to have your property be the List interface and still leverage the underlying List implementation that you choose to use. To accomplish this a JAXB implementation will call the get method to see if the List implementation has been initialized. It it has the List will be populated using the add method.
public List<String> getThings() {
if(null == things) {
things = new ArrayList<String>();
}
return things;
}
public List<String> getThings() {
if(null == things) {
things = new LinkedList<String>();
}
return things;
}
If you don't pre-initialize the List property then MOXy/JAXB will build an instance of the List (default is ArrayList) and set it on the object using the set method.
private List<Something> things; // Don't Initialize
public List<String> getThings() {
return things;
}
public void setThings(List<String> things) {
this.things = things;
}
Given the reason in #Blaise's answer, it doesn't seem possible to have MOXy (or any JAXB implementation in general?) populate a lazily-initialized collection via a setter method on the collection. However, a combination of xml-accessor-type="FIELD" (or #XmlAccessorType if using annotations) and defining a JAXB unmarshal event callback will get the job done. In my afterUnmarshal() implementation I do the special work on Something instances that is done in addSomething().
private void afterUnmarshal(Unmarshaller, Object parent) {
for (Something aThing : getSomethings()) {
// Do special stuff on aThing
}
}
Using FIELD access type gets JAXB/MOXy to directly inject the collection into the field, bypassing the getter. Then the call back cleans things up properly.

Something other than INotifyPropertyChanged?

I have the following property and pseudo-code method:
private DataModelMember _PropertyMember = new DataModelMember();
public DataModelMember PropertyMember
{
get { return _PropertyMember; }
}
void GetWCFData()
{
DataModel d = client.getWCFData();
this._PropertyMember = d.result.anotherclass; //*(DataModelMember is anotherclass)
}
So, "this._PropertyMember = value" does in fact change the private member, it however does not update any of the properties inside (as evident with the databinding). It almost seems like my 'DataModelMember' class needs to inherit some other interface to notify of the class copy?
INotifyPropertyChanged is not magic.
You need to raise the PropertyChanged event yourself whenever the property changes.

How does Undo work?

How does undo work? Does it copy all the managed objects every time any of the values change? Or does it only copy the actual changes together with an information which objects were affected? Is that heavy or lightweight?
The 'undo' mechanism for pretty much any language that supports Object-Oriented constructs uses the Memento Design Pattern to make it happen.
Here's a rough implementation to get you thinking. This handles your stack of undoable operations. (It doesn't handle redo, but that's easy to support by replacing the stack with a list and keeping track of the current item.)
public class Undoable {
public static void Do(Action do, Action undo) {
do();
sUndoStack.Push(new Undoable(do, undo));
}
public static void Undo() {
sUndoStack.Pop().mUndoCallback();
}
private Undoable(Action doCallback, undoCallback) {
mDoCallback = doCallback;
mUndoCallback = undoCallback;
}
private Action mDoCallback, mUndoCallback;
// note: using a global stack here is lame, but works for demo purposes
private static readonly Stack<Undoable> sUndoStack = new Stack<Undoable>();
}
To use this, let's say the user can change a value in some object like this:
public class Foo {
public string Bar {
get { return mBar; }
set {
if (mBar != value) {
mBar = value;
}
}
}
private string mBar;
}
To make that operation undoable, we just change the setter to:
set {
if (mBar != value) {
string oldValue = mBar;
Undoable.Do(() => mBar = value,
() => mBar = oldValue);
}
}
Now, if you call Undoable.Undo() from anywhere in the application, your instance of Foo will restore the previous value of Bar. If Foo also raises an event when Bar changes (not shown here), the UI will also properly refresh on undo too.