Sunday, August 26, 2018

How to work with fake REST API?


Sometimes it is necessary to work with fake REST API for practice projects. To achieve such necessity we can implement JSON Server as follows:

npm install --save json-server

the above command is to install json-server package on nodejs project. Then next we can create a json file name db.json and can add json data as follows:

{
    "users": [
        {"id": "23", "firstName": "Bill", "age": 20},
        {"id": "44", "firstName": "Samantha", "age": 30}
    ]
}

Now we need to add script inside the package.json file with this text "json:server": "json-server --watch db.json" and full scripts as follows:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "json:server": "json-server --watch db.json"
  },


To run json server we can execute the command as follows:

npm run json:server

We can now access the db.json file's contents using the server url http://localhost:3000/users. 

To know more: https://github.com/typicode/json-server

Friday, August 24, 2018

How To Setup GraphQL With NodeJs

We know about RESTFul API which has some complexity in different cases, for example nested http request like domain.com/api/user/frinds/positions/companies and also mutiple http requests concurrently which make the server slow down. And of-course chunk of information instead of full model.

To overcome such problems, GraphQL comes which is a query language for API and querying data as runtime.

To setup GraphQL with NodeJs following steps need to be followed:

npm init 

the above command is to initiate NodeJs environment.

npm install --save express express-graphql graphql lodash

through the above command we will install some dependency packages like express for NodeJs server express-graphql the middleware or bridge layer between express and graphql and lodash is for some utility features.

After installing dependency packages above we need to create express server by creating a file named server.js and add code as follows:

const express = require('express');
const expressGraphQL = require('express-graphql');

const app = express();

app.use('/graphql', expressGraphQL({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening');
});

in the above code we have created express nodejs http server to listen the port number 4000 and then bound graphql middleware with expressjs.

Tuesday, August 21, 2018

Configuring Webpack for Development Purpose


In my earlier post I have discussed about the installation of webpack and webpack-dev-server for a project. In this post I will discuss how to start/run webpack dev server configuring with webpack. To do so, first of all we need to add a command in scripts of package.json file as follows:

"start": "webpack-dev-server"

Make sure “webpack-dev-server” is the package name installed under devDependencies. And the full scripts will be looked like below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server"
  },

When we run npm start command the “webpack-dev-server” will be executed but it will seek a webpack config file which need to be created in the project root folder and the name should be webpack.config.js. We will add some configuration settings in this file as follows:

const path = require('path');
const autoprefixer = require('autoprefixer');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    devtool: 'cheap-module-eval-source-map',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        chunkFilename: '[id].js',
        publicPath: ''
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 1,
                            modules: true,
                            localIdentName: '[name]__[local]__[hash:base64:5]'
                        }
                     },
                     {
                         loader: 'postcss-loader',
                         options: {
                             ident: 'postcss',
                             plugins: () => [
                                 autoprefixer({
                                     browsers: [
                                        "> 1%",
                                        "Last 2 versions"
                                     ]
                                 })
                             ]
                         }
                     }
                ]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                loader: 'url-loader?limit=8000&name=images/[name].[ext]'
            }
        ]
    },
    plugins: [
        new htmlWebpackPlugin({
            template: __dirname + '/src/index.html',
            filename: 'index.html',
            inject: 'body'
        })
    ]
};

In the above configuration code “devtool” is used to generate source map. The “entry” option is used to set entry point from where the webpack should start. And “output” option is used to set output location and filename of “bundle.js” that is the compressed version of all js into a single file. 

The “resolve” key is using for automatically finding extensions like .js or .jsx if we don’t add these extension with the file location while importing into the react code. 

The “module” key is used to add some rules on js/css or other files excluding certain unnecessary files to be optimized.

We also need to install some dependencies which are needed for this configuration as follows:

npm install –save-dev css-loader style-loader postcss-loader autoprefixer url-loader file-loader webpack-cli html-webpack-plugin rimraf

We also need to config babel which can found through this link below:


Monday, August 20, 2018

Configuring Babel with A Project

Babel is one of the architecture of modern javascript eco-system which works as a transpiler or converter to compile next generation javascript code to be worked with older browser. To work with babel we need to configure with the project. First of all we need to create babel config file in the project root folder as follows:

.babelrc

before going with the settings we need to install all the dependencies of babel using npm package as follows:

npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-env babel-plugin-syntax-dynamic-import babel-preset-stage-2 babel-polyfill 

After installing babel dependencies we need to set those presets we have installed as npm package as follows:

{
    "presets": [
        ["env", {
            "targets": {
                "browsers": [
                    "> 1%",
                    "Last 2 versions"
                ]
            },
            "useBuiltIns": "entry"
        }],
        "stage-2",
        "react"
    ],
    "plugins": [
        "syntax-dynamic-import"
    ]
}

In the above settings we have added "env" preset to support target browsers from minimum to maximum version of browsers. Then we have added "react" preset to work with react jsx and next generation javascript code.

Sunday, August 19, 2018

Installing ReactJs Production Dependencies


It is crucial to know production dependencies for ReactJs application. And here are some listed as follows:

react
react-dom
react-router-dom

We basically import React for JSX and Component for class or container based component from dependency 'react'.

ReactDOM to render entry point component into DOM from 'react-dom' and Link, BrowserRouter from 'react-router-dom'.

Since these are production dependencies so we can install using npm package adding white spaces as follows:

npm install --save react react-dom react-router-dom

Wednesday, August 15, 2018

How to set up webpack for a project?

In one of my project I needed to work with webpack and for this I need to install webpack and other dependency modules using npm package as follows:

npm init
npm install --save-dev webpack webpack-dev-server

in above two commands the first one is to set up node package configuration file the package.json to install node modules.

And the second line is to install depedency modules like webpack and webpack-dev-server which is the developement server to test the application locally.

Tuesday, August 7, 2018

Angular Style Guide

It is good practice to update yourself when needs. Recent I have been working in an angular project so it is important to update myself with the style guide of angular. I have found a tutorial from angular official site as follows:

https://angular.io/guide/styleguide

it may help me or you later :)

AngularJs Style Guide

Recent I have come up with my angularJs knowledge shaping up with a style guide. I have found a tutorial to make it possible as follows:

https://github.com/toddmotto/angularjs-styleguide

it may help me or someone later :)

Saturday, July 21, 2018

FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformClassesWithDexBuilderForDebug'. > java.io.IOException: Could not delete path

I was working in a ReactNative project and while setting up it's environment was getting error as follows:

FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformClassesWithDexBuilderForDebug'. > java.io.IOException: Could not delete path


After removing the build directory from root directory -> android -> app 

it just did the trick :)

Error: Incompatible HAX module version 3, requires minimum version 4 in Android Studio


Sometimes it is needed to create virtual device while working on android studio that I did on working in an android project. But when tried to launch the device some errors occurred as follows:

Emulator: Incompatible HAX module version 3, requires minimum version 4
Emulator: No accelerator found.
Emulator: failed to initialize HAX: Invalid argument

So found the solution to sort this out as follows:

Steps:

Android Studio: Tools -> SDK Manager

Under Default Settings:

Appearance & Behavior -> System Settings -> Android SDK:

You should see “Android SDK Location” with text field. Copy that location and search through in your windows explorer. For me the location is: “C:\Users\YourUser\AppData\Local\Android\Sdk” in this location navigate through other segment like: 

\extras\intel\Hardware_Accelerated_Execution_Manager so the full path is: 

C:\Users\YourUser\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager

And there find the file name “intelhaxm-android.exe” and click on it to install. 

After installing it launch again the AVD device.

Cool! It’s done J

Wednesday, July 18, 2018

Sort array of objects by property name in javascript

I was working with javascript sort method to sort out an array of objects with a scenario like I needed to sort by object property 'name' but using only sort method didn't fullfill my requirements so I came with additional method implemented as a middleware of sort method like below:

Current Result:
const objArray = [
{ name: 'Z', age: 32},
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'A', age: 53}
];

Expected result:
const objArray = [
{ name: 'A', age: 53}
{ name: 'B', age: 23},
{ name: 'C', age: 45},
{ name: 'E', age: 33},
{ name: 'Z', age: 32}
];

objArray.sort(sortBy('name', false));


function sortBy(key, reverse) {
 var moveSmaller = reverse ? 1 : -1;
 var moveLarger = reverse ? -1 : 1;
 return function(a, b) {
  if (a[key] < b[key]) {
    return moveSmaller;
  }
  if (a[key] > b[key]) {
    return moveLarger;
  }
  return 0;
 };
 
}

It may help someone like me :)

Tuesday, June 5, 2018

Some necessary git commands

While working on git I had to follow some git commands to execute some tasks which are following:

git Add -A //(add to stage)

git commit 'message' //(commit stage files)

git commit -am 'message' //(add to stage and commit stage files in one command)

git push origin branchName //(push all your local changes to production in specific branch)

git branch branchName //(create branch)

git checkout master //(switch branch to master branch)

git merge branchName //(merge specific branch with selected branch)

git pull origin master //(pull changes from master branch from production)

git branch //(list all created branch)

git branch -d branchName //(delete a specific branch)

git checkout -b branchName //(create and switch to a specific branch in one command)

Hope it may helps someone or me later :)

Tuesday, January 2, 2018

More than one DbContext was found while updating sql database in EF

While updating my sql database after adding migration I have got error from console like below:
More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.
because I have two dbcontext in my project. so here is the solution for it if someone face such problem:
Update-Database -Context MyContext1