How to use SMS service in BB10 using BB10 webworks? - blackberry-webworks

I am trying to use SMS service in BB10 through webworks.But I always get an error "Cannot read property 'sms' of undefined" .The code I am using is :
Javascript :
blackberry.message.sms.send('hello world', '9999999999');
Config file :
<feature id="blackberry.message.sms" />
Is there any way to use the SMS service ?

Edit: My bad.. there is on SMS API just yet. Generally if you get an error stating blackberry is not defined, and it is an API that's available, this will help you troubleshoot though.. :)
--
Looks like the 'blackberry' namespace is undefined? Are you loading the webworks.js file properly, and waiting for it to have initialized before you try to access the API?
You include the webworks.js file like so in the index html file for your app..
<script src="local:///chrome/webworks.js" type="text/javascript"></script>
Also, you need to have something similar to this (also in the index) which triggers after the 'webworksready' event fires
<script type="text/javascript">
document.addEventListener("webworksready", function(){
// webworks is now ready, do cool stuff here
});
</script>
Also, check-out our Getting Started material if you wish: http://developer.blackberry.com/html5/documentation/getting_started_with_bb10_ww_sdk_2007056_11.html

Currently there is no SMS extension for webworks on BB10

in your config.xml file add this:
<feature id="blackberry.invoke" required="true" version="1.0.0.0"/>
<feature id="blackberry.invoke.card" />
then use this invocation function in your script file:
doSMSinvokation = function(ppsEncode) {
blackberry.invoke.invoke({
target: "sys.pim.text_messaging.composer",
action: "bb.action.COMPOSE",
data: ppsEncode({"to":["55555"], "body":"body of SMS", "send":"false"})},
function(successEvt) {
alert("Success");
},
function(errorEvt) {
alert("error");
}
);
var ppsEncode = function(obj) {
var data = '', name, value;
for (name in obj) {
data += name + ':';
value = obj[name];
if (typeof value === 'string') {
data += ':' + value;
}
else if (typeof value === 'number') {
data += 'n:' + value;
}
else if (typeof value === 'boolean') {
data += 'b:' + value;
}
else if (typeof value === 'object') {
data += 'json:' + JSON.stringify(value);
}
data += '\n';
}
return data;
}
doSMSinvokation(ppsEncode);
My referance from Blackberry itself

Related

How to redirect to url within same context

I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":
router.get("/logout").handler((ctx) => {
if (ctx.user()!=null) {
ctx.clearUser()
//flash message
ctx.put("msg", "Logout succeed")
}
ctx.reroute("/login")
})
What I want, but url should be "/login":
Better to use(?):
ctx.response.putHeader("location", "/login").setStatusCode(302).end()
But there is different context. So I haven't flash message.
How to redirect to /login within same context?
Upd.
Question related to this issue
In order to work with flash messages you should add a cookie to the redirect with the content:
// this makes the message available to the client
ctx
.addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
.putHeader("location", "/login");
// perform the redirect
ctx.end(302);
Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 3000 });
if (!options.message) {
options.message = getFlashMessageFromCookie();
deleteFlashMessageCookie();
}
if (options.message) {
if (typeof options.message === "string") {
target.html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
function getFlashMessageFromCookie() {
return $.cookie("FlashMessage");
}
function deleteFlashMessageCookie() {
$.cookie("FlashMessage", null, { path: '/' });
}
};
And add a placeholder in your HTML like:
<div id="flash-message"></div>
And trigger it like:
$(function() {
$("#flash-message").flashMessage();
});

How to replace Angular2 Http to upload files?

The following code attempts to send a file from an Angular2 app. It always end-up in the REST API not being able to recognize the file in the request it is receiving. (Even if the content seams to be there !)
After spending hours searching StackOverflow and countless other online sources, i came to the conclusion that the most recent version of Angular2 Http module/service should now be capable of handling file uploads. (The fact that it wasn't able to do so in the past is just amazing !)
See this article or even this git sample.
If i am to use an external lib like ng2-file-upload, it needs to be able to replace Angular2::Http with as little modification as possible to the following code. (i.e. I cannot change the HTML form.)
Component.html
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" novalidate>
<label>Votre avatar !</label>
<input class="form-control" type="file" name="avatar" (change)="imageUpload($event)" >
Component.ts
imageUpload(e) {
let reader = new FileReader();
//get the selected file from event
let file = e.target.files[0];
reader.onloadend = () => {
this.image = reader.result;
}
reader.readAsDataURL(file);
}
onSubmit() {
if (this.image){
this.authService.setAvatar(this.image).subscribe(
d => {
//Do Nothing... Will navigate to this.router.url anyway so...
},
err =>{
this.errorMessage = err;
console.log(err);
}
);
}
}
authService.ts
setAvatar(image:any){
let form: FormData = new FormData();
form.append('avatar', image);
return this.http.post (Config.REST_URL + 'user/setAvatar?token=' +localStorage.getItem('token'), form,
{headers: new Headers({'X-Requested-With': 'XMLHttpRequest' })}
).catch(this.handleError);
}
REST_API Php (LARAVEL)
public function setAvatar(Request $request){
if($request->hasFile("avatar")) { // ALWAYS FALSE !!!!
$avatar = $request->file("avatar");
$filename = time() . "." . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300)->save(public_path("/uploads/avatars/" . $filename));
return response()->json(['message' => "Avatar added !"], 200);
}
return response()->json(['message' => "Error_setAvatar: No file provided !"], 200);
}
Content of the Request Payload (As seen from Chrome Inspect/Network)
------WebKitFormBoundary8BxyBbDYFTYpOyDP
Content-Disposition: form-data; name="avatar"
Should be more like...:
Content-Disposition: form-data; name="avatar"; filename="vlc926.png"
Content-Type: image/png
Turns out Angular2's Http can now send files... And it's super easy !.... I just can't believe there are just no documentation out there showing this !
Except this one. (Credits to MICHAƁ DYMEL)
The HTML
<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>
Component.ts
#ViewChild("fileInput") fileInput;
addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
this.uploadService
.upload(fileToUpload)
.subscribe(res => {
console.log(res);
});
}
}
The service.ts
upload(fileToUpload: any) {
let input = new FormData();
input.append("file", fileToUpload);
return this.http.post("/api/uploadFile", input);
}

Including and using Zend Service ReCaptcha in ZF2 (v2.3.3)

how to include Recaptcha service in zend framework 2?
I tried to do like this:
public function contactAction()
{
$formContact = new ContactForm();
$pubKey = 'mypubkey';
$privKey = 'myprivkey';
$recaptcha = new ZendService\ReCaptcha\ReCaptcha($pubKey, $privKey);
return array ('formContact' => $formContact, 'recaptcha' => $recaptcha);
}
but I discovered that ZendService\ReCaptcha is not present by default when you download the framework.
So, I downloaded it from here
https://github.com/zendframework/ZendService_ReCaptcha
and I placed it into vendor\zendframework\zendframework\library\zend together with the other parts of the library.
I tried to refresh the page but doesn't work again because it can't find the zend service recaptcha.
Fatal error: Class 'Application\Controller\ZendService\ReCaptcha\ReCaptcha' not found in C:\Program Files (x86)\xampp\htdocs\Zf-tutorial\module\Application\src\Application\Controller\IndexController.php on line 79
can someone help me? I thought it was simple to implement recaptcha, but it is not so ! thanks!
Add the zendservice-recaptcha module to your composer.json file and run an update:
{
...
"repositories": [
{
"type": "composer",
"url": "http://packages.zendframework.com/"
}
],
...
"require": {
...
"zendframework/zendservice-recaptcha": "*",
...
}
...
}
update composer :
php composer.phar update
This will install the module and configure the relevant class mapping and you will be able to access the classes by adding the use statements as with any other classes you use.
Even i tried recaptcha but with no success so implemented something different to refresh captcha and worked very well, try this once
resetCaptcha function:
$form = $this->getServiceLocator()->get('zfcuser_register_form');
$captcha = $form->get('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl() .
$captcha->getId() .
$captcha->getSuffix();
return $data;
ajax request :
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
var data = [];
var form = <?php $this->registerForm; ?>
data.push({name: "action", value: 'resetCaptcha'});
data.push({name: "params[form]", value: form});
$.post("<?php echo BASE_URL ?>/user/iajax", data,
function(data) {
$('#form_reg img').attr('src', data.src);
$('#captcha-id-hidden').attr('value', data.id);
}, 'json');
});
});
Html call :
<p class="refresh_captcha"><?php echo $this->formCaptcha($form->get('captcha')); ?>
<input type="button" id="refreshcaptcha" value="refresh">
</p>
You do not properly install the library ZendService\ReCaptcha.
your system write:
Class 'Application\Controller\ZendService\ReCaptcha\ReCaptcha' not found
You must:
placed it into vendor\zendframework\zendframework\library
In the file vendor/ZF2/library/Zend/Loader/StandardAutoloader.php insert string
$this->registerNamespace('ZendService', dirname(dirname((__DIR__)))
. '/ZendService');
in case self::AUTOREGISTER_ZF:
in the file init_autoloader.php insert string
$loader->add('ZendService', $zf2Path);.

upload a file using angular, express and mongodb's gridfs

I am new to these technologies and hence have limited knowledge on how to upload a file. During my research, I have seen ngUpload and other javascript/directive based solutions. However, I am trying the following and not sure what else I am missing to complete it.
I am trying to upload file after creating a blog using angular-express-blog application. I have the following code
In view.jade
fieldset
h5 Add Media
form(name='theForm', enctype="multipart/form-data")
.clearfix
label Document Name
.input: input(ng-model='form.docName', name='docName', type='text')
.clearfix
label File
.input: input(ng-model='form.file', type="file", name="file")
.actions
button(ng-click="uploadFiles('/page3files')") Upload Files
the controller, I do need to return to the uploadfile page hence, I am passing in /page3files.
$scope.uploadFiles = function( path ) {
//alert("upload files clikced");
$http.post('/api/uploadFile', $scope.form).
success(function(data) {
$scope.form.docName='';
$scope.form.file='';
$location.path(path);
});
};
In the express routes file
exports.uploadFile = function (req, res) {
console.log("doc name: " + req.body.docName);
console.log("file name: " + req.body.file.name);
console.log("file path: " + req.body.file.path);
res.json(true);
};
Unfortunately, I am getting an exception at req.body.file.name saying cannot read property 'name' of undefined.
Any assistance is much appreciated.
Thanks,
Melroy
for the $http.post() to be able to upload files you need to set some configurations.
headers : {'Content-Type': undefined},
transformRequest: angular.identity
You can use the simple/lightweight angular-file-upload directive that takes care of that for you.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim.
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
There are more info on the README page and there is a Demo page
You can send file data with FormData object. For Example:
HTML:
<fieldset>
<legend>Upload Video</legend>
<input type="file" name="photo" id="photo">
<input type="button" ng-click="uploadVideo()" value="Upload">
</fieldset>
JS:
$scope.uploadVideo = function () {
var photo = document.getElementById("photo");
var file = photo.files[0];
var fd = new FormData(); //Create FormData object
fd.append('file', file);
$http.post('/uploadVideo', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
// Do your work
});
};

Looking for working example of WP7 PhoneGap Facebook plugin for signin button

I've tried all the code at https://github.com/davejohnson/phonegap-plugin-facebook-connect
that is recommended by the phonegap community, but i keep running into errors trying to get it to work.
As you can see I'm using cordova 1.6.0 which maybe the problem?
i've added the script files to in my html page
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript" charset="utf-8" src="cdv-plugin-fb-connect.js">/script>
<script type="text/javascript" charset="utf-8" src="facebook_js_sdk.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
And I've added the ChildBrowserCommand.cs into the plugins directory.
I then added this to device ready listener with my authentic app id (the real id not shown here)
document.addEventListener("deviceready",onDeviceReady,false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
//document.getElementById("welcomeMsg").innerHTML += "Cordova is ready! version=" + window.device.cordova;
console.log("onDeviceReady. You should see this message in Visual Studio's output window.");
//fb connect sign in
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
console.log('Device is ready! Make sure you set your app_id below this alert.');
FB.Cookie.setEnabled(true); // this seems to be duplicate to 'cookie: true' below, but it is IMPORTANT due to FB implementation logic.
FB.init({ appId: "311961255484993", nativeInterface: CDV.FB, cookie: true });
login();
} catch (e) {
//alert(e);
console.log("Init error: " + e);
}
};
function login() {
FB.login(
function (response) {
if (response.session) {
console.log('logged in');
} else {
console.log('not logged in');
}
},
{ scope: 'email, read_stream, read_friendlists' }
);
}
The error i get is
Unable to locate command :: org.apache.cordova.facebook.Connect
Any help?
EDIT: I also realize it's coming from cdv-plugin-fb-connect.js in here but not sure why?
cordova.exec(function () {
var authResponse = JSON.parse(localStorage.getItem('cdv_fb_session') || '{"expiresIn":0}');
if (authResponse && authResponse.expirationTime) {
var nowTime = (new Date()).getTime();
if (authResponse.expirationTime > nowTime) {
// Update expires in information
updatedExpiresIn = Math.floor((authResponse.expirationTime - nowTime) / 1000);
authResponse.expiresIn = updatedExpiresIn;
localStorage.setItem('cdv_fb_session', JSON.stringify(authResponse));
FB.Auth.setAuthResponse(authResponse, 'connected');
}
}
console.log('Cordova Facebook Connect plugin initialized successfully.');
}, (fail ? fail : null), 'org.apache.cordova.facebook.Connect', 'init', [apiKey]);
},