Thursday 13 March 2014

Login with GitHub OAuth using PHP

Nowadays GitHub.com(web based hosting service) is the most import part in developer’s life. In this I want to discuss how to implement GitHub OAuth login system for your web project, this is very simple adopt and sure it will helps you to increase your web project registrations. Please check my previous posts for Google, Facebook and Instagram OAuth login system scripts.




Database
Sample database design 
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) UNIQUE,
fullname VARCHAR(100),
company VARCHAR(50),
blog VARCHAR(50),
location VARCHAR(50),
github_id VARCHAR(50),
github_username VARCHAR(50),
profile_image TEXT,
github_url TEXT
)


Step 1: Github New Application
Register new application at click here.


Step 2: Create Github Application
Submit your website details.


Step 3: Github OAuth Detials
Here the application OAuth client ID and client secret.


The script contains one folder called Github_Lib with PHP files.
Github_Lib
-- githubConfig.php //Github app configuration file.
-- githubApi.php //Github OAuth API.
db.php //Database connection 
github_login.php //Githut Login 
index.php
home.php
logout.php

GitHub API Developer


githubConfig.php
Here modify your application client id, client secret, redirect url and app name values.
<?php
$config = array(
'client_id' => 'Your Client ID',
'client_secret' => 'Your Client Secret',
'redirect_url' => 'http://www.yourwebsite.com/github_login.php',
'app_name' => 'Your Application Name'
);
?>

github_login.php
GitHub OAuth login system, just include the file in index.php
<?php
require_once('Github_Lib/githubConfig.php');
require_once('Github_Lib/githubApi.php');
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
if(isset($_GET['code']))
{
$git = new githubApi($config);
$git->getUserDetails();
$_SESSION['github_data']=$git->getAllUserDetails();
header("location: home.php");
}
else
{
$url = "https://github.com/login/oauth/authorize?client_id=".$config['client_id']."&redirect_uri=".$config['redirect_url']."&scope=user";
header("Location: $url");
}
}
?>

index.php
Calling Github login system. 
<?php
session_start();
if (isset($_SESSION['github_data'])) {
// Redirection to application home page.
header("location: home.php");
}
//HTML Code
<a href="github_login.php">Login with Github</a>
?>

home.php
Contains PHP code inserting GitHub user session details into users table. 
<?php
session_start();
include('db.php'); //Database Connection.
if (!isset($_SESSION['github_data'])) {
// Redirection to application index page.
header("location: index.php");
}
else
{
$userdata=$_SESSION['github_data'];
$email = $userdata->email;
$fullName = $userdata->name;
$company = $userdata->company;
$blog = $userdata->blog;
$location = $userdata->location;
$github_id = $userdata->id;
$github_username = $userdata->login;
$profile_image = $userdata->avatar_url;
$github_url = $userdata->url;

$q=mysqli_query($connection,"SELECT id FROM github_users WHERE email='$email'");
if(mysqli_num_rows($c) == 0)
{
$count=mysqli_query($connection,"INSERT INTO github_users(email,fullname,company,blog,location,github_id,github_username,profile_image,github_url) VALUES('$email','$fullName','$company','$blog','$location','$github_id','$github_username','$profile_image','$github_url')");
}
print_r($userdata); // Full data
echo "<a href='logout.php'>Logout</a>";
}
?>

logout.php
Unsetting the GitHub user session data.
<?php
session_start();
unset($_SESSION['github_data']);
header("Location: index.php");
?>

db.php
Database configuration file, modify username, password and database values. 
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

Creating a new Visual Studio C# Project

At this point we have a new Visual Studio project and are ready to begin the process of adding user interface components to our application. At the moment ouWindows Form (entitled Form1) is empty. The next step is to start dragging components from the Toolbox to the Form.
To access the Toolbox click on the Toolbox tab located along the left hand edge of the main Visual Studio window. This will display the Toolbox which contains a number of different categories of components available for addition to the Form.
If the All Common Components category is currently folded click on the small + sign to unfold the list of components. With the components visible drag and drop two Button components and two TextBox components onto the Form canvas position and resize them such that the Form appears as shown in the following figure.
Repeat the above task by selecting each component in the Form in turn and changing the (Name) property. The second textBox should be named nameText, the left hand and right hand buttons helloButton and closeButton respectively.

Changing Component Properties

In addition to changing the names of components it is also possible to change a myriad array of different properties via the properties panel. To demonstrate this concept we will change the text on the two buttons such that they read "Hello" and "Close". Select helloButton in the Form, scroll down the list of properties to locate the Text value and change it from button1 to Hello. Repeat this for closeButton so that it displays Close.
To try out the application so far press the F5 button on your keyboard to build and run the application. After a few seconds the executing application will appear. Enter some text into the TextBoxes to prove it is a live application.

Adding Behavior to a Visual Studio C# Application

The next task in creating our application is to add some functionality so that things happen when we press the two buttons in our form. This behavior is controlled via events. For example, when a button is pressed a Click event is triggered. All we need to do, therefore, is write some code for the Click events of our buttons. To display the code associated with the closeButton double click on it. The display will change to show the code for the application. Amongst the code is the closeButton_Click event method:



When the closeButton is pressed by the user we want the application to exit. We can achieve this by calling the Close() method in the closeButton_Click event:
        private void closeButton_Click(object sender, EventArgs e)
        {
            Close();
        }
The next task is to read the text entered into nameText and use it to display a message in welcomeText. This will take place whenhelloButton is pressed. Click on the Form1.cs [Design] tab above the code area to return to the visual view of the Form and double click onhelloButton to access the code. This time we will be adding code to the helloButton_Click event method to read the value from nameText, combine it with some extra text and then display the result in welcomeText:
       private void helloButton_Click(object sender, EventArgs e)
       {
            welcomeText.Text = "Hello " + nameText.Text;
       } 
We will learn more about what is happening in the above method in later chapters but in summary we are setting the Text property of thewelcomeText component to a string comprised of a string containing "Hello " and the Text property value of the nameText component.
Build and run the application by pressing F5 and when the application runs enter your name into the second text field and press the Hellobutton. The hello message will subsequently appear in the top text field. Press the Close button to exit the application.
You have now built for first GUI based C# application and are ready to begin learning the basics of the C# programming language in C# Variables and Constants.

Insert, Update, Delete with DataGridView Control in C# (Windows Application)

DataGridView control is one of the coolest features of Dot Net Framework. You can use this control in Windows Form using Wizard or programmatically.
Add a DataGridView control and two Buttons on a Form. One Button is for deleting the selected row and other one is for updating or inserting new row.
Declare those variables as shown below.
public partial class DataTrialForm : Form
    {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataTrialForm()
        {
            InitializeComponent();
        }
In the Form Load event set data source for the DataGridView control.
private void DataTraiForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            selectQueryString = "SELECT * FROM t_Bill";

            sqlConnection.Open();

            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

            dataGridViewTrial.DataSource = bindingSource;
            
            // if you want to hide Identity column
            dataGridViewTrial.Columns[0].Visible = false;
        }

To update, insert or delete data in database from DataGridView have a look at this code snippet.
private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }


        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
               dataGridViewTrial.Rows.RemoveAt(dataGridViewTrial.CurrentRow.Index);
               sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
               MessageBox.Show(exceptionObj.Message.ToString());
            }
        }
Download Source Code and start exploring DataGridView control.

SQL: Managing the joins (INNER JOIN, OUTER JOIN))

Overview
To select some records coming from several data files, some joins must be used in the SQL query.
Two types of joins can be used in the queries in SQL code:
  • the inner joins.
  • the outer joins.
Note: These joins can be used:
The joins cannot be nested.
See a documentation specific to the SQL language for more details.
To find out all the SQL commands (functions, clauses, operators, and so on) that can be used in a SQL query manage by HyperFileSQL, see Commands that can be used in a SQL query managed by HyperFileSQL.
Inner joins
Definition

An inner join is used to select the records that have correspondence between two joined files.
For example, to list all the customers who have placed orders, the "Customer" file must be linked to the "Orders" file via an inner join. The query will select the customers linked to at least one order number. The customers wo have placed no order will not be listed.

Use format

Three syntaxes are available:
  • Syntax 1: Correspondence between identical items found in different files (using WHERE)
SELECT ...
FROM File1, File2, File3
WHERE File1.ItemName1 = File2.ItemName1
File2.ItemName2 = File3.ItemName2
  • Syntax 2: Correspondence between identical items found in different files (using INNER JOIN)
SELECT ...
FROM File1INNER JOIN File2
ON (File1.NameItem1 = File2.NameItem1),
File2 INNER JOIN File3
ON (File2.NameItem2 = File3.NameItem2)
  • Syntax 3: Correspondence between identical items found in different files (using INNER JOIN): syntax compatible with SQL Server, Access and MySQL.
SELECT ...
FROM (File1 INNER JOIN File2
ON File1.NameItem1 = File2.NameItem1)
INNER JOIN File3
ON File2.NameItem2 = File3.NameItem2
You also have the ability to establish links between several files on different items.

Example: the following SQL codes are used to select the customers who have placed orders:
SELECT CUSTOMER.CustomerLastName,
ORDERS.OrdNum
FROM CUSTOMER, ORDERS
WHERE CUSTOMER.CustNum = ORDERS.CustNum
equivalent to:
SELECT CUSTOMER.CustomerLastName,
ORDERS.OrdNum
FROM CUSTOMER INNER JOIN ORDERS
ON (CUSTOMER.CustNum = ORDERS.CustNum)

External joins
Definition

An outer join is used to select both:
  • the records that have correspondence between the two linked files.
  • the records that have no correspondence in the first file, in the second file or in all the linked files.
For example, to find out the total amount spent by each customer:
  • By using an inner join, only the customers who have already placed an order (whose amount spent is different from 0) will be selected.
  • By using an outer join, all the customers will be selected, even the ones who have never placed an order.

The different types of outer joins

FULL OUTER JOINUsed to select:
  • the records that fulfill the join.
  • the records of the first listed file that do not fulfill the join. The name of the first listed file is found to the left of the OUTER JOIN.
  • the records of the second listed file that do not fulfill the join. The name of the second listed file is found to the right of the OUTER JOIN.
LEFT OUTER JOINMost common join. Used to select:
  • the records that fulfill the join.
  • the records of the first listed file that do not fulfill the join. The name of the first listed file is found to the left of the OUTER JOIN.
RIGHT OUTER JOINUsed to select:
  • the records that fulfill the join.
  • the records of the second listed file that do not fulfill the join. The name of the second listed file is found to the right of the OUTER JOIN.

Use format

The available syntaxes are as follows:
  • Syntax 1: Correspondence between identical items found in different files
SELECT ...
FROM (File1 LEFT/RIGHT/FULL JOIN File2
ON File1.NameItem1 = File2.NameItem1)
LEFT/RIGHT/FULL JOIN File3
ON File2.NameItem2 = File3.NameItem2
  • Syntax 2: Correspondence between identical items found in different files: syntax compatible with SQL Server, Access and MySQL.
SELECT ...
FROM File1LEFT/RIGHT/FULL JOIN File2
ON File1.NameItem1 = File2.NameItem1,

LEFT/RIGHT/FULL JOIN File3
ON File2.NameItem2 = File3.NameItem2
You also have the ability to establish links between several files on different items.

Example: The following SQL code is used to list the total amount spent by each customer. Even the customers who have never placed an order will be selected.
SELECT CUSTOMER.CustomerLastName,
SUM(ORDERS.TotalIOT) AS TotalIOT
FROM CUSTOMER LEFT OUTER JOIN ORDERS
ON (CUSTOMER.CustNum = ORDERS.CustNum)
GROUP BY CUSTOMER.CustomerLName

Example: The following SQL code is used to list the number of products ordered by each customer who has placed at least one order.
SELECT CUSTOMER.CustNum,
COUNT(DISTINCT PRODUCT.Reference) AS NbProducts
FROM CUSTOMER LEFT OUTER JOIN ORDERS
ON CUSTOMER.CustNum = ORDERS.CustNum,
ORDERS JOIN ORDLINE
ON ORDERS.OrdNum = ORDLINE.OrdNum,
ORDLINE JOIN PRODUCT
ON ORDLINE.Reference = PRODUCT.Reference
GROUP BY CUSTOMER.CustNum, PRODUCT.Reference
Equivalent to:
SELECT CUSTOMER.CustomerLastName,
COUNT(DISTINCT PRODUCT.Reference) AS NbProducts
FROM CUSTOMER, ORDERS, ORDLINE, PRODUCT
WHERE CUSTOMER.CustNum = ORDERS.CustNum(+)
AND ORDERS.OrdNum = ORDLINE.OrdNum
AND ORDLINE.Reference = PRODUCT.Reference
GROUP BY CUSTOMER.CustNum, PRODUCT.Reference
Also equivalent to:
SELECT CUSTOMER.CustNum,
COUNT(DISTINCT PRODUCT.Reference) AS NbProducts
FROM ((CUSTOMER LEFT OUTER JOIN ORDERS
ON CUSTOMER.CustNum = ORDERS.CustNum)
JOIN ORDLINE
ON ORDERS.OrdNum = ORDLINE.OrdNum)
JOIN PRODUCT
ON ORDLINE.Reference = PRODUCT.Reference
GROUP BY CUSTOMER.CustNum, PRODUCT.Reference