Friday 12 December 2014

Facebook Open Authentication (OAuth 2.0) Implementation

Introduction and Facebook App Setup

Hi folks,
I'm gonna explain that how you can implement facebook open authentication to your Application.

As we know Facebook is social giant and have lots and lots of data regarding users and they perform data analysis too on user activities to generate data. In real world all businessmen want their business grow rapidly and it can grow rapidly only if more and more people know about it, so they advertise by giving their business advertisement to websites who have more traffic and there is another way to reach people is through social sites like Facebook and their are several others too, but facebook is one of the sites that is accessed frequently by users.


Now coming to the point, Facebook launched its API's and tools on May 24, 2007 for third party application developers to access the Facebook data.
To access the Facebook data you must have a Facebook account first ( FYI :D ), after logging in to your account create your Facebook App from here: https://developers.facebook.com . Under the Menu Apps, select Add New App. see the below screen:


Now select the App Type you want to add according to your requirement, in my case i have a website so i will go for it.

In Next step give your App name and generate a unique App id for it.

Next step will ask you to select your App category, according my need i have to set a business App, you can select up to your requirement.



Facebook will create a App Id and App Secret for your app, that you have to use in your application to call the facebook api on behalf of user to access his/her private data if they provide permission while performing OAuth.
For a web application you can use localhost as a site url as in the below image, when you move it to production, you use the real one.Below is the screen where you can see the App Id and App Secret and some basic setting.



By default :


email
Provides access to the person's primary email address. This permission is approved by default.
public_profile
Provides access to a person's basic information, including first name, last name, profile picture, gender and age range. This permission is approved by default.
user_friends
Provides access to a person's list of friends that also use your app. This permission is approved by default.


Your App has these permissions on, if you want more scopes (scopes are the set of permissions) to be added to your App then you have to click on START SUBMISSION button. After you complete all the settings of your App. Then its time move towards Code.

OAuth 2.0

Facebook implements Open Authentication system version 2.0 (OAuth 2.0). OAuth specifies a process for Facebook to authorize third-party access to their server resources without sharing their credentials. You can explore it more from here:  http://oauth.net/2/Facebook provides Access Token through which your App can Access user's private data if user provides your App permission to access. Access Token has a short lifetime i.e it is valid for around 1 hour. Here's the facebook documentation over token's https://developers.facebook.com/docs/facebook-login/access-tokens


Facebook provides the access token's once, you have persist it somewhere in the management systems and when it expires you can ask for another access token by sending the previous expired token.
I will provide a code sample which do not uses facebook c# library for the OAuth process, this will clear the concept of Facebook OAuth process. Code is for Asp.net(web forms) using C# as script.
        string OAuthURL = "https://www.facebook.com/dialog/oauth";
        string OAuthTokenURL = "https://graph.facebook.com/oauth/access_token";
        string client_id = "YOUR APP CLIENT ID;
        string client_secret = "YOUR APP SECRET ID";
        string scope = "email,user_birthday,user_location,user_about_me,user_likes";
        string redirect_uri = "http://localhost:1234/facebook.aspx";
        string serviceURL = "https://graph.facebook.com/me";

        protected void Page_Load(object sender, EventArgs e)
        {
            OAuthLabel.Text = "OAuth Redirect Page";

            if (Request["code"] != null)
            {
                //Build the form request from the parameters
                string formData = "client_id=" + client_id +
                    "&client_secret=" + client_secret +
                    "&redirect_uri=" + redirect_uri +
                    "&grant_type=authorization_code" +
                    "&code=" + Request["code"];

                //Exchange code for access token
                System.Net.WebClient WC = new System.Net.WebClient();
                WC.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                var Results = WC.UploadString(new System.Uri(OAuthTokenURL), formData);
                                
                //Extract token from the results
                string access_token = "";
                try
                {
                    JObject TokenData = JObject.Parse(Results);
                    access_token = TokenData["access_token"].ToString();
                }
                catch (Exception) //next try URL encoded data
                {
                    string[] URLParts = Results.Split('&');
                    foreach (string S in URLParts) //extract the code from the URL
                    {
                        string[] param = S.Split('=');
                        if (param[0].Replace("?", "") == "access_token")
                        {
                            access_token = param[1];

                            //Build the form request from the parameters
                            string formData1 = "client_id=" + client_id +
                                "&client_secret=" + client_secret +
                                "&grant_type=fb_exchange_token" +
                                "&fb_exchange_token=" + access_token;

                            //Exchange code for long access token
                            System.Net.WebClient ExchangeWC1 = new System.Net.WebClient();
                            ExchangeWC1.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            var Results1 = ExchangeWC1.UploadString(new System.Uri(OAuthTokenURL), formData1);
                                
                            break;
                        }
                    }
                }

                //Call a service with the token
                System.Net.WebClient ProfileWC = new System.Net.WebClient();
                ProfileWC.Headers.Add("Authorization", "Bearer " + access_token);
                Results = ProfileWC.DownloadString(new System.Uri(serviceURL));

                //Display the users name..
                JObject UserProfile = JObject.Parse(Results);
                OAuthLabel.Text = "Hi, " + UserProfile["name"].ToString();

            }
            else //no "code" detected, redirect to OAuth service
            {
                string URL = OAuthURL + "" +
                    "?client_id=" + client_id +
                    "&scope=" + scope +
                    "&redirect_uri=" + redirect_uri +
                    "&response_type=code";

                Response.Redirect(URL);
            }
        }


Wednesday 5 March 2014

Google Adx Seller Rest API using .NET

Introduction

Hello everyone,
Recently i have worked with Adx Seller Api using .Net, i have also prepared the sample code for you guys.
Basically i will be focusing more on how to access the Api not on the Adx Seller Program, to know about what is it, just read it here Adx Seller Program.

To access the Google data via its API we need Access Token, to obtain the access token, we need to perform OAuth with Google which i have explained in my previous blog here http://sanjaybathre.blogspot.com/2014/01/sample-for-google-analytics-api-version.html.


Adx Seller


Under this title, i will explain the parameters used by the Adx Seller Api.
I am using the latest(till now) version (v 1.1) of the API, here is the details of the API resources, and here is the Rest Api playground provided by the Google - Playground.




See the List of Metrics and Dimensions required for Api.
Install the Adx Client Library in your solution, Open the Nuget Package Manager Console, and type in the following command: 
PM> Install-Package Google.Apis.AdExchangeSeller.v1_1 -Pre


Code

//Performing Google OAuth 2.0
            UserCredential OAuthcredential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                OAuthcredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AdExchangeSellerService.Scope.AdexchangeSellerReadonly },
                    "user", CancellationToken.None, new FileDataStore("AdexchangeSeller.Auth.Store")).Result;
            }
//AdExchange Seller Service object
            AdExchangeSellerService service_adex = new AdExchangeSellerService(new AdExchangeSellerService.Initializer()
            {
                HttpClientInitializer = OAuthcredential,
                ApplicationName = "AdExchange API sample",
            });

            ReportsResource.GenerateRequest gr = new ReportsResource.GenerateRequest(service_adex, "2014-02-27", "2014-02-27");
            List<string> Dimensions = new List<string>
            {
                "DATE",
                //"DOMAIN_NAME",
                "AD_TAG_NAME"
            };
            List<string> Metrices = new List<string>
            {
                "INDIVIDUAL_AD_IMPRESSIONS",
                "EARNINGS"
            };
            gr.Dimension = Dimensions;
            gr.Metric = Metrices;
            gr.Sort = "DATE";
            gr.Filter = "AD_TAG_NAME=@XYZ123";
            Report data = gr.Execute();

i have attached the code sample please find it and use it, replace 
client_secrets.json file with your file.


Monday 24 February 2014

Acquisition Channels Report using Google Analytics API dotNet


Introduction

Hello everyone,

In this blog, i have analysed the Google Analytic Channels data and according to it i have filtered the available data through the API to form the data for Channels report.

I have fetched the data for Default Channel Grouping labels and its detailed view.

For those who don't know, can find there Channels Report under Acquisition>Channels section. see the Screenshot below:


As we can see Channels Report is new and Google didn't provided its API's. I have analysed data under All Traffic (traffic Source), and filtered that data using filters provided by google(Filter Operation) to get appropriate result.
Use this tool: GA Tool, to analyse data before implementing it in your code.

Code

Here is the sample code, you can also download it here: Samples, put the credentials in your client_secrets.json file.
List of all Metrics and Dimensions are here: Metrics and Dimension

Social:
Fetching Social data, 
Dimension = ga:socialNetwork
Metrics   = ga:visits (change it according to your need)
Filter    = ga:socialNetwork!=(not set);ga:socialNetwork!=(none)

   //Social 
   var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
   request.Dimensions = "ga:socialNetwork";
   request.StartIndex = 1;
   request.Filters = "ga:socialNetwork!=(not set);ga:socialNetwork!=(none)";
   request.MaxResults = 10000;
   request.Sort = "-ga:visits";
   GaData results = request.Execute()

Organic Searches:
Fetching Organic data,  
Dimension = ga:sourceMedium,ga:keyword
Metrics = ga:visits (change it according to your need)
Filter  = ga:sourceMedium=@/ organic

//Organic Searches
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );

request.Dimensions = "ga:sourceMedium,ga:keyword";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@(direct)";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Direct:
Fetching Direct data,  
Dimension = ga:sourceMedium,ga:pagePath 
Metrics  = ga:visits (change it according to your need)
Filter    = ga:sourceMedium=@(direct)

//Direct
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:pagePath";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@(direct)";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Email:
Fetching Email data,  Dimension = ga:sourceMedium,ga:pagePath 
Metrics = ga:visits (change it according to your need)
Filter   = ga:sourceMedium=@/ email 

//Email
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:pagePath";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@/ email";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Other
Fetching Other data,  Dimension = ga:sourceMedium,ga:pagePath 
Metrics = ga:visits(change it according to your need)
Filter = ga:ga:sourceMedium!@(direct);ga:sourceMedium!@/ referral;ga:sourceMedium!@/ email;ga:sourceMedium!@/ organic 

//Other
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:source";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium!@(direct);ga:sourceMedium!@/ referral;ga:sourceMedium!@/ email;ga:sourceMedium!@/ organic";
request.MaxResults = 10000;
request.Sort = "-ga:visits";
results = request.Execute();

Download sample code Samples.

Wednesday 29 January 2014

Sample for Google Analytics Api Version 3.0 using dotnet (C#) and OAuth 2.0

Hello everyone, Recently I have worked on some cool stuff regarding Google, I want to share my experience with you all.

here is the source code download link:
https://docs.google.com/file/d/0B1Wv6jrLHNQkRTNObllUUDJNNHM/edit

Introduction

Google, as everyone knows is famous for its various online service which includes accurate search (crawling, indexing, powerful algorithm) and its online business. Google have huge amount data from all around the world, and Google Provide API's  to access its data programmatically (that's the good part i like), in this blog i will explain how to access the data from Google using .Net(c#).
Now Coming to Google Analytics, It is a online service of Google which track your website or blog and provide data like: what is the visit count, how many visitors you have, from which country you have visits, and etc. to study more about it here https://support.google.com/analytics/answer/1008065?hl=en.
Accessing the analytics API Requires following steps:
  1. OAuth (OAuth stands for Open Authentication, i will use OAuth 2.0 which is latest, OAuth 1.0 is deprecated by Google)
  2. GA API

OAuth 2.0

Suppose you have a website or application and in that you want, the user to sign up into your App. via his/her existing Google account and provide his/her data, for this we use Google OAuth Service.

Before using the OAuth in your application, you register your application in Google API Console.
Here are the steps to register your Application in Google developer console.

click here to go in Google developer console:  https://developers.google.com/
then go to: Developer Tools>API Console>Projects>Create Project
now create ClientId for Installed (Or any application you want) application and download the json file.

More detailed steps are below, follow the screens. 
(i have provided the sample code which is downloadable, its a windows form application)

1. Select Api Console



2. Under APIs and auth, select credentials then Create your client id


3. Select the application type you want


4. Then download the json file for OAuth.





I have been using OAuth a lot, now comes the interesting part, what is OAuth?

 Diagram above, explains the concept of OAuth clearly, to access the Google API you need the Access Token, which google provides you after authenticating you, that you are a valid and  registered user of Google.
You can  go through this whole article provided by Google, here https://developers.google.com/accounts/docs/OAuth2

Include the OAuth2 dll in your application:
  1. Open your Nuget package console manager.
  2. Just type in the following command :  PM> Install-Package OAuth2
  3. Put in the downloaded client_secrets.json file in your application.

Code sample for OAuth 2.0

using Google.Apis;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System.IO;

................
................
UserCredential OAuthcredential;            
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                OAuthcredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsService.Scope.AnalyticsReadonly },
                    "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;
            }
................
................

Google Analytics Service API

Include the Google analytics dll in your application:
  1. Open your Nuget package console manager.
  2. Just type in the following command :  PM> Install-Package Google.Apis.Analytics.v3 -Pre

This image below explains the conceptual view of GA.
before writing code, just try this tool: GA Tool, this tool will help you a lot for analysis.


Code:
using Google.Apis;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;

private void Form1_Load(object sender, EventArgs e)
        {
               //Performing OAuth 2.0
                UserCredential OAuthcredential;            
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                OAuthcredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsService.Scope.AnalyticsReadonly },
                    "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;
            }
            
           //we need to create AnalyticsService class object to use GA api
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = OAuthcredential,
                ApplicationName = "Analytics API sample",
            });

            ManagementResource.AccountsResource.ListRequest AccountListRequest =            service.Management.Accounts.List();

            //
            Profiles _Profiles = service.Management.Profiles.List("~all", "~all").Execute();

            if (_Profiles.Items.Count > 0)
            {
                // get sample statistics for first profile found
                var request = service.Data.Ga.Get(
                    "ga:" + _Profiles.Items[0].Id,
                    "2013-12-01", // start date 
                    "2014-01-29", // end date
                    "ga:visitors,ga:pageviews" // metrices
                    );

                request.Dimensions = "ga:date";                
                request.Sort = "ga:date";
                request.StartIndex = 1;
                request.MaxResults = 500;
                GaData results = request.Execute();
            }
}

here is the source code download link::
https://docs.google.com/file/d/0B1Wv6jrLHNQkRTNObllUUDJNNHM/edit
This code sample is for Installed Application.