Thursday, June 20, 2019

Kony Push Notification using FCM

Steps

1) Create new project in kony visualizer 8.x version.

2) Go to firebase console, create a new project and select android. Then provide the package name taken from kony visualizer->settings->native->android.

3) From firebase messaging part, note down the server key and sender id.

4) In kony visualizer, create functions for kony.push.register api with the sender id from firebase. and kony.push.setCallback api for all callback functions.

5) Go to kony mobile fabric -> Engagement. Click android and in the field for server key, provide the server key taken from firebase and save.

6) Publish application in mobile fabric.

7) Associate the fabric application to visualizer project.

8) Select FCM in push notification under Kony visualizer->settings->native->android.

9) Take build for android.

10) Once you call the kony.push.register api with the sender id, Your device will be registered in kony engagement server. So that from Adhoc, you will be able to send push notification to selected devices.

Program

var KMSPROP = {};
var pushCallbacks = {
onsuccessfulregistration: regSuccessCallback,
onfailureregistration: regFailureCallback,
onlinenotification: onlinePushNotificationCallback,
offlinenotification: offlinePushNotificationCallback,
onsuccessfulderegistration: unregSuccessCallback,
onfailurederegistration: unregFailureCallback
};

/*
 * @function setAllCallbacks
 * this function will set the call backs for push notification 
 */
function setAllCallbacks() {
try {
kony.push.setCallbacks(pushCallbacks);
} catch (err) {
kony.print("KMS Module" + JSON.stringify(err));
}
}
/*
 * @function registerKMS
 * this function will register the divice for GMS console and APS console using
 * register API
 */
function registerKMS() {
try {
//#ifdef android
KMSPROP.osType = "androidgcm"; // ostype to sent if it is android
var configRegister = {
senderid: "sender id from firebase"
};
//#endif
//#ifdef iphone
KMSPROP.osType = "iphone";
var configRegister = [0, 1, 2];
//#endif
//this will check whether the device is al
if (kony.store.getItem("isRegisteredForKMS") === undefined || kony.store.getItem("isRegisteredForKMS") === "" || kony.store.getItem("isRegisteredForKMS") === null) {
kony.push.register(configRegister);
}
} catch (err) {
kony.print("KMS Module" + JSON.stringify(err));
}
}
/*
 * @function regSuccessCallback
 * This function is registration success callback on successful registration of APS or GCM
 * this function is used to register to kony messaging  for push notification
*/
function regSuccessCallback(regId) {
try {
      alert("reg successful");
kony.store.setItem("isRegisteredForKMS", "true");
KMSPROP.deviceId = kony.os.deviceInfo().deviceid; // device id
KMSPROP.device_rec = kony.os.deviceInfo().deviceid; // unique key
var messagingSvc = KNYMobileFabric.getMessagingService();
messagingSvc.register(KMSPROP.osType, KMSPROP.deviceId, regId, KMSPROP.device_rec, successCallbackForSubscribe, failureCallbackForSubscribe);
function successCallbackForSubscribe(res) {
kony.application.dismissLoadingScreen();
kony.print(JSON.stringify(res));
}
function failureCallbackForSubscribe(err) {
kony.store.removeItem("isRegisteredForKMS");
kony.application.dismissLoadingScreen();
kony.print(JSON.stringify(err));
kony.print("Subscription Failed.");
}
} catch (err) {
kony.print("KMS Module" + JSON.stringify(err));
}
}
/*
 * @function regFailureCallback
 * This function is registration failure callback on failure registration of APS or GCM
 */
function regFailureCallback(errormsg) {
kony.print(errormsg);
kony.print("Registration Failed ");
}

/*
 * @function onlinePushNotificationCallback
 * This function is the callback for online push notification
 */
function onlinePushNotificationCallback(msg) {
try {
alert("push message received"+JSON.stringify(msg));
} catch (err) {
kony.print("KMS Module" + JSON.stringify(err));
}
}
/*
 * @function offlinePushNotificationCallback
 * This function is the callback for offline push notification
 */
function offlinePushNotificationCallback(msg) {
try {
alert("push message received"+JSON.stringify(msg));
} catch (err) {
kony.print("KMS Module" + JSON.stringify(err));
}
}

function unregSuccessCallback() {
kony.print("Unregisterd Succesfully!!");
}
function unregFailureCallback(errormsg) {
kony.print(" Unregistration Failed!!" + errormsg);
}

Note:  If you get package generation failed after selecting FCM in push notification, from firebase-> your apps, download the google-services.json file. Create a folder named "fcm" in project location->resources->mobile->native->android and paste the json file. Restart the visualizer and take build.

Sunday, March 10, 2019

Segment row slide animation in kony

//call this function in preshow()
function initCB(){
  flxTemp.setGestureRecognizer(2, {fingers: 1},animateRow);
}


function animateRow(widgetRef, gestureInfo, context){
  try{
   
   
    var animationObject = kony.ui.createAnimation(
    {"0":{"left":"0%","stepConfig":{"timingFunction":kony.anim.LINEAR}},
    "100":{"left":"-30%","stepConfig":{"timingFunction":kony.anim.LINEAR}}});
   
    var animationConfig = {
    duration: 0.2,
    fillMode: kony.anim.FILL_MODE_FORWARDS
    };
   
    var animationCallbacks = {"animationEnd":function(){
    }};
   
    var animationDefObject={definition:animationObject,config:animationConfig,callbacks:animationCallbacks};
   
     var row1 = {
    sectionIndex: context.sectionIndex,
    rowIndex: context.rowIndex
};
   
   
  var rowList = [row1];
  frmHome.segMain.animateRows({rows: rowList,widgets: ["flxFirst"],animation: animationDefObject });
   
  }catch(err){
alert("Error "+err);
  }
 
}

Wednesday, January 16, 2019

Taking iOS build in kony

How to Take i-os build:-

KAR file that means Karoke File.
from KAR file to generate the IPA file.
(Note:-
In Our Visualizer Plugins Doesn't Deleted.it is kept on same place.)

Steps to Take a i-os Build:-

1.Right Click that application shortcut
2.File location
3.in search box type - plugins ios
4.Copy Plug in & KAR file

  Here after we use mac System

5.Paste that KAR file into MAC Explorer.
6.An MAC Explorer Produce once JAR file from KAR file.
7.Double click that JAR file that produce another one ZIP file.
8.Extract that ZIP file.
9.On Version wise some files are in same name.so based on that you have
to Extarct that.
10.on Right side .gen file has there.
11.Open Terminal
12.Go that gen file directory Drag and drop the gen file into Terminal
click Enter it will produce Address.

13.Type the Command "perl extract -pl" then Drag & Drop that build file
Click Enter.it will produce json file.

14.After DONE "VMAWithKonyLib" double click that it will open the another
prompt
15.It run's only on MAC in-build simulator
16.If you want to take IPA file for iphones you have to give "UDID" number
to that BUILD
17.For Taking i-os build or .IPA file you have to give Authorized Certificate
through ONLINE.



Sunday, December 9, 2018

Performing a search in a segment using with textbox

//call this function in ontextchange event of textbox
function search(){
  try{

    if(frmCountryCodeList.txtSearch.text !== ""){

      var searchArr = [];

      for(var i = 0; i<gbl_country_code.length; i++){
        if(gbl_country_code[i].lblCountry.toLowerCase().includes(frmCountryCodeList.txtSearch.text.toLowerCase())){
          searchArr.push(gbl_country_code[i]);
        }
      }
      frmCountryCodeList.segCountryCode.setData(searchArr);

    }else{
      frmCountryCodeList.segCountryCode.setData(gbl_country_code);
    }


  }catch(err){
    dialogue("Err "+err);
  }
}

Disabling kony default loader

//call this function in postappinit
function avoidDefaultLoader(){
  try{
    kony.application.setApplicationBehaviors({ "hideDefaultLoadingIndicator":true});
  }catch(err){
    dialogue("Error "+err);
  }
}

Opening gallery and select and set image to an image widget

function gallerImages(){
  var querycontext = {mimetype:"image/*"};
  var Status = kony.phone.openMediaGallery(onselectioncallback, querycontext);

  function onselectioncallback(rawbytes)
  {
    frmProfile.flxCameraGallery.setVisibility(false);
    if(rawbytes !== null){
      base64Str = kony.convertToBase64(rawbytes);
      frmProfile.imgProfile.base64=base64Str;
      frmDashBoard.imgMenuProfile.base64 = base64Str;
    }else{
             alert("Please select image");
    }
  }
}

Getting card number format in textbox

var str, strc;

//call this function in ontextchange
function cardNumberFormat(){
  try{
    if(str !== null && str !== undefined){
      if(frmPaymentMode.txtCardNumber.text.length > str.length){
        if(frmPaymentMode.txtCardNumber.text.length ===4){
          frmPaymentMode.txtCardNumber.text = frmPaymentMode.txtCardNumber.text+" ";
        }else if(frmPaymentMode.txtCardNumber.text.length ===9){
          frmPaymentMode.txtCardNumber.text = frmPaymentMode.txtCardNumber.text+" ";
        }else if(frmPaymentMode.txtCardNumber.text.length ===14){
          frmPaymentMode.txtCardNumber.text = frmPaymentMode.txtCardNumber.text+" ";
        }
      }else{

      }
    }
    str = frmPaymentMode.txtCardNumber.text;

  }catch(err){
    dialogue("Error "+err);
  }
}

Getting current position and displaying in map

function getPosition(){
    var positionoptions = {timeout: 15000};
    frmLocation.mapLocation.zoomLevel=15;
    kony.location.getCurrentPosition(successcallback, errorcallback, positionoptions);
}


function successcallback(position){
  var lat = position.coords.latitude;
  var long = position.coords.longitude; 
  var locationData = [{
           lat: lat,
       lon : long,
       image : "dest.png",
           desc: "your location",
           name: "location"
        }];
//setting current position in map
  frmLocation.mapLocation.locationData = locationData;
  frmLocation.show();
}

function errorcallback(positionerror){
    var errorMesg = "Error code: " + positionerror.code;
    errorMesg = errorMesg  + " message: " + positionerror.message;
    alert(errorMesg);
  frmLocation.show();
}

Internationalization in kony

// for changing default locale
function changeLanguage(){
  try{
    var lang = frmLanguages.sgmLanguages.selectedRowItems[0].lblLanguage;
    alert(lang);
    if(lang === "English"){
      kony.i18n.setDefaultLocaleAsync("en_US", onsuccesscallback, onfailurecallback);
    }else if(lang === "Hindi"){
      kony.i18n.setDefaultLocaleAsync("hi_IN", onsuccesscallback, onfailurecallback);
    }else{
      kony.i18n.setDefaultLocaleAsync("te_IN", onsuccesscallback, onfailurecallback);
    }
  }catch(err){
    dialogue("Error "+err);
  }
}




function onsuccesscallback(oldlocalename, newlocalename){

  alert("success "+oldlocalename +" "+newlocalename);
}

function onfailurecallback(errCode, errMsg){
  alert("failure "+errCode +" "+errMsg);
}

//for dynamically changing text
frmRecharge.headers[0].lblHeader.text = kony.i18n.getLocalizedString("recharge");

Auto scrolling paging segment

function bannerAutoScroll(){
  try{
    kony.timer.schedule("paychargeTimer", changeBanner, 5, true);
  }catch(err){
    dialogue("Error "+err);
  }
}

var banner_count = 0;

function changeBanner(){
  try{

    banner_count+=1;
    if(banner_count > 2){
      banner_count = 0;
      frmDashBoard.segBanner.selectedRowIndex = [0,banner_count];
    }else{
     
      frmDashBoard.segBanner.selectedRowIndex = [0,banner_count];
    }

  }catch(err){
    dialogue("Error "+err);
  }
}

Moving car animation in desktop application

var car_rev = false;

function moveCar(eventobject) {
    function MOVE_ACTION____dfd6b03fc1d949e5ac881fe735e6eccf_Callback() {
      car_rev = !car_rev;
     
      if(car_rev){
        frmCar.imgCar.src = "carleft.gif";
        frmCar.imgCar.height = "60%";
        frmCar.imgCar.animate(
    kony.ui.createAnimation({
        "100": {
            "left": "-30%",
            "stepConfig": {
                "timingFunction": kony.anim.EASE
            }
        }
    }), {
        "delay": 0,
        "iterationCount": 1,
        "fillMode": kony.anim.FILL_MODE_FORWARDS,
        "duration": 10
    }, {
        "animationEnd": MOVE_ACTION____dfd6b03fc1d949e5ac881fe735e6eccf_Callback
    });
      }else{
        frmCar.imgCar.src = "movingcar.gif";
        frmCar.imgCar.height = "30%";
        frmCar.imgCar.animate(
    kony.ui.createAnimation({
        "100": {
            "left": "100%",
            "stepConfig": {
                "timingFunction": kony.anim.EASE
            }
        }
    }), {
        "delay": 0,
        "iterationCount": 1,
        "fillMode": kony.anim.FILL_MODE_FORWARDS,
        "duration": 10
    }, {
        "animationEnd": MOVE_ACTION____dfd6b03fc1d949e5ac881fe735e6eccf_Callback
    });
      }
     
    }
    frmCar.imgCar.animate(
    kony.ui.createAnimation({
        "100": {
            "left": "100%",
            "stepConfig": {
                "timingFunction": kony.anim.EASE
            }
        }
    }), {
        "delay": 0,
        "iterationCount": 1,
        "fillMode": kony.anim.FILL_MODE_FORWARDS,
        "duration": 10
    }, {
        "animationEnd": MOVE_ACTION____dfd6b03fc1d949e5ac881fe735e6eccf_Callback
    });
}

Moving a button according to tap or finger movement

//setting pan and tap gesture to the man flex
function setGest(){
  var tapdata = {fingers:1,taps:1};
var pandata = {fingers: 1, continuousEvents: true};

frmGesture.flxMain.addGestureRecognizer(1, tapdata, gestureFunc);
frmGesture.flxMain.addGestureRecognizer(4, pandata, gestureFunc);
}

//moving button position in the callback
function gestureFunc(widgetRef, gestureInfo, context){
  try{

   
    if(gestureInfo.gestureType === 1 || gestureInfo.gestureType === "1" ){
      frmGesture.btn.left = gestureInfo.gestureX * 2/3;
      frmGesture.btn.top = gestureInfo.gestureY * 2/3;
    }else{
        frmGesture.btn.left = gestureInfo.gestureX * 2/3;
      frmGesture.btn.top = gestureInfo.gestureY * 2/3;
    }
  }catch(err){
    alert("Error "+err);
  }
}

Dynamic setting section data and expand or collapse on click

var headerTittle = ["GENERAL","SECURITY","OTHERS"];
    var rowTittles = [
      {
        "rowTtile":"Change User ID",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"Change Password",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"User Information",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"Set Default Account",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"Block Card",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"Deactivate Device",
        "Category":"GENERAL"
      },
      {
        "rowTtile":"Change Mobilepin",
        "Category":"SECURITY"
      },
      {
        "rowTtile":"FingerPrint",
        "Category":"SECURITY"
      },
      {
        "rowTtile":"Facial Recognition",
        "Category":"SECURITY"
      },
      {
        "rowTtile":"Notification",
        "Category":"OTHERS"
      },
      {
        "rowTtile":"Change Language",
        "Category":"OTHERS"
      },
      {
        "rowTtile":"Terms & Condition",
        "Category":"OTHERS"
      },
      {
        "rowTtile":"About",
        "Category":"OTHERS"
      },
      {
        "rowTtile":"FAQ",
        "Category":"OTHERS"
      },
    ];


function segSetting(){
  try{
    var arr = [];
 
 
    for(var i =0; i<headerTittle.length; i++){
   
      var arrRow = [];
   
      var json = {"lblHead":headerTittle[i]};
   
      arr.push([json]);
   
      for(var j = 0; j<rowTittles.length; j++){
        if(headerTittle[i] === rowTittles[j].Category){
          var rowObj = {"lblText":rowTittles[j].rowTtile, "btnText":{"text": rowTittles[j].rowTtile}, flxSeg:{height: "0%"}};
          arrRow.push(rowObj);
        }
      }
   
      arr[i].push(arrRow);
   
    }
 
    frmSeg.segSeg.setData(arr);
 
  }catch(err){
    alert("Error "+err);
  }
}


function segShowRow(context){
  try{
 
    var index = context.sectionIndex;
 
    var data = frmSeg.segSeg.data;
 
    for(var i = 0; i < data.length; i++){
      if( index === i){
     
        for(var j = 0; j < data[i][1].length; j++){
       
          if(data[i][1][j].flxSeg.height === "0%"){
            data[i][1][j].flxSeg.height = "7.5%";
          }else{
            data[i][1][j].flxSeg.height = "0%";
          }
       
        }
     
      }
    }
 
    frmSeg.segSeg.setData(data);
 
  }catch(err){
    alert("Error "+err);
  }
}

Wednesday, October 31, 2018

Validation using regular expression in Javascript

Validation is an essential process in any mobile or web applications where we use forms. So I am sharing some ideas on how to do some basic validations ion Javascript using regular expressions. As this is for Javascript, there won't be much changes in other languages also.

Some regular expressions for basic validations.

            "/\d/g"             : For matching any digits if present in the string.
            "/\s/g"             : For matching any whitespace character if present in the string.

            "/[a-zA-Z]/g"    : For matching any letters if present in the string.
            "/[0-9]/g"         : For matching any numbers from 0-9 if present in the string.

            "/[abc]/g"         : will check for letters inside the square bracket if present throughout the string.
            "/[a-b]/g"         : will check for items between the range given inside square bracket if present throughout the string.

            "/[a|b]/g"         : will check for any of the items given inside square bracket if present throughout the string.


Test Method

We can use mainly Javascript test() method for pattern checking.

            var pattern = new RegExp("[a-zA-Z]+");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);

this will print true as letters are present inside the string str;

like this for checking digits present inside string, we can perform

            var pattern = new RegExp("/\d/g"); OR var pattern = new RegExp("/[0-9]/g");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);

for checking whitespace present inside string, we can perform

            var pattern = new RegExp("/\s/g");
            var str = "Hello World";
            var res = pattern.test(str);
             alert(res);

Replace method

If we want to find a pattern in a string and change it with something else, we can use the Javascript replace() method.

If we want to remove all the whitespace characters from the string, we can perform it by

            var pattern = new RegExp("/\s/g");
            var str = "Hello World";
            var res = str.replace(pattern, "");

This will remove all the whitespace characters with empty, like this we can remove any pattern found inside a string, or replace the pattern with some other patterns