Category Archives: Software Development

Anything to do with developing Apps, Desktop application, server application, API etc.

Apache Cordova Gotchas

Few months ago I have started developing a hybrid mobile app using Cordova. I encountered a lot of headaches and frustrations using this technology but the more time you spend on it, the better you get at googling about your issues (lol). Here I list all my headache and quirk fixes I found make it at least bearable to develop for Cordova.

  • Apache Cordova is Phonegap/Ionic . Phonegap and Ionic builds on top of Cordova so most likely ionic or phonegap plugin will work with Cordova.
  • Push notifications.  Use Google Firebase (https://firebase.google.com/docs/cloud-messaging) messaging platform. You create an application for free app for iOS and Android. You must provide the same app ID you set in your application. Use this plugin https://www.npmjs.com/package/cordova-plugin-fcm-with-dependecy-updated , as this allows you to avoid build errors.
  • Use the latest version of Cordova. If for some reason the current version is spitting out errors , use Cordova 8. npm install -g cordova@8.1.2 as this is a stable version.
  • Accessing photos , camera, videos and files. If by any chance you need to access the local resources of the device. Use
    cordova-plugin-file plugin. Take note android/ios has different path scheme. Use window.resolveLocalFileSystemURL to access the local file to get the blob or base64 encoded data eg. data://…  Dont forget that also when you take a photo, the image orientation might not be correct. Use https://github.com/blueimp/JavaScript-Load-Image , this library will sniff the EXIF data and return the correct orientation of the image as a BLOB.
  • Fetch() is a function that lets you grab the blob of the file to be inserted into formData to submit files to the server. It works for base64 encoded data or localhost file such as ‘/path/to/something’
  • Keyboard is recently my main issue making chat system by having a text field on top of soft keyboard. Use cordova-plugin-keyboard (iOS) , cordova-plugin-ionic-keyboard (Android) . Make sure you have cordova-plugin-ionic-webview installed otherwise on iOS you will see a black panel when keyboard is up. And since you are using ionic webview, you must add <preference name=”ScrollEnabled”value=”true”/> to enable body scrolling particularly with iOS.
  • Chat feature , creating a chat feature in cordova is hard/tricky. Remember when the soft keyboard in iOS is up , position: fixed wont work anymore. Remember to Keyboard.shrinkView(true); (disable by default) for the view to shrink and make the div bottom: 0px to attach to the keyboard. It will also help to
    Keyboard.disableScrollingInShrinkView(true); to disable any scrolling while the soft keyboard is up. Put them back to normal afterwards.

Apache Cordova – Set up Windows & Mac

I have finally entered the world of mobile app. Namely Cordova.  Before anything else … Its a pain. Nothing like elbow grease! For anyone reading this section, and you are starting out on your journey with hybrid-app, especially when you develop in Visual Studio. DONT DO IT.  Anyways as I learn the hard way, I thought VS can make the installation of packages easy, as it turns out It did not.

How to set up your Windows for Apache Cordova (Not in order)

  1. Install Node.JS,
    • Run npm install -g cordova
  2. Install Java (JDK)
    • Add the /bin folder to the PATH
    • Add a new environment variable named JAVA_HOME and set value to the JDK path.
  3. Install Gradle (https://gradle.org/install/)
    • Add the /bin folder to the PATH
  4. Install Android SDK (https://developer.android.com/studio/)
    • Add the [sdk folder]/tools folder to the PATH
    • Add the [sdk folder]/platform-tools folder to the PATH
    • Add a new environement variable named ANDROID_HOME and set the value to the SDK path folder.
  5. Then run “cordova requirements” to see whether you have installed everything right.
  6. Now you are ready to create your first mobile hybrid app using HTML/CSS/JS.
    • run “cordova create FolderName com.yourdomain.app MyAppName”

How to set up your Mac for Apache Cordova (Not in order)

  1. Check this link for detailed info: https://www.fiznool.com/blog/2017/05/29/a-guide-to-installing-cordova-on-your-mac/
  2. Install Xcode from the website or app store.
    • Run “xcode-select  –install” on the terminal. This will install cli for Xcode.
  3. Install Java JDK http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  4. Install Android SDK https://developer.android.com/studio/index.html#command-tools
    • Extract the content(/tools) under /android anywhere in your drive system.
    • Run cmd
      • cd ~/android/tools/bin
        ./sdkmanager "build-tools;25.0.3" "emulator" "platforms;android-25" "platform-tools" "system-images;android-25;google_apis;x86" --verbose
        ./avdmanager -v create avd -n x86 -k "system-images;android-25;google_apis;x86" -g "google_apis"
    • This will generate /build-tools, /emulator, /platforms and /system-images.
  5. Install Gradle https://gradle.org/releases
    • Unzip the gradle content inside the android we created.
  6. Configure ANDROID_HOME env variable and PATH.
    • Open ~/.bash_profile and enter and save.
    • export ANDROID_HOME=$HOME/android
      export PATH=$PATH:$ANDROID_HOME/emulator:$ANDROID_HOME/gradle/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools/bin
    • Depends where you extracted /android-sdk, /gradle and android tools.
  7. Install Cordova via NPM “npm install -g cordova”
  8. Install iOS-sim and iOS-deploy “npm install -g ios-sim ios-deploy” Lets you deploy to simulator and device.
  9. Then you can start creating projects using “cordova create myapp me.domain.myapp myapp”
  10. After you created your app and adding a iOS platform. You would build it “cordova build ios”. And the .xcworkspace in the platforms/ios/ folder must be opened in Xcode and you would build it from Xcode.

Notes: AVD Manager manages virtual devices while SDK Manager manages APIs currently installed on the system.

References:

https://docs.microsoft.com/en-us/visualstudio/cross-platform/tools-for-cordova/publishing/publish-to-a-store?view=toolsforcordova-2017

—-

Troubleshooting:

  1. Error: Cordova Could not reserve enough space for 2097152KB object heap

—-

Tips

  1. Run “cordova emulate android” to deploy application to virtual emulator device.
  2. If you are using AVD(Android Virtual Device). And run your emulator and get “PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT”. Set your environment to where your android-sdk is, and this should fix it. Note: You would need HAXM Accelerator and you will need Hyper-V disabled if you are using Windows. Download and install this in the SDK Manager.

And just bite on something and hope for the best. You will want look how to deploy and debug your app. I recommend using Visual studio code -> cordova plugin. It allows you to have a emulator for the browser to just hammer on development.

Good luck!

Project/CMS Development Workflow

Lately I been pondering about CMS development since I work alone on projects. It didnt matter but then what if I dont work alone? What if we use WP or Drupal on our website. I read a lot of articles how it can be done.

I keep getting swept away about this article and how they are doing it. Then I realised , well I am already learning Docker/Vagrant. But its just fixing one issue anyways. Here I most of the issue encounters when developing a project be it a CMS or a stand alone one.

  • Setting up development-server ENV. This includes the server, this is where Docker comes in.
  • Setting up development set-up , the stacks you use for your project SPA, a plugin for CMS, theme , etc. (try to include unit testing)
  • Database migration set up. You cant just develop a database driven project without thinking how you can easily migrate your database schema, required data , etc. It is as important as your main application itself.
  • Using version control. You also have to think what files needs to be included to your repository. If its a public repo and your project is a public facing site, you might want to have .gitignore and exclude config files and other folders like node_modules etc.
  • Above has although bullet-ed does not mean straight forward. There is a lot of separation that needs to be done to make your workflow manageable and understandable for you(or your team).
  • Deployment. And high overview how its going to work after we set up the development side. We DEVELOP -> PUSH TO GIT -> AUTOMATION SERVER (eg. Jenkins) -> FEEDBACK TO DEVELOPER(testing etc) -> CREATE IMAGE FROM DOCKER -> DEPLOY TO PRODUCTION (CLOUD)
  • There is a lot in deployment , I mean a LOT of moving parts. But in the end, you do it often and hopefully like driving it becomes second nature until another NEW KID in town comes along. Such life for us Technologizt.

Learning Python: Gunicorn

Just putting this on here little quick.

What is Gunicorn? Apparently its sort of like a middle man between your user and application. Python is good and all handling request but its not made to be a web server handling 1000s or more of requests. For eg. Flask application can handle several request at ones locally. Web servers are good with that.

So the workflow pretty much like this:

[USER] -> [LOAD BALANCER (eg. nginx) ] -> [WEB SERVER LIKE (GUNICORN) ] -> [FLASK APP]

Very intuitive indeed!

Learning Python: Arguments, *args and **kwargs and Decorators

While reading through python. I came across some python only terms. And a very odd syntax using * and **.  And then there is this @ symbol called decorator.

Positional and Keyword Arguments 

Lets start with positional argument. This is pertaining to how a normal function with arguments is define.

# POSITIONAL ARGUMENT (conventional)
def myfunc(a,b,c):
   print a + b + c
myfunc(1,2,3)
# Output: 123
""" 
In this example a normal function is called , with their argument in order of a ,b ,c. This is positional and very common in any programming languages.
""" 
# KEYWORD ARGUMENT
def myfunc(a,b,c)
  print a + b + c
myfunc(c=3,b=2,a=1)
# Output: 123
"""
In this example same function definition, but the arguments are reflecting the argument names in the function thus the same output regardless of order.
"""

*args and **kwargs (unpacking)

Now lets look at *args, in other programming languages we can have optional arguments like in C# eg. main(string[] arg) or C++ main(int argc, char [] *argv) or main(int argc ,char ** argv).

So its basically similar with python see below:

def myfunc(*argv)
  argc = len(argv)
  for x in argv:
    print (x)
myfunc(1,2,3)
# output: 
1
2
3

** args is a bit similar above. It lets the caller specify the name of the argument. Confused? See below

def myfunc(**kwargs)
  print (a + b + c)
myfunc(a=1,b=2,c=3)
# Output: 123
# See what happens there? another way to access is
def myfunc(**kwargs)
  for key in kwargs:
    print (kwargs[key])
myfunc(a=1,b=2,c=3)
# Output: 
1
2
3
# You can also use to unpack collections and provide to the function
# using *args for a list or tuple
def myfunc(arg1, arg2, arg3):
  print (arg1 + arg2 + arg3)
mytup = (1,2,3)
myfunc(*mytup)
# Output: 123
# using **args for dictionary
def myfunc(**args):
  print (arg1 + arg2 + arg3)
mydict = {"arg1":1, "arg2":2, "arg3":3 }
myfunc(**mydict)
# Output: 123

@ Decorators

We will start with an example first below as this is the best way to explain it.

def mydecor(another_func):
    print ("Im in first")
    another_func()
    print ("Im in last")
@mydecor
def thisfunc():
    print ("I am in the middle")
thisfunc 
# Note: Do not call it like this thisfunc() check this for information:
https://www.thecodeship.com/patterns/guide-to-python-function-decorators/
#What is happening is another_func() will call the "thisfunc" function thus you dont need the "()" when calling it.
# Output:
Im in first
Im am in the middle
Im in last

Learning Python: List, Tuple, Dictionary and Set

Taken from w3schools.com. These are collections in Python

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
a_list = ["I","am","list"] # a_list[0]
for x in a_list:
   print x
-----------
a_tuple= ("I","am","tuple") # a_tuple[0]
// Loop save as above
-----------
a_set  = {"I" , "am" , "set"} # to access you need to iterate through it eg. get_i = next(iter(a_set))
for x in a_set:
   print x
-----------
a_dict = {"say":"I am", "respond": "dict"}  # a_dict["say"]
for name, value in a_dict.items():
   print(name + ' says ' + str(value))

This is a quick overview how to use these array like objects. I know this is very basic but since in the real world development we will most likely use one of these collections.

Learning Python: Class Object, Inheritance and Comments

I’m going to start learning python as a side hobby. So with all upcoming python related topics will have the title “learning”. Anyways the syntax of python is fairly straight forward but there are some of those bits that is not “fairly” straight forward. Like declaring a class object.

In python  depending on the version , there is an old style class and new style class. Old style don’t have inheritance but new style do.

# old style
class myClass():
  pass
# new style
class myClass2(Object) # all class inherits Object
  pass
# inheritance
class myClass3(myClass, myClass2)
  pass

The new style class in here has “Object” as base class. All class inherits from Object.

Thats it for class.

By the way comments in python is # and multi-line comments is a little weird but like this

# One line comment
"""
 Im a multi-line comment, and please dont indent this block as it becomes an error.
"""

YAML

Meet Uncle Yammy, or Yamel or Yamil?

I been using JSON and XML as my standard go to objects for as long as I can remember. They are both very capable. But I think I need to give YAML a try too as its good for storing very simple to very complex representation of your data.

The syntax? [ my_yaml.yml ]

PROPERTY_NAME: VALUE

Thats it. Yaml is also structured with indentation. Its actually pretty straight forward. Theres also parsers available already to use yml type files.

Please see video below by Giraffe Academy for more syntax specification

Programmer Code Guidelines

Been reading lots lately and never actually put into writing how I write my code. First thing first, variety of things and habits what you should keep in the back of mind.

Functions and Methods I’ve been writing functions and methods and never in my mind try to stop between the difference. Here is what I’ve learn about functions

  • Functions should be stateless and only cares about the argument being passed.  Can return a value or just do any work. Mostly use for utility helpers.
  • Methods are usually part of an object. When methods are called it should change a state or depends on the state the object belongs to.

Arguments pass as Copy or Reference When passing an argument to a method or function, should we consider passing a value or a reference? Passing a value means creating a copy of the argument that can increase memory usage, passing a reference avoid this. This is basically useful when passing a resource reference value.

Modularity Write codes in a modular way, this decreases headaches of debugging later on. Making it modular allows for add ons and modules to be added later on. Modularity is separation of functions and logic  in your code. If you can have separate files for each function is ideal.

Naming Convention make sure to adhere to a convention in declaring functions , objects and variables. I have decided to use this convention for general programming, although different conventions works for different  languages. For C# and windows related code, function name starts with capital letter. And private property starts with “_” underscore. For other things I use, “_” underscore for variables and camel casing for functions. Classes starts with capital letter.