I have a form model created as following:
from plone.app.directives import Form
class IFormSchema(form.Schema):
foobar = schema.Bool(title=u"Just another field")
I'd like to register an adapter against this definition:
#component.adapter(IFormSchema)
#interface.implementer(ITreeSelectURLProvider)
def TreeSourceURL():
"""
"""
return "http://foobar"
The registration goes correctly.
However, there is an issue that I don't know if IFormSchema is directly provided by any object in any point of z3c.form processing chain, so that I could call:
provider = ITreeSelectURLProvider(someObject)
Does IFormSchema get directly applied to some object (zope.interface.directlyProvides?) in any point of z3c.form or plone.autoform chain
If not, what is the recommended practice so that I can register adapters against the model? What classes I should make to implement this interface?
To make matters worse, the context in the question is not a real content item but a subform object.
Dexterity make sure that the schema interface (be that defined on the filesystem and referenced in the FTI, or defined through the web or in an XML file) is provided by instances of the content type.
This isn't really about forms, it's about Dexterity. The form.Schema base class is just a marker that extends Interface, and which allows some of plone.autoform's processing to take place at configuration time.
Related
I am trying to extend the SearchableText index for my content type.
I have succeeded in getting multiple fields to be included by marking them as indexer:searchable="true" in the model file.
However I can't extend the SearchableText from my type's py as follows:
class IMyBehavior(form.Schema):
dexteritytextindexer.searchable('description')
description = schema.Text(title=u'Precis')
alsoProvides(IMyBehavior, IFormFieldProvider)
class MySearchableTextExtender(object):
adapts(IMyBehavior)
implements(dexteritytextindexer.IDynamicTextIndexExtender)
def __init__(self, context):
self.context = context
def __call__(self):
"""Extend the searchable text with a custom string"""
return 'some more searchable words'
I have to admit, I don't really know how the first class works. Do I have to set the searchable fields in this class to be able to extend the SearchableText in the second?
If I remove all the indexer:searchable="true" from the model, then the SearchableText is just empty.
Is the first class trying to register the schema at the same time? If so what should this look like if it's just extending the SearchableText?
The collective.dexteritytextindexer provides two important features:
As you already achieved, dexteritytextindexer gives you the ability to put values into Plone's SearchableText index. By adding dexteritytextindexer.searchable(FIELDNAME) to your form, the value of the field will appear in the SearchableText. In Archetypes you have the same feature, by adding searchable=True to the field definition.
collective.dexteritytextindexer gives you also the ability to extend the searchableText manually by registering an IDynamicTextIndexExtender adapter. It extends the values from part 1 with the values from your adapter.
I guess the Problem in your case is, that you have missed to register the adapter: https://github.com/collective/collective.dexteritytextindexer#extending-indexed-data
Example:
<adapter
factory=".yourbehavior.MySearchableTextExtender"
provides="collective.dexteritytextindexer.IDynamicTextIndexExtender"
name="IMyBehavior"
/>
Here's a working example:
This code extends the SearchableText of a container with the searchableText of it's children.
IDynamicTextIndexExtender adapter:
https://github.com/4teamwork/ftw.simplelayout/blob/a7d631de3984b8c1747506b9411045fdf83bc908/ftw/simplelayout/indexer.py
Register the adapter with zcml:
https://github.com/4teamwork/ftw.simplelayout/blob/a7d631de3984b8c1747506b9411045fdf83bc908/ftw/simplelayout/behaviors.zcml#L21
And the most important part - test the implementation:
https://github.com/4teamwork/ftw.simplelayout/blob/a7d631de3984b8c1747506b9411045fdf83bc908/ftw/simplelayout/tests/test_indexer.py#L31
I am creating some hack kind of thing in existing android code to verify database creation and its accessibility across layers in application.
For this I have modified an existing function of .java file but I am facing an issue while calling constructor of SQLiteOpenHelper.
The signature is SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
And I don't know how to create this Context instance. From googling I am seeing it is being some kind of activity class instance.
What ways are there to create this Context instance? Do we have to have activity class implemented?
Have a look at this question. It shows how to obtain a reference to the current Context object statically.
The gist of it is that you have to store a reference to the context that can be accessed statically from other sections of code.
P.S. You can't really "create" a context. That is something that is provided to you by the Android platform.
Just call:
this.getApplicationContext()
from wherever you are trying to create the instance of SQLiteOpenHelper.
At a high level, how do these dep. injection frameworks work?
I can understand if you always instantiate an object via a custom factory like:
IUser user = DepInjector.Get<User>();
I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.
Are there dep. inj. frameworks that would work like:
IUser user = new User();
If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?
If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:
"By default, the StandardKernel will
create dynamic methods (via
System.Reflection.Emit.DynamicMethod)
that can be used to inject values into
the different injection targets. These
dynamic methods are then triggered via
delegate calls."
As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.
AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.
I am creating a custom route by subclassing RouteBase. I have a dependency in there that I'd like to wire up with IoC. The method GetRouteData just takes HttpContext, but I want to add in my unit of work as well....somehow.
I am using StructureMap, but info on how you would do this with any IoC framework would be helpful.
Well, here is our solution. Many little details may be omitted but overall idea is here. This answer may be a kind of offtop to original question but it describes the general solution to the problem.
I'll try to explain the part that is responsible for plain custom HTML-pages that are created by users at runtime and therefore can't have their own Controller/Action. So the routes should be either somehow built at runtime or be "catch-all" with custom IRouteConstraint.
First of all, lets state some facts and requirements.
We have some data and some metadata about our pages stored in DB;
We don't want to generate a (hypothetically) whole million of routes for all of existing pages beforehand (i.e. on Application startup) because something can change during application and we don't want to tackle with pushing the changes to global RouteCollection;
So we do it this way:
1. PageController
Yes, special controller that is responsible for all our content pages. And there is the only action that is Display(int id) (actually we have a special ViewModel as param but I used an int id for simplicity.
The page with all its data is resolved by ID inside that Display() method. The method itself returns either ViewResult (strongly typed after PageViewModel) or NotFoundResult in case when page is not found.
2. Custom IRouteConstraint
We have to somewhere define if the URL user actually requested refers to one of our custom pages. For this we have a special IsPageConstraint that implements IRouteConstraint interface. In the Match() method of our constraint we just call our PageRepository to check whether there is a page that match our requested URL. We have our PageRepository injected by StructureMap. If we find the page then we add that "id" parameter (with the value) to the RouteData dictionary and it is automatically bound to PageController.Display(int id) by DefaultModelBinder.
But we need a RouteData parameter to check. Where we get that? Here comes...
3. Route mapping with "catch-all" parameter
Important note: this route is defined in the very end of route mappings list because it is very general, not specific. We check all our explicitly defined routes first and then check for a Page (that is easily changeable if needed).
We simply map our route like this:
routes.MapRoute("ContentPages",
"{*pagePath}",
new { controller = "Page", action = "Display" }
new { pagePath = new DependencyRouteConstraint<IsPageConstraint>() });
Stop! What is that DependencyRouteConstraint thing appeared in mapping? Well, thats what does the trick.
4. DependencyRouteConstraint<TConstraint> class
This is just another generic implementation of IRouteConstraint which takes the "real" IRouteConstraint (IsPageConstraint) and resolves it (the given TConstraint) only when Match() method called. It uses dependency injection so our IsPageConstraint instance has all actual dependencies injected!
Our DependencyRouteConstraint then just calls the dependentConstraint.Match() providing all the parameters thus just delegating actual "matching" to the "real" IRouteConstraint.
Note: this class actually has the dependency on ServiceLocator.
Summary
That way we have:
Our Route clear and clean;
The only class that has a dependency on Service Locator is DependencyRouteConstraint;
Any custom IRouteConstraint uses dependency injection whenever needed;
???
PROFIT!
Hope this helps.
So, the problem is:
Route must be defined beforehand, during Application startup
Route's responsibility is to map the incoming URL pattern to the right Controller/Action to perform some task on request. And visa versa - to generate links using that mapping data. Period. Everything else is "Single Responsibility Principle" violation which actually led to your problem.
But UoW dependencies (like NHibernate ISession, or EF ObjectContext) must be resolved at runtime.
And that is why I don't see the children of RouteBase class as a good place for some DB work dependency. It makes everything closely coupled and non-scalable. It is actually impossible to perform Dependency Injection.
From now (I guess there is some kind of already working system) you actually have just one more or less viable option that is:
To use Service Locator pattern: resolve your UoW instance right inside the GetRouteData method (use CommonServiceLocator backed by StructureMap IContainer). That is simple but not really nice thing because this way you get the dependency on static Service Locator itself in your Route.
With CSL you have to just call inside GetRouteData:
var uow = ServiceLocator.Current.GetService<IUnitOfWork>();
or with just StructureMap (without CSL facade):
var uow = ObjectFactory.GetInstance<IUnitOfWork>();
and you're done. Quick and dirty. And the keyword is "dirty" actually :)
Sure, there is much more flexible solution but it needs a few architectural changes. If you provide more details on exactly what data you get in your routes I can try to explain how we solved our Pages routing problem (using DI and custom IRouteConstraint).
Is there any way to get interface to play along with custom namespace? Example follows.
IHeaderRenderer.as:
public interface IHeaderRenderer{
function set header(value:IHeader):void;
function get header():IHeader;
}
HeaderRenderer.as
import fi.test.internalNamespace;
public class HeaderRenderer implements IHeaderRenderer{
internalNamespace function set header(value:IHeader):void{
// do something
}
internalNamespace function get header():IHeader{
// do something
}
}
This gives you the basic compiler error:
1044: Interface method get header in namespace fi.gridutils.headerrenderers:IHeaderRenderer not implemented by class fi.gridutils.headerrenderers.implementation:HeaderRenderer.
Why is this needed, you might ask. I'm developing a component, where the header accessors should not be directly visible to the components end user (developer), but if the developer wants to create his own Renderer he should know that they are needed. This is because the parent component will use these accessors to give the custom renderer the data it needs to render the header correctly.
Now to my mind there seems to be only three choices:
1) use public access control. This has the setback that the end developer will see accessors, which should not be directly accessed by him. Plus they add unnecessary clutter as they appear in auto-complete.
2) do not use interface. This means the end user has pretty poor options of developing the component further.
3) use the interface, but omit the accessors that use internalNamespace. Now the end developer will not know that he should add also header accessors to his custom headerrenderer class, which ends up in Flash Player giving following error to the developer in runtime:
Cannot create property internalNamespace/::header on fi.gridutils.headerrenderers.implementation.HeaderRenderer.
Sorry for all the blabbing. Any cunning ideas how this kind of situation could be handled?
In ActionScript, the interface methods need to be public. What good is an interface, if you can't guarantee the component using it can access the relevant interface methods?
that said, you can use the exclude metadata to prevent properties from showing up in code hinting.
Something like this:
[Exclude(name="header", kind="property")]
More info