Complex (deeply nested) request validation in ServiceStack, using Fluent Validation - servicestack

I'm coming up short, trying to use Fluent Validation in the ServiceStack DTOs, when the model have properties nested several levels.
Ex.: The model is structured like this
A => B => C => D
=> E
To validate B without risking a nullref. exception, I need to (successfully) validate A.
To Validate C, A and B must be not null.
D and E have cross dependencies so to validate E then A, B, C AND D must not be null.
The only way that is seemingly available for this scenario, is wrapping the entire thing in when/dependent blocks, but that quickly becomes unmanageable.
Any ideas would be appreciated!
Thanks,

Alternatives of using multiple validators constrained by When() blocks is to either use a "Must" predicate validator, create a Custom Validator or avoid using Fluent Validation for these complex validations and validate them in your Service where you can use full C# to validate them as normal.
Throwing a ArgumentException(message,paramName) in your Service using the name of the Request DTO property will populate the Error in the structured ResponseStatus Errors collection.

Related

Asp.net core 2.0 Conditional DI

I have an interface that has 2 implementation
IMYService
MyServiceA
MYServiceB
Here the Implementation is dependent on some data in the request header used by the construtor of the Services like
If Header has value of internalId then use MyServiceA and pass that Id to the services in constructor
while if the value is missing use MyServiceB where as this service construct does not expect id.
My Controller is defined with DI for IMyservice
In general, you need a factory. That's generally a separate class that is responsible to managing instances of a particular similar type of thing and returns the appropriate instance based on some sort of convention or condition. For example, if you've used IHttpClientFactory, you've see one in action.
Since the implementation depends on the request, you can cheat a little by using the "factory" overload of AddScoped:
services.AddScoped<IMyService>(p =>
{
// return either MyServiceA or MyServiceB
});
The p param of the lambda is actually a scoped instance of IServiceProvider, so you can do stuff like pull out IHttpContextAccessor to look at the request details.

Use NSExpression CAST with NSPredicate in Core Data

My problem is exactly the same as you can read in this thread:
stackoverflow thread
But there is a small difference. I try to explain it using the above thread's image.
The CS relationship contains C type objects as it is described, but also contains E type objects too, because the E type objects are derived from the C type object.
On thread's image the E type object is not present and this is the difference. The E type property also has a CS relationship.
The problem comes when I try to reach the E type object's CS property using the following query: SUBQUERY(bs, $x, ANY $x.cs.cs ....
The query is not finished, but the important code is there. As I observed, the predicate creation fails, because it tries to use the CS relationship on the C type object. I've tried to use the CAST operator on the $x.cs variable without success.
Do anybody has a clue for this?
Edit: Added image
The values of the MKMultiAttribute entity can contain MKAttribute and MKMultiAttribute types. And this is the problem, because the values is set to be a relationship to MKAttribute, but, because MKMultiAttribute is derived from MKAttribute the values can contain MKMultiAttribute entities and currently I can't call the values again.

Partial objects with JAXB?

I'm working to create some services with JAX-RS, and am relatively new to JAXB (actually XML in general) so please don't assume I know the pre-requisites that I probably should know! Here's the questions: I want to send and receive "partial" objects in XML. That is, imagine one has an object (Java form, obviously) with:
class Thing { int x, String y, Customer z }
I want to be able to send an XML output that contains (dynamically chosen, so I can't use XmlTransient) just x, or just z, or x and y, but not z, or any other combination that suits my client. The point, obviously, is that sometimes the client doesn't need everything, so I can save some bandwidth (particularly with lists of deep, complex objects, which this example clearly doesn't illustrate!).
Also, for input, the same bandwidth argument applies; I would like to be able to have the client send just the particular fields that should be updated in, say, a PUT operation, and ignore the rest, then have the server "merge" those new values onto existing objects and leave the un-mentioned fields unchanged.
This seems to be supported in the Jackson JSON libraries (though I'm still working on it), but I'm having trouble finding it in JAXB. Any ideas?
One thought that I was pondering is whether one can do this in some way via Maps. If I created a Map (potentially nested Maps, for nested coplex objects) of what I want to send, could JAXB send that with a plausible structure? And if it could create such a map on input, I guess I could work through it to make the updates. Not perfect, but maybe?
And yes, I know that the "documents" that will be flying around will probably fail to comply with schemas, having missing fields and all that, but I'm ok with that, provided the infrastructure can be made to work.
Oh, and I know I could do this "manually" with SAX, StAX, or DOM parsing, but I'm hoping there's a rather more automatic way, particularly since JAXB handles the whole objects so effortlessly.
Cheers,
Toby
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
EclipseLink JAXB (MOXy) offerst this support through its object graph extension. Object graphs allow you to specify a subset of properties for the purposes of marshalling an unmarshalling. They may be created at runtime programatically:
// Create the Object Graph
ObjectGraph contactInfo = JAXBHelper.getJAXBContext(jc).createObjectGraph(Customer.class);
contactInfo.addAttributeNodes("name");
Subgraph location = contactInfo.addSubgraph("billingAddress");
location.addAttributeNodes("city", "province");
Subgraph simple = contactInfo.addSubgraph("phoneNumbers");
simple.addAttributeNodes("value");
// Output XML - Based on Object Graph
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, contactInfo);
marshaller.marshal(customer, System.out);
or statically on the class through annotations:
#XmlNamedObjectGraph(
name="contact info",
attributeNodes={
#XmlNamedAttributeNode("name"),
#XmlNamedAttributeNode(value="billingAddress", subgraph="location"),
#XmlNamedAttributeNode(value="phoneNumbers", subgraph="simple")
},
subgraphs={
#XmlNamedSubgraph(
name="location",
attributeNodes = {
#XmlNamedAttributeNode("city"),
#XmlNamedAttributeNode("province")
}
)
}
)
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
For More Information
http://blog.bdoughan.com/2013/03/moxys-object-graphs-partial-models-on.html
http://blog.bdoughan.com/2013/03/moxys-object-graphs-inputoutput-partial.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

How to serialize class that derives from class decorated with DataContract(IsReference=true)?

I have class A that derives from System.Data.Objects.DataClasses.EntityObject.
When I try to serialize using
var a = new A();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(a.GetType());
serializer.WriteObject(Response.OutputStream, a);
I get error
TestController+A._Id' is not marked with OptionalFieldAttribute, thus indicating that it must be serialized. However, 'TestController+A' derives from a class marked with DataContractAttribute and an IsReference setting of 'True'. It is not possible to have required data members on IsReference classes. Either decorate 'TestController+A._Id' with OptionalFieldAttribute, or disable the IsReference setting on the appropriate parent class.
Even if I decorate the field with OptionalFieldAttribute I get
The type 'TestController+A' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.
I cannot modify EntityObject class. I thought to create A_Bag class exactly as A class and fill it and serialize it instead of A, but I think there's more elegant way to do it.
Can you suggest how I can do it?
I think you can use a "data contract surrogate" here (used via the IDataContractSurrogate interface.)
The data contract surrogate is an advanced feature built upon the Data Contract model you're already using. It lets you do type customization and substitution in situations where you want to change how a type is serialized, deserialized, or (if you're dealing with XML) projected into schema.
In your case, the use of IDataContractSurrogate lets you do custom JSON serialization and deserialization on a per-type or per-object basis. An IDataContractSurrogate would provide the methods needed to substitute one type for another by the DataContractSJsonerializer during serialization and deserialization, and you may want to provide a different "special" intermediary type for your scenario.
Hope this helps!
JSON.Net supports serialization of objects marked with IsReference=true.
There is a detailed walkthrough here:
http://dotnet.learningtree.com/2012/04/03/working-with-the-entity-framework-and-the-web-api/

Subsonic 3.0 and SqlHierachyID

I am having trouble with Subsonic 3.0 generating an object for a table which contains the new HeirachyID datatype. From what I have found, there is no corrosponding .Net type, and subsonic doesn't seem to know how to handle the hierachyid data.
Error that is thrown:
Object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' cannot be converted to type 'System.String'.
Code:
foreach (MyDB.DataAccess.ThingCategory tc in DataAccess.ThingCategory.Find(x => x.fk_Thing.Equals(thingId)))
{
sb.AppendFormat("<{0}>{1}</{0}>", wrapTag, tc.Categories.ToList<DataAccess.Category>()[0].Name);
}
tc.Categories.ToList() generates the error
Alternatively, I tried to get around this by writing a sproc to return the hierachyid column as a string, and noticed SubSonic 3.0 sprocs are not strongly-typed. or am I doing something wrong?
Sprocs can be strongly-typed by calling ExecuteTypedList()
I would create an issue on the Github tracker to either add support for the type (someone will have to contribute this since I don't think it's a high priority) or to gracefully handle it when they exist.

Resources