How to use Rhino.Mocks to evaluate class Properties (getters and setters) - c#-4.0

I'm studying how Rhino.Mocks works and trying to understand how can I set manually a value in a class Property.
I have seen a sample in internet where you have only desired Property as argument of Expect.Call(), instead of using a method.
MockRepository mocks = new MockRepository();
Person p = mocks.StrictMock<Person>();
Expect.Call(p.FirstName).Return("John");
Person is a class such as:
public class Person
{
public string FirstName {get;set;}
}
I always receive the error:
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).
Am I missing something? Is it possible to set manually class Properties and evaluate them to see if getters and setters are working fine?

As with any mocking framework, Rhino Mocks can only mock interfaces or classes that defines virtual methods and properties.
That's because when implementing a class, Rhino creates a derived class from the one you specify, replacing every virtual (or Overridable in VB) method with a stub implementation that uses an interceptor to handle the call.
When you specify a non virtual method, Rhino can't create a wrapper.
That is also true tor sealed (NonInheritable in VB) classes.
So for your class to work, you should implement the property as such:
public class Person
{
public virtual string FirstName { get; set; }
}
This way Rhino can override the poperty accordingly.

Related

How to use the strategy pattern with managed objects

I process messages from a queue. I use data from the incoming message to determine which class to use to process the message; for example origin and type. I would use the combination of origin and type to look up a FQCN and use reflection to instantiate an object to process the message. At the moment these processing objects are all simple POJOs that implement a common interface. Hence I am using a strategy pattern.
The problem I am having is that all my external resources (mostly databases accessed via JPA) are injected (#Inject) and when I create the processing object as described above all these injected objects are null. The only way I know to populate these injected resources is to make each implementation of the interface a managed bean by adding #stateless. This alone does not solve the problem because the injected members are only populated if the class implementing the interface is itself injected (i.e. container managed) as opposed to being created by me.
Here is a made up example (sensitive details changed)
public interface MessageProcessor
{
public void processMessage(String xml);
}
#Stateless
public VisaCreateClient implements MessageProcessor
{
#Inject private DAL db;
…
}
public MasterCardCreateClient implements MessageProcessor…
In the database there is an entry "visa.createclient" = "fqcn.VisaCreateClient", so if the message origin is "Visa" and the type is "Create Client" I can look up the appropriate processing class. If I use reflection to create VisaCreateClient the db variable is always null. Even if I add the #Stateless and use reflection the db variable remains null. It's only when I inject VisaCreateClient will the db variable get populated. Like so:
#Stateless
public QueueReader
{
#Inject VisaCreateClient visaCreateClient;
#Inject MasterCardCreateClient masterCardCreateClient;
#Inject … many more times
private Map<String, MessageProcessor> processors...
private void init()
{
processors.put("visa.createclient", visaCreateClient);
processors.put("mastercard.createclient", masterCardCreateClient);
… many more times
}
}
Now I have dozens of message processors and if I have to inject each implementation then register it in the map I'll end up with dozens of injections. Also, should I add more processors I have to modify the QueueReader class to add the new injections and restart the server; with my old code I merely had to add an entry into the database and deploy the new processor on the class path - didn't even have to restart the server!
I have thought of two ways to resolve this:
Add an init(DAL db, OtherResource or, ...) method to the interface that gets called right after the message processor is created with reflection and pass the required resource. The resource itself was injected into the QueueReader.
Add an argument to the processMessage(String xml, Context context) where Context is just a map of resources that were injected into the QueueReader.
But does this approach mean that I will be using the same instance of the DAL object for every message processor? I believe it would and as long as there is no state involved I believe it is OK - any and all transactions will be started outside of the DAL class.
So my question is will my approach work? What are the risks of doing it that way? Is there a better way to use a strategy pattern to dynamically select an implementation where the implementation needs access to container managed resources?
Thanks for your time.
In a similar problem statement I used an extension to the processor interface to decide which type of data object it can handle. Then you can inject all variants of the handler via instance and simply use a loop:
public interface MessageProcessor
{
public boolean canHandle(String xml);
public void processMessage(String xml);
}
And in your queueReader:
#Inject
private Instance<MessageProcessor> allProcessors;
public void handleMessage(String xml) {
MessageProcessor processor = StreamSupport.stream(allProcessors.spliterator(), false)
.filter(proc -> proc.canHandle(xml))
.findFirst()
.orElseThrow(...);
processor.processMessage(xml);
}
This does not work on a running server, but to add a new processor simply implement and deploy.

How to access external class within a class in groovy

I'm new to groovy...
I've made a class. Within this class, I'd like to call an external method : LOG.error, but somehow, groovy is complaining about the method not being part of the class... how should I call that external method ?
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
LOG.error("test")
}
}
Groovy provides #Slf4j annotation that can add log field to your class, e.g.
#Slf4j
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
log.error("test")
}
}
Alternatively you can use #Log annotation that adds log field that uses java.util.logging.Logger instead of one provided with Slf4j. However in this case you have to be aware that java.util.logging.Logger uses different API, so there is no log.error() method.
In your example Groovy throws MissingPropertyException, because LOG is not defined in your class. If there is a class LOG with static method error you will have to import this class. But most probably you should just create LOG field (with annotation or manually) and call it to be most explicit (otherwise your code gets unreadable).

How to override protected methods of a class of MVCResourceCommand in liferay?

I want to override a protected method in the class ExportArticleMVCResourceCommand which extends theBaseMVCResourceCommand class.
I want to convert journal article's to pdf in liferay 7 . I have written this functionality in its own method and wish to call that method in the doServeResource(...) method. But as doServeResource() is protected, I am not able to call it on a button submit. Therefore, I want to ask how to override this doServeResource() method in liferay 7.
Dissecting the problem
Liferay 7 is an open source Java platform an as such the best way to troubleshoot (absent any documentation) is to first at the code. You will notice that theExportArticleMVCResourceCommand class extends BaseMVCResourceCommand. In the ExportArticleMVCResourceCommand class you can see that the doServeResource method overrides it's parent's doServeResource method. In BaseMVCResourceCommand there are several things to note.
It is an abstract class
There is protected abstract void doServeResource method with no implementation.
The serveResource method simply calls the doServeResource
Piecing it together
So you want to override the doServeResource method in the ExportArticleMVCResourceCommandclass because that method does not work when the "targeted extension" is of type PDF (purportedly). You cannot override the doServeResource by extending or implementing any *MVCResourceCommand class or interface because it's either protected (and your OSGi component override is bundled separately) or in the case of MVCResourceCommand interface it doesn't exist.
Solution
Remember the doServeResource method is simply called by the serveResource method in ExportArticleMVCResourceCommand, and the serveResource method is public in both the MVCResourceCommand interface and BaseMVCResourceCommand class. Therefore to override the doServeResource method you simply need to create your own OSGi component with that appropriate annotations, have it override the serveResource method, and do not the referened serveResource method at the end of your own.
#Component(
property = {
"javax.portlet.name=" + JournalPortletKeys.JOURNAL,
"mvc.command.name=exportArticle"
},
service = MVCResourceCommand.class
public class CustomExportArticleMVCResourceCommand implements MVCResourceCommand {
#Override
public boolean serveResource
(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
// Call your custom method here
// ExportArticleUtil.sendFile("pdf", resourceRequest, resourceResponse);
}
#Reference(target = "(component.name=com.liferay.journal.web.internal.portlet.action.ExportArticleMVCResourceCommand)")
protected MVCResourceCommand mvcResourceCommand;
}

Adding attributes to parent class fields and properties

In my example to illustrate my use case I have a parent class that is purposely database agnostic (let's say I can't change the code of it for some reasons, because the class come from a commercial assembly or the .net framework or are auto generated by entity framework):
public class Father
{
public string Field1;
public string Field2;
}
Now I'd like to store an object derived from it into MongoDB (again, it's only for the example, there a lot of other use cases and my question has nothing to do with MongoDB):
public class Child:Father
{
public ObjectId Id;
public DateTime DateCreation;
}
But I'd like to add attributes to some elements of the father, like [BsonIgnoreIfNull], without overriding (they are not marked as virtual) or having to fully reimplement the Father in my Child class.
What would be the cleanest way to do this?
Thanks!

How do I make a public view model base with WinRT classes?

I wanted to create an abstract base class for all of my view models, but I'm running into accessibility issues and can't seem to navigate through the errors. Here's an example of my code:
public ref class ViewModelBase {
...
}
public ref class OtherViewModel : ViewModelBase {
...
}
When I define my code as state above, I get the following error:
error C4585: 'MyNamespace::ViewModelBase' : A WinRT 'public ref class' must either be sealed or derive from an existing unsealed class
If, instead, I make ViewModelBase private, I get this error:
error C3213: base class 'MyNamespace::ViewModelBase' is less accessible than 'OtherViewModel'
This seems like it should be incredibly simple. What am I doing wrong?
What you are attempting is not strictly possible in C++/CX, as in VS 2012 C++/CX does not support public class inheritance for general-purpose scenarios. It is only supported enough to have the XAML scenarios work; the only possible public unsealed types are those found under the Windows::UI::Xaml namespace, and users are not able to author their own public unsealed types.
If you want to have a base class for all your view models, your only options to make all your classes private or to inherit from a base class from Windows::UI::Xaml (such as DependencyObject).
Each of these approaches has drawbacks:
using DependencyObject as your base makes all your viewmodels STA objects (so they can only be manipulated from the UI thread) in addition to having a lot of overhead that isn't really necessary.
Making your classes private means you cannot use the [Bindable] attribute to do databinding, so you would need to have a private databinding implementation. (Your private class would need to implement ICustomPropertyProvider and related interfaces.)
The "sealed" keyword means that the class cannot be inherited from. Your implementation should look something like this:
ref class ViewModelBase sealed
If you want to inherit from ViewModelBase then you need to have only the subclasses be ref classes like this:
class ViewModelBase
...
public ref class OtherViewModel sealed : ViewModelBase

Resources