Pages

Sunday, 28 December 2014

Oauth and Oauth2 authentication in .NET



Registering on websites is hard. So is trying to remember yet another username and password combination. Social logins makes it easy for people to register on your site and quickly sign in using the social network or email identities they already have.

To implement social Login in asp.net website follow these steps

Step 1:

Install OAuth2 package via NuGet
Install-Package OAuth2

Step 2:


Configure library in web.config
<configuration>
  <configSections>
    <section name="oauth2" type="OAuth2.Configuration.OAuth2ConfigurationSection, OAuth2, Version=0.1.*, Culture=neutral"/>
  </configSections>

  <oauth2>
    <services>
      <add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="FacebookClient"
           enabled="false"
           clientId="000000000000000"
           clientSecret="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
           scope="email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="VkClient"
           enabled="false"
           clientId="AAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="offline"
           redirectUri="~/Auth" />
      <add clientType="TwitterClient"
          enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="LinkedInClient"
          enabled="false"
           clientId="aaaaaaaaaaaa"
           clientSecret="AAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="OdnoklassnikiClient"
           enabled="false"
           clientId="AAAAAAA"
           clientSecret="AAAAAAAAAAAA"
           clientPublic="AAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="YandexClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="MailRuClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="FoursquareClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="WindowsLiveClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="wl.basic wl.emails"
           redirectUri="~/auth" />
      <add clientType="InstagramClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="basic"
           redirectUri="~/auth" />
      <add clientType="DigitalOceanClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="read write"
           redirectUri="~/auth" />
    </services>
  </oauth2>

Step 3:

Add a private variable in your Accounts controller
AuthorizationRoot authorizationRoot = new AuthorizationRoot();

Step 4:

Add Social Login Action in your Accounts Controller. 
public ActionResult SocialLogin(string ProviderName)
{
    //user will hit the following action on button click 
}

Step 5:

Add Get client private Method in your controller
private IClient GetClient(string ProviderName) 
{ 
   return authorizationRoot.Clients.First(c => c.Name == ProviderName); 
} 

Step 6:

Add following code in your Social login Action 
public ActionResult SocialLogin(string ProviderName)
{
 Session["ProviderName"] = providerName;      return new RedirectResult(GetClient().GetLoginLinkUri());
}

Step 7:

Add oauth Action method to the controller
public ActionResult Auth() 

 { 

 if (Session["ProviderName"] == "google") 

 { 

 GoogleClient google = GetClient(Session["ProviderName"] ) as GoogleClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store this if you want to make api calls 

 Session["googleAccessToken"] = google.AccessToken; 

} 
if (Session["ProviderName"] == "twitter") 
 { 
 TwitterClientgoogle = GetClient(Session["ProviderName"] ) as TwitterClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store token if you want to make api calls 

 Session["twitterAccessToken"] = google.AccessToken; 

} 
//and so on for other social logins
} 

Step 8:

Making Api calls Define scope in config to get user permission for the resources
<add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
and add following code to the any action where you want the user data
RequestFactory _factory = new RequestFactory(); 

 var client = _factory.CreateClient(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 var request = _factory.CreateRequest(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 request.AddParameter("alt", "json"); 

 request.AddHeader("Authorization", "Bearer " + Session["googleAccessToken"]); 

request.RequestFormat = RestSharp.DataFormat.Json; 

 RestSharp.RestResponse a = RestClientExtensions.ExecuteAndVerify(client, request) as RestSharp.RestResponse; 

jsonData = a.Content; 
and do whatever you want to do with it !!!.

:)

Tuesday, 21 October 2014

Come And See The Core Of Computer

Jab bhe ham kisi JOURNEY ki suruat karte hai, tab ye hamesha acha idea hota hai ki ham jis raste se hoker ja rahe hai uska ek MANTEL MAP hmare pass ho. Ye baat  INTELLECTUAL JOURNEY ke lie bhe TRUE hai, such as learning to write COMPUTER PROGRAMS. Hamare case me ham logo ko ye janna bahut jaruri hai ki computers kaam kaise karte hai. App logo ko ye janna jaruri hai ki computer program akhir hai kya? Kis tareke se kuch ENGLISH WORDS(code) calculates a Complex Math problem and other things.
Jab aap mere is post ko aage Read karenge, don’t worry if you can’t understand everything in detail. (asliyat main, ye namumkin hai that You understand every Detail  brief exposition of this blog post). Bas itna padhne par dimag lagao ki apko ek big IDEA ho COMPUTER WORKING ke bare main.
So Let,s Start…
1) Fetch And Execute Cycle IN Computer
Computer bahut he complex system hai jo bana hai bahut sare components se. but at the HEART — or the brain, jo bhe aap kahna chahe— of the computer is CPU. Aaj kal ke morden computers main CPU is a single chip Like intels i3 i5 i7 you all are familiar with but there are more, like one in your 100-MS calculator, or one in your Android Phone or one in Smart TV and the list goes on. But the main job of a CPU is to execute programs.
Jab bhe CPU starts Executing a program, it do the first work to COPY THE PROGRAM FROM HARD DISK TO RAM(Primary Memory) and why it do so ? I think you all Know the answer. After all it is a point What we all Prepare for our UPTU external exam and my frnds You all are absolutely right Ram is faster than HardDisk so it is ideal to use RAM. But i know some of you might thinking so why not to build a whole computer of 1 TB Ram. Why we even use harddisk ? There are two reason to use harddisk.
  1. Ram is very costly so it is not economical.
  2. It is Volatile, every time turn off the computer it erases all the data in it. So if we want that our cute pics, movies and songs not get erased every time we have to use a hard disk.
Programs ke sath - sath RAM also store the inputs , intermediate outputs and final result of the program. Main memory consists of a sequence of locations. These locations are numbered, and the sequence number of a location is called its address. Ye addresses bahut he important hai inke through hm RAM main rakhi Millions of Informations main se kisi bhe information tak pahunch sakte hain. And most amazing part(Actually, this is why I love RAM) of the RAM is  that its Speed is independent of Information’s memory Location means, chahe info ka address 0 ho ya 100K it can be fetched in a constant time. Is’nt it is amazing and if you want to know how it happens i will suggest u to read your CO and DLD books carefully it has all the answers.
When the CPU needs to access the program instruction or data in a particular location it sends the address of that information as a signal to the memory, memory responds by sending back the data contained in the specified location.
Machine Language ke level par CPU ke Operation Bahut simple hain(Waise in detail it is very Complicated). The CPU executes a program that is stored as a sequence of machine language instructions in main memory. It does this by repeatedly fetching an instruction from memory and executing that instruction. This process goes in this why —
1. Fetch an Instruction -> 2. Execute It
3. Fetch another Instruction -> 4. Execute it  And this Process goes on Forever.
and this process is called FATCH AND EXECUTE CYCLE. And this is all that the CPU ever does.
Details of fatch-and-execute cycle ko janna koi itna jaruri nahi hai, lakin kuch bahut basic cheje hai jo apko janni he chahie. EVERY cpu contains  a few internal registers, you can think of it as a VERY small RAM which also have Addresses and it is even faster than ram, almost equal to the speed of cpu itself. Some of these registers are used for internal purpose like LC(Location Counter Register). LC is very important because it is used to keep track of where it is in the program it is executing. Actually it holds the next Memory location (address) of instruction to be fetched from RAM. During the fatch it is update for next instruction location.
Ek computer machine language programs ko execute krta hai wo bina samghe ki what it actually means and what it do, iska sidha sa reason ye hai ki isko banaya he aise gaya hai. This is not an easy concept. Agar hm computers main aur deep jae to pta chalta hai ki asliyat main computer bna hai millions of TINY SWITCHES se jisko hm transistor kahte hai, every transister have to state on and off(or 0,1), ye transistor bade anokhe hote hain kyunki inko ek dusre se is tarike se joda ja sakta hai ki output of one switch can turn on and off another switch. As a computer computes, these switches turn each other on or off in a pattern which is determined by your program and how actually they wired up.
Now In my entire post i keep repeating the Word Machine Language. But What actually a machine language is ?
Can you tell what this means 1000 1111 ? Some would say it is a sequence of 0’s and 1’s.(Binary) some would convert it Decimal No and some one in Hexa No. But, I will suggest every one to recall the definition of Information. It is nothing, it is simply raw data which has no meaning. Now if i put the same question in this way, Can you tell what this means 1000 1111 BCD ? Now every body reading this post have a common answer 08 15. Similarly Every CPU has an instruction set in binary and whenever cpu encounter these binary number in specific pattern it perform an operation for which it is coded in chip.
Like following code perform addition in 8085 processor  
10001111 00000111 00000011 (1st bunch of sequence is opcode ADD and 2nd 3rd is 7 and 3) 
May be i was wrong because it is 5:00 in the morning and i am little tired and it is possible that i incorrectly computed the opcode of add to binary But the general idea is a machine language instruction is just a sequence of zeros and ones. Each particular sequence encodes some particular instruction. The data that the computer manipulates is also encoded as binary numbers. A computer can work directly with binary numbers because switches can readily represent such numbers. When a machine language instruction is loaded into the CPU, all that happens is that certain switches are turned on or off in the pattern that encodes that particular instruction. The CPU is built to respond to this pattern by executing the instruction it encodes

Monday, 13 October 2014

Programming Pattern #Singleton


Sometime in programming we need to have only one instance of object for example in logger class.
Such type of situation in programming is mostly handled by Singleton Classes.

Singleton is a software design pattern which ensures only one object of a type is created. This is useful when we want to create an object, which manages or coordinates some tasks in the system. A WindowManager, a FileSystem, Mouse Pointer would be good examples for places where Singleton design pattern can be applied.

The singleton pattern is one of the simplest design patterns it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

How To follow Singleton programming Pattern

  • Make sure class can't create more than one variable
  • Provide a global access to that instance 

 Implementation 

  • Singleton class have a private constructor which restricts programmers to create instance of the  class.
  • Singleton class also have a static method and a private variable of the Singleton class type, this private variable used to hold the single instance of the class.
  • Static method is used to expose the private variable.
    class MySingletonClass
     {
	private static MySingletonClass instance;
	private MySingletonClass()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new MySingletonClass();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}

        public void doSomethingElse()
	{
		...	
	}
    }

Uses Of Singleton Pattern

  • Logger Class
  • Configuration Class
  • Centralized Coordination of task 

 Profit 

  • Single instance save memory which is very important for low memory devices
  • Simple accessibility of shared Resource 

Note :- 

To keep things simple, above implementation not Support Multithreaded programs. If you are curious and know about multithreaded programming than i am sure you also know that "Locking the Methods" is the way.

Saturday, 8 February 2014

JavaFx : Tutorial Series - part 3

Creating UI using FXML and Scene Builder

You can use FXML to create any user interface, FXML is particularly useful for user interfaces that have large, complex scene graphs, forms, data entry, or complex animation. FXML is also well-suited for defining static layouts such as forms, controls, and tables. In addition, you can use FXML to construct dynamic layouts by including scripts.

We use the scene builder tool to create FXML. Scene Builder is a GUI tool which generates FXML.

Open Sample.fxml

1.) In your project double click on Sample.fxml
2.) The file is automatically opened in Scene Builder.

3.) Drag and drop the elements from library to workspace to create GUI.


4.) FXML is not a compiled language so you can preview it by pressing ctrl+p.

Next :- JavaFx : Tutorial Series - part 3 ( Controls )


JavaFx : Tutorial Series - part 2

Structure of JavaFX application 

     Every JavaFX application's main Class extends the Application Class and Override the start(Stage stage) Method. Start Method is entry point of Application. Stage is the the top most container which contains UI components, whether it is deployed on desktop,within a browser, or other Devices.

    Stage class has set of properties and methods.

 1.) A Scene - It contains the graphical nodes in the user interface.
 2.) A title - appears in the title bar of the window(when deployed on the desktop).
 3.)Width, Hight, X, Y, Opacity, fullScreen etc.

Using Stage Class

Add following method calls in your application ....





 public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml")); //load the ui from fxml file
        
        Scene scene = new Scene(root); //A scene container
        
        stage.setScene(scene); //add the scene to stage
        stage.setTitle("My First JavaFX App"); //set the title of stage
        stage.setWidth(500); //width of stage
        stage.setHeight(500); //height of stage
        stage.setOpacity(.8); //Transparency of stage 0 for fully transparent 1 for no transparency.
        stage.show();
    }



Next:- JavaFx : Tutorial Series - part 3

Wednesday, 5 February 2014

JavaFx : Tutorial Series - part 1

JavaFx is API of java which is designed to develop Rich Internet Application. It is used to create very dynamic and attractive java applications. JavaFx uses CSS for styling GUI of java application. If one want to separate presentation of ui and back-end logic it can be done via a scripting language called FXML.

Actually it is very similar to web Programing in the sense that it uses CSS for styling like web Programming, FXML for presentation like HTML and JAVA for back-end logic like JAVASCRIPT do in web Programming.

Tools 

To develop JavaFX application following tools are needed..
  1. Latest JDK 7
  2. JRE 7
  3. IDE NetBeans 7.2 or above or Eclips
  4. JavaFx Scene Builder

First Java Application 

1 . Open NetBeans and click on New Project.
2. Select JavaFX --> JavaFX FXML Application & click Next.


3. Enter name of Project And click Finish.
4. Run your project to see sample application Hello world example.
JavaFX Sample

Monday, 27 January 2014

Very Basic chat Application using TCP/IP

In my last post i showed how TCP programming is done using java. In this post i will show you how to build a very basic command line chat application.



Very Basic Chat App:-

  1. Establish Connection between sender and receiver (Client & Server).
  2. sender(Client) sends the message Receiver(Server) display it continuously . 
  3. when client send the message "quit" both server and client quits.

Server Logic:-

  1. Create a ServerSocket object.
  2. Wait for a client to connect.
  3. If connection is established receive message .(Do this in a While loop so it can receive msg after msg)
  4. If message is "quit" break the loop.
  5. close the connection and terminate.

Server Code:-

I have commented all the importent points in code.




import java.net.*;
import java.io.*;

public class ChatServer
{  private Socket          socket   = null;
   private ServerSocket    server   = null;
   private DataInputStream streamIn =  null;

   public ChatServer(int port)
   {  try
      {  //server code to read msg from connection and write it to the cmd 
         System.out.println("Binding to port " + port + ", please wait  ...");
         server = new ServerSocket(port);  //acquiring port
         System.out.println("Server started: " + server);
         System.out.println("Waiting for a client ..."); 
         socket = server.accept(); //waiting for connection 
         System.out.println("Client accepted: " + socket);
         open();
         boolean done = false;
         while (!done) //reading again and again until quit message is not recived
         {  try
            {  String line = streamIn.readUTF();
               System.out.println(line);
               done = line.equals(".bye");
            }
            catch(IOException ioe)
            {  done = true;
            }
         }
         close();
      }
      catch(IOException ioe)
      {  System.out.println(ioe); 
      }
   }
   public void open() throws IOException  //get the input stream to read msg from connection
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
   }
   public void close() throws IOException  //close the connection
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
   }
   public static void main(String args[]) //Main Method
   {  
      ChatServer server = null;
      if (args.length != 1)
         System.out.println("Usage: java ChatServer port");
      else
         server = new ChatServer(Integer.parseInt(args[0]));
   }
}

Client Logic:-

  1. create a Socket.
  2. establish the connection
  3. read message from cmd and send it to connection
  4. on "quit" msg exit

Client Code:-

I have commented all the importent points in code.



import java.net.*;
import java.io.*;

public class ChatClient
{  private Socket socket              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;

   public ChatClient(String serverName, int serverPort)
   {  System.out.println("Establishing connection. Please wait ...");
      try
      {  socket = new Socket(serverName, serverPort);
         System.out.println("Connected: " + socket);
         start();
      }
      catch(UnknownHostException uhe)
      {  System.out.println("Host unknown: " + uhe.getMessage());
      }
      catch(IOException ioe)
      {  System.out.println("Unexpected exception: " + ioe.getMessage());
      }
      String line = "";
      while (!line.equals(".quit"))  //quit logic
      {  try
         {  line = console.readLine();
            streamOut.writeUTF(line);
            streamOut.flush();
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
         }
      }
   }
   public void start() throws IOException //Start
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void stop() //stop
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ...");
      }
   }
   public static void main(String args[])// Main method
   {  ChatClient client = null;
      if (args.length != 2)
         System.out.println("Usage: java ChatClient host port");
      else
         client = new ChatClient(args[0], Integer.parseInt(args[1]));
   }
}


How to Run the Code :-

  1. Open two cmd
  2. compile both file
  3. first run ChatServer using the cmnd--->  java ChatServer 5001 (where 5001 is port no)
  4. than run ChatClient using the cmnd---->java ChatClient 127.0.0.1 5001 (127.0.0.1 is your own machine address and 5001 is the port on which Server is running)

My next post is on making this chat app to handle multiple client and may be add some gui to give it a touch.
If you liked or learned something  from post than follow me on google+ and share the post .

ThankYou.

Sunday, 26 January 2014

Client Server (TCP) programming

Before diving in the programming first we have to understand how TCP protocol works -

  1. It take your data, message, etc and break it in In segments and address them by adding destination address, source address etc in the header of the Message.
  2. Establish Connection between source and destination.
  3. Sends data over a Physical medium and wait for Acknowledgment from destination.
  4. If data packets lost (Acknowledgment not received in specified time) in between the data is resent.
  5. on receiving end data is arranged in sequence using header sequence of segment. 
  6. connection is closed.

Few key Terms of Network Programming:-

  • IP Address :- it is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255. It is not your machine actual address (mac address) rather than it is the address your ISP provided to you. They maintain a table to work it out.
  • Port :- There are more than one application running on a machine.so It is a unique address which is used to identify the application which has to receive data, message, etc etc.

Programming Logic :-

  1. establish connection b/w Sender and receiver so they can talk to each other.
  2. send message .
  3. display message.
  4. Stop if connection is closed.

Prequest :-

  • Basic Understanding of programming logic and control structure (if,else,for etc).
  • Basics of java.

Programming :-


  • ServerSocket class is used to  acquire a port for application and getting the TCP connection.  ServerSocket  represents the Receiving end of communication.
  • Socket Represents the Connection and used to get data input output streams


  1. import java.io.*;  
  2. import java.net.*;  
  3.   
  4. public class MyServer {  
  5. public static void main(String[] args){  
  6. try{  
  7. ServerSocket ss=new ServerSocket(6666);  
  8. Socket s=ss.accept();//establishes connection   
  9.   
  10. DataInputStream dis=new DataInputStream(s.getInputStream());  
  11.   
  12. String  str=(String)dis.readUTF();  
  13. System.out.println("message= "+str);  
  14.   
  15. ss.close();  
  16.   
  17. }catch(Exception e){System.out.println(e);}  
  18. }  
  19. }  

Friday, 24 January 2014

Network Topology


What is Network Topology ?

Distributed computing systems have become the essential aspect of growing information technology. The performance of any distributed system is certainly influenced by the technology, which we adopt in making network interconnections. In mathematics topology is concerned with the connectedness of objects which is the most basic properties of space. In simple way network topology refers to the configuration of cables computers and other peripheral.

Each topology is suited to specific tasks and has its own advantages and disadvantages. A most simple and good example of network topology is LAN. Where it  has one or more physical links to other devices in the network. In recent days there are basically two basic categories of network topologies: Physical and Logical Topologies.

  1. Physical topologies 
Physical Network Topology emphasizes the hardware associated with the system including workstations, remote terminals, servers, and the associated wiring between assets. Physical topology defines how the systems are physically connected. It means the arrangement of devices on a computer network through the actual cables that transmit data. There are eight basic topologies.

Point To Point Topology

In a point-to-point link,  two devices monopolize a communication medium.  Because the medium is not shared,  a mechanism is not needed to identify the computers.  Therefore, a simple, two-device point-to-point network has no need for addressing.
Point-to-point links can be simplex, half-duplex, or full-duplex.  When devices must engage in bi-directional communication on a half-duplex link,  some turnaround mechanisms must be in place to switch the roles of the sending and receiving devices.

Bus Topology

In a bus topology, all devices attach to the same transmission medium. The medium has a physical beginning and end. All buses are implemented using electrical cable, usually coax, and the ends of the cable must be terminated with a terminating resistor that matches the impedance of the cable. The terminating resistor prevents data reflections from coming across as data corruption. The bus is considered a multipoint system because all devices tap into the same backbone cable.



An important characteristic to remember in bus topologies is that all data signals are broadcast throughout the bus structure.  In the following diagram, if first computer sends a signal to node last computer, the signal propagates for the length of the cable and is seen by all computers as well. It is necessary to have an addressing mechanism so that each node understands which messages it is to receive and which to ignore.

Benefits of Bus topology
Bus topology has the following advantage:
  • Cabling costs are minimized because of the common trunk.
Disadvantages of Bus topology
Disadvantages of bus topology are as follows:
  • Difficult to trouble shoot because no central distribution points exist.
  • Cable breaks can disable the entire segment because they remove the required termination from each of the two cable fragments.


Star Topology

The star topology is a popular method of connecting the cabling in a computer network. In a star, each device connects to a central point via a point-to-point link. Depending on the logical architecture used, several names are used for the central point including the following:
  • Hub
  • Multipoint Repeater
  • Concentrator
  • Multi-Access Unit (MAU)

The central hubs also can be classified in the following manner:
  • Passive hub - A passive hub is a simple signal splitter. Its main function is to connect the arms of the star while maintaining the proper electrical characteristics.
    • A passive hub routes all traffic to all nodes. This means that a tremendous load can be created when much communication takes place between computers. Every computer has the additional burden of reading the address of each piece of information it receives to determine if the information is intended for that computer. Information containing other addresses are discarded.
  • Active hub - An active hub performs the same function as a passive hub, but contains electronic circuits that regenerate and retransmit the information. Thus, active hubs can be used to extend the size of a network.
  • Intelligent hub - Intelligent hubs perform the same functions as passive and active hubs; however, they can make informed path selections and perform some network management. Intelligent hubs route traffic only to the branch of the star on which the receiving node is located. If redundant paths exist, an intelligent hub can route information around normally used paths when cable problems occur.
    • Routersbridges, & switches  are examples of hub devices that can route transmissions intelligently. Intelligent hubs also can incorporate diagnostic features that make it easier to troubleshoot network problems.
Benefits of Stars
Most modern cabling systems are designed in a star physical topology. The benefits of the star topology are many, including the following:
  • Each device is isolated on its own cable. This makes it easy to isolate individual devices from the network by disconnecting them from the wiring hub.
  • All data goes through the central point, which can be equipped with diagnostic devices that make it easy to trouble shoot and manage the network.
  • Hierarchical organization allows isolation of traffic on the channel. This is beneficial when several, but not all, computers place a heavy load on the network. Traffic from those heavily used computers can be separated from the rest or dispersed throughout for a more even flow of traffic.
Disadvantages of Star topology
Star topology has the following disadvantages:


  • Because point-to-point wiring is utilized for each node, more cable is required.
  • Hub failures can disable large segments of the network.


Ring Topology



The ring topology is a physical, closed loop consisting of point-to-point links. In the diagram, you can see how each node on the ring acts as a repeater. It receives a transmission from the previous node and amplifies it before passing it on.

Benefits of Ring topology
Ring topology has the following advantage:
  • Each repeater duplicates the data signals so that very little signal degradation occurs.
Disadvantages of Ring topology
Ring topology has the following disadvantages:
  • A break in the ring can disable the entire network. Many ring designs incorporate extra cabling that can be switched in if a primary cable fails.
  • Because each node must have the capability of functioning as a repeater, the networking devices tend to be more expensive.

Mesh Topology

In this type of topology each device is interconnected with one another, allowing for most transmissions to be distributed even if one of the connections goes down. A major disadvantage is high chances of redundancy in many of the network connections and overall cost is too high compared to any other network topology. 

Benefits of Mesh topology

  •  Enhance for error tolerance provided by redundant links.
  •  Easy to troubleshoot.
Disadvantages of Mesh topology

  • Difficult to install and maintain.
  • Expensive.

Tree Topology


Tree Structure suits best when the network is widely spread and vastly divided into many branches. Tree topology is a combination of two or more bus and the Star Topology connected together. Each star network is a local area network (LAN) in which there is a central computer or server to which all the connected nodes directly linked. The central computers of the star networks are connected to a main cable called the bus. 

A major disadvantage is the length of the network depends on the type of cable that is being used and tree topology network is entirely dependent on the trunk which is the main backbone of the network. If that has to fail then the entire network would fail. 


Benefits of Tree topology
  • This topology is easy to control.
  • The root provides centralised management and monitoring.
Disadvantages of Tree topology
  • If the backbone cable breaks, the entire segment goes down.
  • The tree topology is difficult to configure, wire, and maintain, especially in extensive networks.

Hybrid Topology


Hybrid topology is a network topology that is composed of one or more interconnections of two or more networks that are based upon different physical topologies or a type of network topology that is composed of one or more interconnections of two or more networks that are based upon the same physical topology, but where the physical topology of the network resulting from such an interconnection does not meet the definition of the original physical topology of the interconnected networks. 

A major disadvantage is typically more expensive than other networks since it exploits the features of its component topologies. It requires more cabling between its hardware devices than other types of network topologies. Hybrid networks are difficult to set up and troubleshoot. 

Benefits of Hybrid topology
Hybrid topology has the following advantages:
  • One company can combine the benefits of several different types of topologies.
  • Workgroup efficiency and traffic can be customized.
Disadvantages of Hybrid topology
The disadvantages of hybrid topology include the following:
  • Devices on one topology cannot be placed into another topology without some hardware changes.

  1. Logical Topologies
Logical Network Topology emphasizes their presentation of data flow between nodes. It means logical topology is associated with the arrangement of devices on a computer network and how they communicate with one another. The main role of logical topology is to communicate across the physical topologies among different systems. There are two categories of logical topologies: Shared media topology and token-based topology.

Shared Media Topology

In shared media topology the systems have unrestricted access to the physical media that is all the systems in a network have the ability to access the physical layout whenever they need it. Collision is the main disadvantage of this topology as more than one system send information out on the wire at the same time, the packets collide and as a result this collision kills the packets. Ethernet is an example of a shared media topology. As a remedy some huge networks are broken down into smaller networks. Some ethernet uses Carrier Sense Multiple Access protocol to reduce the number of collisions. 


Token Based Topology

In token based topology a token is used which travels around the network to access the physical media. If any node wants to send a packet to another one it should wait for the token which is traverse within the network either clockwise or anti-clockwise direction. After getting the token a node can send the packet towards the network and all the nodes within the path from sender node to destination node, and all the intermediate nodes should check the destination address, if it matches to anyone it should accept the packet and generate an acknowledgement packet. Acknowledgement packet should follow the reverse path to acknowledge the sender node that the packet is received by the destination node.