Server Side Rendering using React16, material-ui and redux Video Tutorial

Complete Source Code for server side rendering in ReactJS using material-ui and redux is explained step by step here

You can also see details about each code segment and download source code from github here

Life Beyond Structure, Analysis, program and computers

I found this wonderful video and found the meaning of life, you may be a programmer, a civil engineer, a car maker, a researcher, a teacher or a student whoever you may be, but one must listen to this talk by Prof. Devdas Menon, Department of Civil Engineering, IIT Madras

Some of the very interesting point taken out from this video are as follows

George Calvin’s famouse quote in 80’s
The paradox of our time and history is that


We tall the buildings but short the temper,
wide our free ways but narrowed our view point
we spend more but we have less
we buy more but we enjoy less
we have bigger houses but smaller family
we have more knowledge but less judgement
we have more experts but yet more problems
we have more medicines but less wellness
we multiplied our positions but reduced our values
we talk too much , drive too fast , stay up too late, getup too tired, we have reached moon and back to earth but trouble crossing a road to meet a neighbour,
we have conquered outer space but not inner space
we have done larger things but not better
we have learnt to rush but not to wait
we have fast food but slow digestion
a big men but small character
too many young couple but more divorces
more entertainment but less happiness

MASLOW’s Hierarchy Of Needs

Matthieu Ricard’s Quote

A French Scientist, who turned as tibetan monk

We all tried consciously or unconsciously, competently or clumsily , Passionately or calmly, adventurously or routinely to be Happier, Yet we more often confuse the genuine happiness with merely seeking enjoyable sensation. Happiness is state of inner fulfilment but not the gratification of inexhaustible desire for outer things. This is traditional wisdom.

Kabir Das Said it beautifully in 15th century in one of his famous doha as

कस्तूरी कुंडल बसे,मृग ढूँढत बन माही। ज्योज्यो घट– घट राम है,दुनिया देखें नाही ।।

Listen to this nice video by Prof. Devdas Menon, Department of Civil Engineering, IIT Madras

java.lang.BootstrapMethodError: Exception from call site bootstrap method

Exception – BootstrapMethodError: while parsing CSV using OpenCSV in Android App


java.lang.BootstrapMethodError: Exception from call site #30 bootstrap method
        at org.apache.commons.lang3.Validate.notNull(Validate.java:225)
        at org.apache.commons.lang3.reflect.FieldUtils.getAllFieldsList(FieldUtils.java:217)
        at org.apache.commons.lang3.reflect.FieldUtils.getAllFields(FieldUtils.java:202)
        at com.opencsv.bean.util.OpencsvUtils.determineMappingStrategy(OpencsvUtils.java:66)
        at com.opencsv.bean.CsvToBeanBuilder.build(CsvToBeanBuilder.java:210)
        at com.example.rkmmedialibrary.MainActivity.importCsv(MainActivity.java:95)
        at com.example.rkmmedialibrary.MainActivity.onActivityResult(MainActivity.java:80)
        at android.app.Activity.dispatchActivityResult(Activity.java:7454)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassCastException: Bootstrap method returned null

Solution: for BootstrapMethodError

The issue is probably due to Java Version Mismatch, Kindly add below code in your build.gradle file


compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

Reference: SO Post

Sequelize: Using “Include” when we are joining same table multiple times.

“Include” with single join

Let us first see how we can use include when we are joining 2 simple tables.

Note: If you are already aware of single join, then jump to section “Include” with multiple joins

Consider the following two tables,

User Table

const UserModel = db.define(
  "users",
  {
    userId: {
      field: "userId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    firstName: {
      field: "firstName",
      type: sqlOperator.STRING(100),
      require: true
    },
    lastName: {
      field: "lastName",
      type: sqlOperator.STRING(100),
    },
    email: {
      field: "email",
      type: sqlOperator.STRING(255),
      validate: {
        isEmail: true
      }
    },
    {
    tableName: "users",
    timestamps: true
  }
);

Notice Table

const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId"
  });

When we want to fetch the user who has posted the notice, we will use the following code,

const query ["include"] = [{model: UserModel}]
// query can include all some conditions required, this is out of scope of this tutorial, for the same you can check out this 
const notices = await NoticeModel.findAll(query);

Reference

After executing the above findAll, we will get all the notices and the respective user who has created that.

“Include” with multiple joins

In this section we will learn how to use when there are multiple join of the same table.

We will make some changes in the Notice table as follows,

const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId"
  });

//Added one more new relation
NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeTo",
      allowNull: false
    },
    targetKey: "userId"
  });

Now we will try to run the same above findAll, we will observe that neither noticeTo nor noticeBy will be filled.

What is happening here is Sequelize finds multiple userModels so it will not be sure which one to fetch.

Solution

To solve the above issue we will have to make the following changes

const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId",
    as : "noticedBy"
  });

//Added one more new relation
NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeTo",
      allowNull: false
    },
    as: "noticedTo",
    targetKey: "userId"
  });

And in the find we will do this,

const query["include"] = [{model: UserModel, as: "noticedBy"}, {model: UserModel, as: "noticedTo"}]

const notices = await NoticeModel.findAll(query);

Once we add the above changes, both noticedBy and noticeTo will be filled. (Observe we have not kept the alias name same, we have changed them slightly).

Possible errors

uncaughtException: Naming collision between attribute ‘noticeTo’ and association ‘noticeTo’ on model notices. To remedy this, change either foreignKey or as in your association definition\nError: Naming collision between attribute ‘noticeTo’ and association ‘noticeTo’ on model notices

What does the above error mean?

It says that we have given same names to the attribute i.e foreign key and alias. We get this with the following code,

  NoticesModel.belongsTo(UserModel, {
    foreignKey: "noticeTo",
    as: "noticeTo",
    targetKey: "userId"
  });

As we can see the highlighted rows, both have the same names. Solution to this is very simple, just rename alias to something else.

  NoticesModel.belongsTo(UserModel, {
    foreignKey: "noticeTo",
    as: "noticedTo",
    targetKey: "userId"
  });

TADA!!! everything will work fine now.

For More Sequelize Errors: Read More Here

Client Server Architecture And Basics of Server Side Rendering – Video Tutorial

A Video Tutorial on Server Side Rendering, which describes how exactly client side rendering happens, what are the benefits on Server Side Rendering.

React16 Server Side Rendering (SSR) CSS and Images Not Loading Issues

Before looking into React16 SSR css and images related issues first check go through a Step By Step guide for implementing React16 Server Side Rendering (SSR) with Material-ui library

React16 SSR css & public images not loading issue

Since in SSR applications we configure our own http server using expressjs or any other framework, we have to configure the path for public folder and css files folder path so that http server finds the file when request comes.

To fix css and public images not loading issue which is a very common issues in react ssr applications, we have to add following below lines in our server side script

//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build'))); 
app.use(express.static(path.join(__dirname, 'public')));

if above two lines are not added in your server side script then you may face following common issues.

  1. Bootstrap/jquery css files are not getting included after running npm run build and running the app
  2. images referred from public folder will not be loaded

ComponentDidMount not getting called in React SSR application

Another very common problem in react ssr applications is once we enable server side rendering client side rendering will stop happening. Since client side rendering doesn’t happen componentDidMount will not be fired some times.

React run build generates lots of javascript files under build/static/js folder, if these files are not served by our server side script when browser requests those files then client side rendering fails. when we generate build using npm run build, react-scripts refers those static js files in index.html file. When page is loaded browser requests for those js files but our server side script fails to serve those files.

again to solve this issue the above two lines code is important especially,

//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build')));

COVID-19 : corona virus epidemic, What one can do to stop it?

The world has hit badly by an invisible tiny virus who is shaking the entire scientific, medical community and challenging to save the lives. Corona virus is not that critical if every one takes some simple precautions but as usual we did mistakes, we neglected and hence paying for it and struggling to escape from it.

Coronavirus is spreading very fast, its an exponential way, person to person through different medium and hence an extreme precautions has to be taken to stop it

Social Distancing:

A simple technique can save our life and save your family, social distancing. Virus can spread through person to person when a infected person cough, spit, sneezes.

It will also spread through some surfaces when an infected person touch any metal surface, cardboard, plastic the virus can survive several hours on the surface and some one else touch the same surface it will transfer to his body.

Look at the below animated view which helps us to understand how social distancing helps us to stop coronavirus spread drastically

Is’t it a simple solution ? but we are failing follow.

“By our most conservative estimate, at least 59% of the infected individuals were out and about, without being tested and potentially infecting others,” says lead study author Prof. Wu Tangchun. Reference

What you should not do ?

Avoid

  1. Parties, functions
  2. Smoking
  3. Avoid taking tablets on your own for fever , cold or headache.
  4. touching your eyes, nose and mouth without washing it properly with soap and water or sanitisers

Social Warriors and NGOs working for Covid-19

There are lot of NGOs, social warriors working for coronavirus epidemic to stop it, lot of awareness programs running for COVID-19, lot of donations are being raised by many organisations to help the needy people in this lockdown situation almost everywhere in the world

Awareness Programs Run by SociallyGood Platform through some of the organisations

Awareness Campaign For Pandemic COVID-19

Awareness program by Sewa USA :

Coronavirus-(COVID-19) Awareness Program

Donate for Covid-19 epidemic

Donation Campaigns run by SociallyGood Platform through some of the organisations

Groceries to daily wage workers in view of outbreak of COVID-19

Support to Fight COVID-19

know more about COVID-19 through SociallyGood Platform

COVID-19 Campaigns on SociallyGood Platform

Let us stop Coronavirus by following the protocol

  1. Lockdown : Be at home, do not go out without the real need
  2. Social Distancing: Keep distance between people
  3. Be wise not panic
  4. Improve your health by doing simple physical work like yoga

COVID-19 Information Center on Facebook

Amazon AWS RDS Failed to Connect to MySQL at with user using MySql Workbench

When trying to connect to Amazon AWS RDS from local machine using MySql Workbench , if you face connection issue like error: Failed to Connect to MySQL at with user Kindly follow below steps

Follow setting up security group : Refer

Then set public access try by following these steps

To change the Publicly Accessible property of the Amazon RDS instance to Yes:

1.    Verify that your VPC has an internet gateway attached to it and that the inbound rules for the security group allow connections.

2.    Open the Amazon RDS console.

3.    Choose Databases from the navigation pane, and then select the DB instance.

4.    Choose Modify.

5.    Under Network & Security, choose Yes for Public accessibility.

6.    Choose Continue.

7.    Choose Modify DB Instance.

DB Import Error due to Triggers :

ERROR 1419 (HY000) at line 918: You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

To fix this issue follow steps

  1. Open the RDS web console.
  2. Open the “Parameter Groups” tab.
  3. Create a new Parameter Group. On the dialog, select the MySQL family compatible to your MySQL database version, give it a name and confirm. Select the just created Parameter Group and issue “Edit Parameters”.
  4. Look for the parameter ‘log_bin_trust_function_creators’ and set its value to ’1′.
  5. Save the changes.
  6. Open the “Instances” tab. Expand your MySQL instance and issue the “Instance Action” named “Modify”.
  7. Select the just created Parameter Group and enable “Apply Immediately”
  8. Click on “Continue” and confirm the changes.
  9. Wait for the “Modifying” operation to be completed.
  10. Again, open the “Instances” tab. Expand your MySQL instance and
  11. expand “Instance Action” tab and select “Reboot”.