facebook messenger chat bot with Watson conversation api Context variable manipulation - facebook-graph-api

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

Related

How to count elements inside array in Postman test

I was unable to find correct answer and therefore posting a question.
Return response on Postman is as below:
[
{
"AttemptNumber":1,
"LoginID":test123,
"CurrentStatus":2
}
]
I'm trying to count elements in this array object.
this is what I was doing:
countItems = JSON.pase(responseBody)
for (var i = 1, l = Object.keys(countItems).length; i <=3){
}
but I keep getting 1. 1 is array but I'm looking for count to be 3.
I'll appreciate your expertise.
Thanks.
This should log the number of items from each object in the response array:
let res = pm.response.json()
_.each(res, (obj) => {
console.log(_.keys(obj).length)
})
It's using some methods from Lodash, which is one of the built-in libraries.
https://lodash.com/docs/4.17.15

Authorize.net Sandbox Accept page testing- always declined?

I’m attempting to test Accept Hosted payment page(redirect-method) with my sandbox. For this, I’m using the GetAnAcceptPaymentPage from the Java sample code application to generate a token string for a payment, specified the autoLoginId and transactionKey for my sandbox, and setting $1.00 as the amount. I’m then posting the returned token string to https://test.authorize.net/payment/payment with a “token” form element containing that string. This much appears to be working, and I do get a payment page showing the $1.00 amount. However, no matter what values I enter onto that payment page, pressing the “Pay” button just shows “The transaction has been declined.” in red text at the bottom of the form. I’ve confirmed that my sandbox is set to “Live” mode, and have looked at the following link to use what I believe should be valid values for testing: https://developer.authorize.net/hello_world/testing_guide/. I'm hoping someone can tell me why I can't get any result other than "The transaction has been declined".
public String getTokenValue() {
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
merchantAuthenticationType.setName("xxxxx");
merchantAuthenticationType.setTransactionKey("xxxxxx");
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
// Create the payment transaction request
TransactionRequestType txnRequest = new TransactionRequestType();
txnRequest.setTransactionType(TransactionTypeEnum.AUTH_CAPTURE_TRANSACTION.value());
txnRequest.setAmount(new BigDecimal(1.00).setScale(2, RoundingMode.CEILING));
OrderExType order = new OrderExType();
order.setInvoiceNumber("2");
txnRequest.setOrder(order);
CustomerProfilePaymentType cpp = new CustomerProfilePaymentType();
cpp.setCustomerProfileId("xxxx");
cpp.setCreateProfile(true);
txnRequest.setProfile(cpp);
SettingType setting1 = new SettingType();
setting1.setSettingName("hostedPaymentButtonOptions");
setting1.setSettingValue("{\"text\": \"Proceed\"}");
SettingType setting2 = new SettingType();
setting2.setSettingName("hostedPaymentOrderOptions");
setting2.setSettingValue("{\"show\": false}");
SettingType setting3 = new SettingType();
setting3.setSettingName("hostedPaymentPaymentOptions");
setting3.setSettingValue("{\"cardCodeRequired\": true}");
SettingType setting4 = new SettingType();
setting4.setSettingName("hostedPaymentIFrameCommunicatorUrl");
setting4.setSettingValue("{\"url\": \"http://example.com/abc\"}");
ArrayOfSetting alist = new ArrayOfSetting();
alist.getSetting().add(setting1);
alist.getSetting().add(setting2);
alist.getSetting().add(setting3);
alist.getSetting().add(setting4);
GetHostedPaymentPageRequest apiRequest = new GetHostedPaymentPageRequest();
apiRequest.setTransactionRequest(txnRequest);
apiRequest.setHostedPaymentSettings(alist);
GetHostedPaymentPageController controller = new GetHostedPaymentPageController(apiRequest);
controller.execute();
GetHostedPaymentPageResponse response = new GetHostedPaymentPageResponse();
response = controller.getApiResponse();
if (response != null) {
if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(response.getToken());
} else {
System.out.println("Failed to get hosted payment page: " + response.getMessages().getResultCode());
}
}
return response.getToken();
}
>>> order.setInvoiceNumber("2");
Set the invoice number to a different value than 2, this value is used in Sandbox to trigger decline for testing purposes.

Replicating Google Analytics DateRange picker

I need to replicate the Google Analytics date picker (plus a few new options). Can anyone tell me how to highlight all the cells on a calendar between two dates. My basic JavaScript is OK but I think I'm getting a bit out of my depth.
I'm using JQuery 1.5.1 and JQuery UI 1.8.14.
In needed to replicate Google Analytics date picker as well. I know you were asking just about highlighting cells, but if someone else would prefer complete solution, you can see my answer from another question: jquery google analytics datepicker
Here's a solution using the built-in 'onSelect' event (jsFiddle):
$(document).ready(function() {
'use strict';
var range = {
'start': null,
'stop': null
};
$('#picker').datepicker({
'onSelect': function(dateText, inst) {
var d, ds, i, sel, $this = $(this);
if (range.start === null || range.stop === null) {
if (range.start === null) {
range.start = new Date(dateText);
} else {
range.stop = new Date(dateText);
}
}
if (range.start !== null && range.stop !== null) {
if ($this.find('td').hasClass('selected')) {
//clear selected range
$this.children().removeClass('selected');
range.start = new Date(dateText);
range.stop = null;
//call internal method '_updateDatepicker'.
inst.inline = true;
} else {
//prevent internal method '_updateDatepicker' from being called.
inst.inline = false;
if (range.start > range.stop) {
d = range.stop;
range.stop = range.start;
range.start = d;
}
sel = (range.start.toString() === range.stop.toString()) ? 0 : (new Date(range.stop - range.start)).getDate();
for (i = 0; i <= sel; i += 1) {
ds = (range.start.getMonth() + 1).toString() + '/' + (range.start.getDate() + i).toString() + '/' + (range.start.getFullYear()).toString();
d = new Date(ds);
$this.find('td a').filter(function(index) {
return $(this).text() === d.getDate().toString();
}).parents('td').addClass('selected');
}
}
}
}
});
});
I became desperate and came up with a solution on my own. It wasn't pretty but I'll detail it.
I was able to construct a div that had the text boxes, buttons and the datepicker that looked like the Google Analytics control but I couldn't make the datepicker work properly. Eventually, I came up with the idea of creating a toggle variable that kept track of which date you were selecting (start date or end date). Using that variable in a custom onSelect event handler worked well but I still couldn't figure out how to get the cells between dates to highlight.
It took a while, but I slowly came to the realization that I couldn't do it with the datepicker as it existed out of the box. Once I figured that out, I was able to come up with a solution.
My solution was to add a new event call afterSelect. This is code that would run after all the internal adjustments and formatting were complete. I then wrote a function that, given a cell in the datepicker calendar, would return the date that it represented. I identified the calendar date cells by using jQuery to find all the elements that had the "ui-state-default" class. Once I had the date function and a list of all the calendar cells, I just needed to iterate over all of them and, if the date was in the correct range, add a new class to the parent.
It was extremely tedious but I was able to make it work.

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!

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

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);
}