Warning: The magic method TVA_SendOwl::__wakeup() must have public visibility in /home/imolexbg/codingsrc.com/wp-content/plugins/thrive-apprentice/inc/classes/class-tva-sendowl.php on line 136

Warning: Cannot modify header information - headers already sent by (output started at /home/imolexbg/codingsrc.com/wp-content/plugins/thrive-apprentice/inc/classes/class-tva-sendowl.php:136) in /home/imolexbg/codingsrc.com/wp-includes/feed-rss2.php on line 8
Page not found – CodingSrc https://codingsrc.com Your source to learn coding Wed, 08 Apr 2020 10:15:18 +0000 en-US hourly 1 https://wordpress.org/?v=5.4.23 https://codingsrc.com/wp-content/uploads/2020/03/codingsrc_black_rounded-1.png Page not found – CodingSrc https://codingsrc.com 32 32 JavaScript Multidimensional Array https://codingsrc.com/javascript-multidimensional-array/ https://codingsrc.com/javascript-multidimensional-array/#respond Tue, 07 Apr 2020 21:44:40 +0000 http://codingsrc.com/?p=1257 Arrays provide a great way to organize related data together. In programming languages, like JavaScript, the simplest form of an array is known as a one-dimensional array or single-dimensional array. But, most of the time, we require to store multiple types of data for each element of an array. Here, JavaScript introduces the concept of […]

The post JavaScript Multidimensional Array appeared first on CodingSrc.

]]>
Arrays provide a great way to organize related data together. In programming languages, like JavaScript, the simplest form of an array is known as a one-dimensional array or single-dimensional array. But, most of the time, we require to store multiple types of data for each element of an array. Here, JavaScript introduces the concept of a multidimensional array. Basically, it allows us to create a nested array or in simple words, arrays inside an array.

Today, I’ll explain the usage of JavaScript multidimensional array with the help of step by step examples. For the purpose of this tutorial, I’ll create a multidimensional array of college students. In parent array, each item contains a child array that is used to store the details of a specific student.

Usage of JavaScript Multidimensional Array

Unlike regular variables, arrays are useful when you want to display a lot of related data with the help of a loop. Let’s quickly have a look at the possible use cases where JavaScript multidimensional array might be suitable.

Use case 1: Google Search Engine Results Page

Did you notice that Google Search Engine Result displays only 10 records per page? This is a great place to make use of a multidimensional array. Here, they might store data of each record in a separate array and at last group them in a parent array after applying some sorting. This way, it is very easy to loop through the main array in order to display the records on the screen.

Use case 2: Facebook’s News Feed

Similarly, Facebook’s News Feed is a place which frequently updates with the latest post from your friends, groups or pages you like and some sponsored stuff. It is quite possible that they use a multidimensional array to store the data of posts that should be displayed on the user’s screen.

Now you might be wondering that the above-mentioned websites process data on the server while JavaScript is used on a client. So, how these use cases apply to us. Let me tell you that with the advent of Node.js it is possible to use JavaScript programming language on the server-side for developing dynamic web applications.

Create a Multidimensional Array in JavaScript

There are two different ways to define an array in JavaScript. One method is to make use of Array() constructor while the other is known as “array literal notation” where you simply use square brackets to mark the start and end of your array.

I’ll use the second method because it is the preferred way to create arrays in JavaScript by many professional web developers.

let students = [
    ['furqan', 1001, 24],
    ['ali', 1002, 35],
    ['john', 1003, 20]
];

In the above code, I’ve defined an array of arrays to store the data of three students. The first element of each child array contains the student name, second element stores the roll number and at last, I’ve provided the age of each student. Always remember to put a comma after each array item, no matter whether it is the main array or a nested one.

A point to be noted is that just like variables you need to place string type data inside single or double quotes while numbers can be used as it is inside an array.

Access Specific Element

Now that we’ve initialized an array, its time to retrieve an existing value from it. To do so, we have to provide the array index where the value exists. In JavaScript arrays, each item is stored in a specific index. An index is a number that starts from zero and keeps infringement by 1 until the end of an array.

To access and display the age of the second student we have to use the below code snippet.

document.write(students[1][2]);

Here, you might be wondering why I’ve provided two separate indexes in square brackets. The reason is that the first index refers to the parent array while the second index is used to specify the item inside the child array.

Update Value of Specific Array Index

To update a value inside an array, we first need to access that specific array element using its index and then simply initialize it with a new value. Just like any other JavaScript variable.

In our case, I’ll update the age of the first student using the below code.

students[0][2] = 30;

Now to check whether our change is applied to the array element or not, simply display it just like we did in the previous section.

document.write(students[0][2]);

Add New Items in JavaScript Multidimensional Array

Once again we’ve two options to add an item inside our array. One is by using the push() method and the other one uses the “square bracket notation”.

Using push() method

students.push(['ibrar', 1004, 21]);

Using Square Brackets

students[4] = ['Mark', 1005, 50];

Delete Element From Multidimensional Array JavaScript

JavaScript comes with two functions shift() and pop() that allow us to remove first and the last item from an array respectively.

If you want to remove the first student from the JavaScript multidimensional array then use this code:

students.shift();

Similarly, you can also delete the last array element using the below code.

students.pop();

Please note that both of these functions will in turn also update the length of an array.

Display JavaScript Multidimensional Array

In this section, I’ll guide you about how you can use a JavaScript for loop to iterate through each element of an array. In our case, I will use the existing “students” array and display each student on a separate line.

You might already be familiar with how to create a “for” loop. But, as we need to automate the retrieval process of each and every item inside an array. So, we can check how many items there are in a specific array by using its length property.

for(let i = 0; i < students.length; i++) {
    document.write(students[i]);
    document.write('<br />');
}

Conclusion

As you have just seen that JavaScript multidimensional arrays provide a way better organization of data than a bunch of random variables. It is all possible because arrays take consecutive storage space inside our memory.

The post JavaScript Multidimensional Array appeared first on CodingSrc.

]]>
https://codingsrc.com/javascript-multidimensional-array/feed/ 0
Node.js Tutorial for Beginners in Visual Studio Code https://codingsrc.com/node-js-tutorial-for-begginers-in-visual-studio-code/ https://codingsrc.com/node-js-tutorial-for-begginers-in-visual-studio-code/#respond Sun, 22 Mar 2020 19:41:06 +0000 http://codingsrc.com/?p=1222 With the evolution of web development, faster and better technologies are coming day by day to enhance our workflow. Node.js is one of them. Previously, JavaScript programming language was only restricted inside a client-side web browser environment. But with the advent of Node.js, it provides us the ability to execute JavaScript code on the server. […]

The post Node.js Tutorial for Beginners in Visual Studio Code appeared first on CodingSrc.

]]>
With the evolution of web development, faster and better technologies are coming day by day to enhance our workflow. Node.js is one of them.

Previously, JavaScript programming language was only restricted inside a client-side web browser environment. But with the advent of Node.js, it provides us the ability to execute JavaScript code on the server.

This significant invention opens up a door for hundreds of possibilities for JavaScript front-end developers. Now, you don’t have to learn a separate language in order to become a full-stack developer. You can simply use your existing JavaScript skills on both front-end as well as the back-end of a website.

This tutorial will cover the “What, Why and How” for beginners who are completely unfamiliar with the word Node.js. So, let’s jump into the actual content of this article to understand it.

What is Node.js?

Different web browsers use some kind of an engine to understand the code written in JavaScript programming language. Google Chrome uses “V8”, Microsoft Edge has its own “Chakra” while Mozilla Firefox is packed with “SpiderMonkey”.

The idea behind the development of Node.js is that a software engineer named Ryan Dahl wants to use the engine of web browsers for any kind of JavaScript-based software development. So, he reviewed the pros and cons of different browser engines and found that Chrome’s V8 is way better than its competitors. He decided to use it for his ambitious project.

Ryan Dahl uses C++ programming language to create a runtime environment for JavaScript that is completely built on top of Google Chrome’s V8 engine. He named this new project “Node.js”. Now, through Node.js you can use JavaScript code to create a website or a full-fledged desktop application, the ball is in your court now.

What can I do with it?

Mostly Node.js is suitable for creating real-time applications like online games or chat systems. But, in general, it can be used for any kind of software development. It provides complete flexibility for creating a Content Management System (CMS), Blog, Social media or an eCommerce store.

A lot of companies prefer Node.js for developing their RESTful API’s. The reason is simple, unlike other web programming languages or frameworks it supports non-blocking asynchronous programming. In turn, it makes our apps very memory efficient.

Let’s Setup Node.js

To start writing server-side code in JavaScript we first need to download and then install Node.js on our computer system. You can use their official website to download the original software.

On their home page, you might have noticed two buttons. One for the “LTS” version and the other one is for the “Current” version. In most cases, we only need to download the LTS (Long Term Support) version because it is very stable. But, if you want to try bleeding-edge features of Node.js then I would recommend you to install its “Current” release.

A point to be noted is that these days the developers of Node.js have integrated npm (Node Package Manager) inside Node. It is a great utility tool that helps you automatically manage the dependencies of your projects. So, from now onwards you will get both software under one roof.

Download and Install Visual Studio Code

There are tons of code editors and IDE’s (Integrated Development Environment) that allows you to write JavaScript code. Among them, Visual Studio Code is a popular choice of many Node.js developers. It is powered by the tech giant Microsoft and is completely free for personal or commercial use.

It comes with a lot of advanced features that are necessary to increase the productivity of a programmer. Some of them include real-time debugging, IntelliSense, ability to add extensions as well as built-in support for version control using Git.

Hello World Program Using Node.js

At this point, you have Node.js and Visual Studio Code installed on your computer. So, let’s get started by writing a hello world program.

First of all, create a project directory where you will store all of your code files. For now, we’ll only create one file.

Let’s name that file “index.js”, after all, it will contain JavaScript code. Now, put the below source code inside it and save the file.

console.log('Hello World');

To see the above code in action, simply open a command prompt or terminal window in the project folder and execute the below command. It will display “Hello World” in the console.

node index.js

Mini Project

Node.js is packed with a lot of commonly used modules which allows us to do plenty of stuff. For example, it has an “http” module that provides us a head start if we want to create a server. This core module is mostly used when we develop web-based services using Node.js.

Let’s move ahead and use it to set up a local server on our computer so that we can view some output in a web browser.

At first, create a folder that will be used to hold this project’s source code files. Then, create a file named “server.js” where we’ll write the code. For now, type below code inside this file, I’ll explain it in a moment.

const http = require('http')
const server = http.createServer((req, res) => {
	if (req.url === '/') {
		res.write('This output will display in a web browser')
		res.end()
	}
})
server.listen(5000)
console.log('Listening on port 5000')

At the beginning of the above code, I’ve included an “http” module which will be used to create localhost or a local development environment.

Then, I created a server using createServer() method of http module. It accepts 2 parameters, one for “request” and another for a “response”.

The request contains the metadata or the header that provides information like what page to visit etc. Whereas response is used to return data towards the user.

In the conditional statement, I check the URL path of request and if it is from the root page then simply display output using write() function of response. Finally, I closed the response by calling its end() method.

Later on, I ordered the Node.js server to listen on port 5000 and display a console message if everything works as expected. You may change the port if you like, but for the purpose of this tutorial, let’s use it as it is.

It’s time to see our code in action. To do so, open the terminal inside the project folder and run the below command.

node server.js

Now open below URL in any web browser to view the output of our mini-project.

http://localhost:5000/

The post Node.js Tutorial for Beginners in Visual Studio Code appeared first on CodingSrc.

]]>
https://codingsrc.com/node-js-tutorial-for-begginers-in-visual-studio-code/feed/ 0
How to Use Node.js Express Middleware in your Web Application? https://codingsrc.com/how-to-use-node-js-express-middleware-in-your-web-application/ https://codingsrc.com/how-to-use-node-js-express-middleware-in-your-web-application/#respond Sun, 15 Mar 2020 15:12:04 +0000 http://codingsrc.com/?p=1107 Middleware plays an important role when building Node web applications using Express framework. Simply put, you cannot build an Express application without incorporating middleware. So, the possibility is, knowingly or unknowingly, you have used middleware in your Express applications before. Then, it’s high time that you get to know what exactly middleware is and how […]

The post How to Use Node.js Express Middleware in your Web Application? appeared first on CodingSrc.

]]>
Middleware plays an important role when building Node web applications using Express framework. Simply put, you cannot build an Express application without incorporating middleware. So, the possibility is, knowingly or unknowingly, you have used middleware in your Express applications before. Then, it’s high time that you get to know what exactly middleware is and how to get the maximum advantage out of it.

What is Express Middleware?

Middleware is a function that runs in between two other functions. In Express, middleware is run in the time between the server receiving a request and the request approaching its route handler. Middleware function accepts three basic inputs: HTTP request and response objects, and the next middleware function that is going to be called.

function middlewareExample(req, res, next) {
	if (req.someParameter === 1) {
		next()
	} else {
		res.send("Can't continue further")
	}
}

As the example shows, middleware can be used to determine whether the request should be passed on to the next middleware. If not, an appropriate response is sent, ending the lifetime of the request.

Where should Express Middleware be Used?

In general, middleware can be used to carry out any process that has to be completed before finally passing the request to the route handler. However, there are three main occasions where middleware is commonly used.

1. Authentication & Authorization

Express middleware can be used to check whether the requesting user has permission to access the route handler. If the user does not have permission, the request is terminated and a message denying access is sent. Otherwise, the request gets permission to proceed to the next step.

function verifyUser(req, res, next) {
	let token = req.headers['x-access-token']
	if (!token) {
		return res.status(403).json('Log in to continue')
	}

	jwt.verify(token, config.secret, (error, decoded) => {
		if (error) {
			return res.status(403).json('Invalid token')
		} else {
			next()
		}
	})
}

2. Error Handling

Error handling middleware can be used in Express to handle any unhandled error that occurred during the execution. This type of middleware accepts an additional argument, error, along with the previous three arguments.

function handleUnhandledError(err, req, res, next) {
	if (err) {
		res.status(500).send('An error occured')
	} else {
		next()
	}
}

Middleware can then handle the error in an appropriate manner.

3. Logging

Express middleware can be used to logging user requests. Before directing the request to the route handler, the user’s request is logged to keep a record of the user’s access history.

function logUserRequest(req, res, next) {
	logger.info(req.url)
	next()
}

How to Use Express Middleware?

There are several ways to use middleware in an Express application.

The simplest method is using the middleware before all the route handlers in your application.

const app = express()
const middleware = require('/middleware')

app.use(middleware)

app.get('/firstRoute', firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

In this example, the middleware is used before both ‘firstRoute’ and ‘secondRoute’ route handlers.

You can also introduce a route handler specific to a particular route as shown in the following example.

app.get('/firstRoute', middleware)
app.get('/firstRoute', firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

In the above method, the middleware is only used on requests coming to the ‘firstRoute’ route handler.

The final method to use middlewares is using them inside the route handler before the handling function.

app.get('/firstRoute', middleware, firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

Here, the middleware is used inside the ‘firstRoute’ route handler and it applies only to the requests coming to this endpoint.

You can also ‘chain’ middleware functions. Middleware chaining indicates directing the request from one middleware function to another. Chaining can be implemented in any of the three ways shown in the previous examples.

app.use(middleware1)
app.use(middleware2)
app.get('/firstRoute', middleware1)
app.get('/firstRoute', middleware2)
app.get('/firstRoute', middleware1, middleware2, firstRouteHandler)

Here, when the next is called inside the middleware1 function, middleware2 starts its implementation.

Built-in and Third-party Middleware

In addition to defining your custom middleware, Express applications can use built-in or third-party middleware. Here, you can see examples of such usage.

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'))

 

The post How to Use Node.js Express Middleware in your Web Application? appeared first on CodingSrc.

]]>
https://codingsrc.com/how-to-use-node-js-express-middleware-in-your-web-application/feed/ 0
Node.js Express hbs Tutorial (Handlebars) https://codingsrc.com/node-js-express-hbs-tutorial-handlebars/ https://codingsrc.com/node-js-express-hbs-tutorial-handlebars/#respond Mon, 09 Mar 2020 09:36:43 +0000 http://codingsrc.com/?p=1064 Most of the time when we start working on a web project, then it quickly gets complex as we write more and more code. In the beginning, if we don’t structure our code efficiently then it will most probably affect the scalability of our application in later stages. A good starting point is to separate […]

The post Node.js Express hbs Tutorial (Handlebars) appeared first on CodingSrc.

]]>
Most of the time when we start working on a web project, then it quickly gets complex as we write more and more code. In the beginning, if we don’t structure our code efficiently then it will most probably affect the scalability of our application in later stages.

A good starting point is to separate our website logic from the design and view part. This will make the source code a bit more clean and manageable.

If we talk about Node.js and Express application, then you might have noticed that we use JavaScript variables and logical statements directly inside our HTML files. So, in this tutorial, I’ll help you understand the power and usability of Handlebars (a JavaScript Template Engine).  So let’s start with this Node.js Express Hbs tutorial with the available template engines:

Available Template Engines

First of all, let’s have a quick look at available JavaScript template engines that might be more suitable in different scenarios.

Now you have seen that there are tons of template engines that are based on JavaScript language. But, the main reason behind using Handlebars in this tutorial is that it provides a more minimalistic approach than others.

In simple words, through Handlebars, you can achieve more by just writing a few lines of code.

What is Handlebars?

Handlebars is a free and opensource JavaScript Template Engine that allows us to inject JavaScript property values directly into our HTML code. Basically, it works as a compiler, which means that it takes some input, then compiles and transforms it into a result.

In our case, we have to input the HTML and JavaScript code inside the Handlebars file. It will then automatically compile the code (fill the values) and return the actual HTML web page.

At the time of this writing, Handlebars aka hbs has received 15.2K stars on its Github repository. It has a large community of users while 150+ professional developers had contributed their code and time for the enhancement of this library.

It is designed to be the superset of popular library Mustache that is used for generating logic-less templates. To speed up the overall process, it transforms the hbs templates into JavaScript functions.

Setup a Project

Before writing any code, I assume that you have already installed Node.js and Npm on your computer. If so, we’re good to set up our Node.js, Express and Handlebars project.

At first, you need to create a folder that will contain our whole project. After that, install Express and Handlebars in it.

npm i express

npm i express-handlebars

Now we need to create some more folders that will help us arrange our Handlebars templates. I’ll name the main folder as “views” while also adding 2 sub-folders in it with the name “layouts” and “partials”.

Mostly, the templates inside “layouts” folder is used to implement a common style on all web pages of a website while on the other hand “partials” folder contains small reusable parts like header, menu, footer, etc.

For the purpose of this tutorial, let’s create a file named “home.hbs” in “views” and “main.hbs” inside the sub-folder “layouts”.

We will use “main.hbs” to store the layout of our website that can be easily applied on different web pages. Similarly, “home.hbs” refers to the actual file that contains the data of a specific web page.

In this tutorial, I’ll also apply some style to our web page using CSS. So, let’s create a “public” folder inside your project and then place a file called “styles.css” in it.

Start Writing Some Code

Create a file named “index.js” inside your project root and import the recently installed JavaScript modules in it.

Load Express module

const express = require('express');

Load Handlebars module

const handlebars = require('express-handlebars');

To create an Express application you need to initialize it using the below code.

Run Express

const app = express();

Now its time to configure the Handlebars template engine for our app.

Configure our application to utilize the Handlebars engine

app.set('view engine', 'hbs');

Settings for Handlebars

app.engine('hbs', handlebars({
    layoutsDir: __dirname + '/views/layouts',
    extname: 'hbs',
    defaultLayout: 'main'
}));

The first line of the above code snippet is really simple and straightforward as here we are just telling Express to use Handlebars for rendering our web pages. Later on, I added some settings to define the layouts directory, file extension and default layout of Handlebars templates.

Let’s inform Express to allow the usage of static files inside our application from “public” folder. Please note that this step is very important to use static files like CSS on our website.

app.use(express.static('public'));

Now set up a route through which we can access or view our web page.

app.get('/', (req, res) => {
    // Integrates the body of "home.hbs" inside the defaultLayout "main.hbs"
    res.render('home');
});

At last, we just need to set a port and execute our code.

Set a port

const port = 3000;

Start our application

app.listen(port, () => console.log(`App listening to port ${port}`));

Create and Style Web Pages

We already created our template and CSS files. In this section, we have to add some code there.

Open “main.hbs” layout file and insert the below code in it.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>

</body>
</html>

Open “home.hbs” and enter the below code.

<h1>List of Countries</h1>
<ul>
	<li class="blue_item">Australia</li>
	<li class="blue_item">USA</li>
	<li class="red_item">Pakistan</li>
	<li class="blue_item">UK</li>
	<li class="red_item">Japan</li>
</ul>

Now style the above markup language code using CSS.

li {
	list-style: none;
	font-size: 20px;
	width: 300px;
	margin: 5px;
	padding: 5px;
}

.blue_item {
	background-color: #0000ff;
	color: #fff;
}

.red_item {
	background-color: #ff0000;
}

Test our application

Write below code in project console.

node index.js

After that open the website in a browser by typing this URL.

http://localhost:3000/

Now that you have a complete project learn how you can deploy to Heroku under 5 minutes

Conclusion

Handlebars templating engine can have a significant impact on the growth and scalability of your project. It enables us to write better, cleaner and less code due to its minimalistic structure.

A lot of enterprise-level companies use it in their tech stack. Among them, the most noticeable are Intel, Slack, DuckDuckGo and Khan Academy. So, It’s great to have Handlebars.js listed among your professional skills.

The post Node.js Express hbs Tutorial (Handlebars) appeared first on CodingSrc.

]]>
https://codingsrc.com/node-js-express-hbs-tutorial-handlebars/feed/ 0
Eslint Prettier Create React App Best Configuration Setup [2019] https://codingsrc.com/eslint-prettier-create-react-app-best-configuration-setup-2019/ https://codingsrc.com/eslint-prettier-create-react-app-best-configuration-setup-2019/#comments Thu, 07 Nov 2019 10:01:45 +0000 http://codingsrc.com/?p=648 Have you ever wanted to configure Eslint to work correctly with Prettier and your Create React App? If so in this video you will learn the best settings to do that. Steps: 1.Install Eslint Globally npm i -g eslint 2. Open your create-react-app react project or create one by typing npx create-react-app name-of-project (needs npm […]

The post Eslint Prettier Create React App Best Configuration Setup [2019] appeared first on CodingSrc.

]]>
Have you ever wanted to configure Eslint to work correctly with Prettier and your Create React App? If so in this video you will learn the best settings to do that.

Steps:
1.Install Eslint Globally
npm i -g eslint

2. Open your create-react-app react project or create one by typing
npx create-react-app name-of-project
(needs npm 5.2+)

3. Initiate Eslint in your project:
eslint --init
(answer the questions)

4. Confirm installation of eslint-plugin-react

5. Leave this in your ESlint config:

"env": {
      "browser": true,
      "es6": true
},
"extends": ["eslint:recommended"],
"plugins": ["react"],
"parserOptions": {
      "ecmaVersion": 2018
},
"rules": {}

6. Install eslint-config-react-app peer dependencies:
npm install-peerdeps --dev eslint-config-react-app

7. Install prettier dependencies:
npm i -D eslint-config-prettier eslint-plugin-prettier prettier

8. Configure Prettier through ESlint example:


{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": ["react-app", "prettier"],
    "plugins": ["react", "prettier"],
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "rules": {
        "prettier/prettier": [
            "error",
            {
                "printWidth": 80,
                "trailingComma": "es5",
                "semi": false,
                "jsxSingleQuote": true,
                "singleQuote": true,
                "useTabs": true
            }
        ]
    }
}

9. Change your VScode settings

"eslint.autoFixOnSave": true

10. Check for conflicting rules with the following script in package.json:

{
    "scripts": {
        "eslint-check": "eslint --print-config path/to/main.js | eslint-config-prettier-check"
    }
}

 

The post Eslint Prettier Create React App Best Configuration Setup [2019] appeared first on CodingSrc.

]]>
https://codingsrc.com/eslint-prettier-create-react-app-best-configuration-setup-2019/feed/ 2
Solidity Tutorial – Intro To Solidity Programming Language https://codingsrc.com/solidity-tutorial/ https://codingsrc.com/solidity-tutorial/#respond Mon, 03 Jun 2019 21:41:19 +0000 http://codingsrc.com/?p=602 In this lecture we are going to talk about contracts, constructors and functions. OK, let’s dive right in. Let’s first see what is the structure of a solidity source file. Here we can see a sample contract. On the top of every solidity file there is the so called version pragma, which tells us the […]

The post Solidity Tutorial – Intro To Solidity Programming Language appeared first on CodingSrc.

]]>
In this lecture we are going to talk about contracts, constructors and functions.

OK, let’s dive right in.

Let’s first see what is the structure of a solidity source file.

Here we can see a sample contract.

On the top of every solidity file there is the so called version pragma, which tells us the lowest version of solidity supported by the contract.

After that we have the contract and its name.

Inside  it we can put variable declarations, mappings, constructors, functions, modifiers etc.

Now, let’s see a sample contract.

Here we have two contracts called Owned Token and Token Creator. You can have multiple contracts declared in one solidity file.

As you can see we can also call contracts from other contracts as in this example.

After this we have the variable declarations owner and name, which are used to store the address of the owner of the contract and the name of the contract.

Just below them we have a constructor. Keep in mind that several versions before a constructor was declared as a function with the same name like the contract. However, now we use the keyword constructor.

So a constructor is a function that runs only once when the contract is deployed to a network.

When we deploy this contract we can send the variable name with it. This variable is saved in the state variable name and our wallet address, from which we deployed the contract with, is saved in the state variable owner.

Now we can use this reference to check and restrict functions to be used by someone who is not the owner of the contract.

Ok, now lets see what is the structure of a function.

If you are familiar with JavaScript., functions look a lot like the ones there. However, we have some additional modifiers. After the function name and the variables that the function receives, we have visibility declaration, state mutability and the return types of the function.

For visibility we can have public, private, internal and external. For the state mutability we can have pure, view and payable. And in order to return some variables from a function at the end we should add the keyword ‘returns’ and in brackets the type of variables that we want to return. Here we can return more than one variable, so keep that in mind.

Ok, let’s look at the different types of visibility in more detail. As we said we have 4 different types of visibility – public, external, internal and private.

Those visibility declarations can be applied both to functions and variables except for the external keyword which is only for functions.

When we declare a function the default visibility of it is public. Basically we can call this function internally and externally and everyone has access to it.

The external keyword works almost the same, however, when you try to call the function internally (from within the contract or another function in the contract) you will need to use the ‘this.’ in order to access it.

This might seem a little inconvenient, however external functions can cost less gas sometimes, because sometimes they are more efficient when they receive large arrays of data.

We can also have internal functions that can only be accessed internally from the current contract or from contracts deriving from it.

And last but not least, we have private functions which can be called ONLY from the contracts they are defined in. The are usable only internally in the same contract.

Now let’s see an example of external and public functions.

Here we have а Sample contract.

At the first line as you can see I have declared a variable as external. If you try to do that you will get an error and the contract will not compile. Remember – state variables do not have an external visibility.

However, here I have created public and external functions. Both of them do the same operation, but the external function will cost less gas in the end. External functions are more efficient when they receive large arrays of data so you can use them to make your contract more efficient.

And at the end I have declared a function in which i try to call the external function test2. However, I needed specify it as this.test2() in order to access the external function internally.

So remember if you want to call external functions internally you need to add the keyword this. In front of the function.

Now, let’s look at an example of internal and private functions.

Here we have 3 contracts C, D and E.

Contract C has one private function, two public functions and an internal function called compute.

In contract D if we try to call the function f of the contract C we are going to get an error because the function is declared private and is visible only inside the contract that it is defined in.

Also if we try to call the function compute from contract D we are also going to get an error because contract D is not derivative of contract C.

However, contract E is derivative of C. We declare this with the keyword ‘is’ as you can see in the example. If you have any prior programming knowledge this is called inheritance.

Because, our contract is derivative of contract C we can now call the the compute function as it is internal member.

Now, let’s talk about the state mutability of function.

We have three different modifiers for that.

We have view, pure and payable.

If we declare a function to be a view function we basically promise no to modify the state.

Pure functions are derivatives of view functions. However, pure functions promise not only not to modify the state, but also not to read from state.

In the next slides we will see more specific restrictions to those functions.

The last state mutability we can have is payable. Basically, the functions that are annotated with this modifier can receive ether and can make operations with those ethers.

Now, let’s look at some examples.

Here is an example of a view function that you can create.

This function takes two variables “a” and “b” and returns “a” times (b + 42) + now.

Now is a global variable that gives you the time now as a timestamp variable.

When you have a view function you CAN NOT write to state variables, emit events, send ether, call functions that are not pure or view, etc. I have listed the things that are not allowed in view functions on the right side here.

Now… Pure functions have the same restrictions as view functions as well as that they can’t read form state variables.

In this example we have 3 pure functions. The first two functions take variables  x and y and do some mathematical operations and return the result. The third one just returns a string of “You are AWESOME!”. Those are some perfect examples of pure functions that you can use.

However, there are some additional restrictions that you should keep in mind like that you can’t access this.balance, <address>.balance, blocks, tx, msg variables or call functions that are not marked as pure.

Now let’s see and example of a payable function.

In order to receive Ether you need to provide the ‘payable’ keyword to a function, otherwise the function will reject all Ether send to it.

In this example contract we have a public declared variable amount of 0 and we have a payable function pay me. The variable msg.value gives the amount of ether that was send to the function and adds it to the variable amount.

The post Solidity Tutorial – Intro To Solidity Programming Language appeared first on CodingSrc.

]]>
https://codingsrc.com/solidity-tutorial/feed/ 0
Why Learn Solidity? 5 Benefits Of Learning Solidity Today! https://codingsrc.com/why-learn-solidity-5-benefits-of-learning-solidity-today/ https://codingsrc.com/why-learn-solidity-5-benefits-of-learning-solidity-today/#respond Thu, 16 May 2019 11:46:28 +0000 http://codingsrc.com/?p=575 Yesterday I was SHOCKED to find out that some of my students haven’t even started my bestselling course Solidity Smart Contracts: Build DApps In Ethereum Blockchain and they have already got enrolled I understand that some of you might have decided to get it and start at some point in the future… However, the sooner you learn […]

The post Why Learn Solidity? 5 Benefits Of Learning Solidity Today! appeared first on CodingSrc.

]]>
Yesterday I was SHOCKED to find out that some of my students haven’t even started my bestselling course Solidity Smart Contracts: Build DApps In Ethereum Blockchain and they have already got enrolled

I understand that some of you might have decided to get it and start at some point in the future…

However, the sooner you learn this technology the better. You will come ahead of the completion as there isn’t so much at the moment.

This is why today I wanted to share with you why you should learn Solidity:

  1. Learning Solidity will increase your chances of getting hired as a freelancer or scoring a full time job. According to USAToday it is the #1 in-demand skill to have as a developer.
  2. Scoring a job in the field will get you the average of over $120,000 per year. That is over $10,000 per month. Don’t believe me? Check the stats here:
    https://cryptocurrencyjobs.co/salaries/solidity-developer/

  3. Launching your own cryptocurrency can earn you between $1000-$1 million depending on your marketing efforts. ICOs have been the main funding source of ideas in the recent years.
  4. Build a dApp and monetizing it is a great business idea. The famous CryptoKittis have $12 millions raised. The first generation of kitties they sold they got %100 of the profits and %3.5 for every transaction after that in the dApp. Not bad, huh?
  5. Cryptocurrencies, web3 and smart contracts are the future! Even Opera, the third most used browser worldwide, has integrated crypto in their software. The future is here, old man!

So what are you waiting for?

Start The Course -> Solidity Smart Contracts: Build DApps In Ethereum Blockchain

Thanks for reading and I hope to see you inside the course!

The post Why Learn Solidity? 5 Benefits Of Learning Solidity Today! appeared first on CodingSrc.

]]>
https://codingsrc.com/why-learn-solidity-5-benefits-of-learning-solidity-today/feed/ 0
VSCode Sync Settings and Extensions Tutorial – Synchronize Devices! https://codingsrc.com/vscode-sync-settings-and-extensions-tutorial-synchronize-devices/ https://codingsrc.com/vscode-sync-settings-and-extensions-tutorial-synchronize-devices/#respond Wed, 15 May 2019 11:08:19 +0000 http://codingsrc.com/?p=570 Isn’t it a nightmare to switch from your P.C. to your laptop and you don’t have any of the Visual Studio Extension snippets and settings. If you want to know how to sync your visual studio across multiple devices in this article you will learn how to do that. So the best way that I […]

The post VSCode Sync Settings and Extensions Tutorial – Synchronize Devices! appeared first on CodingSrc.

]]>
Isn’t it a nightmare to switch from your P.C. to your laptop and you don’t have any of the Visual Studio Extension snippets and settings. If you want to know how to sync your visual studio across multiple devices in this article you will learn how to do that.

So the best way that I have found to sync your visual studio code is this extension here. Settings sync:

https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync

The first thing that you need to do is to install the extension on your VSCode.

Now this extension is using GitHub, where it uploads y our settings to a gist and after that you use the gist to sync your settings to other devices.

Now to start uploading our settings, just press SHIFT + ALT + U for upload, and Visual Studio should open your GitHub page.

There you can create personal access tokens.

If you’re not logged in, make sure you do that. So you would want to click on the “Generate New Tokens” here, on top of it and should ask you to type your password again.

After you are in, you would want to give your access token description or a name  basically. I will give mine the description VSCode Sync Tutorial and after that go ahead and scroll down to where the guest check-box is and check it.

Now let’s click on generate token. This will generate a token for us that we will need to use in VSCode.

Please save this somewhere as we would need it on the other machines as well. Now open back the Visual Studio Code and it should be asking you now for your GitHub token. Go ahead and paste it there and click ENTER. Now you can upload your settings by either pressing SHIFT + ALT + U or if you forget the keyboard shortcut for any reason whatsoever, you can also trigger the plot by pressing F1 and searching for “sync”.

There you should be able to find the command “Sync Update/Upload Settings”. I also want to show you how you can update your token or find it in case you forget it. Search again for “sync” and now click on Advanced Settings. On top you will see ” Edit Extension Local Settings”. C lick on that and you’ll be opening the Sync Local Settings JSON file, and let’s first format it, so we can read it better, by pressing SHIFT + ALT + F.

Now, here you can see our GitHub token. You can change it from here or recover it in case you forget it. Now in order to simulate a new system, let’s reset the extension settings and delete all of our saved extensions and restart this VSCode. O pen the Visual Studio Code again and go ahead and install only the settings sync extension.

After you install it, l et’s download our settings by pressing SHIFT + ALT + D. I t will ask us for our GitHub token again, t hat I told you to save somewhere. So paste that there. Now it will also ask those for GistID that sync settings has created. S o in order to find that, go to your GitHub and open your Gists, and find the one that was last created by the settings sync. Now open this and in the browser address, after your name and the forward slash, t his would be the ID of your Gist.

Copy this and paste it in the extensions. Now you can freely sync your settings. One other cool thing that you can do this with this extension is that you can share your settings in a public Gist and everyone will be able to sync with them.

For example if a colleague of yours likes your settings, you can give him the gist and he will be able to download it. You can also do this if you don’t want to use tokens when syncing, but if you do that, remember to share your settings to a public guest by using this option.

If you have enjoyed this article hit the Like button below and share it. Also don’t forget to subscribe to the CodingSRC Youtube Channel so you don’t miss anything.

See you next time.

The post VSCode Sync Settings and Extensions Tutorial – Synchronize Devices! appeared first on CodingSrc.

]]>
https://codingsrc.com/vscode-sync-settings-and-extensions-tutorial-synchronize-devices/feed/ 0
Heroku Tutorial For Beginners – Deploy Your App to Heroku Under 5 Minutes! https://codingsrc.com/heroku-tutorial-for-beginners/ https://codingsrc.com/heroku-tutorial-for-beginners/#respond Wed, 06 Feb 2019 21:56:23 +0000 http://estudiopatagon.com/themes/wordpress/recov3/?p=343 If you don’t know already Heroku is a cloud platform as a service supporting several programming languages. You can deploy projects written in many kinds of languages in there. They support NodeJS, Ruby, Java, Php, Python and other languages and the best part is that they have a free plan. So, now let’s go to heroku.com and […]

The post Heroku Tutorial For Beginners – Deploy Your App to Heroku Under 5 Minutes! appeared first on CodingSrc.

]]>
If you don’t know already Heroku is a cloud platform as a service supporting several programming languages. You can deploy projects written in many kinds of languages in there. They support NodeJS, Ruby, Java, Php, Python and other languages and the best part is that they have a free plan.

So, now let’s go to heroku.com and click on the sign up for the free button there.

Create an account there and confirm your email address. After that create a password and log into the dashboard…

Now you would want to create a new application.  Click on the new button here and give your application a name

You must give your app a unique name so let’s think of something. Ok, now click on “Create App”.

Now what you would want to do is install the Heroku CLI. <– Click on the link here and download the installer.

Start the installer and follow the steps. Now one thing that I came across when I was installing the CLI was that the path variable was not added. So if you come across this you will need to add the path variable manually.

  1. To do so go to search “path” in your windows search and click on Environment Variables:
  2. Now find your path variable and click on it and then click on edit:
  3. Add a new line and type:
    C:\Program Files\heroku\bin

adding path variable

Now to check if your Heroku CLI was properly installed open a command prompt and type Heroku. If everything was fine you should see this in your terminal. If not make sure you added your path correctly. So now go to your NodeJS project open the terminal there and type:

heroku login

Enter your username and password and log in through the command line interface

Now in order to deploy our app to Heroku, we need to create a git repository. If you haven’t installed Git on your pc please make sure you have it. If you don’t go to https://git-scm.com/downloads and download and install it

After that go back to the terminal and type the following

git init

This will initiate a git repository in our project. After that, we need to type the following

(type the name of your project instead of heroku-tutorial)

heroku git:remote -a “heroku-tutorial”

This Heroku as your remote git repository. After that, we need to add all of our files in the git.

However, before you do this make sure you have added your node_modules folder inside your gitignore file. We don’t want to upload them in our git.

After you do this type:

git add .

Now let’s create a commit and publish it. Type the following:

git commit -am "initial commit"

Now the only thing that is left to do is to push our project to Heroku by typing:

git push heroku master

Now after everything is published you can open your DApp by typing:

heroku open

Now here I have published my decentralized application to the web. If you are interested in how to create DApps and smart contracts with solidity. I have created a whole course about this on Udemy.

If you are interested there will be a link in the description to the course with a discount coupon there.

The post Heroku Tutorial For Beginners – Deploy Your App to Heroku Under 5 Minutes! appeared first on CodingSrc.

]]>
https://codingsrc.com/heroku-tutorial-for-beginners/feed/ 0