I have some records in a DNN database used by a custom module, it is important that they are never cached, but rather the fresh data is returned each time it is requested.
Is it better to set a cachable attribut to zero, or remove the cachable attribute all together (or is this the same)?
Imports DotNetNuke.ComponentModel.DataAnnotations
Namespace Components
<TableName("vw_MyView")>
<PrimaryKey("PrimaryKey", AutoIncrement:=True)>
<Cacheable("vw_MyView", CacheItemPriority.Default, 0)>
<Scope("PortalID")>
Public Class vw_KrisisShifts_Expired_ShiftTrade_Details
....
End Class
End Namespace
OR
<TableName("vw_MyView")>
<PrimaryKey("PrimaryKey", AutoIncrement:=True)>
<Scope("PortalID")>
Public Class vw_KrisisShifts_Expired_ShiftTrade_Details
....
End Class
Related
I recently encountered a situation where one might want to run a datastore query which includes a kind, but the class of the corresponding model is not available (e.g. if it's defined in a module that hasn't been imported yet).
I couldn't find any out-of-the-box way to do this using the google.appengine.ext.db package, so I ended up using the google.appengine.api.datastore.Query class from the low-level datastore API.
This worked fine for my needs (my query only needed to count the number of results, without returning any model instances), but I was wondering if anyone knows of a better solution.
Another approach I've tried (which also worked) was subclassing db.GqlQuery to bypass its constructor. This might not be the cleanest solution, but if anyone is interested, here is the code:
import logging
from google.appengine.ext import db, gql
class ClasslessGqlQuery(db.GqlQuery):
"""
This subclass of :class:`db.GqlQuery` uses a modified version of ``db.GqlQuery``'s constructor to suppress any
:class:`db.KindError` that might be raised by ``db.class_for_kind(kindName)``.
This allows using the functionality :class:`db.GqlQuery` without requiring that a Model class for the query's kind
be available in the local environment, which could happen if a module defining that class hasn't been imported yet.
In that case, no validation of the Model's properties will be performed (will not check whether they're not indexed),
but otherwise, this class should work the same as :class:`db.GqlQuery`.
"""
def __init__(self, query_string, *args, **kwds):
"""
**NOTE**: this is a modified version of :class:`db.GqlQuery`'s constructor, suppressing any :class:`db.KindError`s
that might be raised by ``db.class_for_kind(kindName)``.
In that case, no validation of the Model's properties will be performed (will not check whether they're not indexed),
but otherwise, this class should work the same as :class:`db.GqlQuery`.
Args:
query_string: Properly formatted GQL query string.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
Raises:
PropertyError if the query filters or sorts on a property that's not indexed.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
namespace = None
if isinstance(app, tuple):
if len(app) != 2:
raise db.BadArgumentError('_app must have 2 values if type is tuple.')
app, namespace = app
self._proto_query = gql.GQL(query_string, _app=app, namespace=namespace)
kind = self._proto_query._kind
model_class = None
try:
if kind is not None:
model_class = db.class_for_kind(kind)
except db.KindError, e:
logging.warning("%s on %s without a model class", self.__class__.__name__, kind, exc_info=True)
super(db.GqlQuery, self).__init__(model_class)
if model_class is not None:
for property, unused in (self._proto_query.filters().keys() +
self._proto_query.orderings()):
if property in model_class._unindexed_properties:
raise db.PropertyError('Property \'%s\' is not indexed' % property)
self.bind(*args, **kwds)
(also available as a gist)
You could create a temporary class just to do the query. If you use an Expando model, the properties of the class don't need to match what is actually in the datastore.
class KindName(ndb.Expando):
pass
You could then do:
KindName.query()
If you need to filter on specific properties, then I suspect you'll have to add them to the temporary class.
My goal is to keep session size as small as possible. (Why?.. it's other topic).
What I have is Phase listener declared in faces-config.xml
<lifecycle>
<phase-listener>mypackage.listener.PhaseListener</phase-listener>
</lifecycle>
I want to save all other views, except the last one(maximum two) , in some memcache. Getting the session map:
Map<String, Object> sessionMap = event.getFacesContext().getExternalContext().getSessionMap();
in beforePhase(PhaseEvent event) method is giving me access to all views. So here I could save all views to the memcache and delete them from the session. The question is where in jsf these views that are still loaded in the browser are requested so that I can refill with this view if it's needed. Is it possible at all? Thank you.
To address the core of your question, implement a ViewHandler, within which you can take control of the RESTORE_VIEW and RENDER_RESPONSE phases/processes. You'll save the view during the RENDER_RESPONSE and selectively restore, during the RESTORE_VIEW phase. Your view handler could look something like the following
public class CustomViewHandlerImpl extends ViewHandlerWrapper{
#Inject ViewStore viewStore; //hypothetical storage for the views. Could be anything, like a ConcurrentHashMap
ViewHandler wrapped;
public CustomViewHandlerImpl(ViewHandler toWrap){
this.wrapped = toWrap;
}
public UIViewRoot restoreView(FacesContext context, String viewId) throws IOException{
//this assumes you've previously saved the view, using the viewId
UIViewRoot theView = viewStore.get(viewId);
if(theView == null){
theView = getWrapped().restoreView(context, viewId);
}
return theView;
}
public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException{
viewStore.put(viewToRender.getId(),viewToRender);
getWrapped().renderView(context, viewToRender);
}
}
Simply plug in your custom viewhandler, using
<view-handler>com.you.customs.CustomViewHandlerImpl</view-handler>
Of course, you probably don't want to give this treatment to all your views; you're free to add any conditions to the logic above, to implement conditional view-saving and restoration.
You should also consider other options. It appears that you're conflating issues here. If your true concern is limit the overhead associated with view processing, you should consider
Stateless Views, new with JSF-2.2. The stateless view option allows you to exclude specific pages from the JSF view-saving mechanism, simply by specifying transient="true" on the f:view. Much cleaner than mangling the UIViewRoot by hand. The caveat here is that a stateless view cannot be backed by scopes that depend on state-saving, i.e. #ViewScoped. In a stateless view, the #ViewScoped bean is going to be recreated for every postback. Ajax functionality also suffers in this scenario, because state saving is the backbone of ajax-operations.
Selectively set mark components as transient The transient property is available for all UIComponents, which means, on a per-view basis, you can mark specific components with transient="true", effectively giving you the same benefits as 1) but on a much smaller scope. Without the downside of no ViewScoped
EDIT: For some reason, UIViewRoot#getViewId() is not returning the name of the current view (this might be a bug). Alternatively, you can use
ExternalContext extCtxt = FacesContext.getCurrentInstance().getExternalContext();
String viewName = ((HttpServletRequest)extCtxt.getRequest()).getRequestURI(); //use this id as the key to store your views instead
We are building a WPF Prism application. We have different developers working on different module projects, and multiple modules are injected into the main Application Shell. The main application is also a separate project. We also want to be able to use the modules in different applications. We do not want to have to name the Regions with the same names in every application.
For instance, say we have a module to be used in two different applications. In one application, its developer may name the module's region "DetailsRegion," and in the other, its developer may name it "ResultsRegion."
Every example I can find registers the View with the Region by hard-coding the region name in the module's class definition:
myRegionManager.RegisterViewWithRegion("RegionNameHere", GetType(ModuleViewType))
What I want to do is put the Region name in the main application's app.config file, and pass this name to the module. Something like this:
In the main Shell Application's app.config:
<Modules>
<SearchModule>
<add key="RegionName" value="SearchRegion" />
</SearchModule>
</Modules>
And in the module's class file:
Dim settings As NameValueCollection = CType(ConfigurationManager.GetSection("Modules/SearchModule"), NameValueCollection)
Dim regionName as string = settings("RegionName")
myRegionManager.RegisterViewWithRegion(regionName, GetType(SearchModuleType)
In a way, this would be the last step to completely decouple the modules from the shell and from each other.
This works perfectly in the views of the module. But I cannot do it in the module's class definition file, as ConfigurationManager is not available at that level.
I can do this by putting the region name in the ApplicatonSettings section of the module's app.config. But this defeats the purpose of being able to store the module in one location to be loaded by multiple applications. It really needs to be in the main application's app.config.
Is there a way to register a module's View with a Region, without hard-coding the name of the Region in the code? We try so hard NOT to hard-code anything. Is it truly necessary here?
As Meleak already mentioned in his comment: Use a static class
namespace Infrastructure
{
public static class RegionNames
{
public const string MainRegion = "MainRegion";
}
}
In your xaml code you can use the region name as follows:
<UserControl
xmlns:Inf="clr-namespace:Infrastructure;assembly=Infrastructure"
xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism">
<ContentControl Regions:RegionManager.RegionName="{x:Static Inf:RegionNames.MainRegion}"/>
</UserControl>
I got it. Turns out I was wrong on one point, and I apologize for that. The parent application's .config settings ARE available at the Module class definition level. One must add the correct references and make the correct Imports (or using) entries. I must have been napping at the keyboard.
In the host application's app.config, add configSection definitions. Here I define sections for two modules:
<configSections>
<sectionGroup name="Modules">
<section name="SearchModule" type="System.Configuration.NameValueSectionHandler" />
<section name="HeaderModule" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
...
</configSections>
In the host application's app.config, add a Modules section, and a subsection for each module:
<Modules>
<SearchModule>
<add key="Region" value="SearchRegion"/>
</SearchModule>
<HeaderModule>
<add key="Region" value="HeaderRegion"/>
</HeaderModule>
</Modules>
In the Module project, add a reference to System.Configuration.dll. Add "Imports" (VB) or "using" (C#) for System.Collections.Specialized and System.Configuration:
VB:
Imports System.Collections.Specialized
Imports System.Configuration
C#:
using System.Collections.Specialized;
using System.Configuration;
In the Initialize method of the Module's Class definition file:
VB:
Public Sub Initialize() Implements Microsoft.Practices.Prism.Modularity.IModule.Initialize
Dim settings As NameValueCollection = CType(ConfigurationManager.GetSection("Modules/SearchModule"), NameValueCollection)
MyRegionManager.RegisterViewWithRegion(settings("Region"), GetType(SearchModuleView))
End Sub
C#:
public void Initialize() : Microsoft.Practices.Prism.Modularity.IModule.Initialize
{
(NameValueCollection)settings = (NameValueCollection)ConfigurationManager.GetSection("Modules/SearchModule");
MyRegionManager.RegisterViewWithRegion(settings["Region"], typeof(SearchModuleView));
}
This, then, registers the View with a Region from entries made in the Host application's app.config. This means one module can be built for multiple host applications, and it can be inserted in a Region of any name in the Host. No need to make changes in compiled code, or to make a separate RegionNames class for each application.
Our application is also built using MVVM architecture. We define the View-Models in the Host application, and expose them to the modules by names defined the app.config using RegionContext or EventAggregator. This now completely decouples the modules from the application, and makes the modules totally reusable in different applications without modification.
Thanks for the input, and I hope this helps someone else in the future.
In the python app engine docs, I see something called dbReferenceProperty. I can't understand what it is, or how it's used. I'm using the java interface to app engine, so I'm not sure if there's an equivalent.
I'm interested in it because it sounds like some sort of pseudo-join, where we can point a property of a class to some other object's value - something like if we had:
class User {
private String mPhotoUrl;
private String mPhone;
private String mState;
private String mCountry;
.. etc ..
}
class UserLite {
#ReferenceProperty User.mPhotoUrl;
private String mPhotoUrl;
}
then if we had to update a User object's mPhotoUrl value, the change would somehow propagate out to all UserLite instances referencing it, rather than having to update every UserLite object instance manually,
Thanks
A db.ReferenceProperty simply holds the key of another datastore entity, which is automatically fetched from the datastore when the property is used.
There's some additional magic where the entity that is referenced has access to a query for entities of type Foo that reference it in the special attribute foo_set.
The Java datastore API instead has owned relationships, which serve the same purpose.
I want to have a field in my entity where the returned data comes from a class function in mydomainservice and not from the database.
The reason is that I want to generate an image URL (Silverlight bind) based rather loosely upon other fields in a table
How can I obtain that ?
The other two have mentioned a partial class. They are correct. Here's an example...
public partial class MyImage
{
public string CompleteUrl
{
get { return string.Format("http://{0}/{1}/{2}.png", Host, Folder, Filename); }
}
}
This would assume that you already have columns named "Host", "Folder", and "Filename" in your database, and those have already been mapped to the appropriate columns.
L2S generates partial classes for all of its implementations. You shouldn't be doing your own mapping. These partial classes allow you to create a new file (with ClassName.cs) that will allow you to extend the functionality of your domain objects.
You can extend your linq2sql generated class by making a partial class with the same name (in the same namespace) and putting the method in that file.
Declare a partial class with the same name as the entity class and in the same assembly. Declare your function/property as usual.