How to perform Cache Storage concept in Blackberry? - blackberry

I need to create an application,that should contain two storage,one is persistent storage and another one is cache storage.After loading, the application should check the username and password with the cache storage data if it is empty then it should check with the persistent storage.How to accomplish this task?Is there any separate concept of cache or we have create the persistent as cache.please help me.

You can use RecordStore which is also persistent, or RuntimeStore which is shared between all apps but is non persistent.
Alternatively you can use some custom storage class to implement cache functionality,
storing, updating values in that class, sharing it as a field of Application class:
class Cache {
String mName = null;
String mPhone = null;
}
public class CacheApp extends UiApplication {
Cache mCache = null;
public static void main(String[] args) {
CacheApp app = new CacheApp();
app.enterEventDispatcher();
}
public CacheApp() {
initCache();
CacheScr scr = new CacheScr();
pushScreen(scr);
}
private void initCache() {
mCache = new Cache();
mCache.mName = "Name";
mCache.mPhone = "Phone";
}
}
class CacheScr extends MainScreen {
public CacheScr() {
CacheApp app = (CacheApp) UiApplication.getUiApplication();
String name = app.mCache.mName;
String phone = app.mCache.mPhone;
}
}

Coldice is correct, however I fail to see why one would use a store separate from PersistentStore (or RecordStore) for data that must endure and may be shared, and RuntimeStore for data which is shared but not durable. This just seems to be adding complexity to normal application transient storage.

Related

Manage multiple ravendb document stores through castle windsor in an MVC app?

I twist myself around a workable solution to use several databases in RavenDB for an ASP.Net MVC app using Castle Windsor for the wiring.
This is the current installer
public class RavenInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IDocumentStore>().Instance(CreateDocumentStore()).LifeStyle.Singleton,
Component.For<IDocumentSession>().UsingFactoryMethod(GetDocumentSesssion).LifeStyle.PerWebRequest
);
}
static IDocumentStore CreateDocumentStore()
{
var store = new DocumentStore { ConnectionStringName = "RavenDb_CS9" };
store.Initialize();
IndexCreation.CreateIndexes(typeof(Users).Assembly, store);
return store;
}
static IDocumentSession GetDocumentSesssion(IKernel kernel)
{
var store = kernel.Resolve<IDocumentStore>();
return store.OpenSession();
}
}
The above works perfect but only for one Database.
I can't find the proper thinking how to handle another database. The whole chain starts with a domain service asking for an IDocumentSession. Then the flow is as specified in the above installer. But where/how do I ask for a "SessionToDb1" or a "SessionToDb2"?
The important is of course what connection string to use (where the DB property is specified) but also what indexes to create in respective DB / DocumentStore.
Did anyone accomplish this using Windsor? Am I thinking/attacking it wrong here?
Thanks!
Because you have:
Component.For<IDocumentSession>()
.UsingFactoryMethod(GetDocumentSesssion)
.LifeStyle.PerWebRequest
Your GetDocumentSession method is going to be called any time you inject an IDocumentSession. This is good.
When working with multiple databases, you need to pass the database name as a parameter to OpenSession. So, you need some way to resolve which database you would like to connect to based on the current web request.
You need to modify the GetDocumentSession method to implement whatever custom logic you are going to use. For example, you may want to look at a cookie, asp.net session item, current thread principal, or some other criteria. The decision is custom to your application, all that matters is somehow you open the session with the correct database name.
I've run into this problem before with nhibernate.
I found the best solution is to create a SessionManager class which wraps the Creation of the document store and the Session..
So I.E.
public interface ISessionManager
{
void BuildDocumentStore();
IDocumentSession OpenSession();
}
public interface ISiteSessionManager : ISessionManager
{
}
public class SiteSessionManager : ISiteSessionManager
{
IDocumentStore _documentStore;
public SiteSessionManager()
{
BuildDocumentStore();
}
public void BuildDocumentStore()
{
_documentStore = new DocumentStore
{
Url = "http://localhost:88",
DefaultDatabase = "test"
};
_documentStore.Initialize();
IndexCreation.CreateIndexes(typeof(SiteSessionManager).Assembly, _documentStore);
}
public IDocumentSession OpenSession()
{
return _documentStore.OpenSession();
}
}
// And then!.
Container.Register(Component.For<ISiteSessionManager>().Instance(new SiteSessionManager()).LifestyleSingleton());
// And then!.
public class FindUsers
{
readonly ISiteSessionManager _siteSessionManager;
public FindUsers(ISiteSessionManager siteSessionManager)
{
_siteSessionManager = siteSessionManager;
}
public IList<User> GetUsers()
{
using (var session = _siteSessionManager.OpenSession())
{
// do your query
return null;
}
}
}
Rinse and repeat for multiple databases.!

HttpCache vs Singleton - Best practice for an MVC application

I am little bit confused in understanding of the HttpCache and Singleton approaches.
My application uses Asp.net MVC and the scenario is that, I have some List of Data that will never change and some data that might rarely change.
I have developed and deployed application using a Singleton repository for this type of data.
It performs great. The only issue is that when a rare case occur, i have to restart IIS to take effect.
What is the best solution.?
Singleton implementation
public class SingletonRepository : ISingletonRepository
{
private static SingletonRepository singleInstance;
private readonly IStateRepository stateRepo;
private readonly ICountryRepository countryRepo;
private readonly ITDPaymentModeRepository paymentModeRepo;
private readonly ITDPlanRepository planRepo;
private readonly ITDOrderTypeRepository orderTypeRepo;
private readonly IKeywordRepository keywordRepo;
private readonly IAgencyRepository agencyRepo;
private readonly IList<AT_STATE> lstState;
private readonly IList<AT_COUNTRY> lstCountry;
private readonly IList<TDPaymentMode> lstPaymentMode;
private readonly IList<TDPlan> lstPlan;
private readonly IList<TDOrderType> lstOrderType;
private readonly IList<Keyword> lstKeyword;
private readonly IList<Agency_MST> lstAgency;
private SingletonRepository()
{
stateRepo = new StateRepository();
countryRepo = new CountryRepository();
paymentModeRepo = new TDPaymentModeRepository();
planRepo = new TDPlanRepository();
orderTypeRepo = new TDOrderTypeRepository();
keywordRepo = new KeywordRepository();
agencyRepo = new AgencyRepository();
lstState = stateRepo.GetAll().Where(x => x.CountryId == 101).ToList();
lstCountry = countryRepo.GetAll().ToList();
lstPaymentMode = paymentModeRepo.GetAll().ToList();
lstPlan = planRepo.GetAll().ToList();
lstOrderType = orderTypeRepo.GetAll().ToList();
lstKeyword = keywordRepo.GetAll().ToList();
lstAgency = agencyRepo.GetAll().ToList();
//lstState = stateRepo.GetAll().Take(20).ToList();
//lstCountry = countryRepo.GetAll().Take(20).ToList();
//lstPaymentMode = paymentModeRepo.GetAll().Take(20).ToList();
//lstPlan = planRepo.GetAll().Take(20).ToList();
//lstOrderType = orderTypeRepo.GetAll().Take(20).ToList();
//lstKeyword = keywordRepo.GetAll().Take(20).ToList();
//lstAgency = agencyRepo.GetAll().Take(20).ToList();
}
public static SingletonRepository Instance()
{
return singleInstance ?? (singleInstance = new SingletonRepository());
}
public IList<AT_STATE> GetState()
{
return this.lstState;
}
public IList<AT_COUNTRY> GetCountry()
{
return this.lstCountry;
}
public IList<TDPaymentMode> GetPaymentMode()
{
return this.lstPaymentMode;
}
public IList<TDPlan> GetPlan()
{
return this.lstPlan;
}
public IList<TDOrderType> GetOrderType()
{
return this.lstOrderType;
}
public IList<Keyword> GetKeyword()
{
return this.lstKeyword;
}
public IList<Agency_MST> GetAgency()
{
return this.lstAgency;
}
}
}
The purpose of using the singleton pattern generally is not for static data storage. You should use a singleton when you only want one object instance to be able to perform certain actions. It may be fast, but as you can see, when the data changes, you need to reset the heap to get the new data (as you say, by restarting IIS).
HttpCache (more specifically, the ObjectCache which Http caching uses by default), stores the data in the same place as the heap: in Random Access Memory. So, it is just as fast as static data stored in a class or instance on the heap. The difference is that you can set up the cache to periodically go stale, so that it will get new data when the data changes. You can even set up SqlCacheDependencies so that the cache is made stale whenever your database's state changes.
Another advantage of cache is that it more efficiently utilizes your server's RAM resources. With your singleton, no matter what, this data will always be occupying memory, even when the data is not being used. With cache, the server only stores the data in memory when it is being used. The disadvantages with cache are that occasionally, a user here and there will get a slower response when they request data after the cache has expired. However, after they do, other users will benefit from the data being cached for a time.
You can actually reload the singleton by creating a reload method such as this:
public static void ReloadSingletonRepositoryInstance()
{
singleInstance = null;
SingletonRepository sr = SingletonRepository.Instance;
}
Hope that helps.

Delete Persistent Object when app is Deleted in Blackberry

I am using persistent object in blackberry to store config details specific to the app. Here is how I am implementing the class
public class Preferences implements Persistable
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static Hashtable tbl = new Hashtable();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
Hashtable tbl = (Hashtable)persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
But if I uninstall/delete the app these stored values are not getting deleted. When I installs the app for next time the app is fetching the old stored values.
How can i do this properly in blackberry?
Thanks
Create a custom hashtable class like this
package com.myapp.items;
import net.rim.device.api.util.Persistable;
import java.util.*;
public class MyAppHashtable extends Hashtable implements Persistable{
}
And change your code to
public class Preferences
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static MyAppHashtable tbl = new MyAppHashtable ();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
MyAppHashtable tbl = (MyAppHashtable )persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
This is so that we adhere to the following info from RIM
The BlackBerry persistence model
When you use the BlackBerry persistence model, data is only deleted if the store contains data that belongs to the removed application.
For example, if an application stores an object with a package called com.mycompany.application.storage and no other application on the BlackBerry smartphone makes reference to the package, the persistent store and the removed application are deleted.
The same is true if the object is wrapped in a container such as a Vector. Even if only one of the elements of the Vector has a package name that is not used by other applications, the entire Vector is removed from the persistent store.
Note: If the application does not store any objects with an identifying package structure, (for example, an application that stores java.util.Vector or javax.microedition.location.AddressInfo objects), the application should create and use a class that extends Vector in order to identify that Vector belongs to the given application. When you store this Vector, which is identified uniquely by its package, you guarantee that the data is removed from the persistent store when the application is removed.
This info is from here

Using persistence to display number of times visits for a BB Application?

I have developed an application. I want to display a message before the user starts implementing my application. Like when it is used first time i want to show "Count = 1". And when app is visited second time, "Count = 2".
How can i achieve it? I had done such thing in android using sharedperferences. But how can i do it in blackberry. I had tried something with PersistentStore. But cant achieve that, for i dont know anything about the Persistance in BB.
Also i would wish to restrict the use for 100. Is it possible?
sample codes for this will be appreciable, since i am new to this environment..
You can achieve it with Persistent Storage.
Check this nice tutorial about storing persistent data.
Also you can use SQLite. Link to a development guide which describes how to use SQLite databases in Java® applications: Storing data in SQLite databases.
You can restrict user for trying your application at most 100 times using your own logic with the help of persistent data. But I think there may be some convention, so try Google for that.
got it...
I created a new class which implements Persistable. In that class i had created an integer variable and set an getter and setter function for that integer...
import net.rim.device.api.util.Persistable;
public class Persist implements Persistable
{
private int first;
public int getCount()
{
return first;
}
public void setCount()
{
this.first += 1;
}
}
Then in the class which initializes my screen, i had declared persistence variables and 3 functions to use my Persist.java, initStore(), savePersist(), and getPersist()
public final class MyScreen extends MainScreen implements FieldChangeListener
{
/*
* Declaring my variables...
*/
private static PersistentObject store;
public Persist p;
public MyScreen()
{
//my application codes
//here uses persistence
initStore();
p = getPersist();
if(p.getCount()<100)
{
savePersist();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(p.getCount.toString());
}
});
}
else
{
close();
System.exit(0);
}
}
//three function....
public static void initStore()
{
store = PersistentStore.getPersistentObject(0x4612d496ef1ecce8L);
}
public void savePersist()
{
synchronized (store)
{
p.setCount();
store.setContents(p);
store.commit();
}
}
public Persist getPersist()
{
Persist p = new Persist();
synchronized(store)
{
p = (Persist)store.getContents();
if(p==null)
{
p = new Persist();
}
}
return p;
}
}
I hope u all will get it right now....
If there are another simple way, plz let me know...
Thanks

Using Persistent Store in BlackBerry

I am developing a BlackBerry application. I want to store the details of multiple users in my mobile. I have to store data like username, first name, last name ,email id ,phone number for each user. Can any one please provide me a sample code for persistent store using which I can store all this data in a vector and retrieve later.
This link should answer most of what you need to know - http://www.miamicoder.com/post/2010/04/13/How-to-Save-BlackBerry-Application-Settings-in-the-Persistent-Store.aspx.
Below is some code from one of my projects.
public class PreferencesStore
{
// Not a real key, replace it with your own.
private static long m_lTabulaRectaKey = 0l;
public static Vector getTabulaRectas()
{
Vector vecTabulaRectas = new Vector();
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
if(poObject.getContents() != null)
{
vecTabulaRectas = (Vector)poObject.getContents();
}
return vecTabulaRectas;
}
public static void addTabulaRecta(TabulaRecta a_oTabulaRecta)
{
Vector vecTabulaRectas = getTabulaRectas();
vecTabulaRectas.addElement(a_oTabulaRecta);
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
poObject.setContents(vecTabulaRectas);
poObject.commit();
}
}

Resources