fluent nhibernate polymorphism. how to check for type of class - nhibernate

I have an Icon which has a Content (one to one) relationship.
public class Icon
{
public virtual Content Content {get; set;}
}
By default, it is lazy loaded which is what I want.
However, at some point in the code, I need to check what kind of Content is, Content being polymorphic, something like
if(icon.Content is TextContent)
{
...
}
Icon is part of another association and it is automatically obtained by the NHibernate, I do not get it manually.
What is the recommended way of checking for the actual type in this situation?
I can have a specific property like ContentType which will be an enum in order to identify the actual content type, but I am looking to know if there's a different way.

If you want to do that kind of check, you have to remove the proxy from the property.
There is a few ways to do it:
If you have access to the session call:
session.PersistenceContext.Unproxy(icon.Content);
Implement a virtual method (in a base class if possible) that forces the removal of the proxy by returning the instance with the proper type.
public virtual U As<U>() where U : YourType {
return this as U;
}
Disable the lazy initialization of the property.

This is very similar to another recent question.
To add to csanchez's list, a fourth method is to add a Self property to the Content base class that returns the un-proxied type:
public virtual void Self
{
get { return this; }
}
And a fifth method is to use 'lazy="no-proxy"` in the mapping as described on Ayende's blog.

Thanks for the suggestions but meanwhile I found an interesting solution, better I think.
Using the Visitor pattern, I can define an IconContent visitor and pass an Action to be executed to it.
For example, suppose there is a TextContent and an ImageContent, it will be something like this:
IconContentVisitor.Func(()=> { Console.WriteLine("this is TextContent"; }, ()=> { Console.WriteLine("this is ImageContent"));
Idea came from here: http://mookid.dk/oncode/archives/991

Related

Deserializing IEnumerable with private backing field in RavenDb

I've been modeling a domain for a couple of days now and not been thinking at all at persistance but instead focusing on domain logic. Now I'm ready to persist my domain objects, some of which contains IEnumerable of child entities. Using RavenDb, the persistance is 'easy', but when loading my objects back again, all of the IEnumerables are empty.
I've realized this is because they don't have any property setters at all, but instead uses a list as a backing field. The user of the domain aggregate root can add child entities through a public method and not directly on the collection.
private readonly List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts { get { return _veryImportantParts; } }
And the method for adding, nothing fancy...
public void AddVeryImportantPart(VeryImportantPart part)
{
// some logic...
_veryImportantParts.Add(part);
}
I can fix this by adding a private/protected setter on all my IEnumerables with backing fields but it looks... well... not super sexy.
private List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts
{
get { return _veryImportantParts; }
protected set { _veryImportantParts = value.ToList(); }
}
Now the RavenDb json serializer will populate my objects on load again, but I'm curious if there isn't a cleaner way of doing this?
I've been fiddeling with the JsonContractResolver but haven't found a solution yet...
I think I've found the root cause of this issue and it's probably due to the fact that many of my entities were created using:
protected MyClass(Guid id, string name, string description) : this()
{ .... }
public static MyClass Create(string name, string description)
{
return new MyClass(Guid.NewGuid(), name, description);
}
When deserializing, RavenDb/Json.net couldn't rebuild my entities in a proper way...
Changing to using a public constructor made all the difference.
Do you need to keep a private backing field? Often an automatic property will do.
public IList<VeryImportantPart> VeryImportantParts { get; protected set; }
When doing so, you may want to initialize your list in the constructor:
VeryImportantParts = new List<VeryImportantPart>();
This is optional, of course, but it allows you to create a new class and start adding to the list right away, before it is persisted. When Raven deserializes a class, it will use the setter to overwrite the default blank list, so this just helps with the first store.
You certainly won't be able to use a readonly field, as it couldn't be replaced during deserialization. It might be possible to write a contract resolver or converter that fills an existing list rather than creating a new one, but that seems like a rather complex solution.
Using an automatic property can add clarity to your code anyway - as it is less confusing whether to use the field or the property.

Building one object given another

Say I am calling a third-party API which returns a Post, and I want to take that and transfer properties from it into my own Post class. I have in the past had a method like public static my.Post build(their.Post post) which maps the properties how I want.
However, is it better/valid to have a constructor that accepts their.Post and does the property mapping in there? Or should there always be a separate class that does the converting, and leaves my.Post in a more POJO state?
Thanks for your thoughts!
These answers always starts with "it depends."
People generally argue against using public static methods, based on the fact that it is hard to mock them (I don't buy into that bandwagon).
This comes down to design, do you want their post to be part of your class? If you add it as a "copy" constructor then it will now be part of your class and you are dependent on changes to post. If they change their post, your code has to adapt.
The better solution is to decouple it. You would need to find some extenal method to map the two. One way is to use a static builder method (like you mentioned) or if you want to take it a step further, a more complicated solution would be to extract the information you want from their post into some type of generic collection class. Then create a constructor that will accept that constructor class. This way if they change their design your class stays in tact and all you have to do is update the mappings from their post to your generic representation of it.
public class MyPost{
public MyPost(ICollectionOfProperties props){
//copy all properties.
}
}
public static class TheirPostExtensions{
public static ICollectionOfProperties ExtractProperties(this TheirPost thePost){
return new CollectionOfProperties(){
A = thePost.PropA,
B = thePost.PropB
};
}
}
public class Example{
public Example(){
TheirPost tp = new TheirPost();
ICollectionOfProperties props = tp.ExtractProperties();
MyPost mp = new MyPost(props);
}
}

Do write-only properties have practical applications?

I don't know why I started thinking about this, but now I can't seem to stop.
In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:
class WeirdClass
{
private void Hello(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
public string Name
{
set { Hello(name); }
}
}
In other words, the property has a setter but no getter, it's write-only.
I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:
CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.
But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.
Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?
My first reaction to this question was: "What about the java.util.Random#setSeed method?"
I think that write-only properties are useful in several scenarios. For example, when you don't want to expose the internal representation (encapsulation), while allowing to change the state of the object. java.util.Random is a very good example of such design.
Code Analysis (aka FxCop) does give you a diagnostic:
CA1044 : Microsoft.Design : Because
property 'WeirdClass.Name' is write-only,
either add a property getter with an
accessibility that is greater than or
equal to its setter or convert this
property into a method.
Write-only properties are actually quite useful, and I use them frequently. It's all about encapsulation -- restricting access to an object's components. You often need to provide one or more components to a class that it needs to use internally, but there's no reason to make them accessible to other classes. Doing so just makes your class more confusing ("do I use this getter or this method?"), and more likely that your class can be tampered with or have its real purpose bypassed.
See "Why getter and setter methods are evil" for an interesting discussion of this. I'm not quite as hardcore about it as the writer of the article, but I think it's a good thing to think about. I typically do use setters but rarely use getters.
I have code similar to the following in an XNA project. As you can see, Scale is write-only, it is useful and (reasonably) intuitive and a read property (get) would not make sense for it. Sure it could be replaced with a method, but I like the syntax.
public class MyGraphicalObject
{
public double ScaleX { get; set; }
public double ScaleY { get; set; }
public double ScaleZ { get; set; }
public double Scale { set { ScaleX = ScaleY = ScaleZ = value; } }
// more...
}
One use for a write-only property is to support setter dependency injection, which is typically used for optional parameters.
Let's say I had a class:
public class WhizbangService {
public WhizbangProvider Provider { set; private get; }
}
The WhizbangProvider is not intended to be accessed by the outside world. I'd never want to interact with service.Provider, it's too complex. I need a class like WhizbangService to act as a facade. Yet with the setter, I can do something like this:
service.Provider = new FireworksShow();
service.Start();
And the service starts a fireworks display. Or maybe you'd rather see a water and light show:
service.Stop();
service.Provider = new FountainDisplay(new StringOfLights(), 20, UnitOfTime.Seconds);
service.Start();
And so on....
This becomes especially useful if the property is defined in a base class. If you chose construction injection for this property, you'd need to write a constructor overload in any derived class.
public abstract class DisplayService {
public WhizbangProvider Provider { set; private get; }
}
public class WhizbangService : DisplayService { }
Here, the alternative with constructor injection is:
public abstract class DisplayService {
public WhizbangProvider Provider;
protected DisplayService(WhizbangProvider provider) {
Provider = provider ?? new DefaultProvider();
}
}
public class WhizbangService : DisplayService {
public WhizbangService(WhizbangProvider provider)
: base(provider)
{ }
}
This approach is messier in my opinion, because you need to some of the internal workings of the class, specifically, that if you pass null to the constructor, you'll get a reasonable default.
In MVP pattern it is common to write a property with a setter on the view (no need for a getter) - whenever the presenter sets it content the property will use that value to update some UI element.
See here for a small demonstration:
public partial class ShowMeTheTime : Page, ICurrentTimeView
{
protected void Page_Load(object sender, EventArgs e)
{
CurrentTimePresenter presenter = new CurrentTimePresenter(this);
presenter.InitView();
}
public DateTime CurrentTime
{
set { lblCurrentTime.Text = value.ToString(); }
}
}
The presenter InitView method simply sets the property's value:
public void InitView()
{
view.CurrentTime = DateTime.Now;
}
Making something write-only is usefulwhenever you're not supposed to read what you write.
For example, when drawing things onto the screen (this is precisely what the Desktop Window Manager does in Windows):
You can certainly draw to a screen, but you should never need to read back the data (let alone expect to get the same design as before).
Now, whether write-only properties are useful (as opposed to methods), I'm not sure how often they're used. I suppose you could imagine a situation with a "BackgroundColor" property, where writing to it sets the background color of the screen, but reading makes no sense (necessarily).
So I'm not sure about that part, but in general I just wanted to point out that there are use cases for situations in which you only write data, and never read it.
Although the .NET design guidelines recommend using a method ("SetMyWriteOnlyParameter") instead of a write-only property, I find write-only properties useful when creating linked objects from a serialised representation (from a database).
Our application represents oil-field production systems. We have the system as a whole (the "Model" object) and various Reservoir, Well, Node, Group etc objects.
The Model is created and read from database first - the other objects need to know which Model they belong to. However, the Model needs to know which lower object represents the Sales total. It makes sense for this information to be stored a Model property. If we do not want to have to do two reads of Model information, we need to be able to read the name of Sales object before its creation. Then, subsequently, we set the "SalesObject" variable to point to the actual object (so that, e.g., any change by the user of the name of this object does not cause problems)
We prefer to use a write-only property - 'SalesObjectName = "TopNode"' - rather than a method - 'SetSalesObjectName("TopNode") - because it seems to us that the latter suggests that the SalesObject exists.
This is a minor point, but enough to make us want to use a Write-Only property.
As far as I'm concerned, they don't. Every time I've used a write-only property as a quick hack I have later come to regret it. Usually I end up with a constructor or a full property.
Of course I'm trying to prove a negative, so maybe there is something I'm missing.
I can't stop thinking about this, either. I have a use case for a "write-only" property. I can't see good way out of it.
I want to construct a C# attribute that derives from AuthorizeAttribute for an ASP.NET MVC app. I have a service (say, IStore) that returns information that helps decide if the current user should be authorized. Constructor Injection won't work, becuase
public AllowedAttribute: AuthorizeAttribute
{
public AllowedAttribute(IStore store) {...}
private IStore Store { get; set; }
...
}
makes store a positional attribute parameter, but IStore is not a valid attribute parameter type, and the compiler won't build code that is annotated with it. I am forced to fall back on Property Setter Injection.
public AllowedAttribute: AuthorizeAttribute
{
[Inject] public IStore Store { private get; set; }
...
}
Along with all the other bad things about Property Setter instead of Constructor Injection, the service is a write-only property. Bad enough that I have to expose the setter to clients that shouldn't need to know about the implementation detail. It wouldn't do anybody any favors to let clients see the getter, too.
I think that the benefit of Dependency Injection trumps the guidelines against write-only properties for this scenario, unless I am missing something.
I just came across that situation when writing a program that reads data from a JSON database (Firebase). It uses Newtonsoft's Json.NET to populate the objects. The data are read-only, i.e., once loaded they won't change. Also, the objects are only deserialized and won't be serialized again. There may be better ways, but this solution just looks reasonable for me.
using Newtonsoft.Json;
// ...
public class SomeDatabaseClass
{
// JSON object contains a date-time field as string
[JsonProperty("expiration")]
public string ExpirationString
{
set
{
// Needs a custom parser to handle special date-time formats
Expiration = Resources.CustomParseDateTime(value);
}
}
// But this is what the program will effectively use.
// DateTime.MaxValue is just a default value
[JsonIgnore]
public DateTime Expiration { get; private set; } = DateTime.MaxValue;
// ...
}
No, I can' imagine any case where they can't be replaced, though there might people who consider them to be more readable.
Hypothetical case:
CommunicationDevice.Response = "Hello, World"
instead of
CommunicationDevice.SendResponse("Hello, World")
The major job would be to perform IO side-effects or validation.
Interestingly, VB .NET even got it's own keyword for this weird kind of property ;)
Public WriteOnly Property Foo() As Integer
Set(value As Integer)
' ... '
End Set
End Property
even though many "write-only" properties from outside actually have a private getter.
I recently worked on an application that handled passwords. (Note that I'm not claiming that the following is a good idea; I'm just describing what I did.)
I had a class, HashingPassword, which contained a password. The constructor took a password as an argument and stored it in a private attribute. Given one of these objects, you could either acquire a salted hash for the password, or check the password against a given salted hash. There was, of course, no way to retrieve the password from a HashingPassword object.
So then I had some other object, I don't remember what it was; let's pretend it was a password-protected banana. The Banana class had a set-only property called Password, which created a HashingPassword from the given value and stored it in a private attribute of Banana. Since the password attribute of HashingPassword was private, there was no way to write a getter for this property.
So why did I have a set-only property called Password instead of a method called SetPassword? Because it made sense. The effect was, in fact, to set the password of the Banana, and if I wanted to set the password of a Banana object, I would expect to do that by setting a property, not by calling a method.
Using a method called SetPassword wouldn't have had any major disadvantages. But I don't see any significant advantages, either.
I know this has been here for a long time, but I came across it and have a valid (imho) use-case:
When you post parameters to a webapi call from ajax, you can simply try to fill out the parameters class' properties and include validation or whatsoever.
public int MyFancyWepapiMethod([FromBody]CallParams p) {
return p.MyIntPropertyForAjax.HasValue ? p.MyIntPropertyForAjax.Value : 42;
}
public class CallParams
{
public int? MyIntPropertyForAjax;
public object TryMyIntPropertyForAjax
{
set
{
try { MyIntPropertyForAjax = Convert.ToInt32(value); }
catch { MyIntPropertyForAjax = null; }
}
}
}
On JavaScript side you can simply fill out the parameters including validation:
var callparameter = {
TryMyIntPropertyForAjax = 23
}
which is safe in this example, but if you handle userinput it might be not sure that you have a valid intvalue or something similar.

Property chaining in RhinoMocks

I have a class TxRx with a property called Common. Common then has a property called LastMod. I want to write a RhinoMock expectation to show that LastMod has been set with something. So I tried:
var txRx = MockRepository.GenerateMock<TxRx>();
var common = MockRepository.GenerateMock<Common>();
txRx.Expect(t => t.Common).Return(common);
txRx.Expect(t => t.Common.LastMod).SetPropertyAndIgnoreArgument();
But I get the following exception:
System.InvalidOperationException: Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.RhinoMocksExtensions.Expect[T,R](T mock, Function`2 action)
at ...
I presume this means Common needs to be virtual, but as it is a property on a LinqToSql generated class I can't make it virtual (other than hacking the autogen code which is not really an option).
Is there any way around this?
One possibility is to wrap TxRx in a mockable class (i.e. one that has overridable methods and properties which you wish to mock out or implements an interface which defines the properties or methods that you're interested in) and then pass around the wrapper rather than the LinqToSQL class itself.
Perhaps something like the following:
public class TxRxWrapper : ITxRxWrapper
{
private TxRx m_txrx;
public object LastMod
{
get { return m_txrx.Common.LastMod; }
}
...
}
public interface ITxRxWrapper
{
public object LastMod { get; }
...
}
Not ideal (i.e. it can get somewhat cumbersome to pass wrappers around just for mockability!) but that's the only way you can get RhinoMocks to mock properties/methods for you.
The other option is to use TypeMock instead which I believe uses a different mechanism to mock stuff out. I don't think it's free, though.
You would need to replace your second expectation with
txRx.Expect(() => common.LastMod).SetPropertyAndIgnoreArgument();
But the Common property itself needs to be virtual for this to work.

hibernate - pattern for mapping a default entity?

Is there a sleek way to map a default database object in Hibernate?
For example, in this class, a Foo should always be able to return a Bar, whether it's custom defined for the Foo, or it comes from a default value that's stored in the database somewhere. Users of Foo should be able to set a custom Bar object in it, but they don't need write access to Bar - hence the reduced visibility. :
public Class Foo {
public Bar Bar {
get {
return CustomBar ?? DefaultBar;
}
}
public Bar CustomBar { get; set; }
protected Bar DefaultBar { get; private set; }
}
The thing I'm wondering about is how to hibernate map that DefaultFoo property. All the Bar classes should be able to get to that single DefaultFoo object. The only way I know how to do this in Hibernate is with a one-to-many mapping in Foo. (Foo containing one to many Bars)...this seems a little kludgy, since there's always at most one Bar. Is there a better pattern for this type of behavior? TIA.
This is also called the NullObject or DefaultObject pattern. There has been some discussion on the Hibernate mailing lists about this. But I haven't seen anything about how you would actually store it in the database. If you want a real NullObject, external of the Database, then you can implement a Singleton default object and implement the ILifecycle interface (I think) and veto the OnSave event to prevent it from being persisted.