Robust method for making a copy of a TRemotable object in Delphi 2007 - web-services

Is there a robust mechanism for making a copy of TRemotable object (or descendant) in Delphi 2007?
I'm creating a Delphi web service client that receives a variety of objects from a web service; of course, all are descendants of TRemotable. In the client, I create a matching object, then copy all the properties from the web service provided TRemotable to my own object. This is done via TypInfo.GetPropList() and then a loop around TypInfo. GetPropValue() and TypInfo.SetPropValue() method calls. Although this works great for the simple types - strings, ints, bool, etc, it doesn't work for complex types, like dates, times or sub-object types. And I assume that if the web service ever makes use of a new complex type, my copy code would also break.
It looks like one possibility is to serialize the object out to an XML document, then read it into the new object. But this seems like a great deal of overhead to just copy a series of properties around.

Found a more robust solution, seems to work fine for simply types, TXS... derivative types and subobject types:
procedure CopyNormal(Source, Target: TRemotable);
var
Converter: IObjConverter;
NodeObject: IXMLNode;
NodeParent: IXMLNode;
NodeRoot: IXMLNode;
XML: IXMLDocument;
XMLStr: WideString;
begin
XML:= NewXMLDocument;
NodeRoot:= XML.AddChild('Root');
NodeParent:= NodeRoot.AddChild('Parent');
Converter:= TSOAPDomConv.Create(NIL);
NodeObject:= Source.ObjectToSOAP(NodeRoot, NodeParent, Converter, 'CopyObject', '', [ocoDontPrefixNode], XMLStr);
Target.SOAPToObject(NodeRoot, NodeObject, Converter);
end;

TDateTime is just a Double by a different name, and you ought to be able to copy it without trouble. Or are you using some other format for your dates and times?
As for sub-objects, they can be handled by making your copy routine recursive. If it comes across a property that's an object, have it make a copy of that object and assign it to the parent object. (NOTE: This will only work if the sub-object also has published properties.)

Yes you could make the copy recursive, but that still leaves you with problems, how to copy internal private fields. You would have to expose all fields as properties and in my opinion that is not clean and is cumbersome.
I would definitely serialize the object. SOAP has so much overhead on its own that serialization is super fast in comparison. I would even argue that a simple HTTP approach using REST would be better.
You can look at my SimpleStorage framework that was made with such tasks (serialization) in mind. Especially look at adapters feature.
You can get it at: http://www.cromis.net/blog/downloads/
There are also articles there that show how to use it. If you are already using other XML library and don't want to switch I would still prefer the serialization approach if I were you.
I doubt that you can make a http request last under 30ms. Serialization would take way less than that. Now add the SOAP overhead and you are super fast compared to it :)

Related

framework/library for property-tree-like data structure with generic get/set-implementation?

I'm looking for a data structure which behaves similar to boost::property_tree but (optionally) leaves the get/set implementation for each value item to the developer.
You should be able to do something like this:
std::function<int(void)> f_foo = ...;
my_property_tree tree;
tree.register<int>("some.path.to.key", f_foo);
auto v1 = tree.get<int>("some.path.to.key"); // <-- calls f_foo
auto v2 = tree.get<int>("some.other.path"); // <-- some fallback or throws exception
I guess you could abuse property_tree for this but I haven't looked into the implementation yet and I would have a bad feeling about this unless I knew that this is an intended use case.
Writing a class that handles requests like val = tree.get("some.path.to.key") by calling a provided function doesn't look too hard in the first place but I can imagine a lot of special cases which would make this quite a bulky library.
Some extra features might be:
subtree-handling: not only handle terminal keys but forward certain subtrees to separate implementations. E.g.
tree.register("some.path.config", some_handler);
// calls some_handler.get<int>("network.hostname")
v = tree.get<int>("some.path.config.network.hostname");
search among values / keys
automatic type casting (like in boost::property_tree)
"path overloading", e.g. defaulting to a property_tree-implementation for paths without registered callback.
Is there a library that comes close to what I'm looking for? Has anyone made experiences with using boost::property_tree for this purpose? (E.g. by subclassing or putting special objects into the tree like described here)
After years of coding my own container classes I ended up just adopting QVariantMap. This way it pretty much behaves (and is as flexible as) python. Just one interface. Not for performance code though.
If you care to know, I really caved in for Qt as my de facto STL because:
Industry standard - used even in avionics and satellite software
It has been around for decades with little interface change (think about long term support)
It has excellent performance, awesome documentation and enormous user base.
Extensive feature set, way beyond the STL
Would an std::map do the job you are interested in?
Have you tried this approach?
I don't quite understand what you are trying to do. So please provide a domain example.
Cheers.
I have some home-cooked code that lets you register custom callbacks for each type in GitHub. It is quite basic and still missing most of the features you would like to have. I'm working on the second version, though. I'm finishing a helper structure that will do most of the job of making callbacks. Tell me if you're interested. Also, you could implement some of those features yourself, as the code to register callbacks is already done. It shouldn't be so difficult.
Using only provided data structures:
First, getters and setters are not native features to c++ you need to call the method one way or another. To make such behaviour occur you can overload assignment operator. I assume you also want to store POD data in your data structure as well.
So without knowing the type of the data you're "get"ting, the only option I can think of is to use boost::variant. But still, you have some overloading to do, and you need at least one assignment.
You can check out the documentation. It's pretty straight-forward and easy to understand.
http://www.boost.org/doc/libs/1_61_0/doc/html/variant/tutorial.html
Making your own data structures:
Alternatively, as Dani mentioned, you can come up with your own implementation and keep a register of overloaded methods and so on.
Best

Parsing different xml messages. Versions

Say we want to Parse a XML messages to Business Objects. We split the process in two parts, namely:
-Parsing the XML messages to XML Grammar Objects.
-Transform XML Objects to Business Objects.
The first part is done automatically, generation a grammar object for each node.
The second part is done following the XML architecture so far. Example:
If we have the XML Message(Simplified):
<Main>
<ChildA>XYZ</ChildA>
<ChildB att1="0">
<InnerChild>YUK</InnerChild>
</ChildB>
</Main>
We could find the following classes:
DecodeMain(Calls DecodeChildA and B)
DecodeChildA
DecodeChildB(Calls DecodeInnerChild)
DecodeInnerChild
The main problem arrives when we need to handle versions of the same messages. Say we have a new version where only DecodeInnerChild changes(e.g.: We need to add an "a" at the end of the value)
It is really important that the solutions agile for further versions and as clean as possible. I considered the following options:
1)Simple Inheritance:Create two classes of DecodeInnerChild. One for each version.
Shortcomming: I will need to create different classes for every parent class to call the right one.
2)Version Parameter: Add to each method an Object with the version as a parameter. This way we will know what to do within each method according to each version.
Shortcoming: Not clean at all. The code of different versions is mixed.
3)Inheritance + Version Parameter: Create 2 classes with a base class for the common code for the nodes that directly changes (Like InnerChild) and add the version as a parameter in each method. When a node call the another class to decode the child object, it will use one or another class depending on the Version parameter.
4)Some kind of executor pattern(I do not know how to do it): Define at the start some kind of specifications object, where all the methods that are going to be used are indicated and I pass this object to a class that is in charge of execute them.
How would you do it? Other ideas are welcomed.
Thanks in advance. :)
How would you do it? Other ideas are welcomed.
Rather than parse XML myself I would as first step let something like CodesynthesisXSD to generate all needed classes for me and work on those. Later when performance or something becomes issue I would possibly start to look aound for more efficient parsers and if that is not fruitful only then i would start to design and write my own parser for specific case.
Edit:
Sorry, I should have been more specific :P, the first part is done
automatically, the whole code is generated from the XML schema.
OK, lets discuss then how to handle the usual situation that with evolution of software you will eventually have evolved input too. I put all silver bullets and magic wands on table here. If and what you implement of them is totally up to you.
Version attribute I have anyway with most things that I create. It is sane to have before backward-compatibility issue that can not be solved elegantly. Most importantly it achieves that when old software fails to parse newer input then it will produce complaint that makes immediately sense to everybody.
I usually also add some interface for converter. So old software can be equipped with converter from newer version of input when it fails to parse that. Also new software can use same converter to parse older input. Plus it is place where to plug converter from totally "alien" input. Win-win-win situation. ;)
On special case of minor change I would consider if it is cheap to make new DecodeInnerChild to be internally more flexible so accepts the value with or without that "a" in end as valid. In converter I have still to get rid of that "a" when converting for older versions.
Often what actually happens is that InnerChild does split and both versions will be used side-by-side. If there is sufficient behavioral difference between two InnerChilds then there is no point to avoid polymorphic InnerChilds. When polymorphism is added then indeed like you say in your 1) all containing classes that now have such polymorphic members have to be altered. Converter should usually on such cases either produce crippled InnerChild or forward to older version that the input is outside of their capabilities.

Mix services and leaf objects in constructor for dependency injection?

I am attempting to make my code as testable as possible, which means using dependency injection correctly.
I have read that it's okay to use new() to instantiate an object, if that object meets certain criteria. Notably - it should not accept a "non newable" in its constructor.
For example, I should be able to go
new Form('signup');
because there is no way that my DI container would know how to create the "signup" form ahead of time.
I can make this work most of the time, but now I'd like the Form to be able to validate itself, using a third party validator, like:
$form->validate()->isValid();
...which means that I would have to pass in a validator service.
I'd really prefer to have the validator included already because most of the time the form will need to be validated, and I'd have to go through the extra work to set the validator on my own otherwise.
Is it okay, in this instance to do:
new Form(Validator $validator,$name);
I'd say that any value or object which an object requires in order to be in a valid state is one of that object's dependencies; in your example that would entirely validly include the form's name. I don't think the type of a dependency can be used to say whether it should be injected or not - Martin Fowler in this article for instance shows objects having strings injected into them, and DI containers can usually be configured to supply string values.
With this in mind, injecting the validator and the string is fine and entirely correct in my opinion.

Add constructor to deftype created class

For the purposes of interoperability with Java, I need a class that has a nullary constructor that performs initialization.
Objects of this class need to have something resembling mutable java fields (namely, the object represents the backend of a game, and needs to keep game state).
deftype does everything I want to do except provide a nullary constructor (since I'm creating a class with fields).
I don't need the fields to be publicly readable, so I can think of 4 solutions:
Use gen-class; I don't want to do this if I can avoid it.
Somehow encoding private member variables outside of the knowledge of deftype; I've been told this can't be done.
Writing a modified deftype that also creates a nullary constructor; frankly I don't know clojure well enough for this.
Taking the class created by deftype and somehow adding a new constructor to it.
At the end of this, I need to have a Java class, since I will be handing it off to Java code that will be making a new object from the class.
Are any of the solutions I suggested (or any that I haven't thought of) other than using gen-class viable?
There's absolutely no shame in, where appropriate, writing a dash of Java if your Java interop requirements are simultaneously specific and unshakable. You could write a Java class with a single static factory method that returns an instance of the deftype class and that does whatever initialization/setup you need.
Alternatively, you can write a nullary factory function in Clojure, and call that directly from Java all day long.
In any case, neither deftype nor defrecord are intended to be (or will they ever be) fully-featured interop facilities. gen-class certainly comes the closest, which is why it's been recommended.
I'd suggest just writing the object in Java - for Java-like objects with mutable fields it will probably be more elegant, understandable and practical.
I've generally had pretty good results mixing Java and Clojure code in projects. This seems like one of those cases where this might be appropriate. The interoperability is so good that you barely have any extra complexity.
BTW - I'm assuming that you need a nullary constructor to meet the requirements of some persistence library or something similar? It seems like an odd requirement otherwise. If this is the case then you may find it makes sense to rethink your persistence strategy..... arbitrary restrictions like this always seem like a bit of a code smell to me.

Consuming custom objects between webservices

I have a webservice that is designed to accept performance data via a custom object. The custom object contains a Collection (Generic List) of performance measures among other data. The performance measure consists of simple data types (strings, ints, and a datetime). The only method exposed by the webservice requires this custom object (performance data object) to be passed in.
The problem lies in using this custom object externally. I wish to use the Add() and Item() methods of the Generic List class along with various other features within this class within another webservice. If I request the object from the Performance Data Webservice it seralizes the inner collection to an arrayList. I would like it to remain a generic collection.
I have toyed with using the XmlInclude method but currently havent found a solution with it.
The next thing I tried to do was create an assembly of this specific object that both the Peformance Data web service can use and any satelite programs (i.e. another webservice). The issue here is when I try to pass in the custom object created by the seperate assembly the performance data webservice barks its a different type. (Also I am applying the XmlInclude(GetType( custom assembly)) attribute to the exposed method). However still thinks the types are not convertable.
Note: I would prefer to call the Performance Data WS to get the custom object instead of having to deal with adding assemblies to each project that needs access.
Anyone have an idea other than restructing the program to work with methods exposed by the ArrayList?
If you use WCF, you can configure what type of collection comes out, whether an ArrayList, a fixed array, or a generic List.
I have found a solution that will work with .Net 2.0. By using Web Services Contract First (WSCF http://www.thinktecture.com/resourcearchive/tools-and-software/wscf/wscf-walkthrough)
I was able to pass generic collections between two services. A down side to WSCF, as the name suggests, is the approach requires the use of contract-first instead of the more common code-first methodology. Lucky it is not terribly complicated to modify the class and proxy after they are created. Hope this helps any lost travelers...