Nancy and abstract base module class / creating phantom class instance - reflection

I'm building a small application with Nancy
I want to have a kind of base class, that other modules can inherit from.
See below (there is a reason this isn't an abstract class, which I'll explain below)
public class ImportModule<T> : NancyModule
{
protected ImportModule()
: this(typeof(T).Name.ToLower())
{
Get["/"] = _ => "need to select an action - xxx";
Get["/importnew"] = _ => ImportNew(); //note - method omitted for brevity
}
}
When I run my app, I get
Unable to resolve type: My.NameSpace.TypedImporter`1
As a sidenote, if the ImportModule class is abstract, this doesn't happen
Ok-
Now, I could have a class like this:
public class MyCustomImporter : ImportModule<MyCustomType>
{
//overrides....
}
But, elsewhere, in a "DefaultImportModule" I have the following:
var importerModule = Activator.CreateInstance(typeof(ImportModule<>).MakeGenericType(type));
So I need to be able to create a type of importer, based on a type that's passed in
(Basically, if a user hits the url /customer, it's doing the same as a class like this would)
public class CustomerImporter : ImporterModule<Customer>
{
}
So, as I see it, I have two choices:
1) Stop nancy trying to map my ImportModule
2) Instantiate a "phantom class" that inherits from ImportModule and make ImportModule abstract again

There is a discussion in the Nancy group that may be related to your problem, it is certainly related to the non-abstract base modules not being recognised by Nancy. Here is what Andreas HÃ¥kansson had to say:
Nancy locates everything that's inheriting NancyModule and assumes
it's something it can instantiate. Nancy is aware that it cannot
create an instance of an abstract module. So if you have a base-module
that's not abstract then Nancy will attempt to new it up. I'd like to
think that for 99% of the time, having a non-abstract base class is a
broken design.
And here is the link to the discussion:Unable to resolve type: Nancy.Routing.DefaultRouteResolver

Related

Jackson custom deserializer module to abstract class

I have a big set of classes (like more that 100) and they are all extend from some abstract class, let's call it ParentClass. Let's call child classes ChildA,ChildB, etc. How can I register custom deserializer for all children and get class type inside my Deserializer?
I tried:
module.addDeserializer(ParentClass.class, new MyObjectDeserializer());
but it does not work.
I want to skip doing (what is working):
module.addDeserializer(ChildA.class, new MyObjectDeserializer(ChildA.class));
module.addDeserializer(ChildB.class, new MyObjectDeserializer(ChildB.class));
module.addDeserializer(ChildC.class, new MyObjectDeserializer(ChildC.class));
//etc......
Class type should be known, as I am use Jackson for spring #RequestBody method, what have defined class name there.
Any ideas how this can be done?
As far as I know, I don't think there is a mechanism in jackson that will address your exact needs.
However, there are a couple alternatives you can try.
Deserializing polymorphic types with Jackson describes one such alternative, however, you would still need to explicitly define all of the supported subtypes.
Another alternative that would not require you to explicitly define deserialization relationships would be to change your class hierarchy from one of inheritance to that of a container.
For example, converting your abstract parent class to a container like so:
public class DataContainer<T> {
String commonString;
Integer commonInteger;
T subData;
}
Would allow you to simply define in your controller input function as
public String controllerFunction(DataContainer<ClassA> classA);
without a need to define all these subclass deserializations.
Late to the party but I had a similar problem which I solved by registering a custom Deserializers to my SimpleModule. The code is in Kotlin but it should be easy to port it to Java.
The class itself:
class UseBaseClassSimpleDeserializers(
private val baseClass: Class<*>,
private val baseClassDeserializer: JsonDeserializer<*>
) : SimpleDeserializers() {
#Throws(JsonMappingException::class)
override fun findBeanDeserializer(
type: JavaType?,
config: DeserializationConfig?,
beanDesc: BeanDescription?
): JsonDeserializer<*>? {
val beanDeserializer = super.findBeanDeserializer(type, config, beanDesc)
return if (beanDeserializer == null && baseClass.isAssignableFrom(type!!.rawClass)) {
baseClassDeserializer
} else {
beanDeserializer
}
}
}
How to register the custom Deserializers class to a SimpleModule:
val simpleModule = SimpleModule()
simpleModule.setDeserializers(UseBaseClassSimpleDeserializers(ParentClass::class.java, ParentClassDeserializer()))

EF5 code first - You cannot use Ignore method on the property

This question has been asked all over the place, but the SUPPOSED workaround on CodePlex does not work.
I'm hoping someone has some updated information.
I have an EF5 Code First project where I have dozens of entities directly derived from an abstract base class. After creating some new entities that are derived from a class derived from that base class, when my database is initially created I get the following error:
You cannot use Ignore method on the property 'DisplayString' on type
'Doctor' because this type inherits from the type
'Contact' where this property is mapped. To exclude
this property from your model, use NotMappedAttribute or Ignore
method on the base type.
Here's my classes:
public abstract class AbsoluteBaseClass
{
[NotMapped]
public abstract string DisplayString { get; set; }
...
}
public class Contact : AbsoluteBaseClass
{
[NotMapped]
public override string DisplayString
{
get { return string.Format("{0} {1}", FirstName, LastName); }
set { throw new System.NotImplementedException(); }
}
...
}
public class Doctor : Contact
{
...
}
I have other cases like this (class derived from a class derived from the base) and I've got things working, but adding these new classes broke things again.
I've also tried add .Ignore directives (derived class before base) in OnModelCreating and that does not make any difference either.
modelBuilder.Entity<Doctor>().Ignore(p => p.DisplayString);
modelBuilder.Entity<Contact>().Ignore(p => p.DisplayString);
I have several cases where I have entities derived from AbsoluteBaseClass and most times things work, but then I would add another derived class and things would break again. There appears to be no rhyme or reason to this.
I'd REALLY appreciate some advice on how I can definitively get this to work as I add classes. There appears mention around of a fix applied to the EF5 source,then you build the source. Has anyone tried that and got it to work?
Thanks for any advice!
Corey.
In my case, when using Code First (EF6) on an existing database, I created some base classes to handle the common properties like ID.
(Note: the following are inside the OnModelCreating(DbModelBuilder mb) method)
I then needed to ignore the base classes entirely with:
mb.Ignore(new[] {
typeof(BaseClassA),
typeof(BaseClassB)
});
Then, somewhat counterintuitively, I needed to register the base model properties with:
mb.Entity<BaseClassA>().HasKey(m => m.ID);
mb.Entity<BaseClassB>().Whatever...
One of my derived classes needed to ignore one of the base properties (call it NormallyNotIgnored). I used EntityTypeConfiguration, but I assume you could do the same with regular Fluent:
mb.Entity<DerivedClassB1>().Ignore(m => m.NormallyNotIgnored);
This at least has compiled/migrated (with -IgnoreChanges on the migration, since the tables already exist) and resolved the error in question.

asp.net mvc3, why do I need to constructors for my controller class

I am learning asp.net mvc3. one example I found online is to show me how to use IOC.
public class HomeController : Controller
{
private IHelloService _service;
public HomeController():this(new HelloService())
{}
public HomeController(IHelloService service)
{
_service = service;
}
}
there are two constructors in this example. I understand the second one. the first one I understand what that for, but to me, it seems like extra code, you will never need it.
can someone please explain to me whats the point to add the first constructor.
public HomeController():this(new HelloService())
{}
When the MVC Framework instantiates a controller, it uses the default (parameter-less) constructor.
By default, you are injecting a concrete IHelloService implementation. This will be used when a user navigates to the action.
Unit Tests would use the overload and pass in the mock IHelloService implementation rather than calling the default constructor.
It can be useful if you don't use a dependency injection framework that injects this for you. In this way you never have to manually inject the object, the object will handle that by itself.
The second constructor is, of course, useful to inject custom objects when unit testing.
Normally one would need to do this:
IFoo foo = new Foo();
IBar bar = new Bar(foo);
When your constructor creates a default object you can just do this:
IBar bar = new Bar();
Bar will then create a Foo and inject it into itself.

Access objects instantiated in Flex app's MXML file in other AS classes

I've got an object declared and instantiated in my Flex application's singular MXML file:
public var CDN:CDNClass = new CDNClass;
I would like to access this same CDN object (and its public methods and properties) in another class declared in a separate .as file as such:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
But when I try to access the public method parsePlayList in the CDN object in a method in the class defined in the .as file, I get the following error:
Access of undefined property CDN
The reason I want to do this is to break up the logic of my application into multiple AS files and have minimal MXML files, probably only one.
Thanks - any help is much appreciated. Perhaps my OOD/OOP thinking is not correct here?
IT depends on your class architecture. For your code to work, the CDNClass instance must be defined and implemented inside your SyncConnectorManager.
Generally, you can always call down into components, but should never call up
One option is to pass the instance ofCDNClass to a variable inside SyncConnectorManager. Add this variable to your SyncConnectionManager class:
public var CDN:CDNClass = new CDNClass;
And at some point do this:
syncConnectorManagerInstance.CDN = CDN;
That way both classes will have access to the same CDN instance and can call methods on it.
Yes, your OOP thinking is not correct here. You should take in mind differences between classes and instances. This line declares a filed in a current class and initiates it with an instance:
public var CDN:CDNClass = new CDNClass;
So current instance of your MXML class (you can think about it as usual AS class with some other notation) has public field. To operate with CDN instance you need something from the following:
Read the value of CDN (as far as it is public) from the instance of your MXML class. You need some reference to it for that.
The instance of your MXML class can have a reference to the instance of SyncConnectorManager and SyncConnectorManager should have a way to inject the value of CDN there. Something like:
Your class:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private var CDN:CDNClass;
public function SyncConnectorManager(CDN:CDNClass)
{
this.CDN = CDN;
}
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
In your case SyncConnectorManager class hasn't CDN declared (the problem of the compiler error you mentioned) and instantiated (the problem of NPE even if you just declare field).
As the bottom line I can suggest you to follow ActionScript naming and coding conventions to talk other people and team members about your code :)

Singleton Class in Flex

I have a doubt,.... How would you create a Singleton class in Flex...
Is there any convention like the class name should eb Singleton or it should extend any other class.
How many Singleton class can a project have?
Can anyone say the real time usage of a Singleton class?
I am planning to keep my components label texts in a Singleton class... Is it a good approach.
Can of worms asking about singletons!
There are a few different options about creating singletons mainly due to AS3 not having private constructors. Here's the pattern we use.
package com.foo.bar {
public class Blah {
private static var instance : Blah;
public function Blah( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Blah {
if (!instance) {
instance = new Blah( new SingletonEnforcer() );
}
return instance;
}
...
}
}
class SingletonEnforcer{}
Note that the SingletonEnforcer class is internal so can only be used by the Blah class (effectively). No-one can directly instantiate the class, they have to go through the getInstance() function.
hope I'm not hitting dead horses here :)
(edit: ahh, I'm just repeating phils link)
Gregors singleton implementation does not protect against invoking the constructor with a null value, as in:
var b:Blah = new Blah(null);
You will still have only 1 instance, but invoking the constructor is still possible with the consequences that follows.
If you absolutely must enforce the singleton, the constructor should make sure that the enforcer parameter isn't null.
public function Blah( enforcer : SingletonEnforcer ) {
if(!enforcer){
throw new Error("whoops!");
}
}
You should also be concerned about ApplicationDomain when loading swf files. External swf files that uses the same definitions, may have multiple singleton instances (1 in each separate applicationdomain) if you do not specify that the swf file must be loaded into the existing applicationdomain.
This means that Blah.getInstance() in AAA.swf is not the same instance as Blah.getinstance() in BBB.swf, if AAA.swf loads BBB.swf without a LoaderContext instance that tells the plugin to load BBB.swf into the same ApplicationDomain as AAA.swf
First you can reference a previous question to find out how to create a singleton class. You can find more info from a Yakov Fain presentation as well.
Second question, your project can technology have as may singleton class as you see fit but it will only create 1 instance of each. For example, in the cairngorm architecture you have 3 main singletons: controller, service and model. The number of actual class can very depending on your project.
Finally, A real world solutions would be. You have 2 components that need to talk to each other but you don't want them to know the other exists. Meaning sometimes the components are there and sometimes they are not...so you need them to be loosely coupled. you can uses singletons to pass the data from one component to the other with out "talking" to them directly.
Using singletons is a good approach if you need to pass data around your application from component to component and would like to decouple them from each other.
package com.foo.bar
{
public class MySingleton
{
private static var _instance:MySingleton = new MySingleton;
private var _myName:String;
public static function get instance():MySingleton
{
return _instance;
}
public function set myName(value:String):void
{
_myName = value;
}
public function get myName():String
{
return _myName;
}
}
}
Notice the absence of a constructor here.
Hello you could check out the following of a Flex Singleton Class example on http://www.how-to-code.com/flex/flex-design-patterns/flex-singleton-class.html

Resources