My experience on my daily works... helping others ease each other

Showing posts with label Web-based application. Show all posts
Showing posts with label Web-based application. Show all posts

Monday, February 10, 2025

JHipster vs Vaadin vs Spring Boot - Choosing your framework

 



Java frameworks provide pre-written code and tools that simplify the development of Java applications. They handle common tasks like database interaction, web request handling, and user interface creation, allowing developers to focus on the unique logic of their applications. Frameworks promote code reusability, consistency, and best practices, ultimately speeding up development and improving application quality. They range from lightweight libraries to full-fledged platforms that dictate the structure of your application.


Which ones are suitable for you?

Okay, let’s start with a brief overview of the frameworks.

1. Spring Boot

Spring Boot is not strictly a full-stack framework in the same way as the others. It’s more accurately described as a microframework or a toolkit built on top of the larger Spring Framework. Its primary goal is to drastically simplify the setup and configuration of Spring applications. Think of Spring Boot as the express lane for Spring development.

Key Features:

  • Auto-configuration: Spring Boot automatically configures many beans (objects managed by Spring) based on dependencies in your project. This reduces the amount of manual configuration you have to do.
  • Embedded Servers: Easily embed Tomcat, Jetty, or Undertow directly into your application, making deployment simpler.
  • Spring Boot CLI: A command-line interface that further simplifies development tasks.
  • Spring Initializr: A web-based tool for quickly bootstrapping new Spring Boot projects.
  • Use Cases: Spring Boot is ideal for building REST APIs, microservices, and any backend component where you need the power and flexibility of the Spring ecosystem.

2. JHipster

JHipster takes Spring Boot and combines it with powerful code generation capabilities. It’s a full-stack application generator that helps you create modern web applications with Spring Boot on the backend and popular JavaScript frameworks (Angular, React, or Vue.js) on the front end.

Key Features:

  • Full-stack code generation: Generates both backend and frontend code, including authentication, database integration, and basic CRUD (Create, Read, Update, Delete) operations.
  • Microservices support: Can generate applications designed for a microservices architecture.
  • Blueprint architecture: Allows for customization and extension of the generated code.
  • Use Cases: JHipster is perfect for rapidly prototyping full-stack applications, especially when you want to use Spring Boot and a modern JavaScript framework. It’s less ideal for very small, simple projects where the overhead of JHipster might be too much.

3. Vaadin

Vaadin is a full-stack Java web framework focused on building rich and interactive web UIs. It offers two main approaches:

  • Vaadin Flow: Allows you to build UIs entirely in Java, without writing HTML or JavaScript directly. Vaadin handles the rendering on the client-side.
  • Hilla: A newer approach that combines a Spring Boot backend with a reactive TypeScript frontend.

Key Features:

  • Component-based architecture: UI elements are represented as reusable Java components.
  • Server-side rendering (Vaadin Flow): UI logic is executed on the server, which can simplify development for Java developers. Hilla uses client-side rendering.
  • Rich set of UI components: Vaadin provides a wide range of pre-built UI components, from simple buttons to complex grids and charts.
  • Use Cases: Vaadin is well-suited for building complex, data-driven web applications where a rich user interface is essential. It’s a good choice for Java developers who prefer a Java-centric approach to UI development.

Core Focus, Strength and Weaknesses

1. Spring Boot

  • Core Focus: This is the foundation. Spring Boot simplifies building standalone, production-ready Spring applications. It handles a lot of the boilerplate configuration, making it easier to get a Spring project up and running quickly. Think of it as the engine of your application.

Strengths:

  • Speed: Rapid development with auto-configuration and embedded servers.
  • Flexibility: Works well with various databases, cloud platforms, and other technologies.
  • Mature and Widely Used: Huge community support, extensive documentation, and a vast ecosystem of libraries.

Weaknesses:

  • Not a Full-Stack Solution: You’ll need to choose and integrate your own frontend technologies (like React, Angular, or Vue.js).
  • Learning Curve: While Spring Boot simplifies things, understanding the underlying Spring framework can still take time.

2. JHipster

  • Core Focus: A code generator that helps you quickly create full-stack web applications with Spring Boot on the backend and popular JavaScript frameworks (Angular, React, Vue.js) on the frontend.

Strengths:

  • Rapid Prototyping: Generates a complete application with authentication, database integration, and basic CRUD operations in minutes.
  • Best Practices: Uses well-established technologies and patterns.
  • Microservices Support: Can generate applications designed for a microservices architecture.

Weaknesses:

  • Complexity: Can generate a lot of code, which might be overwhelming for smaller projects or developers new to the technologies.
  • Less Control: You have less control over the initial setup compared to building everything from scratch.
  • Maintenance: Upgrading generated applications can be challenging.

3. Vaadin

  • Core Focus: A full-stack Java web framework that lets you build rich, interactive web UIs with Java. It offers two main approaches:
  • Vaadin Flow: Build UIs entirely in Java, without writing HTML or JavaScript.
  • Hilla: Combines a Spring Boot backend with a reactive TypeScript frontend.

Strengths:

  • Productivity: Vaadin Flow’s Java-centric approach can be very efficient for Java developers.
  • Type Safety: Strong type safety throughout the development process.
  • Excellent UI Components: Provides a wide range of pre-built UI components.

Weaknesses:

  • Steeper Learning Curve: Vaadin has its own way of doing things, so there’s a learning curve.
  • Less Flexibility: Compared to Spring Boot, Vaadin is more opinionated about how you structure your application.
  • Performance: Vaadin Flow’s server-side rendering can sometimes lead to performance issues in complex applications.

Share:

Sunday, April 26, 2020

Improving your Telegram Security


Telegram’s user continues to increase and recently it reaches 400 million user per month
Since its birth, there are many features added plus friendly API allowing various innovative ideas add-in to its base. 



But, having lots of features may also result in lots of possibilities for hacking. One of the many features that may be wrongly used is the Automatic Media Download. 

As noob @ beginner, many do not realize it until their phone or PC slow due to disk space has shrunk as telegram keeps on automatically download all files. 

The most scarier is that the auto-play anything including GIF, video, and audio. All this can be used by hackers to insert a code and inject it upon executed/run by telegram.

However, luckily telegram allow us to modify the setting. Here are the steps to change it:
  1. Go to your telegram setting and choose Advance
Telegram setting window
2. At the Advance screen, go to Automatic media download section
In the Advance setting
3. Click In private chats
In automatic media download setting
4. In the setting, click all the slide-tick to disable it (or you can choose whichever you want to enable or disable). You can even reduce the size to increase the protection rate.

5. Continue the process for all settings within the Automatic media download section.



That’s all.. you are ready to go and you shall be safe.
Share:

Tuesday, February 25, 2020

List of User-Agent for browser compatibility

There are occasions when you would access some website, it does not support your browser. Either Chrome, Edge, Firefox, etc. This mostly applied to old systems or system that is using old technology, framework or library.
What you can do? You already upgrade your browser and you have installed many browsers and it still does not work properly.
The only solution is to change your user agent setting of the browser.
For instance 
  1. in Safari: On the menu bar, go to Develop -> User Agent and select from the list. If there are none, choose Other and enter the user agent setting.
  2. in chrome: refer https://winaero.com/blog/change-user-agent-chrome/
  3. in firefox: refer https://winaero.com/blog/change-user-agent-firefox/
Here are the list of user-agent code you can use
From https://www.whatismybrowser.com/guides/the-latest-user-agent/internet-explorer
Share:

Monday, January 13, 2020

Disruptive UI/UX - The new interactive design of a website

The faces of a website have evolved drastically from normal static one page to multiple page interactive and so on. With Big Data and ML, comes chatbot and more interactive website which more customer engaging concept.

It no time, we will definitely view a website through the Augmented Reality concept. Just read the name on a billboard, and then you will get to see the whole company profile in AR mode. Well, while waiting for this to happen, let us take a look at few revolutionize user engaging designs of a website.

As shared by Bruno Simon at https://bruno-simon.com/


Whom also the master of behind many 'abnormal' website like Orano


and Prior Holding



Go ahead browse the website and you will feel different.




Share:

Sunday, November 17, 2019

Setting up Laravel with Homestead on Mac

First - Don't trust your VirtualBox
Second - Focus on your Terminal only

Then follow the instruction here:
https://www.danwalker.com/setting-up-a-laravel-homestead-box/

if the first one fails, you can follow here https://petericebear.github.io/installing-laravel-homestead-osx-20160514/

Finally, you can take a look at the documentation https://laravel.com/docs/6.x/homestead or start reading the step at https://laravel.com/docs/6.x/installation

Just remember - virtualbox is there for nothing if you follow the instruction from Dan Walker :)

Basically (after you install virtualbox, vagrant and git)
1. Install the Homestead
2. Then, go to Homestead folder and run vagrant up (after you configure Homestead.yaml - follow Dan Walker steps)

Homestead % sudo vagrant up
Password:
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Checking if box 'laravel/homestead' version '8.2.1' is up to date...
==> homestead: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> homestead: flag to force provisioning. Provisioners marked to run always will still run.
Homestead % sudo vagrant provision
==> homestead: Running provisioner: file...
    homestead: /Users/mylap/Homestead/aliases => /tmp/bash_aliases
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: mariadb because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: ohmyzsh because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: webdriver because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/vagrant-shell20191118-12061-jukqa0.sh
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/vagrant-shell20191118-12061-1m33y24.sh
==> homestead: Running provisioner: shell...
    homestead: Running: script: Creating Certificate: mytest.local
==> homestead: Running provisioner: shell...
    homestead: Running: script: Creating Site: mytest.local
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/vagrant-shell20191118-12061-sbf7fz.sh
==> homestead: Running provisioner: shell...
    homestead: Running: script: Checking for old Schedule
==> homestead: Running provisioner: shell...
    homestead: Running: script: Clear Variables
==> homestead: Running provisioner: shell...
    homestead: Running: script: Restarting Cron
==> homestead: Running provisioner: shell...
    homestead: Running: script: Restarting Nginx
==> homestead: Running provisioner: shell...
    homestead: Running: script: Creating MySQL Database: homestead
==> homestead: Running provisioner: shell...
    homestead: Running: script: Creating Postgres Database: homestead
==> homestead: Running provisioner: shell...
    homestead: Running: script: Update Composer
    homestead: You are already using composer version 1.9.1 (stable channel).
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/vagrant-shell20191118-12061-iyqu6p.sh
==> homestead: Running provisioner: shell...
    homestead: Running: script: Update motd
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/T/vagrant-shell20191118-12061-dwbd58.sh


3. Then, open the ssh

Homestead % sudo vagrant ssh
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-64-generic x86_64)

Thanks for using 
 _                               _                 _ 
| |                             | |               | |
| |__   ___  _ __ ___   ___  ___| |_ ___  __ _  __| |
| '_ \ / _ \| '_ ` _ \ / _ \/ __| __/ _ \/ _` |/ _` |
| | | | (_) | | | | | |  __/\__ \ ||  __/ (_| | (_| |
|_| |_|\___/|_| |_| |_|\___||___/\__\___|\__,_|\__,_|

* Homestead v9.2.2 released
* Settler v8.2.0 released

0 packages can be updated.
0 updates are security updates.


vagrant@homestead:~$ ls
code
vagrant@homestead:~$ cd code

 4. Finally, install the laravel (I defined as mytest.local)
vagrant@homestead:~$ laravel new mytest.local 


5. configure your /etc/hosts to have ip 192.168.10.10 pointing to your laravel page. In my example, 192.168.10.10 mytest.local is the name

6. Open browser and go to http://mytest.local (or your page name defined in Homestead.yaml and /etc/hosts)

That's all bro




Share:

Tuesday, September 10, 2019

Is JP contributors to low ridership?

I was thrown a question on this and was also told the reason for low ridership. I am curious about it when it does not make sense to me. The two reasons shared to me are:
1. Ridership goes down because there is no Journey Planner
2. The customer doesn't need real-time data. They just want to have information about the services. It can be 3 minutes ago of information as long as we stated that the information is true 3 minutes ago.


It actually raised a few questions in my mind.
1. Was it really because of JP? or there are different factors.
2. If the information true 3 minutes ago, and I was standing in from of station or stops getting information that was updated saying that the bus or train is at 1 km away 3 minutes ago, will there be bus now (after 3 minutes) or has the bus pass through me 1 minutes ago because the information I get is delay 3 minutes. If I'm doing the planning right now, how can I plan with previous 3 minutes data? Should I add 3 minutes and assume the location of the bus upon receiving the info?

So, to answer my question, I do a quick review of many studies done earlier as listed below.

  1. https://www.edmonton.ca/city_government/documents/RoadsTraffic/transit_factors_ridership.pdf
  2. https://www.researchgate.net/publication/282656951_Factors_Affecting_to_Public_Bus_Transport_Ridership_A_Case_of_Capital_Colombo
  3. https://pdfs.semanticscholar.org/d3f0/63f546d97e676029dc1267ae1c09d9d298c3.pdf
  4. https://www.researchgate.net/publication/298371532_Factors_Affecting_Bus_Ridership_With_Respect_to_Passenger_Demography_A_Case_Study_of_Seberang_Perai_Pulau_Pinang_Malaysia
  5. http://www.reconnectingamerica.org/assets/Uploads/ridersipfactors.pdf
  6. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.683.858&rep=rep1&type=pdf
  7. https://fas.org/sgp/crs/misc/R45144.pdf
  8. http://www.ncarpo.org/uploads/1/3/8/1/13819061/factorsaffectingridership_20181004.pdf
  9. https://la.streetsblog.org/2016/01/29/what-factors-are-causing-metros-declining-ridership-what-next/


Findings:
1. From all papers, only 2 mentioned about information availability as one of the factors impacting ridership.
2. From the two papers, 1 mentioned real-time info is required but it is not one of the key factors. It is 1 out of many factors.
3. On the other papers (studies on bus ridership in Penang) - the author stated that the availability of information only accounts for 12% of the total factors contributing to low ridership.
4. The biggest factors contributed to low ridership are:
4.1 Service availability & reliability
4.2 Drivers behavior
4.3 Fare
4.4 Access to the services
4.5 Disruptor - e-hailing services

Further review on trip planning in new york based on the following two papers revive a few interesting facts.

  1. https://dl.acm.org/citation.cfm?id=2811271.2811272
  2. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.888.1033&rep=rep1&type=pdf

1. Despite was told that in new york, the information display shown is updated 3 minutes ago, I found out that it is actually a real-time update. Just that it stated updated 3 minutes ago because there is no new information at that time of the query.
2. The above two papers clearly state the importance of real-time information and it must be reliable info.

Conclusions:
1. JP is not the main key factors contributing to low ridership but JP availability can affect the decision of the public to use available services.
2. Service availability & reliability is the biggest contributor. If the OTR is reduced, definitely there will be a reduction of riders compared before OTR reduced.
3. e-Hailing has played a significant role in low ridership too. I believed, if Gojek successfully landed here in Malaysia, it will play a vital role in lowering the ridership too.
4. Real-time information and real-time update of information is the key to provide reliable info.

Recommendation:
1. JP is something needed but the information displayed in it shall be reliable and trustworthy. Thus improving the information relay process shall be the main focus.
2. Service availability and reliability shall be improved.
3. Implementation of BOS to complement each other for the benefit of the public.


* it is updated with a recommendation as many have shared their opinion on the post.
Share:

Tuesday, December 25, 2018

NPM and Ionic failed to run - EACCES and EISDIR error

You create new project using ionic framework. And suddently it says that there are new update either ionic update or npm update. You run the npm -i g ionic or npm -i g npm.. and your nightmare starts. You have
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/@ionic/discover-b2d9d3b9/dist'
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/readable-stream-4416b49f/lib'
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/diff-4b455008/lib/util'
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/source-map-848434cb/lib'
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/string_decoder-e05a13c4/lib'
WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/source-map-848434cb/dist'

WARN tar EISDIR: illegal operation on a directory, open '/usr/local/lib/node_modules/.staging/rxjs-db639a40/_esm2015/internal-compatibility'

and EACCES error popping out.

Then suddenly your ionic serve command failed.

Definitely you will try to:

  • Remove the installation
  • Reinstall ionic or npm
  • Clean the cache
  • and so on...

with or without administration privileges (sudo).

AND still you can't run the ionic serve command.

Be cool, I've spent few hours too to figure out that problem. And finally, I found the most reliable method.

Below is the steps taken directly from https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally
  1. Back up your computer.
  2. On the command line, in your home directory, create a directory for global installations:
     mkdir ~/.npm-global
    
  3. Configure npm to use the new directory path:
     npm config set prefix '~/.npm-global'
    
  4. In your preferred text editor, open or create a ~/.profile file and add this line:
     export PATH=~/.npm-global/bin:$PATH
    
  5. On the command line, update your system variables:
     source ~/.profile
    
  6. To test your new configuration, install a package globally without using sudo:
     npm install -g jshint
    
Instead of steps 2-4, you can use the corresponding ENV variable (e.g. if you don’t want to modify ~/.profile):
    NPM_CONFIG_PREFIX=~/.npm-global
and you shall be able to run your ionic serve command again.
Share:

Thursday, September 27, 2018

Writing API using Native API

There are many tools/framework you can use without even need to write code such as strapi, LoopBack, Fusio, Api Umbrella, Kong, etc. If you need to develop it fast and run nginx or nodejs behind, utilizing and highly dependent on the available method and don't want to think or dirty your hand, then, either one of the above lists shall be sufficient.

However, if you need to run complex query upon request, despite all of the API framework/tool allowed you to perform that, but it does not guarantee great flexibility and stability when the framework/tool is updated.

There is a way to handle and overcome the limitation. I'm using native PHP to provide a complex query and processing API.

Feel free to check the code and try it out at github.
Share:

Friday, August 31, 2018

Downloading and Formatting data for PDF output using Ionic, Angular, Cordova and TypeScript

It has been a while I did not focus and wrote anything on this blog and it is good to be back on track.

Lets kick start with writing PDF on your mobile apps. You may have data retrieve and your client require you to download the data as PDF. I've done that on Excel and it was way easy to do that.

Now lets start for PDF. It is pretty much easy too. We are going to use PDFMaker library.

If you follow the steps shows here, it shall be sufficient.

https://ionicacademy.com/create-pdf-files-ionic-pdfmake/

and you can read the entire library here

http://pdfmake.org/#/gettingstarted

You need to download and install three libraries for it to work
# Install Cordova Plugins
1. ionic cordova plugin add cordova-plugin-file-opener2
2. ionic cordova plugin add cordova-plugin-file

#Install NPM packages
3. npm install pdfmake @ionic-native/file-opener @ionic-native/file
Once complete, declare it in your apps.module.ts. The link above shall guide you with the sample.

The link above shows how it was done in a single page.  I, on the other hand, create a service provider to ease me in sharing the service between the apps. Below is the snapshot of my code... and Yup, I'm using Promise to ensure I can control the outcome and catch any error.

#the import
import { Platform } from 'ionic-angular';
//import { Http } from '@angular/http';
import { Injectable, Component } from '@angular/core';

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';

#the control
createPdf( isMin: boolean ): Promise<any>{
return new Promise ((resolve,reject) => {
if( isMin ){
this.createPdfMin()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
} else {
this.createPdfMax()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
}
})
} //end createPdf

#partial code to create pdf
createPdfMin(): Promise<any>{
//let docDefinition = null;

return new Promise((resolve) => {
let docDefinition = {
// a string or { width: number, height: number }
pageSize: 'A4',

// by default we use portrait, you can change it to landscape if you wish
pageOrientation: 'potrait',

// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [ 10, 30, 10, 30 ],

content: [
{ text: 'The Header', style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
//SPA Section
{ text: 'Sub Header', style: 'subheader' },

{ text: 'Sub Sub Header', style: 'subheader2' },
{
columns: [
{
text: 'Intial data'
},
{
width: '*',
text: theValue.toLocaleString('en-US', {
style: 'currency',
currency: 'MYR',
})
}
],
// optional space between columns
columnGap: 10
},
{ text: '---------------------------------------------------', style: 'subheader2' },
],
styles: {
header: {
fontSize: 18,
bold: true,
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 15, 0, 0]
},
subheader2: {
fontSize: 12,
bold: true,
margin: [0, 15, 0, 0]
},
story: {
italic: true,
alignment: 'center',
width: '50%',
}
}
}

this.pdfObj = pdfMake.createPdf(docDefinition);

return resolve( this.pdfObj );
});
} //end createPdfMin

#code to download the pdf
downloadPdf(pdfObj, type:string):Promise<any>{
console.log('fileCreator.downloadPdf()');
return new Promise((resolve) => {
if (this.plt.is('cordova')) {
pdfObj.getBuffer((buffer) => {
var blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.dataDirectory, 'file_' + type + '.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
this.fileOpener.open(this.file.dataDirectory + 'file_' + type + '.pdf', 'application/pdf');
})
});
} else {
// On a browser simply use download!
this.pdfObj.download();
}
return resolve("success");
})
} //end function downloadPdf

#how it is called from other page or file
this.fileCreatorProvider.createPdf(true)
.then((data) =>{
//download the file for min
this.fileCreatorProvider.downloadPdf(data,'type')
.then((data) => {
if ( data === 'success'){
this.presentAlert('Download Complete','Successfully download the file','success');
} else {
this.presentAlert('Download Error','Fail to download the file','error');
}
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})


and you shall be ready.

By the way, it is just snapshot. It shall give you brief idea on how to do that.

Happy Coding!!!


Share:

Sunday, February 18, 2018

Save list as CSV in ionic (PWA)

Read/Write file into devices

Installation (https://ionicframework.com/docs/native/file/)

Install the Cordova and Ionic Native plugins:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save @ionic-native/file
Add this plugin to your app's module

There are few ways you can use to download the file, but I'm using the easiest way, that is implementing the download which I'm not pretty sure if it runs ok on Android and iOS.
I'm not writing directly into the device storage as there are many things to consider such as storage area, security, etc.

Few references:

  1. http://ngcordova.com/docs/plugins/file/
  2. https://www.npmjs.com/package/cordova-plugin-file
  3. https://github.com/apache/cordova-plugin-file
  4. https://github.com/jiahao1553/demo-ionic2-save-csv/blob/master/src/pages/home/home.ts
Share:

Wednesday, February 14, 2018

Synchronizing the Asynchronous - Controlling the flow in ascynchronous type of apps

You have certain process to run in sequence; for instance
1. Login into the system
2. Check if the user valid, user status is valid, user role is valid
3. Store for future references
4. Capture audit trail and set timing, menu etc
5. Finally, show correct page base on user role and preferences

This shall be ok in synchronize programming. However, for programming like javascript, js, etc., you may face issues such as null value on a certain process, invalid id, or pages, etc.

There is ways, 'easy' way, but there is no guarantee that the data you will be receiving is accurate or at the exact time you need it.

Example of easy way is using timeout, as shown below

setTimeout(() => {
resolve('success');
}, 100)


Yet, the above example may not resolve your issues entirely.

Another option that looks promising is using Promise. However, there is a drawback to it. Your program may continue waiting despite it is already completed. Although it is a promise, within promise is still asynchronous program run.

return new Promise( (resolve, reject) => {
if (user) {
console.log("getUserProfile() - Success getting user in "
+ JSON.stringify(user) );
resolve(user);
} else {
this.showError('Access Denied! Invalid User Access');
reject('Access Denied! Invalid User Access');
}
});

Take for example the above code. The console may run after resolve(user) as the JSON.stringify may take few seconds than just return resolve value.

So, what is the best solution. Actually, there are no better solutions. What I did was,
1. Rewrite the code and logic and ensure all setting was done prior to user validation and page movement.
2. You can use Reducer or Promise-Sequential

You may refer here:

  1. https://blog.risingstack.com/node-hero-async-programming-in-node-js/
  2. https://forum.ionicframework.com/t/how-can-i-use-promise/40469/3
  3. https://www.promisejs.org/
  4. https://javebratt.com/wtf-promise/
  5. http://coenraets.org/blog/2016/02/angular2-ionic2-data-services-promises-observables/https://stackoverflow.com/questions/47767654/ionic-3-typescript-promise


For me, I'm using the latter (with timeout) as the former implementation is a bit complicated compared to the latter.

Here how I resolve the problem:
var sequential = require('promise-sequential');
var array = [this.getUserProfile(),this.validateUser()];

sequential(array.map((item) => {
return function(previousResponse, responses, count) {
return new Promise(resolve => {
setTimeout(() => {
resolve('success');
}, 100)
})
}
}))
.then(res => {
this.doLogin()
})
.catch(err => {
console.log('loginWithPromise(): ' + err );
this.showError(err);
})

wallawei!!! Hope it helps :)
Share:

Thursday, February 1, 2018

Running javascript on typescript project (Ionic + Angular) - 'require' not found

Using javascript on Ionic + Angular project which is based on typescript may troublesome and causing you days to figure out. You can get many kind of error such as 'require' not found, 'typescripts' not available, 'no such library' etc.

However, there are ways to implement. You can follow the steps mentioned here. I'm trying to implement bcryptjs on my ionic project. You may have different javascript required. Nonetheless, the steps shall be similar.

First, take a look at https://x-team.com/blog/include-javascript-libraries-in-an-ionic-2-typescript-project/ and follow some of the step shown here.

Then, follow the step discussed at https://stackoverflow.com/questions/31173738/typescript-getting-error-ts2304-cannot-find-name-require

And you shall be successfully run script based on javascript on your Ionic + Angular Project.

Wallawei!!!!
Share:

Sunday, December 31, 2017

Javascript to newbies

Want to learn JavaScript and conquer the world? Start here:

Tutorials and Books
- JavaScript For Cats is a dead simply introduction for new programmers.
- MDN JavaScript Guide has the most standard and straightforward tutorials. If you need references, MDN is here for you
too.
- You Don’t Know JS is the best book to learn JavaScript from. It’s free to read on GitHub.
- Eloquent JavaScript is another great introduction to programming and learning JavaScript.
- Modern JavaScript Cheatsheet helps you understand and learn all the new features in the language.
- JSBooks, a collection of free JavaScript books.

Videos and Courses
- JavaScript: Understanding the Weird Parts an incredible course which teaches the concepts of the language. First 3 hours
are free on YouTube, you can but the whole course from Udemy.
- FunFunFunction makes the learning process enjoyable.
- Javascript30, 30 videos to level up your skills.
- Traversy Media great contents mostly aimed for begginers.

Learn by Doing
- FreeCodeCamp, learn to code by building projects.
- CodeAcademy, learn to code interactively.
- Codewars, train with programming challenges.

Functional Programming
This where the true the good parts show theirselves.
- JSUnconf 2016, learn functional programming basics with this talk from Anjana Vakil.
- FunFunFunction's videos are a great start.
- Mostly Adequate Guide to Functional Programming and Functional Light JS will make you master the functional programming.
- JavaScript Allongé, programming from functions to classes.
- Functional Programming Jargon in simple terms.
- awesome-fp-js is a good reference for functional programming in JavaScript.

Other Resources
- Spellbook of Modern Web Dev is a big picture of modern JavaScript development.
- What the fuck JavaScript?, list of funny and tricky JavaScript examples.

From JS telegram Part of @thedevs 
Rules: @thedevsrules Join other dev groups https://thedevs.network
Share:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Labels

Blog Archive

Blogger templates