June 25, 2019 ademcan No comments

What happened to Saturn’s sixth moon last week?

TLDR; be sure that your node is using the additional storage to write the blockchain data there

As Enter Elastos we are running 3 Elastos supernodes (Titan, Ganymede and Callisto). To have a better overview of the ecosystem and be ready in case of issue we decided to use different approaches to run the different supernodes. There are 3 approaches available to run a supernode: docker, debian packages and binaries. Titan was running the node based on the binary approach. Yesterday, our server was complaining about not having enough space which resulted in the supernode going down and its status changing to inactive. Although an additional 100 GB of SSD was mounted, the system wasn’t using it. So, what happened?

If your run a supernode with the debian package approach, the blockchain data is written to the /data folder, and that’s where our additional SSD was mounted. However, if you use the binary approach, the data is saved to a relative path from where you run the node and not seeing the additional storage (if you have mounted it to /data).

What should you do in such situation?

1. If you are using the debian package approach

1.1. Format (before running the node) and mount the additional SSD to /data. Your SSD should be called /dev/xvdb, you can check with the following command:

lsblk

If you see /dev/xvdb in the list just continue the steps as follow, otherwise adapt the name of your additional storage in the following commands.

sudo mkdir /data
sudo mkfs -t xfs /dev/xvdb
sudo mount /dev/xvdb /data

1.2. Follow the automated script installation procedure

2. If you are using the binary approach

2.1. Format (before running the node) and mount the additional SSD to /home/ubuntu/supernode as an example. Your SSD should be called /dev/xvdb, you can check with the following command:

lsblk

If you see /dev/xvdb in the list just continue the steps as follow, otherwise adapt the name of your additional storage in the following commands. In the example below we will be running the node from the /home/ubuntu/supernode.

sudo mkdir /home/ubuntu/supernode
sudo mkfs -t xfs /dev/xvdb
sudo mount /dev/xvdb /home/ubuntu/supernode

2.2. Follow the binary supernode procedure from your /home/ubuntu/supernode folder

3. How to solve the issue

If your supernode was already running and you are facing the same issue, here is what to do:
1. Stop all the running service (ela, did, token and carrier)
2. Mount your additional storage and move all the data there
3. Restart all the services from the new location
4. Create a new activation transaction

./ela-cli wallet buildtx activate --nodepublickey $YOUR_NODE_PUBLIC_KEY

5. Send the activation transaction

 
./ela-cli wallet sendtx -f ready_to_send.txn --rpcuser $YOUR_RPC_USERNAME --rpcpassword $YOUR_RPC_PASSWORD

You should see your supernode coming back to life in a few minutes!

My main mistake here was not to check where the data was written to. As the REST API was working properly and the node was running fine I didn’t check the data/chain folder where the blockcahin is saved to. I just guessed it was all fine, it wasn’t, but now it is 🙂
I would like to thank Song (@songsjun) and his amazing team/colleagues that took their time to help me on a Sunday, as well as KP (@pachhaisaab) for putting all this information online and sharing his knowledge with the community. I am also somehow happy that this issue happened now (no penalty period) so that we are aware of it in case it happens to any other supernode.

May 11, 2019 ademcan No comments

How to deal with the keyboard appearance in React Native?

Photo by unsplash-logoVincent Yee on Unsplash

    Controlling the appearance of the keyboard is a big headache for mobile app developers. The keyboard should appear smoothly and fit in the user interface without blocking any element. Several solutions exist in React Native to deal with that issue: one can use the KeyboardAvoidingView component or one of the several npm packages that are doing the work for you. Finally, it is also possible to manually take care of the user interface adaptation to the keyboard appearance.
    In this tutorial, we will create a simple view that requires user input (thus keyboard appearance) and that will adapt its component sizes/positions based on the keyboard visibility. We will create a simple view asking the user to fill in the 12 secret words to access a cryptocurrency wallet, the mnemonic. Once the user has provided the mnemonic, the keyboard will disappear and the view components will adapt to their new positions/sizes.
So let’s get started.

1. Create a new React Native app

    Open your terminal and run the following command to create a new React Native project:

react-native init enterMnemonicView

2. The code

    Contrary to the other tutorials, I am giving the whole code here at once first and we’ll go to the details below. Go to your newly created React Native project and open the App.js file, remove its content and add the one below:

import React from 'react';
import {
  Text, View, TextInput, Image, Keyboard, LayoutAnimation, ImageBackground, TouchableHighlight, StyleSheet,
} from 'react-native';

export default class ImportWallet extends React.Component {

  // state
  state = {
    counter: 1,
    word1: '',
    word2: '',
    word3: '',
    word4: '',
    word5: '',
    word6: '',
    word7: '',
    word8: '',
    word9: '',
    word10: '',
    word11: '',
    word12: '',
    topHeight: 150,
    complete: false,
    marginTop: 100,
    marginBottom: 30,
  }

  keyboardDidShowListener = {}
  keyboardDidHideListener = {}

  // add listeners on componentWillMount()
  componentWillMount () {
    Keyboard.addListener('keyboardDidShow', (e) => this.keyboardDidShow(e));
    Keyboard.addListener('keyboardDidHide', (e) => this.keyboardDidHide(e));
  }

  // remove listeners on componentWillUnmont()
  componentWillUnmount () {
    this.keyboardDidShowListener.remove()
    this.keyboardDidHideListener.remove()
  }

  // fired when keybord appears
  keyboardDidShow (e) {
    let newSize = e.endCoordinates.height
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
    this.setState({
      marginTopMenu: 0,
      marginTop: 50,
      topHeight: 100,
      marginBottom: newSize
    })
  }

  // fired when keyboard disappears
  keyboardDidHide (e) {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
    this.setState({
      marginTopMenu: 100, 
      marginTop: 100,
      topHeight: 150,
    })
  } 

  // will check the user input and create a new block when the user presses the [space] button
  _onMnemonicChange = (text) => {
    const lastChar = text[text.length - 1];
    // check for [space]
    if (lastChar === ' ') {
      this.textInput.clear()
      // update the state accordingly
      switch (this.state.counter) {
        case 1:
          this.setState({ word1: text, counter: this.state.counter + 1 });
          break;
        case 2:
          this.setState({ word2: text, counter: this.state.counter + 1 });
          break;
        case 3:
          this.setState({ word3: text, counter: this.state.counter + 1 });
          break;
        case 4:
          this.setState({ word4: text, counter: this.state.counter + 1 });
          break;
        case 5:
          this.setState({ word5: text, counter: this.state.counter + 1 });
          break;
        case 6:
          this.setState({ word6: text, counter: this.state.counter + 1 });
          break;
        case 7:
          this.setState({ word7: text, counter: this.state.counter + 1 });
          break;
        case 8:
          this.setState({ word8: text, counter: this.state.counter + 1 });
          break;
        case 9:
          this.setState({ word9: text, counter: this.state.counter + 1 });
          break;
        case 10:
          this.setState({ word10: text, counter: this.state.counter + 1 });
          break;
        case 11:
          this.setState({ word11: text, counter: this.state.counter + 1 });
          break;
        case 12:
          this.setState({word12: text, counter: this.state.counter + 1 , complete: true});
          break;
        default:
          break;
      }
    }
  }

  // render
  render() {
    return (
      <ImageBackground source={require('./resources/images/main_background.png')} style={{flex:1, height:this.state.topHeight }}>
        <View style={{height: 100, width: 360, borderRadius: 10, borderColor: 'black', alignSelf: 'center', marginTop: this.state.marginTop, backgroundColor: 'white', shadowColor: '#000000', shadowRadius: 10, shadowOpacity: 1.0, justifyContent: 'center' }}>
          <Text style={{textAlign: 'center', fontSize: 24}}>ENTER MNEMONIC</Text>
        </View>

        <View style={{flex:1,  marginTop: this.state.marginTopMenu}}>

          <View style={{flexDirection:'row'}}>
            {this.state.word1 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word1}</Text>
              </View>
              :
              <View ></View>
            }

            {this.state.word2 != '' ?
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word2}</Text>
              </View>
              :
              <View></View>
            }

            {this.state.word3 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word3}</Text>
              </View>
              :
              <View></View>
            }
          </View>

          <View style={{flexDirection:'row', height:70}}>
            {this.state.word4 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word4}</Text>
              </View>
              :
              <View></View>
            }

            {this.state.word5 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word5}</Text>
              </View>
              :
              <View></View>
            }

            {this.state.word6 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word6}</Text>
              </View>
              :
              <View></View>
            }  
          </View>

          <View style={{flexDirection:'row', height:70 }}>
            {this.state.word7 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word7}</Text>
              </View>
              :
              <View></View>
            }

            {this.state.word8 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word8}</Text>
              </View>
              :
              <View></View>
            }

            {this.state.word9 != '' ? 
              <View style={styles.mnemonic_word}>
                <Text style={{color:'white'}}>{this.state.word9}</Text>
              </View>
              :
              <View></View>
            }
            </View>

            <View style={{flexDirection:'row', height:70}}>

              {this.state.word10 != '' ? 
                <View style={styles.mnemonic_word}>
                  <Text style={{color:'white'}}>{this.state.word10}</Text>
                </View>
                :
                null
              }

              {this.state.word11 != '' ? 
                <View style={styles.mnemonic_word}>
                  <Text style={{color:'white'}}>{this.state.word11}</Text>
                </View>
                :
                null
              }

              {this.state.word12 != '' ? 
                <View style={styles.mnemonic_word}>
                  <Text style={{color:'white'}}>{this.state.word12}</Text>
                </View>
                :
                null
              }
            </View>

          <View style={{flex:1, flexDirection:'row', alignItems:'flex-end'}}>
          {this.state.complete ? 
            <View style={{flex:1, bottom:50}}>
              <TouchableHighlight onPress={() => this.props.navigation.navigate("ProvidePwd") } underlayColor='#172D39' style={styles.action_button_above}>  
                <Text style={styles.button_text}>IMPORT</Text>
              </TouchableHighlight>

              <TouchableHighlight onPress={() => this.props.navigation.navigate("ProvidePwd") } underlayColor='#172D39' style={styles.action_button_second}> 
                <Text style={styles.button_text_second}>CLEAR</Text>
              </TouchableHighlight>
            </View>
          : 
            <View style={{flex:1, height:100, marginBottom: this.state.marginBottom}}>  
              <TextInput ref={input => { this.textInput = input }} onChangeText={ (text) => this._onMnemonicChange(text) } autoCapitalize='none'  style={{ marginTop: 10, backgroundColor: 'white', height: 70, borderColor: 'black', borderWidth:1, borderRadius:30}}/>
            </View>
          }
          </View>

        </View>
        </ImageBackground>
    );
  }
}


// styling
const styles = StyleSheet.create({
  action_button_above: {
    justifyContent: 'center',
    alignSelf: 'center',
    width: 270,
    height: 60,
    backgroundColor: '#172D39',
    borderRadius: 30,
    marginBottom: 20,
  },
  action_button_second: {
    justifyContent: 'center',
    alignSelf: 'center',
    width: 270,
    height: 60,
    backgroundColor: 'white',
    borderColor: '#172D39',
    borderWidth: 1,
    borderRadius: 30,
    marginBottom: 20,
  },
  button_text: {
    color: 'white',
    textAlign: 'center',
    fontSize: 24,
  },
  button_text_second: {
    color: '#172D39',
    textAlign: 'center',
    fontSize: 24,
  },
  mnemonic_word: {
    flex: 1,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 10,
    marginRight: 10,
    backgroundColor: '#6C5D81',
    borderRadius: 10,
    marginTop: 20
  },
});

3. Explanation

3.a. Show/hide keyboard listerners

    The first part of the code is taking care of the keyboard appearance. The code needs to be aware of the keyboard visibility to adapt the view accordingly, that’s why we need to instantiate and implement our listeners.
We instantiate our listeners and tell React Native to take care of them at mount and unmount as follow:

keyboardDidShowListener = {}
keyboardDidHideListener = {}

// add listeners on componentWillMount()
componentWillMount () {
  Keyboard.addListener('keyboardDidShow', (e) => this.keyboardDidShow(e));
  Keyboard.addListener('keyboardDidHide', (e) => this.keyboardDidHide(e));
}

// remove listeners on componentWillUnmont()
componentWillUnmount () {
  this.keyboardDidShowListener.remove()
  this.keyboardDidHideListener.remove()
}
3.a. Adapting the view on keyboard show/hide

    We can now check when the keyboard appears/disappears and therefore control the interface according to the visibility of the keyboard. On the render() function we adapted our main View to have some position related values defined in the local state (see L.119 for an example), so that we can play with them. We can now change these values according to the visibility of the keyboard using this.setState() function.

// fired when keybord appears
keyboardDidShow (e) {
  let newSize = e.endCoordinates.height
  LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
  // adapt component positions by updating the local state values
  this.setState({
    marginTopMenu: 0,
    marginTop: 50,
    topHeight: 100,
    marginBottom: newSize
  })
}

// fired when keyboard disappears
keyboardDidHide (e) {
  LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
  // adapt component positions by updating the local state values
  this.setState({
    marginTopMenu: 100, 
    marginTop: 100,
    topHeight: 150,
  })
}

In the end the whole process looks like the image below:

The whole source code is also available on GitHub.

Sources:
React Native’s LayoutAnimation is Awesome
Avoiding the Keyboard in React Native
Let’s Get Moving: An Introduction to React Native Animations — Part 1

February 15, 2019 ademcan No comments

How to add a linter to your React Native project

The definition of linting on Wikipedia is pretty clear :”Lint, or a linter, is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs”.

Clean code

Photo by unsplash-logoJames Pond on Unsplash

By using a linter in your React Native project you’ll be able to catch code errors early on and correct them before it’s too late. For a React Native project, we will rely on ESLint, and this is how we are going to do it:

1. Install the linter plugin for your IDE

I am using VSCode and a great Linter plugin is ESLint. There are usually several plugin alternatives for the most common IDEs, go and grab your favorite.

2. Install ESLint

The eslint package is the tool that will check for errors in our code. Open the command line, switch to your React Native project folder and run:

npm install eslint --save-dev

3. Install the Babel parser

We need the Babel parser to allow ESLint to check for code written using the ES7 syntax, Flow or TypeScript types.

npm install babel-eslint --save-dev

4. Get a list of rules for ESLint

For ESLint to properly work we need to configure ESLint with a list of rules. You can write the instructions yourself but there are already existing solutions, so we will just pick one of them.
Here are a few:
Airbnb JavaScript Style Guide() {
ESLint-plugin-React
ESLint plugin for React Native
We will continue with the esling-plugin-react-native. To install it, run:

npm install eslint-plugin-react-native --save-dev

5. Add the .eslintrc file to your project

To configure ESLint we need to create a .eslintrc file at the root of the project. Open your text editor and add the following to your .eslintrc file:

{
    "plugins": [
        "react-native"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react-native/all"
    ],
    "parser": "babel-eslint",
    "env": {
        "react-native/react-native": true
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "rules":{
        "react-native/no-unused-styles": 2,
        "react-native/split-platform-components": 2,
        "react-native/no-inline-styles": 2,
        "react-native/no-color-literals": 2,
        "react-native/no-raw-text": 2
    }
}

As soon as you save your .eslintrc file, you should see a lot of errors showing up in your code. No worries, these are probably some styling or import related issues, go ahead and fix them. You can now enjoy you clean code😉


We can work together

Share this post on social media:

February 11, 2019 ademcan No comments

Write and compile your first Dapp using Solidity and Node.js

There are already several tutorials of that kind available on the Internet. However, I couldn’t follow any of them from the begining to the end without issues, so here is my own tutorial about how to write and compile your very first smart contract for the Ethereum blockchain. This first article is all about the Dapp code and compiling, a second article about how to deploy our app on the network will follow.

A smart contract corresponds to code instructions that are supposed to run on the network. In the case of Ethereum, a runtime environment called EVM (Ethereum Virtual Machine) takes care of running smart contracts. The instructions of the smart contract are written using the Solidity programming language. There are 2 essential steps to successfully run a smart contract on the network: compiling and deploying. Compiling the smart contract will generate a bitcode that can be later deployed on the network. So, let’s get ready to write our first smart contract!

Required tools

The only tools that you need to follow this tutorial are Node.js and npm installed in your machine.

1. Initialize a new node project

Open your terminal and create a new package.json using the npm command line tool:

npm init helloWorldContract

Confirm all the steps by pressing Enter or adapt the answers if needed. This will create a new package.json file containing all the information provided above.

2. Install solc

The npm solc package is a JavaScript library for the solidity compiler. We will use the solc package to compile our smart contract so that it is ready to be deployed on the network.

npm i solc

3. Write the smart contract

The next step is to write our smart contract. There are several essential points to write a smart contract properly:

  1. a smart contract always starts with the “pragma solidity ^0.5.2;” definition, where 0.5.2 is the version of the Solidity compiler
  2. a smart contract is defined by the “contract” keyword followed by its name
  3. a list of variables and functions defines what the smart contract is meant to do

Copy paste the code below to your text editor and save the file as Hello.sol

pragma solidity ^0.5.2;
contract HelloWorld {
    uint256 counter = 5;
    function increment() public {  
        counter++;
    }
    function decrement() public { 
        counter--;
    }
}

In this example we declared a counter variable of type uint256 and initialized it to 5. We then defined 2 functions in our smart contract; the first one to increment our counter and the second one to decrement it.

4. Write the compiler code

We now need to write the JavaScript code that will compile our smart contract. Create a new file, save it as compileSol.js and add the following code to it

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const helloPath = path.resolve(__dirname, 'Hello.sol');
const hellosol = fs.readFileSync(helloPath, 'UTF-8');

var input = {
	language: 'Solidity',
	sources: {
		'hello.sol': {content : hellosol}
    },
    settings: {
		outputSelection: {
			'*': {
				'*': [ '*' ]
			}
		}
	}
};

var output = JSON.parse(solc.compile(JSON.stringify(input)))
for (var contractName in output.contracts['hello.sol']) {
	console.log(contractName + ': ' + output.contracts['hello.sol'][contractName].evm.bytecode.object)
}

5. Compile

Run the compiler code on your terminal as below

node compileSol.js

The terminal will show you the generated bitcode corresponding to our HelloWorld smart contractas below:

HelloWorld: 6080604052600560005534801561001557600080fd5b5060b7806100246000396000f3fe6080604052348015600f57600080fd5b5060043610604f576000357c0100000000000000000000000000000000000000000000000000000000900480634f2be91f1460545780636deebae314605c575b600080fd5b605a6064565b005b60626077565b005b6000808154809291906001019190505550565b60008081548092919060019003919050555056fea165627a7a7230582010eb14dc210d8b3d190848ce79ded65e30d7502c032655c7889d2fa7d35d3f1d0029

This is what we will need to publish our smart contract to the network. I will explain more in details about how to publish the contract on the network in the next blogpost of the series.


We can work together

Share this post on social media:

November 9, 2018 ademcan 2 comments

How to create a react-native bridge library for iOS

React-Native allows user to create bridges to access native code from JavaScript. Once you have created your own bridges you might want to share them with the community. This article will explain in a few simple steps how to do so.

1. Create a new project with react-native-create-library

Open your terminal and run

react-native-create-library --package-identifier org.domain --platforms android,ios native-bridge

This will create a new project name react-native-native-bridge with all the required files in there.

2. Implement your bridge

Open the Xcode project located in the react-native-native-bridge/ios folder and edit the RNNativeBridge.m file to add your bridge functions accordingly. Here is a simple example that will return “Hello from Xcode!” when called in React-Native

RCT_EXPORT_METHOD(greetings: (RCTResponseSenderBlock)callback){
    callback(@[[NSNull null], @"Hello from Xcode!" ]);
}

If you are not familiar with native modules, go check the great documentation here.

3. Create a new npm package and publish it

Now that our hyper sophisticated bridge library is ready😉, we will propose it as an npm package on npmjs. You first need to create a new account on npmjs if you don’t have one yet. You can run

npm whoami

to check if you are logged in or not. If not, just run

npm adduser

and follow the instructions. Update the package.json file accordingly and run

npm publish

The new package will now be available to the community via the npm command and you can also see it at https://npmjs.com/package/react-native-native-bridge. You can refer to the documentation if you need any help.

4. Create a new React-Native demo app and use the package

Let’s create a new React Native project to test the npm package. Open your terminal and run

react-native init nativeBridgeTest

Install the react-native-native-bridge package and link it

npm install react-native-native-bridge
react-native link react-native-native-bridge

Open the App.js file of your React Native project and edit as follow

import RNNative Bridge from react-native-native-bridge
...
// create a new function in the App class
greetings = () => {
    RNNativeBridge.greetings( (err, res) => {
        console.log(res); 
    });
}
...
// Add a button in the render() function that will call the native function when clicked
<Button title="Greetings" onPress={this.greetings} />

This should print “Hello from Xcode!” in the logs.

Sources:
Creating a React Native Bridge Library


We can work together

Share this post on social media:

August 3, 2018 ademcan No comments

How to convert a NSData hexstring to a NSString in Objective-C

At the QRL we are dealing a lot with hexstrings. Several of our API functions return results in hexstring format and it is sometimes important to be able to reuse them for another call. Here is how to convert a hexstring you received as NSData object (and looks like <24501f40 6cf57975 676b6d34 95d4cd7d 14541ddd 4d44fa4a f08e6faf 9d15252b>) to a string (in our case “24501f406cf57975676b6d3495d4cd7d14541ddd4d44fa4af08e6faf9d15252b”):

NSData *data = YOUR_NSDATA_HEXSTRING;
// we first need to get the length of our hexstring
// data.lenght returns the lenght in bytes, so we *2 to get as hexstring
NSUInteger capacity = data.length * 2;
// Create a new NSMutableString with the correct lenght
NSMutableString *mutableString = [NSMutableString stringWithCapacity:capacity];
// get the bytes of data to be able to loop through it
const unsigned char *buf = (const unsigned char*) [data bytes];

NSInteger t;
for (t=0; t<data.length; ++t) {
  NSLog(@"GLYPH at t : %c", buf[t]);
  NSLog(@"DECIMAL at t  : %lu", (NSUInteger)buf[t]);
  // "%02X" will append a 0 if the value is less than 2 digits (i.e. 4 becomes 04)
  [mutableString appendFormat:@"%02X", (NSUInteger)buf[t]];
}
NSLog(@"Hexstring: %@", mutableString);
// save as NSString
NSString * hexstring =mutableString;

You can check the decimal, hex and corresponding glyph here.

sources
SO question
String Format Specifiers [Apple dev]
Bits and Bytes

July 3, 2018 ademcan 2 comments

How to call native Java functions from JavaScript for a React Native app (Android)

React Native is a great framework to develop mobile apps for iOS and Android with the help of JavaScript. However, at some point of your project you might need to call native functions. In React Native, invoking a native function is called bridging. In this article, I will explain how to implement a bridge communication between Java and JavaScript for your React Native based Android app.

1. Create a new react-native project or open an existing one

To create a new react-native project, open your terminal and enter the following command:

react-native init HelloWorld

This will create a new react-native app called HelloWorld with the corresponding android/ and ios/ folders containing your mobile app’s codes for the different platforms.

2. Open the project on Android Studio

Launch Android Studio and select File -> New -> Import Project… then select the HelloWorld/android folder to import to Android Studio. Your Android Studio Project window should look like this :

3. Create a new Java module

The first step to be able to use Java native code from react-native is to create a new Java module that extends the ReactContextBaseJavaModule class. To do so on the 1:Project pane of Android Studio right click on the com.helloworld folder and select New -> Java Class as shown below.

In the new window enter the following information and click OK:

Important note: in this tutorial, we will be using a callback so that your Java function can send some parameters back to JavaScript. Alternatively, one could also use a Promise (see here) or nothing at all if the main point is just to call a Java class without information going back and forth.
The newly create HelloWorldModule.java will open. You can remove the content of the file and add the following code:

package com.helloworld;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.uimanager.IllegalViewOperationException;

public class HelloWorldModule extends ReactContextBaseJavaModule {

    public HelloWorldModule(ReactApplicationContext reactContext) {
        super(reactContext); //required by React Native
    }

    @Override
    //getName is required to define the name of the module represented in JavaScript
    public String getName() { 
        return "HelloWorld";
    }

    @ReactMethod
    public void sayHi(Callback errorCallback, Callback successCallback) {
        try {
            System.out.println("Greetings from Java");
            successCallback.invoke("Callback : Greetings from Java");
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
}

4. Register the new Java module

Once your module is implemented, you need to register it. For the registration, you will need to create a new package. Create a new Java Class as you did earlier and call it HelloWorldPackage. Copy and paste the following code to your HelloWorldPackage.java file.

package com.helloworld;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.helloworld.HelloWorldModule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelloWorldPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        //this is where you register the module
        modules.add(new HelloWorldModule(reactContext));
        return modules;
    }
}

5. Register the new Java package

Finally, you need to properly register the new package. Open the MainApplication.java and modify it as follow

package com.helloworld;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new HelloWorldPackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

We are simply adding the new HelloWorldPackage() code at line 26, the rest is unchanged.

6. Edit JavaScript code

It is now time to implement the JavaScript side of the app. We will create a simple TouchableOpacity element and call the native Java function on press of this element. Open the HelloWorld/App.js file with your favorite text editor and change it as below:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';

// We are importing the native Java module here
import {NativeModules} from 'react-native';
var HelloWorld = NativeModules.HelloWorld;

type Props = {};
export default class App extends Component<Props> {

  // async function to call the Java native method
  async sayHiFromJava() {
    HelloWorld.sayHi( (err) => {console.log(err)}, (msg) => {console.log(msg)} );
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={ this.sayHiFromJava }>
              <Text>Invoke native Java code</Text>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

7. Start the Android Virtual Device and run the app

On Android Studio click the small AVD manager icon () and start (or create a new one if you don’t have any existing one) your AVD. Then on your terminal enter the following command:

react-native run-android

You should see the following on your Android emulator

8. Invoke the sayHi() Java function from JavaScript

Open the 6:Logcat window of Android Studio to see the Logs and press the “Invoke native java code” button in the emulator. This action will call the native Java function and should indicate the following output in your logs:

I hope this tutorial was clear, let me know how it went for you in the comments😊

Sources:
https://facebook.github.io/react-native/docs/native-modules-android
https://blog.botreetechnologies.com/how-to-build-a-react-native-android-bridge-4166e114a990
https://www.dailydrip.com/topics/react-native/drips/using-android-native-modules.html


We can work together

Share this post on social media:

January 17, 2018 ademcan No comments

How I implemented canSnippet’s newsletter campaign with MailChimp

“An email subscriber is worth 100x twitter or LinkedIn followers or whatever other stuff is out there. An email = a real channel” Andrew Chen

    A newsletter is an essential part of your online business/blog/project. It helps you reach your auditors more easily and keep them informed about any update regarding your project. I recently implemented a newsletter for canSnippet, my snippet management tool. I have already heard a lot about MailChimp and as it is the most commonly used service (and you can create a free account for small projects) I decided to go with it. I had some difficulties to create my first campaign (I didn’t even know what that meant at the time) so I wanted to share some essential points to help you in the creation of your first newsletter.
    There are 4 easy steps to follow for implementing a newsletter with MailChimp (without counting the fact that you already have a MailChimp account…).

1. Create a List

    This list will contain all the email addresses related to your project. You can have different lists for different projects. Connect to your MailChimp account and click on the Lists button on the top menu.

    Click the Create list button and confirm the creation of a new list. Fill the form with all the required information (you can see an example below).

Click Save to create your first list.

2. Design your forms

    Every event can be linked to a form, be it signup, unsubscibe… You can design all of these forms one by one and with great details. After creating your first list, you can click on the Signup forms tab and select General forms.
    For this simple example of a newsletter, all the forms that we will use are located under General forms except for the “Subscribe” form that will be located under Embedded forms.
There are 5 forms that are useful in case of a newsletter implementation. You can see the details of the required forms in the image below.

Click the image to see the full resolution PDF

You can select every form one by one and modify them as you like. I find the default forms already pretty good, I just added the logo and name of canSnippet on the header for additional personalisation.

3. Creating your first campaign

    You can now create your first Campaign that will correspond to your Welcome message. You can actually implement the Welcome message already in the Signup forms section, under Final Welcome email and tick the Send a final welcome email. Alternatively, you can create a Campaign and send a more personalized email every time a new user subscribes to your newsletter. That’s what we will do now, you can also refer to this approach next time you will create a Campaign.

Go to Campaigns and click Create Campaign, click Create an Email and give a name to your campaign.

Select Automated as we want the email to be sent every time a new user registers to our newsletter and select Welcome new subscribers.

In the next step just select the list we created earlier (so-called newsletter).
The final window corresponds to the heart of your campaign and will contain all the required information.
To send an automatic email every time an event is detected you need to adjust the trigger. Click Edit trigger and on the Delay section click on the drop-down menu and select Immediately and click Update Trigger.

4. Design your Welcome email

    Click Design Email and fill the form as you wish with the Email subject and Preview Text (optional) information. Then, select a template and start designing your welcome email. That’s where all the craziness starts as you can do everything you want. For a welcome email you can just start with a Basic – 1 Column layout and modify the text accordingly by adding an image for example. Then you can simply click Save and Close and click Save and Continue once you are done.

Click Next and review your workflow. If there is any issue, MailChimp will let you know. Finally, click Start workflow and confirm.

That’s it, you are done, enjoy your newsletter and share as much as you can✨

November 24, 2017 ademcan 9 comments

Upload/download images to/from AWS S3 in React-Native: a step-by-step guide

I recently struggled a lot to be able to upload/download images to/from AWS S3 in my React Native iOS app. I wanted to allow users to upload images to S3 and access some of the images from other users… I have a server running on Express (nodejs) and here is how I solved my problem.

1. Create an IAM user

Go to the IAM section on your AWS dashboard, select the Users category from the left side menu and press the Add user button.
1.1 Enter a username (test_user in this example) and select the access type Programmatic access, click Next:Permissions.

1.2 Leave this section as is and click Next:Review.

1.3 Finalize the creation of the user by clicking the Create user button.

1.4 Your new IAM user is created, click the Download .csv button and keep the file somewhere safe as it contains the Secret Access Key of your user. We will need this information later to create pre-signed URLs.

2. Create an AWS S3 bucket

Go to the S3 section on your AWS dashboard and click the + Create bucket button.
2.1 Enter a name for your bucket (test-bucket-tutorial in this example), the name has to be unique. Click Next.

2.2 Leave the default parameters in the Set properties section and click Next (you can always change them later)

2.3 Same for Set permissions, leave the default parameters and click Next

2.4 Review and click Create bucket

2.5 Go to your freshly created bucket and click + Create folder . Name your new folder images.

3. Create policy for your IAM user

So far we created our IAM user and our S3 bucket with an images folder. We now need to give permissions to our IAM user to access the S3 test-bucket-tutorial/images folder.
3.1 Go to your IAM section on your AWS dashboard and click the Policies section.

3.2 Click Create policy and select the JSON tab, then copy-paste the text below on the text input.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::test-bucket-tutorial/images"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:GetObjectAcl",
        "s3:GetObjectVersion",
        "s3:PutObjectAcl",
        "s3:PutObjectVersionAcl"
      ],
      "Resource": ["arn:aws:s3:::test-bucket-tutorial/images/*"]
    }
  ]
}

It should look like the picture below:

3.3 Click Review policy, give a name to your policy (test-bucket-tutorial-policy in this example) and click Create policy

4. Attach policy to your IAM user

Now we need to attach the policy to the user.
4.1 On the Policies section, select our freshly created policy.

4.2 Go to the Attached entities tab and click Attach

4.3 Select the IAM user that we created at Step1 and click Attach policy

Now the user has the permissions (listed in the policy) to access the test-bucket-tutorial/images folder in your S3 bucket.

5. Generating pre-signed URL on the server side

Pre-signed URLs allow you to create a unique URL based on the credentials that you will provide and to safely use this URL on your client-side (without providing the Secret Access Key). As written earlier, I am using expressjs as a back-end, however the code below can easily be adapted to other alternatives.
5.1 Install the node aws-sdk package.

npm install aws-sdk

5.2 Copy-paste the following code to your main javascript code when running your server, this will output the generated pre-signed URL to the console.

var AWS = require('aws-sdk');
var s3 = new AWS.S3({accessKeyId:'XXXXXXXXXXXX', secretAccessKey:'YYYYYYYYYYYY', region:'REGION'});

var params = {Bucket: 'test-bucket-tutorial', Key: 'images/myimage.jpg', ContentType: 'image/jpeg'};
s3.getSignedUrl('putObject', params, function (err, url) {
    console.log('Your generated pre-signed URL is', url);
});
  • Replace XXXXXXXXXXXX by your user’s Access Key ID that you can find on the csv file previously downloaded (Step 1.4)
  • Replace YYYYYYYYYYYY by your user’s Secret Access Key that you can find on the csv file previously downloaded
  • Replace REGION by the region of your AWS S3 bucket, you can find this information here

6. Upload images to S3 from the client-side

My client-side is implemented in React-Native. To allow the user to select a picture and send it to our S3 bucket we will use the ImagePickerIOS component (which is not very highly documented…). Put the code below on your RN app wherever you want it to be run.

ImagePickerIOS.openSelectDialog({}, imageUri => {
    const xhr = new XMLHttpRequest()
    xhr.open('PUT', presignedUrl)
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
            console.log('Image successfully uploaded to S3')
        } else {
            console.log('Error while sending the image to S3')
        }
    }
}
xhr.setRequestHeader('Content-Type', 'image/jpeg')
xhr.send({ uri: imageUri, type: 'image/jpeg', name: 'myimage.jpg'})
}, error => console.log(error));

I adapted the original code that I found in this very helpful article. Change the presignedUrl value with the pre-signed URL that you generated on your server (Step 5.2).

7. Downloading images from the client-side

If you want to download some images to your client app, you need to follow a similar approach with some slight changes:

  • remove the ContentType attribute from the params array
  • use the getObject method instead of putObject

The code will then look like:

var params = {Bucket: 'test-bucket-tutorial', Key: 'images/myimage.jpg'};
s3.getSignedUrl('getObject', params, function (err, url) {
    console.log('Your generated pre-signed URL is', url);
});

This code will generate a unique URL to access your image.
Check the AWS.S3 Documentation page if you want to learn more about the different methods that are available.

8. A concrete example

I personally use these examples in my own project as follow :
1 – The user selects a photo from the Gallery
2 – The RN app sends a request to my Express server with the name (and ID) of the user as the image filename
3 – The nodejs server generates the pre-signed URL adapted to the image filename using the AWS SDK
4 – The server sends the generated pre-signed URL to the RN app
5 – The RN app performs a HTTP request with the pre-signed URL to upload the image to S3

Let me know how it goes for you in the comments 🙂


We can work together

Share this post on social media:

August 10, 2017 ademcan No comments

How to get a specific sequence (chromosome, start, end) from the command line?

In several of my projects, I have to focus on specific regions of a genome, let’s say while looking for binding peaks. It is quite common to download a full genome as a fasta file, or each chromosome separately from Ensembl or NCBI. However, it is difficult to get a specific region of a genome (chromosome, start, end). I didn’t find any easy solution for it so far. Therefore, I focused on using tools available directly from NCBI, the e-utilities.

To get a specific region of the genome one needs to know the GI identifier of the chromosome of interest. Let’s say we are interested in sequences from chromosome 2L of Drosophila melanogaster. The first step is to search for it on the Nucleotide database of NCBI.

Here, we have to note the GI identifier (667674288)

Then, the command to run is

efetch -db=nuccore -format=fasta -id=667674288 -seq_start=12200 -seq_stop=13000

This will return the sequence of chromosome 2L between positions 12200 and 13000 in fasta format as follow:

>AE014134.6:12000-12200 Drosophila melanogaster chromosome 2L
ATTTCATATGTATTCACAACTTCATCACATGCGTAGGTTTCCTTATTATTCTCTGCATCATTTTCTTCCA
ACACAGACTCTTCATTTTCTAATGGTTCTACTGGAACAACGCCAGTGGGTTGCACGACTCTGGACGTGGC
TAAAGCAATACGCTGCAGTTCAGAAGAAGACATCATATACAGTGCTTCTCCAGAGTTTGTA

This command gets really handy when working with multiple regions. One could save all the regions of interest in a tab separated file with one column containing the start position and the other the end positions such as:

12000    12200
13500    13700

and then use awk to get the sequences for all those regions and save it as a fasta file:

awk '{ system("efetch -db=nuccore -format=fasta -id=667674288 -seq_start="$1" -seq_stop="$2" ") }' dmel_chr2L_peaks.txt > dmel_chr2L_peaks.fasta

Enjoy and let me know if you have any alternative solution for this problem.