Introduction to C# delegate and multicast delegate

What is a C# delegate?

The C# delegate is a reference data type that defines the method and their signature. The delegate stores the address of one or more methods. When a delegate for a method assigned, it behaves exactly like the method. It can be invoked like any other method with parameters and return value.
A delegate simply stores the reference of the methods with the same signatures such as return type and parameter list. A delegate can be invoked as like a class by creating an object for the delegate. The delegate object allows running the methods at run time without invoking it directly.

Usage of delegate:

When an event needs to be used then delegates can be used. Multicast delegates can be used for invoking many events at a time. When a class need to have more than one implementation of the method and to encapsulate a static method.

Refer for when to use delegates and interfaces -> https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ms173173(v=vs.100)

The Ultimate Managed Hosting Platform

Declaring a delegate:

The System.Delegate class is the base class for the delegate declaration. The delegate keyword is used to declare a delegate. The return type and parameters should same as the methods.

Eg:

public delegate int CalDelegate(int num1,int num2);

Instantiation and invoking delegates:

To instantiate a delegate, an instance is created similar to how a class instance is created. When a delegate is instantiated, the address of the method is stored in the instance.


Eg:
Calculator cal=new Calculator();
CalDelegate sumDel=new CalDelegate(cal.sum);
CalDelegate mulDel=new CalDelegate(cal.multiply);


CalDelegate is the delegate created and the sumDel is the delegate instance instantiated to CalDelegate with the reference to the sum() method in cal instance and mulDel is for reference of multiply() method.


To invoke the delegate, calling the delegate instance with the parameter list referenced by the delegate with the same data type.


Eg:
sumDel(10, 12);

mulDel(10,12);

using System;

public delegate int CalDelegate(int num1,int num2);
public class Calculator
{
	public int sum(int num1,int num2)
	{
		return num1+num2;
	}
	public int multiply(int num1,int num2)
	{
		return num1*num2;
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate sumDel=new CalDelegate(cal.sum); // sumDel for sum() reference
		CalDelegate mulDel=new CalDelegate(cal.multiply); //mulDel for multiply() reference
		Console.WriteLine(sumDel(10,12));
		Console.WriteLine(mulDel(10,12));
	}
}

Output:

22

120

Multicast delegates:

To have a reference of more than one method in delegate multicast delegates is used. This mainly used in the multi-event invocation. The += operator is used to add the methods referred to delegate and -= operator is used to remove the methods. The methods are called in First-In-First-Out(FIFO) order.

Remember when using multicast delegates use void as return types because the use of multiple methods will clash in return type. So void is safe to avoid runtime exception.

Eg:

CalDelegate simpleDel=new CalDelegate(cal.sum);

simpleDel += new CalDelegate(cal.multiply);

simpleDel -= new CalDelegate(cal.sum);

using System;

public delegate void CalDelegate(int num1,int num2);
public class Calculator
{
	public void sum(int num1,int num2)
	{
		Console.WriteLine(num1+num2);
	}
	public void multiply(int num1,int num2)
	{
		Console.WriteLine(num1*num2);
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate simpleDel=new CalDelegate(cal.sum);
		simpleDel+=new CalDelegate(cal.multiply); //multicasting using += operator
		simpleDel(10,12);
	}
}

Output:

22

120

The above delegate example is used with multicast delegates in which the firstsum()method is referenced to thesimpleDeldelegate. Thenmultiply()method is added to multicast using += operator. To remove the methods from delegate simply use -= operator. As said multicast delegate run in FIFO, firstsum()delegate reference is run and thenmultiply()with output 22 and 120 respectively.

For documentation of delegates refer -> https://docs.microsoft.com/en-in/dotnet/api/system.delegate?view=netcore-3.1

In next post, I will explain synchronous delegate, asynchronous delegate and covariance and contravariance delegates.

For my other C# archives -> Go.

If you enjoy my post please share it and if any suggestion please comment on it.

 1,283 total views

How to create C# List generics

C# List<T> generics

  • C# List<T> is a strongly typed collection for creating a list of objects of type <T>. 
  • It is similar to ArrayList, we can add, remove, search, sort, manipulate list-objects.
  • In C#, ArrayList is a non-generic collection whereas List<T> is a generic collection.
  • List<T> has high performance than ArrayList and type-safe. 
  • List<T> has similar methods and properties as the ArrayList.

Creating a C# List<T>

  • List<T> is created by using a new operator either it can be empty capacity or specify the size.

Syntax:

List<T> <list_name> = new List<T>(<capacity>);

  • <T> is the type of object to be created like int, float, double etc.
  • <list_name> name of the list.
  • <capacity> is the size of the list which is optional.

Eg:

List<string> List1 = new List<string>();

Adding object to List<T>

  • Add(T obj) method will add the element type <T> in the list on by one.

Eg:

List1.Add(“Element1”);

  • Insert(int index, T obj) method will add the element at the specified index.

Eg:

List1.Insert(1,”Element1”);

Removing object to List<T>

  • Remove(T obj) method will remove the element in the list.

Eg:

List1.Remove(“Element1”);

  • RemoveAt(int index) Removes the element at the specified index.

Eg:

List1.RemoveAt(1);

Get the size of List<T>:

  • Count property is used to get the size of the list.

Eg:

List1.Count();

To sort the List<T>:

  • Use the Sort() method to sort the array in ascending order.

Eg:

List1.Sort();

Accessing the elements in the List<T>

  • The index number can be used to access the elements like an array.

Eg:

List1[0] // accessing element at index 0;

  • To iterate over the List<T>, use foreach function.

Eg:

foreach(string str in List1)

{

Console.WriteLine(str);

}

Example:

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		//create new List<T> of string type using new operator.
		List<string> list1=new List<string>();
		
		//Adding elements using Add(T) method.
		list1.Add("Element1");
		list1.Add("Element2");
		list1.Add("Element3");
		list1.Add("Element4");
		list1.Add("Element5");
		
		
		Console.WriteLine("Printing elements in list1");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
			
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		//removing 'Element1' 'Element2' using Remove(T) method.
		list1.Remove("Element1");
		list1.Remove("Element2");
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after removing Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Insert(2,"Element1");//inserting 'Element1' in index 2
		list1.Insert(4,"Element2");//inserting 'Element2' in index 4
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after inserting Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Sort();//sorting list1
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after sorting");
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Printing elements in list1
Size of list1: 5
Element1
Element2
Element3
Element4
Element5

Printing elements in list1 after removing Element1, Element2
Size of list1: 3
Element3
Element4
Element5

Printing elements in list1 after inserting Element1, Element2
Size of list1: 5
Element3
Element4
Element1
Element5
Element2

Printing elements in list1 after sorting
Element1
Element2
Element3
Element4
Element5

It is recommended to use List<T> generic over ArrayList since it is type-safe, high performance. 

To more refer:https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0#remarks


For my other programming archives -> Go.

If any suggestions please comment about it.

 756 total views

Learn how to create C# ArrayList

ArrayList in C#

ArrayList is a type of non-generic collection framework available in the .Net framework for creating an array of objects list using C# language. The non-generic refers to that we don’t need to mention the data type of the array list. This array list can be dynamically defined of what size wanted. Unlike array initialization, we don’t need to specify the size of the list. It dynamically allocates size as we add or remove an element in the array list. Since it is a non-generic collection, the elements added to the array are stored as an object.

The basic operation we do in ArrayList add, remove, count, sort list. We can also do many operations such as reverse the ArrayList, get the index value of elements etc.

To view full properties and methods please refer: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1

Create ArrayList

We can create an ArrayList using the ArrayList class and new operator.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		//array1 array list is created using new operator.
		ArrayList array1=new ArrayList();
		
	}
}

Add() method

Add(Object value) method will add the element to the ArrayList one after another.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using ADD() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
	}
}

Remove()

Remove(Object value) method will remove the element mentioned.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using Add() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
		
		Console.WriteLine("Before removing");
		//output of array1 before remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
		//removing Element4 and Element3 from array1 arraylist using Remove().
		array1.Remove("Element3");
		array1.Remove("Element4");
		
		Console.WriteLine("After removing");
		//output of array2 after remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Before removing
Element1
Element2
Element3
Element4
After removing
Element1
Element2

In the above program, foreach used to iterate through array1 ArrayList to display the elements.

Using indexers [<index_number>] we can access the elements in the array list.

The output shows the elements in array1 before and after remove() method is used.

  • To get the no of elements in the ArrayList use Count property.
  • To sort the ArrayList use Sort() method.
  • To check an element is contained in the ArrayList use Contains() method.
		//get the count of elements in array1
		Console.WriteLine(array1.Count);
		//to sort the array1
		array1.Sort();
		//check element contains in an array and return true if it contains the element else return false
		Console.WriteLine(array1.Contains("Element1"));

Some other methods are

Insert(int index,object value)

  • Use to insert the element at the given index.

RemoveAt(int index)

  • Removes the element at the given index.

BinarSearch(object value)

  • Search for an object using binary search.

Clear()

  • Clear all the elements in ArrayList.

IndexOf(object value)

  • Gets the index of the particular object.

For other operations refer .NET docs.


For other C# archives -> Go.

For my other programming archive -> Go.

 1,229 total views

C# interface and multiple interfaces tutorial

What is interface?

The definitions for a group of related functionalities that a non-abstract class or struct can declare is called an interface. The interface is another way of abstraction in C#. The interface is like the abstract class but it only contains the methods definitions, whereas the abstract class contains all methods, fields, constants definitions. Unlike the abstract class, the interface cannot have a constructor. The interface methods should be abstract and public. The interface only provides the definition for the methods. In C# multiple inheritances cannot be done in class but by means of the interface.

The interface in C#:

  • Members in the interface should be abstract and public only no other access specifier used.
  • By interface, we can’t able to create an object like an abstract class.
  • Interface only define the methods, the class needed to override and implement those methods.
  • The interface doesn’t contain a constructor.
  • The interface contains methods and properties but not fields.

Implementation of C# interface:

The interface keyword used to implement the interface. We can also implement multiple interfaces for a single class in C#. It’s suggested to use I before every interface name to identify it has the interface. To use an interface in a class we use (:) to access the interface. For example, demo as interface name then use IDemo.

Syntax:

interface <interface_name>
{
    method definition;
}
class <class_name>:<interface_name>
{
interface_method declaration;
}

Example:

using System;
	
interface IDemo1
{
	void simpleInterface();
}

public class Demo:IDemo1{
	public void simpleInterface(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface();
		Console.ReadLine();
	}
}

Here I implement an interface called IDemo1. Then I use the IDemo1 interface in Demo class using the operator (:). Then I implement the interface method simpleInterface by declaring an output statement which displays Implementation IDemo1 interface.

Multiple interfaces:

To use multiple interfaces, simply use a comma between the interfaces name in class. The above program can be implemented as multiple interfaces with another interface called Idemo2.

using System;
	
interface IDemo1
{
	void simpleInterface1();
}

interface IDemo2
{
	void simpleInterface2();
}
public class Demo:IDemo1,IDemo2{
	public void simpleInterface1(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
	
	public void simpleInterface2(){
		Console.WriteLine("Implementation of Idemo2 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface1();
		d.simpleInterface2();
		Console.ReadLine();
	}
}

From C# 8.0 onwards we can implement a default implementation for the interface methods itself. We can also use other access specifiers such as private, protected, internal, public, virtual, abstract, override, sealed, static, extern. We can also implement static methods in interfaces.

For reference https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#drawbacks

For my other programming post -> Go.

 696 total views

How to restart containers automatically in docker

If we are using docker containers for personal use we can restart it manually using docker restart. The docker restart command allows us to restart containers with some time limit. But, in production, it is difficult to restart by manual. To restart containers automatically, we can use restart policies for docker containers.

Restart policies for docker containers

Restart polies allows the container to restart automatically in required situations. The situations may be when a failure occurs, when daemon starts, when a container stopped.
The --restart flag is used with docker run command when starting a container. There are four restart policies available.

noDo not automatically restart containers anyway
alwaysAlways restart the container even though the container stopped manually. Until the daemon stops or the restart policy is changed, it will restart it in loop.
on-failureRestart the container if it exits due to an error, which manifests as a non-zero exit code. If any container is stopped due to any fault, it will automatically restart those containers with this policy.
unless-stoppedSimilar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

To run a container with restart policies, try with following code pattern

docker run --restart no hello-world

The above command run the hello-world image with restart policy set as no. It will not restart the containers automatically.

docker update --restart always hello-world

Here I use update command to update the restart policy of the hello-world container with always policy. This will restart the container always even though it is stopped manually or start when the daemon starts.

To view the events that occurs during restart we can use event command.

docker event

Open the docker event in one shell and run the container with always policy with another shell. The event shows the hello-world container will restart automatically every times it stopped. The image shows that every time the hello-world container stopped, it restart it.

docker restart containers(1)

We can also restart the containers using process managers such as upstart, systemd, supervisor. I will be posting an article on using process managers for docker in later.

For any reference to docker -> go.

For my other docker archives -> go.

If you like the article feel free to share.

 1,038 total views

The difference between ADD and COPY in dockerfile.

When I was seeing some examples for docker file image building, I came across two things of same functionalities. They are COPY and ADD instructions. This article gives the difference between ADD and COPY in dockerfile. Next it explains how similar they are, then the best practice for using the RUN instead of ADD instruction.

ADD instruction

ADD instruction is an older one, which job is to copy the file or directory from a source to destination.
The ADD instruction can also do operations such as extraction of compressed files or download from an URL path.
Here the source may be a local compressed tar file or the URL path.
If it is a tar file, it extracts the contents to the destination else if it is an URL, then it download the file and extract to the destination in a similar way.
If authentication needs for URL file we can use RUN with curl or wget to download the files.
Since, ADD degrades in performance of the docker containers, COPY is been introduced for simple job.
Syntax for ADD:

ADD <src> <dest>

A simple example to ADD used for local tar file called source.tar.xz to the destination folder /dest.

ADD sourcefile.tar.xz /dest

This syntax example gives how the URL path called https://example.com/source.tar.xz file is downloaded and copied to the /dest.

ADD https://example.com/source.tar.xz /dest

COPY instruction

COPY instruction copies the file or directory from a source path to the destination.
Its job is simple as it duplicates the source file or directory to the destination.
It doesn’t include the operation of extraction or downloading files as ADD instruction.
Syntax for COPY:

COPY <src> <dest>

An example to COPY a file called source.txt to the destination folder /dest.

COPY sourcefile.txt /dest

What to use either COPY or ADD?

In dockerfile we use COPY many time because it only copies the file from a source to destination.ADD used when there is a purpose such as local tar files or URL file source.
For best docker practice, we can use RUN instruction instead of creating an extra layer.
RUN instruction with curl or wget used to get the file direct into the destination.
The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

ADD https://example.com/source.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/source.tar.xz -C /usr/src/things

For instance take the above sentence, where a file called source.tar.gz is downloaded using ADD and extracted using tar with RUN instruction.
This makes two layers that worse the docker performance.
It simply done using RUN with curl tool as follows within a single layer.
If, there is direct copy operation needed than COPY instruction is recommended.
The below dockerfile only takes single layer of operation of file download using curl and then extraction of file using tar with RUN instruction.

RUN mkdir -p /usr/src/things \
    && curl -SL https://example.com/source.tar.xz \
    | tar -xJC /usr/src/things 

Reference to the Best docker practices -> go.
For my docker archives click here -> go.
If any queries please comment it.

 1,104 total views,  1 views today

Deploy a React application using docker containers

This article helps you to deploy a React application using docker containers. To know about docker and docker containers refer this article. This involves creating a react app using npx, then we use the docker file to deploy the docker containers using nginx images.

Create a React application

First, we need to create a React application. For this we can use npx create-react-app tool.

npx create-react-app react-docker-example
cd react-docker-example && npm install
npm start

Run the app in the localhost at http://localhost:3000/ or if any cloud such as AWS or Azure VMs with the 3000 port to check the app is running.

Create dockerfile

First, create a dockerfile in the React app folder with the following lines of dockerfile code.

# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build     

# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
  • The FROM is the base image in which React app needed to run here. Here we use node:lts-alpine image to first build the artifacts for the React app, that it set as build-stage.
  • The WORKDIR is the dir where the app is build and run.
  • Then we copy package.json to the workdir /app.
  • Then run npm install to install dependencies and run npm run build to build the dependencies.
  • In production-stage we run the react application using nginx:stable-alpine image.
    For this we need to copy the files to nginx/html folder, then we expose the port 80.

Build the docker image

Next step is to build the docker image using the docker file using the following command

docker build -t dockertutorial/react-example .

The -t is used for tag command here we named as react-example and we need to mention the folder here . used for selecting all. It take some time to build it and shows following result.

Docker-react-app-build-img
React app image build

Run the container

The last step is to run the container. docker run command is used to run the container from the image we created as following

$docker run -d -it -p 80:80 --name reactapp dockertutorial/react-example:latest 
fd2285a0a2e37afc9d0317ce6c668d2c2bf23a71d75a9df8b8d7134c8d223573
  • -d runs the command in detached mode.
  • -p refers to port which expose container to local system, here it expose port 80 of container to port 80 of local machine.
  • -it runs in interactive mode with the tag name and --name refers to name of the container.
Docker-react-app-container-img
React app container run

Then go to http://localhost:80 or if you use cloud VM use the public IP address and select the port 80. It gives the following results

Docker-react-app-img
React app

This react application can also be run with multiple containers using docker compose. This will be our next article.

  • For my docker archive -> go.
  • My programming archives -> go.
  • Any docker reference -> go.

If any suggestion and queries please comment it, so I can improve my self.

 1,119 total views

Merge conflicts and learn how to resolve them in git.

Merge conflicts

In this article, it gives knowledge about how merge conflicts happen and learn how to resolve merge conflicts using different methods and tools. To resolve merge conflicts we will be using tools and commands in git.

So, what is a Merge conflict? Merge Conflict is a warning when we try to merge branches if the same files are altered in both branches.
For instance, assume you’re working on an HTML file for web development. You use a master branch to have a mainline, and test branch to work without disturbing the master branch. Here, you have a file called index.html, you altered it in the test branch and commit it. You also altered the master branch’s index.html file. When you try to merge the test branch with master, it shows a conflicting message as git suggest you solve it to merge.
This is the same when two developers in a team try to alter files and merge it into the master branch. At, this time it shows merge conflict.

How to resolve a merge conflict

I have illustrated the images for reference please verify it.
Here, I have a directory called git-merge-conflict-demo with file content index.html.
Firstly initialize the git repository.

$ git init

Add the files to the git repository.

$ git add .

Commit the files to the git repository.

$ git commit -m "First commit"

git-merge-conflict-1

Then create the branch called test.

$ git branch test

Navigate to the test branch and change the contents using the nano text editor.

$ git checkout test
$ nano index.html

Then add the file and commit to the git repository.

$ git add . 
$ git commit -m "First test commit"

git-merge-conflict-2

Navigate to the master branch and now change the contents of the index.html file. Add it and commit it to the master branch.

$ git checkout master
$ nano index.html

Alter some contents in index.html, then add and commit it to the master branch.

$ git add . 
$ git commit -m "Altered commit in master"

Now try to merge the test branch with the master branch. It shows the conflict, auto-merge failed.

$ git merge test
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and the commit the result.

Try the status command to show unmerged files and changes. Now, try the diff command it shows the difference between the two files as the following image.
git-merge-conflict-3

How to resolve the merge conflict

1. The direct way to resolve is to clean-up the merge working tree by manual. Abort the merge option using the command

$ git merge --abort

2. Use the git mergetool such a vimdiff, araxis, vimdiff2. mergetool are the different graphical tools that can be used to point out the difference in two files and help to resolve it. The image shows the vimdiff2 tool

$ git mergetool --tool=vimdiff2

mergetool

3. Use the diff command to show the difference between the files in the MERGE_HEAD version.

$ git diff

diff-command

The contents above ======= are contents in our side or current branch. The contents below to it are on the other side. The text in red is the altered content. This is the same as in the mergetool option.

4. Use Status command to show the unmerged files and change contents.

$ git status

5. Use log -- merge -p the command to show log files and changed contents.

$ git log --merge -p

log-command

Use above all these methods use them as a guide to change the content of the files and then merge the files.

Learn how to branch in git -> Go.
Click here for Git archives.

To view official git documentation please visit git docs.

As I’m new to the blog, I trying to improve the contents daily. Please support it through comments.

 982 total views

Git Merging and learn how to merge in git

Git Merging

Though Git Branching is a powerful feature to branch the development work without changing the mainline, to add the features from one branch to another we need of this Git Merging, yet another powerful feature. Git Merging feature by merging the one development work of a branch to another branch it currently resides. This post help you to understand, how to git merge works and merge files in git from one branch to another.

Git Merge working

In Git Merging, we used the main command

  • $ git merge

The merge command will merge the given name branch to the current branch. When a merge command is given, a new snapshot is created in the current branch. Now, the pointer points to both previous snapshots of the current branch and another branch.

Here, we continue from the previous Git branching post(if not read it Git Branching). Assume, you’re currently in the ‘test’ branch. You made some improvements to the ‘test’ branch. Now, you want to add those features to the ‘master’ branches. First, navigate to the ‘master’ branch by the following command

$ git checkout master

Now, you moved to the ‘master’ branch. To merge the files to the ‘master’ branch from the ‘test’, type

$ git merge test

After this, it shows the following image

git-merge-work

The updating of checksums shows in the first line, the type of merge in the second line, the files merged and altered in next and changes in the last.

git-merging

The illustration describes that snapshot s6 from the ‘test’ branch is merged to the s5 ‘master’ branch as s7 snapshot. Now, the pointer heads to s5(master) and s6(test). This is how the basically merging works in git.

Problems with merging

When we try to merge a file, which is altered in both branches, it makes some conflicts with the merging and it shows git asks us to clear the conflict first. This looks like

merge-conflict

Here, I altered a Readme.md files both in master and test branches. When I try to merge it, it shows the ‘CONFLICT’ message.

Learn how to resolve this merge conflicts -> Go.

Learn how to branch in git -> Go.
Click here for Git archives.

To view official git documentation please visit git docs.

As I’m new to the blog, I trying to improve the contents daily. Please support it through comments.

 922 total views

Git Branching and learn how to branch

Git branching

Every version control system has a branching system. Branching is a powerful feature in which it does not disturb the main or actual pipeline. For instance, we can branch the development into main and test, in the main branch actual working content is developed, whereas in the test branch the features to be added can be developed and can be merged with the main branch. Git also supports this branching and merging feature.

Many version control systems make this feature in a heavy way by copying all content from one branch to another. This leads to a high load. But, git makes it in a lightweight process by snapshots(Already mentioned in the post – Git introduction please refer it). It snapshots the content using checksums. This makes git a lightweight and powerful version control system.

branch command

In git, a new branch is created using branch command. The default branch in all git repositories is main branch. The branch command simply creates a new branch only, do not navigate to the branch.

Here, we create a new branch called the ‘test’ branch by the following command.

$ git branch test

To view, the branches execute the log command that shows an arrow specified with the branch name. The log shows the name of the branch currently the pointer present and created.

$ git log

git-branch1

checkout command

To navigate to the branch, use the checkout command. This command takes control of another branch by taking a snapshot of the’master’ branch.

$ git checkout test

Now check out the log, the arrow changes to the test branch.

git-branch2

Now, you can able to work on the test branch freely, without disturbing the main content altering. If checkout is an extra process, use -b option with branch command. It will automatically navigate to target when a new branch is created.

The above picture illustrates how branching is done. Here, the ‘s’ stands for a snapshot. When the branch command is given with the name ‘test’, it creates a branch called ‘test’. Here s3 is the snapshot of the master and pointer points to master snapshot. When checkout command with ‘test’ given, it navigate to test branch. When some alteration made in the ‘test’ branch, commit it. This creates a new snapshot called s4 in the ‘test’ branch.

Edit and commit until the feature is ready. If your features are ready, to make the ‘test’ developments to the ‘master’ branch we must do merging of the branches, this will be available in the next tutorial.

Click here for Git archives.

To view official git documentation please visit git docs.

 663 total views,  1 views today