Monday, 1 May 2017

Sort array of objects using PHP

// Code using Bubble sort


<?php
// Array of objects sort using Bubble sort.

class Student{
   
    //properties
    public $studentName;
    public $rollNumber;
    public $marks1;
    public $marks2;
    public $marks3;
    public $total;
    public $average;
   
    //methods
    function setMarks1($marks1){
         $this->marks1 = $marks1;
      }
    function setMarks2($marks2){
         $this->marks2 = $marks2;
      }
    function setMarks3($marks3){
         $this->marks3 = $marks3;
      }   
    public function total(){           
    $this->total=$this->marks1+ $this->marks2+$this->marks3;   
    return $this->marks1+ $this->marks2+$this->marks3;
    }   
    public function average(){
    $this->average= ($this->marks1+ $this->marks2+$this->marks3)/3;
    return ($this->marks1+ $this->marks2+$this->marks3)/3;
    }
   
}
$s=array();
$s1= new Student();
$s1 -> studentName = 'Student1';
//echo $s1->studentName ."<br>";
$s1 ->rollNumber=1;
$s1->setMarks1(45);
$s1->setMarks2(76);
$s1->setMarks3(78.5);

echo "student1 \n" . $s1->total() ."\n". $s1->average() ."<br>";
$s2= new Student();
$s2 -> studentName = 'Student2';
$s2->setMarks1(27);
$s2->setMarks2(56);
$s2->setMarks3(76);
echo "student2 \n" .$s2->total() . "\n" . $s2->average()."<br>";
$s3= new Student();
$s3-> studentName = 'Student3';
$s3->setMarks1(73);
$s3->setMarks2(89);
$s3->setMarks3(32);
echo "student3 \n" .$s3->total() . "\n" . $s3->average()."<br>";
$s4= new Student();
$s4 -> studentName = 'Student4';
$s4->setMarks1(45);
$s4->setMarks2(45);
$s4->setMarks3(87);
echo "student4 \n" .$s4->total() . "\n" . $s4->average()."<br>";
$s5= new Student();
$s5 -> studentName = 'Student5';
$s5->setMarks1(19);
$s5->setMarks2(22);
$s5->setMarks3(54.5);
echo "student5 \n" .$s5->total() . "\n" . $s5->average()."<br>";
$s6= new Student();
$s6 -> studentName = 'Student6';
$s6->setMarks1(98);
$s6->setMarks2(25);
$s6->setMarks3(65);
echo "student6 \n" .$s6->total() . "\n" . $s6->average()."<br>";
$s7= new Student();
$s7 -> studentName = 'Student7';
$s7->setMarks1(34);
$s7->setMarks2(65);
$s7->setMarks3(32);
echo "student7 \n" .$s7->total() . "\n" . $s7->average()."<br>";
$s8= new Student();
$s8 -> studentName = 'Student8';
$s8->setMarks1(14);
$s8->setMarks2(84);
$s8->setMarks3(72);
echo "student8 \n" .$s8->total() . "\n" . $s8->average()."<br>";

$s9= new Student();
$s9 -> studentName = 'Student9';
$s9->setMarks1(23);
$s9->setMarks2(22);
$s9->setMarks3(76);
echo "student9 \n" .$s9->total() . "\n" . $s9->average()."<br>";

$s10= new Student();
$s10 -> studentName = 'Student10';
$s10->setMarks1(22);
$s10->setMarks2(98);
$s10->setMarks3(43);
echo "student10 \n" .$s10->total() . "\n" . $s10->average()."<br>";


$sortarr = array($s1,$s2,$s3,$s4,$s5,$s6,$s7,$s8,$s9,$s10);
//var_dump($sortarr);
$x=$sortarr[0]->total;
        var_dump($x);
       
echo '<pre>';
 print_r(bubble_sort($sortarr));
echo '</pre>';

function bubble_sort($sortarr){
        // Bubble sorting
        $array_count = count($sortarr);
       
        for($x = 0; $x < $array_count; $x++){
            for($a = 0 ;  $a < $array_count - 1 ; $a++){
                if($a < $array_count ){
                    if($sortarr[$a]->total < $sortarr[$a + 1]->total ){
                            swap($sortarr, $a, $a+1);
                    }
                }
            }
        }
        return $sortarr;   
    }

    function swap(&$arr, $a, $b) {
        $tmp = $arr[$a];
        $arr[$a] = $arr[$b];
        $arr[$b] = $tmp;
    }



?>

Monday, 13 June 2016

Http Errors

Types of  HTTP Errors

Sometimes when you try to visit web page, you’re met with an HTTP error message. It’s a message from the web server that something went wrong. In some cases it could be a mistake you made, but often it’s the site’s fault.
Each type of error has an HTTP error code dedicated to it.

Lets have a look on types of Errors and Error codes.
Http-Hyper Text Transfer Protocol has a list of response status codes.
It was categorized into five classes of response.

  • 1xx Informational
  • 2xx Success
  • 3xx Redirection
  • 4xx Client Error
  • 5xx server error
 1xx Informational                                                                                                                      

Message
Description
100 Continue
The server has received the request headers, and client should proceed to send the request body.

101 Switching Protocols
The requester has asked the server to switch protocols

103 Checkpoint
Used in the resemble requests proposal to resume aborted PUT or POST requests.


2xx Success

Message
Description
200 OK
The request is OK
201 Created
The request has been fulfilled, and a new resource is created 
202 Accepted
The request has been accepted for processing, but the processing has not been completed

203 Non-Authoritative Information
The request has been successfully processed, but is returning information that may be from another source

204 No Content
The request has been successfully processed, but is not returning any content

205 Reset content
The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view

206 Partial content
The server is delivering only part of the resource due to a range header sent by the client


3xx Redirection

Message
Description
300 Multiple choices
A link list. The user can select a link and go to that location. Maximum five addresses  

301 Moved Permanently
The requested page has moved to a new URL 
302 Found
The requested page has moved temporarily to a new URL 

303 See other
The requested page can be found under a different URL

304 Mot modified
Indicates the requested page has not been modified since last requested

306 Switch proxy
No longer used

307 Temorary redirect
The requested page has moved temporarily to a new URL
308 Resume Incomplete
Used in the resemble requests proposal to resume aborted PUT or POST requests.


4xx: Client Error

Message
Description
400 Bad request
The request cannot be fulfilled due to bad syntax

401 Unauthorized
The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided

402 Forbidden
Reserved for future use.
403 Forbidden
The request was a legal request, but the server is refusing to respond to it.
404 Not found
The request page could not be found but may be available again in the future.

407 Proxy Authentication Required
The client must first authenticate itself with the proxy
408 Request Timeout

The server timed out waiting for the request.
409 Conflict
The request could not be completed because of a conflict in the request

5xx Server Error

Message
Description
500 Internal Server error
A generic error message, given when no more specific message is suitable

502 Bad Gateway
The server was  acting as a gateway or proxy and receive an invalid response from the upstream server.

503 Service Unavailable
The server is currently unavailable (overloaded or down)
504 Gateway Timeout
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server





Wednesday, 1 June 2016

Cache Management & Security

What is Caching and what are the benefits of using it?
Caching is an area of a computer’s memory devoted to temporarily storing recently used information. 
    cache memory diagram
  • The content, which includes HTML pages, images, files and Web objects, is stored on the local hard drive in order to make it faster for the user to access it, which helps improve the efficiency of the computer and its overall performance.
  • when a user returns to a Web page they have recently accessed, the browser can pull those files from the cache instead of the original server because it has stored the user’s activity.
Advantages

The advantages of web caching via proxy servers include: 
  • faster access to valid cached resources
  • saving on costly use of bandwidth
  • imposing controls on access to dubious material
  • collecting useful statistics on web access
  • providing cached resources even when origin server is down
Disadvantages
Disadvantages of web caching include 
  • slower performance if the resource isn't found in the cache
  • being given a stale copy of a resource when an uptodate copy is needed
  • resources sometimes getting mangled/lost on route
  • sharing an access point to the web increasing risks to service
  • proxy server access logs invading the privacy of users
  • proxy intermediary confusing logging and access control by subscription services
                                          ------------------------**-------------------------
Cache Management in ASP.NET?
ASP.NET provided support for Cache Management in almost all versions. In .NET Framework 3.5 and older, the support for caching was provided through classes available in System.Web.Caching. But this support was limited to System.Web meaning for ASP.NET Web Applications only. Now, with .NET Framework 4.0 and later, this support is enhance to non-Web Applications also by providing APIs inSystem.Runtime.Caching.
ASP.NET supports three types of Caching:
  • Page Output Caching
  • Partial Page Caching
  • Data Caching
                       ------------------------**-------------------------
How to use Page Output Cache in ASP.NET?
The output of a complete web page is stored in a cache. So, when that web page is accessed again, it will be loaded from cache instead of fetching page data again from data source.
                                          ------------------------**-------------------------
How to use Page Fragment or Partial Page Cache in ASP.NET?
For Partial Page Cache (also known as Page Fragment Cache), a part or fragment of a web page is stored in Cache as opposed to complete page caching for Page Output Cache. For example, caching a user control on a web page that displays product categories using Page Fragment Cache.
                                          ------------------------**-------------------------
How to use Data Cache in ASP.NET?
In some scenarios, we may store frequently used objects into cache using ASP.NET Cache API. So, later on, that object will be loaded from cache instead of instantiating object again and fetching data from original source for it.
                                          ------------------------**-------------------------
Authentication Vs Authorization?
Authentication and Authorization are two key security related concepts that are independent but normally go together.
Authentication is a process that verifies the identity of a user. On ther hand, Authorization is the process of assigning rights/privileges to already authenticated user.
                                          ------------------------**-------------------------
What are the available Authentication modes in ASP.NET?
There are four types of authentications in ASP.NET i.e.
  • Windows Authentication
  • Forms Authentication
  • Passport Authentication
  • Anonymous access
                                          ------------------------**-------------------------

What is Protected Configuration in ASP.NET?
While developing an ASP.NET application, we normally store a number of important sensitive information in our config files like encryption keys, connection strings etc. Application vulnerability increases if this sensitive information is stored as plane text. So Protected Configuration is an ASP.NET feature that enables to encrypt such sensitive information in configuration files.
                                          ------------------------**-------------------------








Tuesday, 31 May 2016

Microsoft's Passport Authentication

What is Passport Authentication?
There are three types of authentications in ASP.NET i.e.
  • Windows Authentication
  • Forms Authentication
  • Passport Authentication
  • Anonymous access
Windows Authentication:
If your application is targeted for use inside an organization, and users accessing the application have existing user accounts within the local user database of the Web server or Active Directory, you should authenticate users with Windows authentication.
Form Authentication:
Form-based authentication presents the user with an HTML-based Web page that prompts the user for credentials.
Passport authentication:
You can also authenticate users using a service from Microsoft called Passport. Passport 
is a centralized directory of user information that Web sites can use, in exchange for a fee, to authenticate users. Users can choose to allow the Web site access to personal 
information stored on Passport, such as the users' addresses, ages, and interests.
We don’t need to implement our own custom authentication mechanism if implementing .NET Passport Single Sign-In (SSI) service.
Anonymous access 
You can explicitly disable authentication for your application if you know that it will be used only by anonymous users. 
<configuration> 
<system.web> 
<authentication mode="None" /> 
</system.web> 
</configuration>
                                     --------------**--------------
Can you briefly explain how Passport Authentication works?
As discussed above that Passport Authentication is a central service. It just authenticate (validate the credentials), no authorization (grant or deny access to a site). So, implementing application will check for the Passport Authentication Cookie. In case of unavailability of Passport Cookie, user is redirected to passport Sign-In page. User provides the credentials on Sign-In page, if validated,  Authentication Cookie is stored on client machine and redirected to the requested page.
Below picture clearly explains step by step process of Passport authentication in ASP.NET.
Passport Authentication in ASP.NET
                                     --------------**--------------

What are the advantages of using Passport Authentication?
Advantages of Passport Authentication are:
  • We don’t need to care of authentication mechanism our self, Passport SSI does this for us.
  • Single login credentials can be used to access multiple sites. User don’t need to remember separate credentials for individual site.
                                     --------------**--------------
What is Role-based Security?
We have discussed about authentication in above questions but another different but related concept is Authorization. Authorization is a process of granting privileges or permissions on resources to an authenticated user. So,
Role Based Security is a technique we use to implement authorization on the basis of user’s roles within an   organization. It’s more granular approach to grant or revoke permissions on resources through user’s roles.
                                     --------------**--------------
What are the different Security Controls in ASP.NET?
ASP.NET provides several security controls which are actually Web Server controls. We can see in Visual Studio Toolbox.
Login Control:
In almost every application we need to take user credentials on a typical login page. Login control provides the same standard functionality and reduces the effort for building it from scratch.
LoginName:
After a user successfully logged in to an application, we normally display his/her username to top right or some other place on the page. Now, this functionality is provided by LoginName control.
LoginView Control:
LoginView control displays different view for different users. Using AnonymousTemplate and LoggedInTemplate, different information can be presented to different users.
LoginStatus Control:
LoginStatus control implies whether a user is authenticated or not. For an unathenticated user, it displays a link to login page. On the other hand, for authenticated user, a logout link is displayed.
LoginRecovery Control:
Password recovery is another important functionality simplified through PasswordRecovery control. It sends an email with login credentials to registered user email.
                                     --------------**--------------

What is Code-Access Security (CAS)?
 Role Based Security that restrict access to resources on the basis of user’s role. CAS (Code Access Security) is entirely a different concept. It’s .NET CLR’s security system that restrict the code to perform an unwanted task by applying security policies.
                                     --------------**--------------
What are the key functions of Code Access Security?
Key functions of Code Access Security are :
  • Defines permissions and permission sets that represent the right to access various system resources.
  • Enables code to demand that its callers have specific permissions.
  • Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code.
  • Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.
                                     --------------**--------------
What .NET Tool can be used to Enable/Disable CAS?
Code Access Security Tool (Caspol.exe) can be used to turn Code Access Security ON or OFF as follows:
  • caspol -security on
  • caspol -security off
We can also list all code groups using following command.
  • caspol -listgroups
                                     --------------**--------------

What is Impersonation in ASP.NET?
Impersonation is an act of a user to pretend itself to be another user. By default, ASP.NET executes application code using the same user account as that of ASP.NET process i.e. Network Service. But with impersonation enabled, it executes code with the windows identity of the user making the request.
For example, if a user ‘user1′ logged in and IIS is setup to run as Network Service. If ‘user1′ call a piece of code on another computer (may be a web service call), the other computer will see the IIS user instead of ‘user1′. But we can enable impersonation to allow ‘user1′ to access the web service using its windows identity instead of Network Service.
                                     --------------**--------------


How to configure Impersonation in ASP.NET??
By default, impersonation is disabled in ASP.NET. Impersonation can be Enabled/Disabled as follows:

</configuration>
      <system.web>
          <identity impersonate=”true”/> <! — To disable set impersonate=”false” –>
       </system.web>
 </configuration>

Impersonate a specific user account as:

<identity impersonate=”true” userName=”user” password=”pwd” />

                                     --------------**--------------




AJAX

Define Ajax
Ajax is a client-side script that communicates to and from a server or database without the need for a postback or a complete page refresh. 
 Ajax is “the method of exchanging data with a server, and updating parts of a web page - without reloading the entire page.
How it works?
AJAX
In this way an ajax script will work.
Please elaborate XMLHttpRequest Object further?
The XMLHttpRequest object is used to exchange data with a server behind the scenes. The XMLHttpRequest object is the developers dream, because you can: Update a web page without reloading the page.
JavaScript uses this Object to exchange XML as well as text data between client and server. An AJAX implementation uses this object and communicate with server but it doesn't require the complete page to be refreshed.

How to send a request to server using XMLHttpRequest Object?
We can send a request to server using HTTP GET and POST methods.

// Simple GET Request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "TestFile.txt", true);
xmlHttp.send();

//Simple POST Request 
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "TestFile.txt", true);
xmlHttp.send();

What is ASP.NET AJAX?
Microsoft simplified the usage of these techniques with its own implementation. ASP.NET AJAX is a set of extensions to ASP.NET and comes with reusable AJAX controls. Using ASP.NET AJAX, we can develop applications that can update partial page instead of a complete page refresh.
Difference between Synchronous and Asynchronous Postback?

Synchronous Postback

Asynchronous Postback

complete web page is sent to server and in return rendering the output
partial page goes to the server and renders only partial (required) part of the page.
 synchronous postback executes all the actions at once.
Asynchronous postback executes only one postback at a time, that is, if you have two buttons doing asynchronous postback, the actions will be performed one by one
 Synchronous postback modifies the entire page. 

Asynchronous postback only modifies the update panel that raises the postback

What are the basic controls in ASP.NET AJAX?
Following controls can be considered as core AJAX controls in ASP.NET.
  • ScriptManager
  • ScriptManagerProxy
  • UpdatePanel
  • UpdateProgress
  • Timer
Later more controls are added to ASP.NET AJAX library e.g. Script Loader, Client Data Context, Client Data Access, jQuery Integration etc.
What is a ScriptManager in ASP.NET AJAX?
In order to use AJAX functionality on a web page, we add a ScriptManager control to the page in most of the scenarios, because ScriptManager control register AJAX library scripts to that particular web page.
ScriptManager Vs ScriptManagerProxy?
As we understand that we can have only one ScriptManager control on a page but we can have multipleScriptManagerProxy controls. Consider a scenario that we have ScriptManager in our MasterPage that is available for all content pages. Now, we wanted to register a web service in a particular page. So, we will not add another ScriptManager to that page instead we will add ScriptManagerProxy to it in order to avoid error
What is the role of UpdatePanel in ASP.NET AJAX?
UpdatePanel is the control that facilitate the partial page rendering functionality in an ASP.NET application. As discussed earlier that using ASP.NET AJAX, we can communicate with a web server asynchronously and update a part of a page without a complete page postback.

What are the limitations of AJAX?
  • AJAX on an application will not work if JavaScript is disabled.
  • In some scenarios, it exposes vulnerability.
  • It will always be difficult to bookmark application state.
  • Application behavior may be slow in some scenarios, because of different loading time of controls on a single page.