What is Solidity Programming

Hello friends, hope you are doing fine and doing great. In the previous tutorial for introducing Smart Contracts, I told you about Solidity. Solidity is a high-level programming language for writing smart contracts. It is the most popular programming language for Ethereum. So, in this article, I will explain the basic components of solidity. Let’s get started by revising the key points of solidity.

Solidity Programming

  • Solidity programming language is made for writing code for the Ethereum platform. These codes (smart contracts) help in executing different functions in Ethereum virtual machine (EVM).
  • It is easy to learn the language. If you are familiar with C and JavaScript, you can easily learn solidity.
  • The code written in solidity is converted into bytecode by solidity compiler. The compiler of solidity language is solc.
  • The extension of a solidity file is .solc.
  • It is a case-sensitive language.
  • Solidity is a statically typed language.
  • The process of writing and compilation is shown in the figure below.

The layout of a Solidity File

In this section, I am going to discuss the general layout of a solidity file. It contains different components. The layout of a solidity file is explained below. It has:
  1. Pragma
  2. Comments
  3. Import
  4. Contract / Library

Pragma in Solidity Programming

  • Before writing the solidity program, you want to mention the version of solidity compiler. So that anyone using the file can choose the correct version for compilation.
  • For this purpose, pragma directive is used. It specifies the compiler version of the file.
  • Solidity is still growing and a lot of improvements have been made since its development. Therefore, the version keeps on improving.
  • The current solidity version is 0.7.4.
  • The version is mentioned by using the following syntax.

pragma Solidity ^0.7.0;

I should mention here that semi-colon is the statement terminator in solidity.
  • It is declared as the first statement of the program.
  • The version number comprises a major build number and a minor build number. When you use ^ character with version number, it means the latest version of the major build number.
  • For example, as I declared the version 0.7.0 with ^ character. Here major build number is 7. So solidity compiler of version 7 will compile it.

Comments in Solidity Programming

  • Guys, if you are familiar with programming, you must know that programming languages support the option of commenting. Solidity also provides this facility.
  • There are two types of comment in solidity:
    • Single-Line Comments: single-line comment means a comment comprising of one line only.
    • Multi-Line Comments: multiline comments consist of more than one line.
  • Forward slashes are used for denoting comments. Single line comment is denoted by double forward slash //. While multiline comment starts with /* and ends with */.
  • It is a good practice to add comments to your program. This improves readability.

Import in Solidity Programming

  • The import keyword helps in importing other solidity files. These files can then be used in code.
  • The functions of the imported file can then be used in a solidity file.
  • This functionality helps us in writing code in the form of modules. In this way, lengthy code can be converted into smaller readable ones.
  • The syntax for using the import keyword is given below:

import filename;

  • The address of the file is mentioned within the import statement.

Contract / Library in Solidity Programming

  • The contracts are defined in the solidity file.
  • You can define more than one contract or library in one file.
  • Contracts, libraries and interfaces can be defined one after the other in a file.
So, this was the general layout of a solidity file. Now, I will move to the next section in which we are going to discuss the structure of a contract.

Structure of a Contract

Contracts are somehow similar to classes in OOP (Object Oriented Programming) Languages. The contracts are written for ethereum virtual machine. Just like other languages, contract code contains functions and variables. The contracts can also inherit from other solidity contracts. There are two special types of contracts in solidity called library and interface. In this section, I have discussed different constructs in a contract. The contract consists of the following:
  1. State Variables
  2. Structures
  3. Modifier Functions
  4. Event Declarations
  5. Enumerations
  6. Functions
Now let’s define these for further understanding.

State Variables

  • Variables store values in storage locations. The value saved in a variable can be change or update while programming execution.
  • Once a variable is declared, you can use it anywhere in your program, at multiple locations.
  • State variables are stored in Ethereum blockchain permanently. The changes in their value and their current value is secured.
  • The data type of state variable is declared while writing the program.
  • Other qualifiers, used while declaration, are listed below:
    • Internal
    • Private
    • Public
    • Constant
  • The following data types can be used in solidity:
    • Bool for boolean
    • Uint / int for unsigned / signed integer
    • Bytes for 8 bit signed integer
    • Address for addresses of accounts
    • Mapping for mappings
    • Enum for enumerations
    • Struct for structures
    • String for character strings

Structure

  • With the help of structure, you can define a data type of your own.
  • A structure is a composite data type and that means it can contain different variables having different or same data types.
  • A group of variables is defined in a structure. Each one is given a name and a data type.
  • A structure is declared by using the struct keyword.

Modifier

  • A modifier is a function that can change the behavior of the code.
  • In solidity, modifiers are used with functions, so they can change the actions of a function.
  • If you are calling a solidity function that has a modifier associated with it, then the modifier function will execute first. After its execution, the called function would be executed.
  • You will define modifier function only once in the program but you can use it anywhere with multiple functions.

Events

  • If you are familiar with programming, you know that different programming languages support events.
  • Solidity also supports events. Events tell about the change in the state of a contract.
  • With the help of logs, the caller can view the state of the contract after execution.
  • Events are declared outside functions, at the global level. Then these events can be called in any function.
  • The keyword for event declaration is an event. After that, the identifier is declared followed by a parameter list. The parameter list contains the data type of the variables.

Enumeration

  • Enumeration provides us with an interesting facility. With the help of it, you can define a data type of your own choice.
  • It contains a list of constants, from which the variable can take values.
  • Each value is given an integer starting from 0 for solidity.
  • The enumeration is declared by the enum keyword. After the keyword, the identifier is defined followed by the list of constant values in brackets.
  • There is no semi-colon at the end of the enum declaration statement.

Function

  • Just like any other programming language, a function is a key component of solidity.
  • Whenever a transaction is initiated, a function of a smart contract is called.
  • Functions can read and write state variables. When a function is executed and a transaction is processed, the state variable may change its state.
  • A function can take input parameters, perform operations on them and can return values. The return values can be more than one.
  • A function has a name that is its identifier. This identifier can be used anywhere in the program for the execution of functions.
  • You can use various qualifiers with a function declaration that decides the visibility of a function. These qualifiers are listed below:
    • Public
    • Private
    • Internal
    • External
  • Other than visibility qualifiers, some other qualifiers are also used with functions. These show the ability of the underlying function in terms of changing values of state variables. The qualifiers are given below:
    • Constant
    • View
    • Pure
    • Payable
So, friends, I have tried to give you a basic idea of the structure of a solidity program. It is not compulsory for a program to have all of the above-listed features. I hope you have learned and got a good understanding of the basics of this language. That was all from my side. Please let me know if you have any questions. I would love to answer them. I am signing off for today, Take care!

Structure of a Block in Blockchain

Hello guys, hope you are doing good and enjoying your lives. Today, I am going to introduce you to the blocks of a blockchain. I gave you an understanding of blockchain, its characteristics, and some idea about accounts and wallets in my previous tutorials, and today my article is about the structure of a block in the blockchain. I will first define the block before going into the details about its structure. So let’s start without any further delay.

Block in Blockchain

  • A block is actually the building block or the key element of a blockchain.
  • The definition of a blockchain is based on its blocks. As I defined in my previous posts, a blockchain is a chain of multiple blocks.
  • Blocks contain transactions. Each block contains a different number of transactions.
  • These transactions are contained in blocks so that they would be added to the distributed ledger.
  • The number of transactions is limited by the block size and gas limit. Generally, the block contains more than 500 transactions.
  • Other than transactions, a block also consists of some metadata. This metadata is stored in the header of the blockchain.
  • The size of a block header is 80 bytes, the detail of which is given in the upcoming sections of this article.
  • Let’s first define a parent block in the next part.

Parent Block in Blockchain

As the blocks are linked together one after the other, they have a parent-child relationship. Each block is the parent of the upcoming block. Each child block contains the hash of the previous block i.e., its parent block. The first block of the blockchain is called Genesis Block and it has no parent. The block contains different fields which can be roughly categorized as listed below:
  • The block size: The size of this field is 4 bytes and it contains the size of the block.
  • The block header: The size of a block header is 80 bytes. It further contains different fields.
  • The transaction counter: This field contains the number of transactions and the size of it is between 1-9 bytes.
  • The transactions: This field contains transactions of the block and its size is variable.
This was some information regarding the fields of an Ethereum block. Now, we will move towards the next part in which I am going to give you an idea about the block header and its fields.

Block Header in Blockchain

The header of an Ethereum block contains different fields of metadata which are listed below.
  • Hash of the previous block: Every block header gives information about the previous or parent block. This field contains the hash value of the previous block and this reference connects all the blocks. The size of this field is 32 bytes.
  • Version: This field stores the version number to show software upgrades. The size of the version field is 4 bytes.
  • Difficulty: The mining difficulty at the time of the block creation is stored in this field. The concept of mining would be explained in the upcoming articles. Its size is 4 bytes.
  • Timestamp: This field contains the time at which the block was created. The size of this field is 4 bytes.
  • Nonce: A nonce is a value used during the mining of the block. This field’s size is also 4 bytes.
  • Merkle tree root: A Merkle tree is a structure obtained from hashing the transactional data of a block. The root of this tree is stored in the block header under this field. 32 bytes is the size of the Merkle tree root field.
This was all about the header of a block. In the next part, I am going to give you an idea about the properties of a block.

Properties of a Block:

There are a lot of properties of a block that give us important information about it. I am listing down the properties here.

Difficulty Property:

  • As I mentioned earlier, this property gives the difficulty level of solving the puzzle to mine the block.

totalDifficulty Property:

  • This property of the block tells us the total difficulty of the blockchain.

gasLimit Property:

  • This property tells us the maximum gas allowed by the block which in turn tells us about the number of transactions that the block can accommodate.

gasUsed Property:

  • The gasUsed property gives the amount of gas used by the block for executing all of its transactions.

Number Property:

The number shows the block number in the list of blocks.

Transactions Property:

  • This means all of the transactions contained in the block.

Hash Property:

  • This property shows the hash of the block.

parentHash Property:

  • This property saves the hash of the previous block.

Nonce Property:

  • Nonce property shows the nonce value that I defined earlier. It is a variable used in mining the block.

Miner Property:

  • The miner property gives information about the miner of the block. This gives the account of the block miner.
So guys these were the properties of a block. I will move towards the next part i.e., the identification of a block.

Block Identification:

The blocks of a blockchain need an identification to refer them or distinguish them from other blocks. Two parameters are used for this purpose which are given below:

1. Block Hash

Block hash is the main identification parameter of a block. This value is obtained by cryptographic hashing of the header of the block. The hashing operation is performed twice. The header of the block contains metadata of the block and when this data is hashed the result is the block hash, whose size is 32 bytes. The hash of the block is not stored in the block’s data whether the block is being transmitted to the other nodes or it is stored as part of the blockchain on some node. When a node receives a block from the network, it computes its hash itself.

2. Block Height

The second parameter used for identifying a block is its height. As we already know that the blocks are linked together in a list type structure starting from the genesis block. The genesis block is given a height 0 zero. The second block in the blockchain or the first block after the genesis block is at height 1 and so on. In this article, I have explained the structure of an Ethereum block. The article explained the header and some properties of the blocks. I hope you have learned something new from it. Take care!

How to Increase EF Core Performance for Saving Multiple Entities?

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Increase EF Core Performance for Saving Multiple Entities? EF Core works well for simple CRUD operations but for saving multiple entities EF Core provides poor performance. So, today we will use a third-party EF Core extension named "Z.EntityFramework.Extensions.EFCore", designed by ZZZ Projects, which will increase the EF Core performance significantly. I will be using a BulkSaveChanges Method of this library which is specifically designed for saving bulk data in an SQL database.

ZZZ Projects is a trusted company and has designed numerous .NET libraries, a few having downloads in millions. So, you can completely trust this extension library.

  • Here's a video for this tutorial, which will give you a practical demonstration of this project i.e. How to add this Library to your project and how to use this extension method BulkSaveChanges:

Before starting with the actual process, let's first have a look at What is EF Core?

What is EF Core?

EF Core is an Object Relational Mapper(ORM) and is used as a bridge between the ASP.Net Core application & its database. Thanks to EF Core, now there's no need to write complex SQL queries for database-related operations, instead, developers can easily perform all database CRUD operations in C# language(using EF Core). Although designed by Microsoft, but EF Core is a separate module and we can add it to our .NET application from the Nuget library.

Low Performance of EF Core

  • ORM(i.e. EF Core) provides a simple instructions-set for database CRUD operations and proves very friendly to developers, but it has few drawbacks as well.
  • One of the main disadvantages of EF Core is its low performance, which not only slows down your application but also increases the database interactions(cloud providers may charge extra).
  • Moreover, as the number of data(you want to save in the database) increases, the EF Core performance decreases.

EF Core Performance for multiple Entities

  • In a professional .NET application development, there come many scenarios where the developer needs to save multiple entities in the database i.e. user notifications, real-time messages etc.
  • When multiple entities are saved using EF Core, it doesn't save them in a single SQL session.
  • Instead, it takes multiple round-trips to the database, which increases the overall time for the data-saving process.

So, now let's have a look at How to increase the EF Core Performance for multiple entities by using BulkSaveChanges(provided by Z Extension), instead of SaveChanges(provided by EF Core):

What is BulkSaveChanges Method?

  • BulkSaveChanges is a simple function, automatically generated by EF Core Extension Library and is used for saving multiple entities in the database.
  • BulkSaveChanges increases the performance of EF Core by 3 to 4 times and its performance is exponential to a number of entities.
  • First of all, you need to download this project designed in ASP.NET Core:
Download Asp.Net Core Project
  • Open it in Visual Studio and first run the Migration commands for setting up the SQL database.

How to add EF Core Extension Library

  • If you check the NuGet packages in the above project, you will find these four packages installed in it, shown in the below figure:
  • You must be familiar with the first 3 NuGet packages, as they are used to add EF Core libraries in the .Net project.
  • The fourth one is the NuGet package of EF Core extension Library, designed by ZZZ Projects.
  • If you click on the Browse tab and make a search for "Z.EntityFramework", you will find results, as shown in the below figure:

Methods offered by Z Extension Library

  • After adding this NuGet package of ZZZ Projects, its methods will become readily available under the instance of DbContext class.
  • I am going to discuss BulkSaveChanges Method only(in today's lecture) but it has a wide range of methods for improving the performance of DBContext class, used in different scenarios, depending on requirements.
  • Here's a list of few other methods, offered by this EF Core Extension Library:

BulkSaveChanges Method to improve performance of EF Core

Now, let's have a look at the implementation of the BulkSaveChanges Method in our Asp.Net Core Application:
  • In the Models folder, open the SubjectRepository.cs file and here you will find two methods, named:
    • Add1() Method: It will use the default SaveChanges() Method of EFCore.
    • Add2() Method: It will be using the new BulkSaveChanges() Method of EF Core Extension Library.
  • Both of these methods are shown in the below figure:
  • As you can see in the above code, it's too easy to use the BulkSaveChanges() method, as it's called on the same instance of DBContext class, on which I have called the default SaveChanges() method.
  • Moreover, I have placed a stopwatch function around these methods to calculate the time taken by them, for saving 5000 entities in the database.
Now, let's save 5000 entities using these two methods, and look at the results:

SaveChanges vs BulkSaveChanges

  •  I have tested these methods three times each and created a comparison table.
  • In each of these testing trials, I have saved 5000 entities in the underlying SQL database.
  • Here's the result of the comparison, SaveChanges vs BulkSaveChanges: (all these readings are in milliseconds)
  • As you can see in the above comparison table, the BulkSaveChanges method is 3 to 4 times faster than the SaveChanges method.

For a practical demonstration of this project, watch the above video, where I have completely demonstrate How to add this Z extension Library to your project and how to use the BulkSaveChanges method to improve the performance of EF Core. So, that was all today, if you have any questions, please ask in the comments. Thanks for reading!!! :)

C# ProgressBar Control

I hope you are doing good, In the tutorial, I'm going to explore C# ProgressBar Control. C# ProgressBar is used to express progress of any process. When you have to perform a long process within your desktop application then you have to use C# ProgressBar to show a user how much time left or how much progress is done. You can use C# ProgressBar for multiple purposes such as the downloading of life and result retrieving.

C# ProgressBar Control

A progress bar is used to show the progress of any process which takes a long time compared to normal processes. Mostly you have viewed these kinds of progress bar during the installation of software. C# ProgressBar has three parameters, Maximum, Minimum and the value. Maximum represents the max progress or upper range of progress and minimum represent the min progress or lower value or range, where the value is the current point of a progress bar. By default in C# ProgressBar, the value of minimum is set to zero and maximum is 100. Progress bar filled from left to right as the universal standard. You can easily drag and drop the C# ProgressBar from the GUI toolbox to your desktop application. By default, the first instance of C# ProgressBar named as the ProgressBar1. If you are wanted to preview the outcome of progress bar then you can simply set the value in the initialize phase, as you can observe in the following code we have used four progress bar with different values.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            progressBar1.Value = 25;
            progressBar2.Value = 50;
            progressBar3.Value = 75;
            progressBar4.Value = 100;
        }      
    }
}
You can observe that we have used four progress bars which have values as 25, 50, 75 and 100. As you know the default value of the minimum range is zero and max range is 100 that's why we have used above values to demonstrate the states of the progress bar. In the following image, you can be observed the output of above code with progress bar states. Default instance named as progressbar1,2,3 and so on following. If you want to rename the object name of progress bar according to you then you have to visit the properties tab after selecting the relative progress bar and then change the name as you can be observed in the following image. If you are wanted to change the size of ProgressBar according to absolute values then there are two methods which you can use. The first method is, you have to select the relative ProgressBar then go to the properties tab and search for the size where you can insert the absolute values to resize the ProgressBar according to your requirements. In the following image, you can be observed the flow of actions. The second method is to do the same action with the help of programming code. We have to use the Size property and pass the values of the width and height in the constructor of Size. You can be observed the following code for better understanding.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TEPprogressBar1.Value = 25;
            TEPprogressBar1.Size = new Size(100,23);
            
        }      
    }
}
If you are looking to change the ProgressBar style then you can change that from the properties tab. There are three styles for the ProgressBar, by default its set to block and others are Continuous and Marquee. Even that you can set the ProgressBar styles from the following code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
            TEPprogressBar1.Style = ProgressBarStyle.Blocks;
            TEPprogressBar2.Style = ProgressBarStyle.Continuous;
            TEPprogressBar3.Style = ProgressBarStyle.Marquee;

            TEPprogressBar1.Value = 25;
            TEPprogressBar2.Value = 50;
            TEPprogressBar3.Value = 75;

        }      
    }
}
We have used three progress bars, before copy, the above code inserts the three progress bar in your desktop application. Then you can be used the above code but replaced the TEPprogressBar1,2,3 with the instance names which are using for your ProgressBars. If you are wanted to make Right to left moving progress bar then you have to activate two properties for this. First, you have to make RightToLeftLayout true and then you have set RightToLeft.Yes as the value of a RightToLeft property of relative progress bar. From the following code, you can get the idea.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
            TEPprogressBar1.Style = ProgressBarStyle.Blocks;
            TEPprogressBar1.RightToLeftLayout = true;
            TEPprogressBar1.RightToLeft = RightToLeft.Yes;

            TEPprogressBar1.Value = 25;
            

        }      
    }
}
Now you can observe the above code, we have activated two properties which are compulsory to change the progress bar flow. We have also attached the Image below which is the exact output of the above code.

C# ProgressBar Event Handlers

After learning the basics, its time to move to advanced level to play with a progress bar. In C# there are several built-in functions which are known as the event handler because they only execute on specific situations. Such as you are wanted to perform any task whenever the user will click on the progress bar. Then you will use a relative event handler to tackle this situation. There are several event handlers which you can use with ProgressBar. In the following section of the article, we are going to explore each event handler to demonstrate their purpose of use.
  • C# ProgressBar Click Event Handler
  • C# ProgressBar MouseEnter Event Handler
  • C# ProgressBar MouseHover Event Handler
  • C# ProgressBar MouseLeave Event Handler
  • C# ProgressBar Resize Event Handler

C# ProgressBar Click Event Handler

This event is designed to perform functionality whenever the user will once click on the progress bar. As much time the user will click on the progress bar that much times function is executed which is declared within the braces of click event handler. Most developers used to execute the notifications and the messages on click event handler, like the warnings. First, you have to activate the click event handler for relative progress bar then you can add your functionalities with that like in the below code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        private void TEPprogressBar1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("You have clicked on the TEP ProgressBar");
        }
    }
}
In the above code, you can observe we have used the message box as the functionality which will be performed on the single click. You can declare any kind of functionality like change the color, size and value of progress bar. In the following image, there is the exact output of above code.

C# ProgressBar MouseEnter Event Handler

This event handler is used to execute any functionality when the mouse cursor enters in the boundaries of the progress bar. The visible part of the progress bar is considered as the boundaries. When you slightly enter the cursor within the visible part this event handler will get executed. You can experiment this situation by the following a code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        private void TEPprogressBar1_MouseEnter(object sender, EventArgs e)
        {
            MessageBox.Show("MouseEnter in the TEP ProgressBar");
        }
    }
}
In the above code, you can be observed that we have used message box as the functionality within MouseEnter Event handler. So that whenever user will enter the mouse cursor within the visible part of progress bar message will get executed. Below is the exact output of the above code is attached.

C# ProgressBar MouseHover Event Handler

This event is designed to perform an action whenever the user will hover the mouse in the visible part, hovers mean to stay for a moment during movement over visible part. Until you will moving the mouse over progress bar it will not execute, you must have to stay for a while over progress bar to activate this event handler. In the following code, we have created the proper code for above scenario.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
   
        private void TEPprogressBar1_MouseHover(object sender, EventArgs e)
        {
            MessageBox.Show("MouseHover in the TEP ProgressBar");
        }
    }
}
You can observe that we have used the message box as the functionality. When the MouseHover event occurs message box prompt and shows a message which is defined by the MouseHover event handler. We have also attached the output of above code which you can preview below.

C# ProgressBar MouseLeave Event Handler

This event is designed to perform functionality whenever the mouse cursor will leave the visible boundaries of ProgressBar. In short, we can be said it is the reciprocal or inverse of MouseEnter event handler. Now we are going to create the code with MouseLeave event handler. After the activation of this event handler, you have to write functionality which you want to perform within MouseLeave event handler. From the following code, you can be observed the sequence of a program which we are going to execute.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        private void TEPprogressBar1_MouseLeave(object sender, EventArgs e)
        {
            MessageBox.Show("MouseLeave the TEP ProgressBar");
        }
    }
}
In the above code, we will observe we have used the message box. So that whenever mouse cursor will leave the visible part of progress bar it will get executed. You can perform any functionality instead of message box as you are required, for this tutorial we have used the message box. In the following image, you can observe the exact output which will come after execution.

C# ProgressBar Resize Event Handler

This event handler is designed to perform whenever the size of a progress bar is get changed in any mean such as the change in width or height. Now we are going to perform this event handler. You have to place a button on which click event handler you will declare the size changed functionality for a progress bar. So that, when you will click on the button size of a progress bar, is get changed. Then we will be used the Resize event handler for a relative progress bar. When size is get changed resize progress bar get executed. You can copy the below code and execute on your computer to get a clear idea.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEPArticle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        private void TEPprogressBar1_Resize(object sender, EventArgs e)
        {
            MessageBox.Show("TEP ProgressBar Size is Changed Now !!");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TEPprogressBar1.Size = new Size(100, 30);
        }
    }
}
In above code, you can observe that we have used message box as the functionality to be executed within Resize event handler. Before copy the above code you must have to place the progress bar and button on your desktop application and don't forget to change their name. Following is the image of exact above code which is taken after execution. In this tutorial, we have tried to summarize the C# ProgressBar in depth. So that beginner can understand their usage in software development. After this, you are able to create your own small application in which you can reflect processing via C# ProgressBar. For further advanced topics, you can read, C# PictureBoxC# Checked ListBoxC# CheckBox, and C# RadioButton. Don't forget to share it with your friends if you found this tutorial informative.  

How to use IF Else in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use IF Else in Python. It's our 5th tutorial in python series. In our previous lectures, we have covered the detailed Introduction to Python and then we have also discussed Data Types in Python & How to use Strings in Python. So, now it's time to move on a little further. In today's tutorial, we will cover If else statement in python and its not that difficult to understand but quite an essential one as its use a lot in programming projects. So, let's get started with How to use IF Else Statement in Python:

How to use IF Else Statement in Python

  • IF Else Statement in python takes a Boolean Test Expression as an input, if this Boolean expression returns TRUE then code in IF body will get executed and if it returns FALSE, then code in ELSE body will be executed.
  • You can understand it better by looking at its Flow Chart in right figure.
  • Here's the syntax of IF Else statement in python:
if number == 10: print(number) else: print('Number is not equal to 10"
  • We use if, in our daily life, it is part of our conversation, most of the time.
  • For example, I say, If I win a lottery then I will go to a world tour! If I clear the test then I will throw a party.
  • Here's another example, that if you are working late hours let say, overtime duty then you will get extra money, else you will not get the extra money.
Let's work with an example:
  • Suppose, we have a food chain and our customer has a voucher for it.
  • He has a voucher number (which is a code) written on it, by showing it, he can get a discount or he can get a free meal.
  • If he is providing a correct secret code, then he will get a free meal offer. Otherwise, he will not be able to avail any offer.
  • So, let's design this simple code using If Else statement:

Offer = 500 (This is, by default, price of a meal)

  • We will take the input from the user.

voucher_number = input("please enter your voucher number: ")

  • Whatever the number he will enter, it will get stored in that "voucher_number".
  • Now let's check if the code, that he has entered is correct or not.
  • We will need to use the IF statement here and first let's add this condition:

if voucher_number=="9753":

  • If the voucher number is matching with the company generated number, then the offer will be:

offer -=300

  • If the code is correct then deduct the amount as a discount.
  • Then print("congratulations, you have got a discount")
  • Then print("your remaining offer has " + str(offer))
  • Run the program
  • See the image, it says to enter the voucher number in the output window:
Suppose I put the wrong code. It will exit the program. Now what error he will face, if he put the wrong Voucher number, Let’s see what will be the next task.
  • We will use else statement for this, if the condition is not correct.
  • I have simply printed the message in else body, as shown in below figure:

Relational Operators in Python

As we are discussing IF Else statement, so we should also have a look at relational operators in python:
  • Relational Operators are used to find a relation between two variables or data packets.
  • We use relational operators in test expressions of IF Else statements.
  • We have five types of Relational Operators i.e.
    • Greater than >
    • Less than <
    • Greater than equals to >=
    • Less than equals to <=
    • Equals to ==
  • Let's understand them with an example. Now I have to check which number is greater so I will write it as:
if first_number > second_number:          print(" First number is greater than second number.") else:        print(“second number is greater than first number.") So, that was all about How to use IF Else statement in Python. If you have any questions, ask in comments. In the next, lecture, we will have a look at How to design a simple calculator in python. Till then take care & have fun !!! :)

How to use Arithmetic Operators in Python

Hello friends, I hope you all are ding great. In today's tutorial, I am going to show you How to use Arithmetic Operators in Python. It's our fourth tutorial in Python series. Arithmetic operators are required in mathematical problem solving. We will first have a look at the arithmetic operators and after that, we also discuss different builtin arithmetic functions in Python Math module. So, let's get started:

Arithmetic Operators in Python

  • Arithmetic operators ( +, -, *, /, ^ etc. ) are used to perform simple arithmetic operations in python.
  • So, let's open up your PyCharm and perform a simple task using these operators, as shown in below figure:
  • I used a single star for multiplication and a double star for the square power.
  • It is showing the results of the operations, which it is performing respectively.
Now let's design a simple calculator using these arithmetic operators but before that let's have a look at How to take input from user in python.

Getting Input from users in Python

  • If we want to work dynamically, we will learn how we get values from users.
  • It quite simple in python, you will just need to use an input method here.
  • It will take input from the user and store it in the assigned variable.
  • If you want to take the full name, age, and qualification of the player, you will write it as shown in the image:

Now I will talk about type conversion and we will make a simple program that will calculate the salary of an employee so that we can learn to perform basic calculations: Type conversion in Python In this part, I will tell you, what is Type Conversion in Python? And why it is required? Let's follow the step.
  • Suppose we want to count the salary of an employee. See the steps in the image.
  • Here I put int. before the fourth string, which is basic pay, but I have put the bonus in the whole numbers and it will be unable to do the concatenation because it is allowing it as a string. So, I typed the data and run it, see the results.

  • You can also use the second method as you can put int. where you are performing calculations, as shown in the image.
  • You can convert it by using three major data types i.e. int, float, string.

Simple Calculator in Python

Now we will design a simple calculator in which the user will enter 1st & 2nd number and our code will perform these operations with those operators like addition, subtraction, division, and multiplications. I typed the following strings below:
  • first_number = float(input("Enter first number : "))
  • second_number = float(input("Enter second number : "))
  • print("All Arithmetic Operations are as under.")
  • print(first_number + second_number)
  • print(first_number - second_number)
  • print(first_number * second_number)
  • print(first_number / second_number)
  • print(first_number ** second_number)
  • I converted the type of first and second strings.
  • Run the program
  • You can see in the printed screen all the arithmetic operations are performed respectively.
  • All the values are in floating points because we converted it into the float.
  • You can also convert it in integer and check it.
  • I wrote 9 and 5 and enter it, results are shown in above figure.

Operator Precedence in Python

Let's suppose, we have a variable here.
  • Profit = 15 + 30 * 25
  • Now let's print it using: print(profit)
  • Run the program.
  • The answer will be 765 in the output window.
Python follows the standard order of precedence. First, it will perform multiplication and then it will perform the addition. However, we can change the order using parenthesis.
  • Suppose, we want to operate the addition method first.
  • So, I will place parenthesis before and after both terms.
  • Then it will perform the addition method first then multiplication.
  • I will write it as:

profit = (15 + 30) * 25

  • Run the program and answer will be 1125.
Now I will expand the equation and will do subtraction with it, let’s see what happens.

profit = (15 + 30) * 25 - 10

  • Run the program and answer will be 1115.
  • If we add parenthesis to it as:

profit = (15 + 30) * (25 - 10)

  • Run the program and we will get 675.
Numbers and Importing Math’s Function in Python In this part of the lecture, I will discuss predefined functions about numbers in Python and I will also show you, how to import math modules for the advanced predefined function and methods, predefined for numbers. So let's get started. round()
  • Suppose we have a variable as, number = 3.7.
  • I want easily round it using:

print(round(number))

  • Run the program and it will round the figure to 4.
abs()
  • Suppose I have negative value -8 and I want to find the absolute value of it.
  • I will use abs() and it It will return 8, as shown in below figure:
min()
  • If I want to find the minimum value among the two numbers. I will write it as:

 print(min(9, 4.5)

  • It will return the minimum value as, 4.5.
max()
  • You can do the exact opposite of min, if you want to find out the maximum value among the two numbers.

print(max(9, 4.5)

pow()
  • If I want to calculate the multiples of itself i.e. square, cube etc. then I will write it as:

print(pow(5, 3)

  • The first number will be base and the second one will be the power.
  • Run the program & it will show the answer, 125.

Import a Math Module in Python

Now let's have a look at How to import a math module in python code:
  • Python Math library has a lot of builtin functions, which we can easily import by writing this statement at the top of our code.

from Math import *

  • By writing this statement we are simply saying that get access to all the functions of Math Library.
Now, let's have a look at few of its functions: sqrt()
  • Suppose I want to take the square root of number = 72
  • I write it as

print (sqrt(number))

  • Run the program and it will return as 8.4 something, as shown in below figure:
Here's the complete list of functions in Python Math Module:
List of Functions in Python Math Module
Function Description
ceil(x) It returns the previous integer value.
copysign(x, y) It will assign sign of y to x.
fabs(x) It returns the absolute value.
factorial(x) It returns the factorial value.
floor(x) It returns the next integer value.
fmod(x, y) It divides x by y and returns the remainder.
frexp(x) It returns the mantissa and exponent as pair value.
fsum(iterable) It returns an accurate floating point sum of values in the iterable
isfinite(x) It returns TRUE, if the number is finite i.e. neither infinite nor NaN.
isinf(x) It returns TRUE, if the number is infinite.
isnan(x) It returns TRUE, if the number is NAN.
ldexp(x, i) It returns x * (2**i).
modf(x) It returns the fractional and integer values.
trunc(x) It returns the truncated integer value.
exp(x) It returns e**x
expm1(x) It returns e**x - 1
log(x[, base]) It returns the logarithmic value to the base e.
log1p(x) It returns the natural logarithmic value of 1+x.
log2(x) It returns the base-2 logarithmic value.
log10(x) It returns the base-10 logarithmic value.
pow(x, y) It returns x raised to the power y.
sqrt(x) It returns the square root of x.
acos(x) It returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
e mathematical constant e (2.71828...)
So that was all about arithmetic operators in Python. I hope now you got the clear idea of how powerful python is. So, that was all for today. In the next lecture, we will have a look at How to create IF Loop in Python. Till then take care and have fun !!! :)

How to use String in Python

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use String in Python. It's our 3rd tutorial in Python series. We have discussed strings in our previous lecture How to use Data Types in Python. String is a most commonly used data type in python that's why I have created a separate lecture on it. Python has many built-in string operations, which we will discuss today in detail. So, let's get started with String in Python:

How to use String in Python

  • String Data Type is used to store or collect one or more characters or sequence of characters, we can place any alphanumerical or special character in a string.
  • Let's create a string in python, it has a simple syntax, as shown below:

first_var = "Hello World"

  • There are two sorts of strings, we can use in python:
    • Single Line.
    • Multiple Lines.
  • The above-given example is for a single line, like if you want to write an email or product name, etc.
Multiple Lines String in Python
  • If you want to write an essay, story, report etc. then you will need to use Multiple Lines string, which is created by placing triple quote around the data, as shown in below figure:
  • As you can see in above figure, we have written multiple lines in welcome string.

Strings Operators

  • If you are using an apostrophe, you will need to use use double quotes, otherwise, the interpreter will not be able to understand it and will give you a syntax error, as shown in below figure:
  • But if I write in double-quotes, then it will work fine, as shown in below figure:

Escape sequences in Python

  • If you are using double quotes in the same string, then you will need to use a backward slash ( \ ), as shown in the image.
  • Run the program and see the result in the console window:
Now I have another escape sequence ( \n )
  • If I want to add a new line break then I will use escape sequence ( \n ).
  • As you can see in below figure, I have printed the name & age of Richard in separate lines using escape sequence ( \n ).
Tab escape sequence is \t
  • I wrote it with tab escape sequence ( \t ) and run the program, see the six spaces in the printed window:
Some useful points before I move further:
  • You can use backward slash and forward slash \/ like this.
  • You cannot use the backward slash at the end of the string before the end of the quote.
  • You will use double backward slash ( \\ ), if you want to print one.

Concatenation in Python

  • In concatenation, we connect multiple strings together, we use ( + ) sign in order to concatenate strings.
  • Let's understand it with an example, as shown in below figure:
  • As you can see in above figure, I have printed multiple strings in a single line using ( + ) sign.

 String Formatting In Python

When we use multiple strings, it gets harder to concatenate those strings, and it is difficult to remember each string format and codes. In such cases, we need to format those strings. Let's understand it with an example:
  • In String Formatting, we simply place our variables in curly brackets, as shown in below figure:
  • No need to add multiple quotes and + symbol, instead simply use curly brackets for variables.

String Indexes in Python

In python, when we store a string, it goes with an index for each of its element one by one, because it is a sequence of characters. Let's understand it with an example:
  • For example, I saved the name "Ali Haider" in a string then each of its character has an index assigned with it.
  • I have shown the string and the index starting with a comment # in below image:
  • So, that means index of  A=0, L=1, I=2, (for blank space, it is also a character and its index is 3), H=4, a=5, i=6, d=7, e=8 and r=9.
  • After that, I have printed first three characters of that string by writing a range of [0:3], it eliminates the ending index and shows the result as from 0 to 2, which makes the word Ali. (see above image )
  • If you want to print till the final value, then you wont need to write the last index, you will just write it as [0: ].
  • If I write in this way, print(player_name[:]), then it will print the whole string again.
  • You can also write negative indexes like print(player_name[-1]) and it will print from the right side.
Before moving further, I will tell you a magical feature that only Python allows.
  • Type print("a" * 30) and check the magic in print window:

Builtin String Functions in Python

Python has numerous excellent builtin string functions, which we can access using  DOT ( . ) operator. These builtin functions are quite helpful, so let's have a loot at few of them: string.upper()
  • This upper() function will make characters of the string uppercase, as shown in below figure:
  • If, I write print(Precaution.isupper()), It will check the string, whether its uppercase or not.
  • If string will be in uppercase it will return True and if it's not in uppercase, it will return False.
string.lower()
  • Now let's convert string characters to lowercase by using lower() function.
  • When I type print(precaution.lower()), It will print the whole string in lowercase, as shown in below figure:
string.replace()
  • Now if we want to replace any word, then we need to use print(precaution.replace("WEAR", 'BUY')), It will replace the WEAR word with BUY, as shown in the image:
So, that was all about How to use Strings in Python. I have tried to cover all the main points and rest we will keep on covering in coming lectures. In the next lecture, we will have a look at How to use Arithmetic Operators in Python. Till then take care & have fun !!! :)

How to use Data Types in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use Data types in Python. It's our 2nd tutorial in Python series. In our first tutorial, we have seen a detailed introduction to python and we have also installed PyCharm IDE to work on python. Today, we will understand data types in detail as in order to design an efficient program, you need to select correct data types. Incorrect selection may cause memory loss and may slow your application. So, let's get started with data types in Python:

Data types in Python

  • Data Types are used for the classification or categorization of similar data packets. There are numerous data types available in python, which we can use depending on our projects' requirement.
  • Let's understand data types with an example: Suppose you have some digital data i.e. ON & OFF then you can save this data in Boolean data type but what if your data ranges from 1 to 10, then you need to use integer data types instead of Boolean.
  • You can save Boolean data in integer data type but that will be a redundant i.e. we are allocating more space to our data by specifying integer, when we can easily assign Boolean to it.
  • Here's the flow chart of available data types in Python language:
Now let's have a look at these data types one by one:

Numeric in Python

  • Numeric data types are used to deal with all types of numerical data packets i.e. integer, float etc.
  • Numeric data types are further divided into 3 types, which are:
    • Integer.
    • Float.
    • Complex Number.
Integer in Python
  • Integer (int) data type only holds integer numbers, it could be positive or negative.
  • We can't save decimal numbers in integer data type.
  • Here's a declaration of a variable x and it is assigned a value a of integer 20:

x = int(20)

Float in Python
  • Float data types are used to hold decimal numerical values i.e. 2.13, 3.14 etc.
  • We can also save whole numbers in float data types.
  • Here's a declaration of a variable x and it is assigned a value a of float 20.5:

x = float(20.5)

Complex Numbers in Python
  • Complex Number data types is used to keep complex numbers in it. Complex numbers are those numerical values which have real & imaginary part.
  • That's the versatility of python language, I haven't seen complex number data type in any other programming language.
  • Here's a declaration of a variable x and it is assigned a complex number 1+3j:

x = complex(1+3j)

Dictionary in Python

  • Dictionary data type is sued to save data in key -> value  form. The data is unordered but the value is paired with its key.
  • Dictionary data is placed inside curly brackets i.e. {1:"Jones", 2:"IronMan", 3:"Football", 4: "Mosque"}.
  • Here's a declaration of a variable x and it's assigned a dictionary data type:

x = dict(name="John", age=36)

Boolean in Python

  • Boolean is the simplest data type of all and has just two values assigned to it i.e. True or False.
  • Although it's quite simple but its too handy as we have to use it a lot in IF statements. ( We will cover that later )
  • Here's a declaration of a variable x, assigned a Boolean data type and it's TRUE:

x = bool(1)

Sequence Type in Python

  • Sequence Type data types are used to save data in characters form.
  • We can't save numerical data in sequence type but we can convert the two. ( We will discuss that later )
  • Sequence Types are further divided into 3 types, which are:
    • String.
    • List.
    • Tuple.
Strings in Python
  • A string is used to save one or more characters and it's the most commonly used data type.
  • Let's understand it with a simple example: You must have seen greeting messages on different projects, we save such data in strings.
  • We will discuss strings in detail in our next lecture, where we will perform different operations using strings.
  • Here's a declaration of a variable x, which is assigned a string "Hello World":

x = str("Hello World")

List in Python
  • List data type is used to collect an ordered data, not necessarily of the same type.
  • List data is displayed with square brackets.
  • We will discuss this in our upcoming lectures in detail, here's a declaration of list:

x = list(("apple", "banana", "cherry"))

Tuple in Python
  • Tuple data type is used to arrange ordered data, it's quite similar to list but the data is displayed with small brackets.
  • Here's a Tuple declaration:

x = tuple(("apple", "banana", "cherry"))

So, we have discussed all these data types in python and if you are not understanding any of them yet then no need to worry as we are going to use them a lot in our coming projects, so you will get them. Before moving to next lecture, let's discuss variables in python a little:

Variables in Python

  • Variable is a temporary location in computer's memory, which is used to save the data.
  • As the name implies, we can change its value using different operations or information given to the program.
  • Typically, a program consists of commands that instruct the computer what to do with variables.
  • Variables are assigned with tag name, using which we call the value saved in it.
  • For examples: x = 5, here x is the name of the variable and 5 is its value.
  • In python, we can use special characters, letters, and any number as a variable name.
  • Wide spaces and signs with meanings like "+" and "-" are invalid in python.
  • You should remember that the names of variables are case sensitive. As the uppercase letter "A" and lowercase letter "a" are considered as different variables.
  • As variables are used to save data thus they also assigned a data type. So, a variable could be of int, float or string. (as we seen above)
  • In python, it's not necessary to define variable data type, python sets it dynamically.
  • There are some variables, which are reserved and we cannot use them.
  • We can also change the variables later and assign it to a new variable.
  • For example, I have set a value 10 in a variable eat.

eat=100

  • Then I added and stored the value of eat+10 in a variable cot.

cot = eat + 10

  • So, now cot will be 110.
Types of Variables Here I have set some examples of Variables and their types.
  • X = 456 #integer
  • X = 456L #Long integer
  • X = 4.56 #double float
  • X = "world" #string
  • X = [1, 2] #list
  • X = (0, 1, 2) #tuple
  • X = open('world.py' , 'r') #file
You may assign a single value to multiple variables at the same time.
  • Variable x, y, and z are assigned with the same memory location with the value of 1.

x = y = z = 1

  • Let's create few variables in python, I have created first_name, date_of_birth & last_name, as shown in below figure:
  • I have printed first_name and its appeared in the output panel.
So, that was all about Python Data Types & variables. I hope you have enjoyed today's lecture. In our next lecture, we will have a look at Strings in Python. Till then take care & have fun !!! :)

Introduction to Python

Hello Engineers! Hope you all are doing great. In today's tutorial, I am giving you a detailed lecture on Python programming language. As I am writing this tutorial for beginners, that's why I will discuss each & everything in detail, so it's going to be a very lengthy tutorial and I have divided it in parts.

We will start from basic concepts in Python and will slowly move towards advanced concepts. It's going to be a quite long bumpy ride but I will try my best to make it as smooth as I can. So, let's get started with basic Introduction to Python Language:

Introduction to python

  • Python is a multi-purpose, object-oriented High-Level Programming language, with applications in multiple areas, including scripting, machine learning, data sciences, scientific learning, cloud computing and artificial intelligence.
  • It is the most popular language of 2019, and it is going to flourish exponentially in upcoming years because of its versatility & flexibility.
  • Organizations like Google, NASA, and CIA are using it already.
  • Python processes at RUNTIME by the INTERPRETER, so you don't need to compile your program before executing it.
  • There are three major versions of Python programming language are available i.e. 1.X, 2.X and 3.X. They have sub-versions such as 2.2.3 and 3.3.1.

So, the IDE (Integrated Development Environment) which I am going to use is PyCharm Community Edition.

  • PyCharm Community Edition is free of cost and open-source. You can use it easily.
  • Jetbrains developed this for professional developers.

Prerequisites for Python

As I have told you earlier, I will start from the very basics and will cover almost everything about Python, so if you follow & practice this tutorial completely then you will surely learn Python, even if you are a beginner and know nothing about programming. But still, it would be better if you have:

  • knowledge of some basic concepts like loops, control statements, variables, etc.
  • It is not required to learn any other programming language before you learn python.
  • It is not required to have an engineering background to learn this language.
  • If you are from any other discipline like Sciences, Social sciences or any other academic field, you can still learn it.

Uses of Python

  • As I have mentioned earlier, Python is used in various areas like Machine learning, scripting, scientific computing, Artificial Intelligence, cloud computing etc.
  • So many communities are forced to use python these days, such as:
    • Network Engineers.
    • Software Engineers.
    • Data Analysts.
    • Mathematicians.
    • Scientists.
    • Accountants.
    • Website & App Developers.
  • A wide range of jobs are using this multi-purpose language, namely:
    • Desktop application development.
    • Mobile application development.
    • Web application development.
    • Automation Scripts.
    • Algorithmic and high-frequency trading.
    • Machine learning.
    • Artificial intelligence.
    • Software testing.
    • Hacking.
    • Mathematics.
    • Networks.
I hope now you have the idea of Python's importance these days. So, let's move on to the next step.

DATA SCIENCE AND MACHINE LEARNING

Data science and machine learning are the main reasons, why programmers are learning this language.
  • Python offers different frameworks and libraries, for example, PyBrain, PyMySQL, and NumPy.
  • Python experience allows you more than R Language.
  • You can create scripts to automate material and go with web developments, and so on, respectively.
  •  If you want to work in machine learning, you can easily work with Python.
  • Some of the examples of machine learning are, google chatbots. They answer your questions and queries through python algorithms.

Download & Install Python

Enough with the theoretical stuff, now let's get our hands on Python software:
  • First of all, you need to download Python, they have provided Python for Windows, Linux/UNIX, Mac OS X etc.
  • At the time of this writing, Python 3.8.3 is the latest version, so download & install it.
  • Make sure you check the Python path when you continue, otherwise, it will not work in the future.
  • Next, we need to download PyCharm, which is the IDE for professional developers.
  • You will find two versions on its download page i.e. Professional and Community.
  • We are going to download the community version for now, as we are in the learning phase.
  • You can download PyCharm for Windows, Mac & Linux.
  • After downloading the PyCharm, simply install it.
  • During installation, you need to check on the
    • 64-bit launcher.
    • Add launcher dir to the PATH.
    • Create Associations .py
  • I have ticked these 3 options, as shown in the below image:
  • Now click on the Next button and then click on Install and PyCharm will be installed on your computer.
  • You need to restart your computer for adding launcher dir to the PATH.

Creating First Python Project on PyCharm

  • Click the PyCharm icon and open the IDE.
  • On its first run, it will ask for the UI theme, which I am going to select Dracula, as I like the dark one.
  • Now, click on "Create New Project, select the location where you want to save your file and then click close.
We have created our first project in PyCharm and next, we need to add python files to this project. So let's start with the first Python program.
  • In the left window titled Project, we have a tree structure of our files.
  • These are library files that are necessary for running the project successfully, we will discuss them later.
  • So, in this Project Panel, we need to right-click on our Project Folder and then New and then select Python File, as shown in the figure on the right side.
  • Give a name to your file, as I have named it myy.py.
  • Now let's write our first line of code:

print("my world, my rules")

  • Click on Run in the top menu bar then select Run. You can also use the shortcut key (Alt+shift+F10).
  • IDE will ask you to select the file for execution, so we need to select our python file.
  • Once you select your python file, a new dialog box will open up at the bottom, and you will find your string printed there i.e. my world, my rules.
  • Here's the screenshot of our first Python code in Pycharm:
  • So, we have successfully executed our first Python code in PyCharm. :)

So, that was all for today. I hope now you have a better understanding of what python is and why its so popular. If you have any questions, please feel free to as kin comments. In the next lecture, we will have a look at datatypes in python. Till then take care and have fun !!! :)

DbContext Class in Entity Framework Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at what is DbContext Class in Entity Framework Core. It's our 17th tutorial in ASP.NET Core series. In our previous tutorial, we have discussed Entity Framework Core in detail and have also installed it in our web application. So, now we need understand how to work with Entity Framework Core and for that we have to look at its classes & functions. So, today we will discuss one of its class named DBContext in detail:

DbContext Class in Entity Framework Core

  • EF Core contains an important class named DbContext, which is mainly responsible for communication between Database & software objects.
  • We communicate with our database using this DbContext class and we can also map our fetched data to software objects i.e. properties.
  • So, in order to use this DbContext class, we have to create a new class and then inherit it from DbContext Class.
  • When we inherit our new class from DBContext Class, then we will be able to call all its members from our new class.
  • So, I am going to create a new class in Models folder, as Models are going to communicate with the database.
  • I have named this class TepDbContext and have inherited it from DbContext class, as shown in figure on right side.
DbContextOptions class in EF Core
  • DbContextOptions class in EF Core contains all the configuration information about database i.e. database name, database provider, database connection string etc.
  • We need to use DbContextOptions class along with DbContext class, so let's create a Constructor of DBContext class, as shown in below figure:
  • You can see in above figure that I have created a constructor of TEPDbContext class and then instantiated DbContextOptions class as a parameter.
  • After that, I have provided TepDbContext as a parameter inside < >, thus this option class is applied to our newly created TepDbContext class.
  • Next, I have created its object titled options and finally called the base constructor from DBContext class and provided this options object as a parameter.
DbSet Property in EF Core
  • So far, we have discussed two classes from EF Core and now it's time to have a look at this property in EF Core titled DBSet.
  • DBSet Property is used to map the data from software objects to underlying database.
  • Currently, we have just Engineers.cs file, which has the data properties, that need to be stored in our database.
  • So, let's create a new property in our TepDBContext class named DBSet, as shown in below figure:
  • As you can see we have created a new DbSet Property of type Engineers and given it a name DbEngineers. ( We will use it later )
So, we have successfully created our TepDbContext class and have updated it, so, now its time to register this newly created class with dependency injection of ASP.NET Core.

Database Connection String in App Settings

  • We need to provide authentication settings for our database, which we will add in appsettings.json file, so that we could use it anywhere in our project.
  • I am using MySQL database and thus provided its connection string, as shown in below figure:
  • You can see in above code that I have created a new section named ConnectionStrings and inside it, I have create DbConnection variable and have assigned DB connection string to it.
  • In the connection string, I have first provided the server i.e. localdb and then provided name of the database i.e. TepDB and finally I have declared it a trusted connection.
  • This MSSQLLocalDB is already available in Visual Studio and we will discuss it in detail in our coming lectures.
  • When we upload our web application on a real server then we will change these server settings but for now, we will use localdb available.

Dependency Injection for DbContext class

  • We have studied Dependency Injection in ASP.NET Core in detail, so now let's register TepDbContext class & provide SQL database connection string using Dependency Injection
  • For that, open your startup.cs file and in ConfigureServices method, on IServicesCollection instance, we have called AddDbContextPool method, as shown in below figure:
  • We have also specidified that we are using SQL Server & have provided the database connection string as well, I have placed a red boundary across it.
  • In order to get the Connection string from appsettings.json file, I have injected IConfiguration using Constructor Injection and have placed a green boundary across it.
  • So, our TepDBContext class is now registered with ASP.NET Core and we have also specified the Database provider & Connection String.
So, that was all for today. We have completed all our settings for database but we haven't yet created it. So, in our next lecture, we will see How to Create Database using EF Core Migrations. Till then take care & have fun !!!
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir