Saturday, 15 October 2016

OOPS Concept -Real World

We write programs to solve our problem and get our work done.

Object Oriented Programming is basically considered as design methodology for creating a non-rigid application. In OOPS every logic is written to get our work done, but this is done based on entity which we call it as Objects. OOP allow us to decompose our problem in to small unit of work which are accessed via Objects. We build function around this objects. There are mainly four pillars (features) of OOP.

If all this features fulfill our programming, then we can say it as perfect Object Oriented Programming.
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Let’s consider an example for explaining each pillar, which at the end will make you understand & follow Object Oriented Programming. Before that, we need to know something

When we take a mobile as an object, its basic functionality for which it was invented were Calling & Receiving a call & Messaging. But now a days thousands of new features & models were added & the count is still increasing.
mobile

Mobile Brand

In above diagram, each brand (Samsung, Nokia, IPhone) have their own list of features along with basic functionality of dialing, receiving a call & messaging. 

When we talk about OOP, as the word indicate it will talk about an object (a real world object)

Objects
Any real world entity which can have some characteristics or which can perform some work is called as Object. This object is also called as an instance i.e. - a copy of entity in programming language. If we consider the above example, a mobile manufacturing company, at a time manufactures lacs of pieces of each model which are actually an instance. This objects are differentiated from each other via some identity or its characteristics. This characteristics is given some unique name.
  1. Mobile mbl1 = new Mobile ();  
  2. Mobile mbl2 = new Mobile ();  
Class
A Class is a plan which describes the object. We call it as a blue print of how the object should be represented. Mainly a class would consist of a name, attributes & operations. Considering the above example, A Mobile can be a class which has some attributes like Profile Type, IMEI Number, Processor, and some more.) & operations like Dial, Receive & SendMessage.

There are some OOPS principle that need to be looked in while creating any of the class. This principle is called as SOLID where each letter has some specification. I won’t be going into this points deeper. A single line of each explanation may clear you with some points.

SRP (The Single Responsibility Principle) 
A class should have one, and only one responsibility

OCP (The Open Closed Principle) 
You should be able to extend a classes behavior, without modifying it. (Inheritance) 

LSP (The Liskov Substitution Principle) 
Derived classes must be substitutable for their base classes. (Polymorphism)

ISP (The Interface Segregation Principle) 
Make fine chopped interface instead of huge interface as client cannot be forced to implement an interface which they don’t use. 

DIP (The Dependency Inversion Principle) 
Depend on abstractions, not on concretions. (Abstraction)

Now this class is represented as shown below
 
class  

  1. public class Mobile  
  2. {  
  3.      private string IEMICode { get; set; }  
  4.      public string SIMCard { get; set; }  
  5.      public string Processor { get; }  
  6.      public int InternalMemory { get; }  
  7.      public bool IsSingleSIM { get; set; }  
  8.   
  9.      public void GetIEMICode()  
  10.      {  
  11.          Console.WriteLine("IEMI Code - IEDF34343435235");  
  12.      }  
  13.   
  14.      public void Dial()  
  15.      {  
  16.          Console.WriteLine("Dial a number");  
  17.      }  
  18.      public void Receive()  
  19.      {  
  20.          Console.WriteLine("Receive a call");  
  21.      }  
  22.      public virtual void SendMessage()  
  23.      {  
  24.          Console.WriteLine("Message Sent");  
  25.      }  
  26.  }  
Abstraction
Abstraction says, only show relevant details and rest all hide it. This is most important pillar in OOPS as it is providing us the technique to hide irrelevant details from User. If we consider an example of any mobile like Nokia, Samsung, IPhone. 

Some features of mobiles
  1. Dialing a number call some method internally which concatenate the numbers and displays it on screen but what is it doing we don’t know.
  2. Clicking on green button actual send signals to calling person’s mobile but we are unaware of how it is doing.
This is called abstraction where creating method which is taking some parameter & returning some result after some logic execution without understating what is written within the method
  1. public void Dial()  
  2. {  
  3.     //Write the logic  
  4.     Console.WriteLine("Dial a number");  
  5. }  
Encapsulation
Encapsulation

Encapsulation is defined as the process of enclosing one or more details from outside world through access right. It says how much access should be given to particular details. Both Abstraction & Encapsulation works hand in hand because Abstraction says what details to be made visible & Encapsulation provides the level of access right to that visible details. i.e. – It implements the desired level of abstraction.

Talking about Bluetooth which we usually have it in our mobile. When we switch on the Bluetooth I am able to connect another mobile but not able to access the other mobile features like dialing a number, accessing inbox etc. This is because, Bluetooth feature is given some level of abstraction. 

Another point is when mobile A is connected with mobile B via Bluetooth whereas mobile B is already connected to mobile C then A is not allowed to connect C via B. This is because of accessibility restriction. 
This is handled by access specifier like public, private, protected, and internal
  1. private string IMEICode = "76567556757656";  

Polymorphism
Polymorphism can be defined as the ability of doing the same operation but with different type of input.

More precisely we say it as ‘many forms of single entity’. This play a vital role in the concept of OOPS.

Let’s say Samsung mobile have the 5MP camera available i.e. – it is having a functionality of CameraClick(). Now same mobile is having Panorama mode available in camera, so functionality would be same but with mode. This type is said to be Static polymorphism or Compile time polymorphism. See the example below:
  1. public class Samsumg : Mobile  
  2. {  
  3.     public void GetWIFIConnection()  
  4.     {  
  5.         Console.WriteLine("WIFI connected");  
  6.     }  
  7.   
  8.     //This is one mwthod which shows camera functionality  
  9.     public void CameraClick()  
  10.     {  
  11.         Console.WriteLine("Camera clicked");  
  12.     }  
  13.   
  14.     //This is one overloaded method which shows camera functionality as well but with its camera's different mode(panaroma)  
  15.     public void CameraClick(string CameraMode)  
  16.     {  
  17.         Console.WriteLine("Camera clicked in " + CameraMode + " Mode");  
  18.     }  
  19. }  
Compile time polymorphism the compiler knows which overloaded method it is going to call.

Compiler checks the type and number of parameters passed to the method and decides which method to call and it will give an error if there are no methods that matches the method signature of the method that is called at compile time.

Another point where in SendMessage was intended to send message to single person at a time but suppose Nokia had given provision for sending message to a group at once. i.e. - Overriding the functionality to send message to a group. This type is called Dynamic polymorphism or Runtime polymorphism.

For overriding you need to set the method, which can be overridden to virtual & its new implementation should be decorated with override keyword.
  1. public class Nokia : Mobile  
  2. {  
  3.      public void GetBlueToothConnection()  
  4.      {  
  5.          Console.WriteLine("Bluetooth connected");  
  6.      }  
  7.    
  8.      //New implementation for this method which was available in Mobile Class  
  9.      //This is runtime polymorphism  
  10.      public override void SendMessage()  
  11.      {  
  12.          Console.WriteLine("Message Sent to a group");  
  13.      }  
  14. }  
By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.

Inheritance
Inheritance

Ability to extend the functionality from base entity in new entity belonging to same group. This will help us to reuse the functionality which is defined before. 

Considering the example, the above figure 1.1 itself shows what is inheritance. Basic Mobile functionality is to Send Message, dial & receive call. So the brands of mobile is using this basic functionality by extending the mobile class functionality and adding their own new features to their respective brand.

There are mainly 4 types of inheritance:
  1. Single level inheritance
  2. Multi-level inheritance
  3. Hierarchical inheritance
  4. Hybrid inheritance
  5. Multiple inheritance
Single level inheritance 
In Single level inheritance, there is single base class & a single derived class i.e. - A base mobile features is extended by Samsung brand.
Single level inheritance

Multilevel inheritance
In Multilevel inheritance, there is more than one single level of derivation. i.e. - After base features are extended by Samsung brand. Now Samsung brand has manufactured its new model with new added features or advanced OS like Android OS, v4.4.2 (kitkat). From generalization, getting into more specification.
 
Multilevel inheritance

Hierarchal inheritance

In this type of inheritance, multiple derived class would be extended from base class, it’s similar to single level inheritance but this time along with Samsung, Nokia is also taking part in inheritance.
 
Hierarchal inheritance

Hybrid inheritance
Single, Multilevel, & hierarchal inheritance all together construct a hybrid inheritance.
 
Hybrid inheritance  
  1. public class Mobile  
  2. {  
  3.        //Properties  
  4.        //Methods  
  5. }  
  6.   
  7. public class Samsumg : Mobile  
  8. {  
  9.        //Properties  
  10.        //Methods  
  11. }  
  12.   
  13. public class Nokia : Mobile  
  14. {  
  15.     //Properties  
  16.    //Methods  
  17. }  
Interface
Multiple inheritance where derived class will extend from multiple base classes.

Samsung will use the function of multiple Phone (Mobile & Telephone). This would create a confusion for complier to understand which function to be called when any event in mobile is triggered like Dial () where Dial is available in both the Phone i.e. - (Mobile & Telephone). To avoid this confusion C# came with the concept of interface which is different from multiple inheritance actually.

If we take an interface it is similar to a class but without implementation & only declaration of properties, methods, delegates & events. Interface actually enforces the class to have a standard contract to provide all implementation to the interface members. Then what’s is the use of interface when they do not have any implementation? Answer is, they are helpful for having readymade contracts, only we need to implement functionality over this contract. 

I mean to say, Dial would remain Dial in case of Mobile or Telephone. It won’t be fair if we give different name when its task is to Call the person.

Interface is defined with the keyword ‘interface’ .All properties & methods with in the interface should be implemented if it is been used. That’s the rule of interface.
Interface  
  1. interface IMobile  
  2. {  
  3.    Void Dial();  
  4. }  
  5.   
  6. interface ITelephone  
  7. {  
  8.    void Dial();  
  9.   
  10. }  
  11.   
  12. public class Mobile : IMobile, ITelephone  
  13.   
  14. {  
  15.     public void Dial()  
  16.     {  
  17.             Console.WriteLine("Dial a number");  
  18.     }     
  19. }  

Conclusion
Following the above principle & keeping in mind the four pillars would lead you develop a good program & linking it with real world scenario will make you think more deeply. I hope you like this article. Don’t forget to share your comment whether it’s good or bad. Sharing is valuable no matter what.

What is encapsulation in Object Oriented Programming (OOP)?

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.
view source code
Encapsulation means hiding the internal details of an object, i.e. how an object does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the other object.
Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property you can validate the data and set it.
Example:
<?php
class YourMarks
{
private $mark;
public Marks
{
get { return $mark; }
set { if ($mark > 0) $mark = 10; else $mark = 0; }
}
}
?>
Below the real life example of encapsulation:
1. I am giving example of Mobile Phone and it’s Manufacture:
Let’s take example of Mobile Phone and Mobile Phone Manufacturer
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works.
This means that you are creating the class with function and by making object (capsule) of it you are making availability of the functionality of you class by that object and without the interference in the original class.
2. I am giving an another example of real life (daily use) that is “TV operation”. Many peoples operate TV in daily life.
It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.


Encapsulation binds together the data and functions that manipulate the data, keeping it safe from interference and misuse.
Real World Example: Every time you log into your email account( GMail, Yahoo, Hotmail or official mail), you have a whole lot of processes taking place in the backend, that you have no control over. So your password, would probably be retrieved in an encyrpted form, verified and only then you are given access. You do not have any control, over how the password is verified, and this keeps it safe from misuse.
Abstraction is a process of hiding the implementation from the user, only the functionality is exposed here. So you are aware only of what the application does, not how it does it.
Real World Example: When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.

PHP: Public, Private, Protected



Public:

When you declare a method (function) or a property (variable) as public, those methods and properties can be accessed by:
  • The same class that declared it.
  • The classes that inherit the above declared class.
  • Any foreign elements outside this class can also access those things.
Example:
<?php

class GrandPa
{
    public $name='Mark Henry';  // A public variable
}

class Daddy extends GrandPa // Inherited class
{
    function displayGrandPaName()
    {
        return $this->name; // The public variable will be available to the inherited class
    }

}

// Inherited class Daddy wants to know Grandpas Name
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

// Public variables can also be accessed outside of the class!
$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Prints 'Mark Henry'

Protected:

When you declare a method (function) or a property (variable) as protected, those methods and properties can be accessed by
  • The same class that declared it.
  • The classes that inherit the above declared class.
Outsider members cannot access those variables. "Outsiders" in the sense that they are not object instances of the declared class itself.
Example:
<?php

class GrandPa
{
    protected $name = 'Mark Henry';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error
The exact error will be this:
PHP Fatal error: Cannot access protected property GrandPa::$name

Private:

When you declare a method (function) or a property (variable) as private, those methods and properties can be accessed by:
  • The same class that declared it.
Outsider members cannot access those variables. Outsiders in the sense that they are not object instances of the declared class itself and even the classes that inherit the declared class.
Example:
<?php

class GrandPa
{
    private $name = 'Mark Henry';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Results in a Notice 

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error
The exact error messages will be:
Notice: Undefined property: Daddy::$name
Fatal error: Cannot access private property GrandPa::$name

Dissecting the Grandpa Class using Reflection

This subject is not really out of scope, and I'm adding it here just to prove that reflection is really powerful. As I had stated in the above three examples, protected and private members (properties and methods) cannot be accessed outside of the class.
However, with reflection you can do the extra-ordinary by even accessing protected and privatemembers outside of the class!

Well, what is reflection?

Reflection adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, they offers ways to retrieve doc comments for functions, classes and methods.

Preamble

We have a class named Grandpas and say we have three properties. For easy understanding, consider there are three grandpas with names:
  • Mark Henry
  • John Clash
  • Will Jones
Let us make them (assign modifiers) public, protected and private respectively. You know very well that protected and private members cannot be accessed outside the class. Now let's contradict the statement using reflection.

The code

<?php

class GrandPas   // The Grandfather's class
{
    public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
    protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected  modifier
    private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier
}


# Scenario 1: without reflection
$granpaWithoutReflection = new GrandPas;

# Normal looping to print all the members of this class
echo "#Scenario 1: Without reflection<br>";
echo "Printing members the usual way.. (without reflection)<br>";
foreach($granpaWithoutReflection as $k=>$v)
{
    echo "The name of grandpa is $v and he resides in the variable $k<br>";
}

echo "<br>";

#Scenario 2: Using reflection

$granpa = new ReflectionClass('GrandPas'); // Pass the Grandpas class as the input for the Reflection class
$granpaNames=$granpa->getDefaultProperties(); // Gets all the properties of the Grandpas class (Even though it is a protected or private)


echo "#Scenario 2: With reflection<br>";
echo "Printing members the 'reflect' way..<br>";

foreach($granpaNames as $k=>$v)
{
    echo "The name of grandpa is $v and he resides in the variable $k<br>";
}
Output:
#Scenario 1: Without reflection
Printing members the usual way.. (Without reflection)
The name of grandpa is Mark Henry and he resides in the variable name1

#Scenario 2: With reflection
Printing members the 'reflect' way..
The name of grandpa is Mark Henry and he resides in the variable name1
The name of grandpa is John Clash and he resides in the variable name2
The name of grandpa is Will Jones and he resides in the variable name3


Wednesday, 4 May 2016

Sending Notification Using Node.Js


Now days nodejs is popular technology  and its growing quickly .As you know Nodejs server can handle 10 thousand of concurrent requests. Basically . Nodejs is non-blocking and event based ,so the best example of nodejs is to developed chat application and also you can use it for Push notifications or desktop notification

Installation 

1. Download node.js  zip from http:://nodesj.org and install it on your linux machine


Once Nodejs installation done. create your project directory , navigate to your project directory and  create package.json file and add dependent module in it .Once package.json file creation done.

run  npm install

Above common will run all the dependent module which has mentioned in package.json file.

So your project directory will look like this

server /db.js
          /index.js

client /index.html [ your Front end file ]

Routes/index.js

node_modules/

Gruntfile.js

You can see Gruntfile.js . run  npm grunt-cli -g globally ,as GRUT is debugging and




Friday, 3 July 2015

Websockets

Source : http://www.html5rocks.com/en/tutorials/websockets/basics/

The Problem: Low Latency Client-Server and Server-Client Connections

The web has been largely built around the so-called request/response paradigm of HTTP. A client loads up a web page and then nothing happens until the user clicks onto the next page. Around 2005, AJAX started to make the web feel more dynamic. Still, all HTTP communication was steered by the client, which required user interaction or periodic polling to load new data from the server.
Technologies that enable the server to send data to the client in the very moment when it knows that new data is available have been around for quite some time. They go by names such as "Push" or "Comet". One of the most common hacks to create the illusion of a server initiated connection is called long polling. With long polling, the client opens an HTTP connection to the server which keeps it open until sending response. Whenever the server actually has new data it sends the response (other techniques involve Flash, XHR multipart requests and so calledhtmlfiles). Long polling and the other techniques work quite well. You use them every day in applications such as GMail chat.
However, all of these work-arounds share one problem: They carry the overhead of HTTP, which doesn't make them well suited for low latency applications. Think multiplayer first person shooter games in the browser or any other online game with a realtime component.

Introducing WebSocket: Bringing Sockets to the Web

The WebSocket specification defines an API establishing "socket" connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time.

Getting Started

You open up a WebSocket connection simply by calling the WebSocket constructor:
var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
Notice the ws:. This is the new URL schema for WebSocket connections. There is also wss: for secure WebSocket connection the same way https: is used for secure HTTP connections.
Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.
The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing protocol property of WebSocket object.
The subprotocol names must be one of registered subprotocol names in IANA registry. There is currently only one subprotocol name (soap) registered as of February 2012.
// When the connection is open, send some data to the server
connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

// Log messages from the server
connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

Communicating with the Server

As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send('your message') method on the connection object. It used to support only strings, but in the latest spec it now can send binary messages too. To send binary data, you can use either Blob orArrayBuffer object.
// Sending String
connection.send('your message');

// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i];
}
connection.send(binary.buffer);

// Sending file as Blob
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);
Equally the server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property.
WebSocket can also receive binary messages in the latest spec. Binary frames can be received in Blob or ArrayBuffer format. To specify the format of the received binary, set the binaryType property of WebSocket object to either 'blob' or 'arraybuffer'. The default format is 'blob'. (You don't have to align binaryType param on sending.)
// Setting binaryType to accept received binary as either 'blob' or 'arraybuffer'
connection.binaryType = 'arraybuffer';
connection.onmessage = function(e) {
  console.log(e.data.byteLength); // ArrayBuffer object if binary
};
Another newly added feature of WebSocket is extensions. Using extensions, it will be possible to send frames compressed, multiplexed, etc. You can find server accepted extensions by examining the extensions property of the WebSocket object after the open event. There is no officially published extensions spec just yet as of February 2012.
// Determining accepted extensions
console.log(connection.extensions);

Cross Origin Communication

Being a modern protocol, cross origin communication is baked right into WebSocket. While you should still make sure only to communicate with clients and servers that you trust, WebSocket enables communication between parties on any domain. The server decides whether to make its service available to all clients or only those that reside on a set of well defined domains.

Proxy Servers

Every new technology comes with a new set of problems. In the case of WebSocket it is the compatibility with proxy servers which mediate HTTP connections in most company networks. The WebSocket protocol uses the HTTP upgrade system (which is normally used for HTTP/SSL) to "upgrade" an HTTP connection to a WebSocket connection. Some proxy servers do not like this and will drop the connection. Thus, even if a given client uses the WebSocket protocol, it may not be possible to establish a connection. This makes the next section even more important :)

Use WebSockets Today

WebSocket is still a young technology and not fully implemented in all browsers. However, you can use WebSocket today with libraries that use one of the fallbacksmentioned above whenever WebSocket is not available. A library that has become very popular in this domain is socket.io which comes with a client and a server implementation of the protocol and includes fallbacks (socket.io doesn't support binary messaging yet as of Februrary 2012). There are also commercial solutions such as PusherApp which can be easily integrated into any web environment by providing a HTTP API to send WebSocket messages to clients. Due to the extra HTTP request there will always be extra overhead compared to pure WebSocket.

The Server Side

Using WebSocket creates a whole new usage pattern for server side applications. While traditional server stacks such as LAMP are designed around the HTTP request/response cycle they often do not deal well with a large number of open WebSocket connections. Keeping a large number of connections open at the same time requires an architecture that receives high concurrency at a low performance cost. Such architectures are usually designed around either threading or so called non-blocking IO.

Server Side Implementations

Protocol Versions

The wire protocol (a handshake and the data transfer between client and server) for WebSocket is now RFC6455. The latest Chrome and Chrome for Android are fully compatible with RFC6455 including binary messaging. Also, Firefox will be compatible on version 11, Internet Explorer on version 10. You can still use older protocol versions but it is not recommended since they are known to be vulnerable. If you have server implementations for older versions of WebSocket protocol, we recommend you to upgrade it to the latest version.

Use Cases

Use WebSocket whenever you need a truly low latency, near realtime connection between the client and the server. Keep in mind that this might involve rethinking how you build your server side applications with a new focus on technologies such as event queues. Some example use cases are:
  • Multiplayer online games
  • Chat applications
  • Live sports ticker
  • Realtime updating social streams

Demos

References