How can I check for a valid contact ID in my Symbian app? - c++

In my application I have two views, Main View and Contacts view, and I have a saved Contacts ID.
When I load my second view, that should access default Contacts Database using my saved ID list and get these contacts information Title, etc. It leaves because the contact has been deleted.
So, How can I check if the contact that I has its ID is exists before I try to access its fields and cause a leave ?
CContactDatabase* contactsDb = CContactDatabase::OpenL();
CleanupStack::PushL(contactsDb);
for (TInt i = 0; i < CsIDs.Count(); i++)// looping through contacts.
{
TRAPD(err, contactsDb->ReadContactL(CsIDs[i])) //---->CsIDs is an array that holds IDs
if(KErrNotFound == err)
{
CsIDs.Remove(i);
}
}
CleanupStack::PopAndDestroy(1,contactsDb);

Thanks Abhijith for your help, and I figured out the reason behind this issue, I shouldn't call
ReadContactL directly under TRAPD under For loop, So I created a function that checks the ID validity
and I called it under TRAPD, and now my Contacts List View loads well, and invalid IDs removed from
My saved IDs list.
Solution is to follow Symbian C++ rules when dealing with "Leave":
void LoadContactsL()
{
CContactDatabase* contactsDb = CContactDatabase::OpenL();
CleanupStack::PushL(contactsDb);
for (TInt i = 0; i < CsIDs.Count(); i++)// looping through contacts.
{
TRAPD(err, ChickValidContactsIDL(i)) //-->Calling IDs checking function under TRAPD
if(KErrNotFound == err)
{
CsIDs.Remove(i);
}
}
CleanupStack::PopAndDestroy(1,contactsDb);
}
// A function that checks invalid IDs.
//Important Symbian rule: Return "void" for functions that "Leave" under TRAP harness.
void ChickValidContactsIDL(TInt index)
{
CPbkContactEngine* iPbkEngine = CPbkContactEngine::NewL(&iEikonEnv->FsSession());
CleanupStack::PushL(iPbkEngine);
iPbkEngine->OpenContactL(CsIDs[index]);
CleanupStack::PopAndDestroy(1,iPbkEngine);
}

Related

facebook messenger chat bot with Watson conversation api Context variable manipulation

I am facing a problem with Facebook meseger chat- bot ,problem is with Context variable storing and update .
My code is divided in two parts
_________**********_________
part 1:
var index = 0;
Facebookcontexts.forEach(function(value) {
console.log(value.From);
if (value.From == sender_psid) {
FacebookContext.context = value.FacebookContext;
console.log("Inside foreach "+JSON.stringify(FacebookContext.context));
contextIndex = index;
}
index = index + 1;
});
Here I have created an array named Facebookcontexts to store contexts for different users.This is where I am getting position of the user in a Facebookcontexts array which is used for later .
_________**************_____________
part 2:
if((FacebookContext.context==null)||(Facebookcontexts.find(v=>v.From==sender_psid)==undefined)){
Facebookcontexts.push({"From":sender_psid,"FacebookContext":response.context})
console.log("I am where sender is unknmown"+JSON.stringify(Facebookcontexts)+"\n"+Facebookcontexts.length);
}
else if(Facebookcontexts.find(v=>v.From==sender_psid)!=undefined){
Facebookcontexts[contextIndex].FacebookContext=response.context;
console.log("I am at where I know the sender"+JSON.stringify(Facebookcontexts)+"\n"+Facebookcontexts.length);
}
I am deciding to create a new record or update old one in if and else
Issue:
My Issue is every time if((FacebookContext.context==null)||(Facebookcontexts.find(v=>v.From==sender_psid)==undefined)) is getting checked and for that array length is 1 all the time
I will look for some help from you guys.
Thanks ins advance

Maintaing List<T> in cache like database

I have a requirement where in i need to maintain a list in memory.
Eg -
list<products>
every user will run the application and add new product/update product/ remove product from the list
and all the changes should be reflected on that list.
I am trying to store the list in the objectcache.
but when i run the application it creates products but the moment i run it second time the list is not in the cache.
need a help.
Following is the code -
public class ProductManagement
{
List<Productlist> _productList;
ObjectCache cache= MemoryCache.Default;
public int Createproduct(int id,string productname)
{
if (cache.Contains("Productlist"))
{
_productList = (List<Productlist>)cache.Get("Productlist");
}
else
{
_productList = new List<Productlist>();
}
Product pro = new Product();
pro.ID = id;
pro.ProductName = productname;
_productList.Add(pro);
cache.AddOrGetExisting("Productlist", _productList, DateTime.MaxValue);
return id;
}
public Product GetProductbyId(int id)
{
if (cache.Contains("Productlist"))
{
_productList = (List<Productlist>)cache.Get("Productlist");
}
else
{
_productList = new List<Productlist>();
}
var product = _productList.Single(i => i.ID == id);
return product;
}
}
how i can make sure that the list is persistent even when the application is not running, can this be possible.
also how to keep the cache alive and to retrieve the same cache next time.
Many thanks for help.
Memory can be different http://en.wikipedia.org/wiki/Computer_memory. MemoryCache stores information in Process Memory, which exists only while Process exists.
If your requirement is to maintain list in process memory - your task is done, and more than you do not need to use ObjectCache cache= MemoryCache.Default; you can just keep the list as a field for ProductManagement.
If you need to keep the list between application launches - you need to do additional work to write the list to file when you close application and read it when you open application.

Magento: Get product id in php block for available in list.phtml

I'm trying to get an attribute for it to be listed on list.phtml, the form that is being made is as follows:
I created a module on the Block and created a function which captures the attribute:
protected function getPreOrder()
{
$productId = $this->getRequest()->getParam('id');
$product = Mage::getModel('catalog/product')->load($productId);
$preOrder = $product->getNewsFromDate();
$preOrder = substr($preOrder, 0, 10);
return $preOrder;
}
public function getViewList()
{
if(strtotime(date('Y-m-d')) <= strtotime($this->getPreOrder()))
{
return true;
} else {
return false;
}
}
However, nothing is returned. I also did this same method to view.phtml and it worked perfectly. That goes for a file before the function getChildHtml() phtml, is not being edited list.phtml
That makes sense to create a loop, but the loop is already list.phtml!
What would be the way?
I thank you.
Have you debugged your block function to see if the product id is correct and if its loading the model correctly ??
Also debug the template list.phtml to check if its correctly loading the block type ?
get_class($this);
and see what class type is it.

Duplicate DB sessions created upon Zend_Auth login

I must be doing something wrong. I can't seem to find the answer to my problem anywhere on the Web, and this generally means that the solution is so simple that no one needs an answer on it.
I am using a database to store my session. I set it up in my bootstrap like this:
protected function _initDBSessions(){
$resource = $this->getPluginResource('db'); //from config.ini?
$db = $resource->getOptions();
$adapter = new Zend_Db_Adapter_Pdo_Mysql($db["params"]);
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);
$config = array('name'=>'sessions','primary'=>'id','modifiedColumn'=>'modified','dataColumn'=>'data','lifetimeColumn'=>'lifetime');
$options = array(
"strict"=>FALSE,
"name"=>"eCubed",
"use_cookies"=>FALSE
);
Zend_Session::setOptions($options);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
}
Next in my bootstrap is my plugin setup
protected function _initPlugins(){
Zend_Controller_Front::getInstance()->registerPlugin(new Acl_Acl());
}
My Acl_Acl looks like this:
class Acl_Acl extends Zend_Controller_Plugin_Abstract{
public function preDispatch(Zend_controller_request_abstract $request){
$acl = new Zend_Acl();
//add roles
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$GUEST));
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$BASIC),Acl_Levels::$GUEST);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$SHOP),Acl_Levels::$BASIC);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$OFFICE),Acl_Levels::$SHOP);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$EXECUTIVE),Acl_Levels::$OFFICE);
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$OWNER));
$acl->addRole(new Zend_Acl_Role(Acl_Levels::$ADMIN),Acl_Levels::$OWNER);
//add resources
$acl->addResource("index");
$acl->addResource("authenticate");
$acl->addResource("error");
$acl->addResource("employees");
$acl->addResource("mold");
$acl->addResource("search");
$acl->addResource("shop");
$acl->addResource("user");
//access rules
$acl->allow(null,array('index','error','authenticate')); //default resources
//Guest member access
$acl->allow(Acl_Levels::$GUEST,'mold',array('index','list-molds'));
$acl->allow(Acl_Levels::$GUEST,'user',array('index','login','new-profile','my-profile'));
//SHOP Member Access
$acl->allow(Acl_Levels::$BASIC,'mold',array('get-mold','get-part','get-order','get-orders','get-parts','print-mold-labels','print-part-labels'));
$acl->allow(Acl_Levels::$BASIC,'user',array('my-profile','profile'));
//OFFICE Member Access
//EXECUTIVE Member Access
//OWNER Member Access
//ADMIN Member Access
//current user
if(Zend_Auth::getInstance()->hasIdentity()){
$level = Zend_Auth::getInstance()->getIdentity()->level;
} else {
$level = Acl_Levels::$GUEST;
}
$conroller = $request->controller;
$action = $request->action;
try {
if(!$acl->isAllowed($level,$conroller,$action)){
$request->setControllerName('application-error');
$request->setActionName('not-authorized');
}
} catch (Exception $e){
$request->setControllerName("application-error");
$request->setActionName("error");
$error = new Zend_Controller_Plugin_ErrorHandler();
$error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
$error->request = clone($request);
$error->exception = $e;
$request->setParam('error_handler',$error);
}
}
}
My Authentication Controller has the following action:
public function loginAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$loginForm = new Form_Login();
$form = $loginForm->getLoginForm();
$form->setAction("/authenticate/login");
if($this->getRequest()->isPost()){
if($form->isValid($_POST)){
$email = $form->getValue('email');
$pass = $form->getValue('password');
$authAdapter = $this->getAuthAdapter();
$authAdapter ->setIdentity($email)
->setCredential($pass);
$result = Zend_Auth::getInstance()->authenticate($authAdapter);
if($result->isValid()){
$omit = array('password','timestamp','temp_password','active','created');
$identity = $authAdapter->getResultRowObject(NULL,$omit);
$authStorage = Zend_Auth::getInstance()->getStorage();
$authStorage->write($identity);
$nickname = $identity->nickname ? $identity->nickname : $identity->first_name;
$this->_helper->flashMessenger("Welcome back $nickname");
//Zend_Debug::dump($identity); exit;
$this->_redirect("/");
} else {
$this->_helper->flashMessenger("Unable to log you in. Please try again");
$this->_redirect("/");
}
}
}
}
My Database Structure:
id : int
modified: int
lifetime: int
data: text
All is well, right? Well, no...
First of all, a session is created every time someone who is not logged in refreshes or navigates to a page. This is acceptable, I guess...
The problem I have is that when I do finally log in, I can see that the database is storing the Zend_Auth identity and Flashmessenger perfectly, BUT ...
... IT IS ALSO CREATING A PHANTOM ROW IN THE DATABASE AS IF A NON-LOGGED IN USER IS NAVIGATING THE WEBSITE....
This makes authentication impossible because when the user is redirected the "Profile" page, for example, Zend is looking at the phantom session data which contains absolutely no data!
Below is the information stored in the Zend_Session database table as proof that stuff is stored:
Zend_Auth|a:1:{s:7:"storage";O:8:"stdClass":7:{s:2:"id";s:1:"2";s:5:"email";s:17:"wes#****.com";s:10:"first_name";s:6:"Wesley";s:9:"last_name";s:7:"*";s:5:"level";s:5:"basic";s:8:"nickname";s:3:"Wes";s:9:"lastlogin";s:19:"2011-07-14 19:30:36";}}__ZF|a:1:{s:14:"FlashMessenger";a:1:{s:4:"ENNH";i:1;}}FlashMessenger|a:1:{s:7:"default";a:1:{i:0;s:16:"Welcome back Wes";}}
This has been driving me nuts for 2 days now. I am under the impression that Zend_Session automatically uses only 1 session to store data, but these multiple entries are driving me mad!!
I hope I've given someone enough information to work off of.
I figured out this problem...
As expected, the solution was a simple typo...
I don't know how to dramatically write the answer here, but the problem was...
My Database table, called "sessions" had the wrong data type.
The datatype for the id column was set to "int" (11)
instead it should be set to "char" (32)
DUH! I hope the 4 days I spent on this problem helps someone else out!

Retrieve List Items from a different Site Collection in SharePoint 2010

I am having issues with retrieving list items from a different site collection. I don't have issues when trying to recieve list items from within my current site collection. For example, http://myintranet.com/Departments/IT works. But http://myintranet.com/sites/Departments/IT returns an error.
if (!String.IsNullOrEmpty(SiteName) && !String.IsNullOrEmpty(SPContext.Current.Web.Url))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite intranetSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb currentWeb = intranetSite.AllWebs["/sites/projects/Physics"])
{
SPList postList = currentWeb.Lists.TryGetList("Issues");
if (postList != null)
{
IssueList.DataSource = postList.Items.GetDataTable();
IssueList.DataBind();
}
}
}
});
}
I haven't used any different code to what I normally do when trying to recieve list items. The only difference is that this time I getting list items from another site collection.
Thanks for any help!
The problem is intranetSite.AllWebs. This will only get SPWeb objects under your current site collection.
You cannot infer another site collection directly from one site collection.
Even though /sites/projects LOOKS like chid site collection from /, it;s not. /sites is just a managed path. / and /sites/projects are at the same level of the site collection hierarchy.
What you need to do is to this:
if (!String.IsNullOrEmpty(SiteName) && !String.IsNullOrEmpty(SPContext.Current.Web.Url))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb currentWeb = new SPSite("http://server/sites/projects/Physics").OpenWeb())
{
SPList postList = currentWeb.Lists.TryGetList("Issues");
if (postList != null)
{
IssueList.DataSource = postList.Items.GetDataTable();
IssueList.DataBind();
}
}
});
}