My studying notebook

Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

2015/02/26

[notebook] Google Push Notification API

2/26/2015 10:06:00 AM Posted by Unknown , , , , 86 comments

Google Push Notification

The Google APIs provides push notification that let you watch for changes to resources

Google Drive Push Notification

Google APIs provides Push Notification

You can visit Google APIs Explorer - search watch. There are few APIs support push notification now. Not all of them.
calendar.settings.watchCalendar API v3Watch for changes to Settings resources.
calendar.acl.watchCalendar API v3Watch for changes to ACL resources.
calendar.calendarList.watchCalendar API v3Watch for changes to CalendarList resources.
calendar.events.watchCalendar API v3Watch for changes to Events resources.
storage.objects.watchAllCloud Storage API v1beta2Watch for changes on all objects in a bucket.
reports.activities.watchAdmin Reports API reports_v1Push changes to activities
directory.users.watchAdmin Directory API directory_v1Watch for changes in users list
directory.users.aliases.watchAdmin Directory API directory_v1Watch for changes in user aliases list
storage.objects.watchAllCloud Storage API v1Watch for changes on all objects in a bucket.
youtube.playlistItems.updateYouTube Data API v3Modifies a playlist item. For example, you could update the item’s position in the playlist.
drive.files.watchDrive API v2Subscribe to changes on a file
drive.changes.watchDrive API v2Subscribe to changes for a user.

2014/01/16

ASP.NET MVC 4 using Google Calendar API via OAuth 2

1/16/2014 10:26:00 PM Posted by Unknown , , , , , 12 comments

Scenario

It's more easily to log in your application via OAuth and OpenID provider in  ASP.NET MVC 4 now. Microsoft has few build-in client for Microsoft, Twitter, Facebook, Google. The Google client is based on OpenID and not OAuth. That's mean you can not access Google Data API. There is a post talk about how to implement custom Google client with Google+ login via OAuth in ASP.NET MVC 4. (http://www.beabigrockstar.com/google-signin-for-asp-net-mvc/ Google+ Signin for ASP.NET MVC - Be A Big Rockstar )

Register a Client ID for web application in Google Developer Console

In order to access Google Data API for web application. You need to register a Client ID to get Client ID an Client Secret for setting in your application.


As above snapshot show, you need to assign redirect URIs for grap OAuth access token callback also. Here we setup Rirect URIs as

 http://localhost:57271/Account/ExternalLoginCallback 

Google Client Library for .NET

The Google APIs Client Library for .NET is generic .NET runtime client for Google Services. The library supports OAuth2.0 authentication, and is able to generate strongly typed client libraries for Discovery-based services.
Google Client library is a higher level library for using Google Data API. You can download beta version from Nuget in visual studio.

 https://www.nuget.org/packages/Google.Apis.Calendar.v3/ 
It's more difficult to handle Google Client Library for .NET with few documents and sample now. Here, just using Google.Apis.Calendar.v3.Data namespace to our strong type class for data binding in deserialize object from API response.

        private Event GoogleEventHandle(string token, string method, string requestURL, string requestBody = null)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.KeepAlive = true;
            request.ContentType = "application/json";
            request.Method = method;
            request.Headers.Add("Authorization", "Bearer " + token);

            if(requestBody != null)
            {
                Stream ws = request.GetRequestStream();
                using (var streamWriter = new StreamWriter(ws, new UTF8Encoding(false)))
                {
                    streamWriter.Write(requestBody);
                }
            }

            var response = request.GetResponse();
            var stream = new StreamReader(response.GetResponseStream());

            var googleEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(stream.ReadToEnd().Trim());

            return googleEvent;  
        }

        private Event CreateGoogleEvent(string token, string calendarId, string requestBody)
        {
            var requestURL = string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events", calendarId);
            return GoogleEventHandle(token, "POST", requestURL, requestBody);              
        }
Above is methods how we are accessing Google Calendar v3 API via webrequest.

MVC view

Now, we are be able to access Google Calendar API via OAuth. Nest step, we will create a simple CRUD UI by AngularJS. 

The Google Event we created and save to database also.

You should choose which calendar you want to create a new event.

You can modify event anytime you want.

What you will see in your Google Calendar.

Summary

  1. It a good topic to discuss where do you store the Access token from Google OAuth. Session or database?
  2. Google Client Library for .NET is a convienient library to access Google Data API with OAuth include. It's still in developing and i hope that there have more documents and samples to show how to use it.

Reference

Github repository

As always, all source code can be found in Github in the repository
 https://github.com/cage1016/ASPNETMvc4GoogleOAuth

2009/12/24

[Chrome Extensions] QuietRead

12/24/2009 07:55:00 PM Posted by Unknown , , , No comments
Two weeks ago. I went to join Taipei GTUG (Google Technology User Group) Google Chrome Hackathon. At the Chrome Hackathon, the people who attended want to developed few useful, interesting, funny Google Chrome extensions.


In my team (although 2 members) want to develop a useful chrome extensions. Nowadays, it's very convenient to search anything on the internet. Shopping, documents, and news for instance.

You might browse a lot links in one day. How come you could remember all of that links. You might say that you can use bookmark to keep the URL you haven't read it but you interested in it. It's a good method. I use the bookmarks in different browsers too. But, i will keep the link to my bookmarks i thought it's helpful to me. So, i need to any way to keep the URL for a while. That's why QuieRead from.

What's QuietRread?

QuietRead is very simple concept. You might have used the similar service on the internet. What's different between they and QuietRead. I assume you already have a Google Account (If you haven't. Have one). Because QuietRead use Google Documnet List Data API & Google SpreadSheet Data API to save the URL in your Google Docs SpreadSheet.

What does QuietRead do?

Quick answer: Add and remove URL on Google Docs specific SpreadSheet.

How does QuietRead work?

Because QuietRead use Google Documnet List Data API & Google SpreadSheet Data API, you have to login your Google account first in QuietRead extensions Option page. Following are simple step.
  1. Login in your Google Account.
  2. If login is succeed. Then, QuietRead will try to get Google Document List Data API & Google SpreadSheet Data API authorization.
  3. Check "QuietreadQueue" spreadsheet file on your Google Docs.
  4. If "QuietreadQueue" is exist, loading data. If "QuietreadQueue" isn't exist. create new one.
  5. now, you can add and remove URL in Chrome QuietRead Extensions.





Google Chrome QuietRead Extensions

2008/07/02

Google AJAX Feed API - AJAX Slide Show Rolling

7/02/2008 07:00:00 PM Posted by Unknown , , , , , 4 comments
AJAX Slide Show 為利用Google AJAX Feed API作出來簡單的應用。允許使用者把 PhotoBucketFlickrPicasa Web Albums的網路相簿以幻燈片的方式嵌在自己的Blog、網站等中。在Slide Show 中Picasa Web Album Feed URL無法動態更改,利用Picasa Web Albums Data API 與 jQurey JSON的操作,即可完成Picasa Web Albums的輪播。


Live Demo
| Download


AJAX Slide Show
<script type="text/javascript">
function load() {
var samples = "http://dlc0421.googlepages.com/gfss.rss";
var options = {
displayTime: 2000,
transistionTime: 600,
linkTarget: google.feeds.LINK_TARGET_BLANK
};
new GFslideShow(samples, "slideshow", options);
}
google.load("feeds", "1");
google.setOnLoadCallback(load);
</script>

var samples 為載入相關的Rss,在Picasa Web Album中都可以訂閱任何一個相簿的Feed。例如訂閱第七屆拼圖馬拉松的Feed(http://picasaweb.google.com/data/feed/base/user/cage.chung/albumid
/5217479087123706369?kind=photo&alt=rss&hl=en_US
)即可將此相簿以Slide Show的方式展示在網頁中。


AJAX Slide Show Advance

scenario
上述的方式,Side Show相簿的Feed為固定的,如果想要展示不同的相簿就必需更改程式碼,這是一件滿煩麻的事情。即然Google公開了Picasa Web Albums Data API,所以我們應該可以使用API搜尋特定user的相簿,以亂數組出Slide Show所需的Feed,達到相簿輪播的效果。

待解決的問題:
  • 選擇Ablum Feed Url
  • 決定Picasa Web Albums Data API回傳資料的格式及接收方式
  • Parser回傳的資料,找出組出Feed最主的資料(Picase Web Album ID)
  • 將亂數選出的Ablum ID帶入AJAX Slide Show

Step1
我們可以要求幾種來自Picase Web Ablum的不同的Feed。依照我們的需求,是搜尋特定user所有公開的相簿,在Picasa Web Albums 搜尋的參數[1]中會使用到kind與access2種參數
  • Kinds指特定類別的參數(ablum、photo、comment、tag、user)在此使用, user
  • Access指定相簿屬性(all、public、private)在此指定user所有公開的相簿, publick
因此,我們Ablum Feed Url則為http://picasaweb.google.com/data/feed/api/user/userID?kind=kinds&Access=publick

Step2
由於 AJAX 程式中的 XMLHttpRequest 只能呼叫同一個 domain 下的 URL,所以呼叫遠端並回傳XML資料型態的資料會以安全性考量被拒絕存取。又因為Picasa Web Albums資料格式提供另一種輕量級的資料交換格式(JSON),只有在Feed Url中指定alt=json即可將XML資料格式轉換成JSON格式並回傳。

選定遠端資料回傳格式為JSON,剩下的就是本機端該如何接收JSON型態資料。在此使用了一個新形態的 JavaScript程式庫(jQuery),程式庫中可以直接使用 jQuery.getJSON( url, [data], [callback][2] 操作JSON並進行AJAX回呼。此時的Ablum Feed Url更改為http://picasaweb.google.com/data/feed/api/user/cage.chung?kind=album&access=public
&alt=json&callback=?


Step3
剩下的部份就是Parser回傳的JSON資料
var numentries = json.feed.entry.length; //每一個相簿都是單獨的entry,numentries則為相簿的數量
var rNum = Math.floor(Math.random() * numentries); //以Random選擇相簿
var item = json.feed.entry[rNum];

var title = item.title.$t; //相簿的標題
var summary = item.summary.$t; //相簿的說明
var id = item.gphoto$id.$t; //最主要的相簿ID


Step4
將亂數選出的Ablum ID帶入AJAX Slide Show var samples 字串中即可




整合之後的Script 如下
<script type="text/javascript">
function load() {
$.getJSON("http://picasaweb.google.com/data/feed/api/user/<span style="
font - weight: bold;
">USERID</span>?kind=album&access=public&alt=json&callback=?", function(json) {

var numentries = json.feed.entry.length;
var rNum = Math.floor(Math.random() * numentries);
var item = json.feed.entry[rNum];

var title = item.title.$t;
var summary = item.summary.$t;
var id = item.gphoto$id.$t;

if (summary.length > 0) $("#msg").html("<h4>" + title + "</h4><p>" + summary + "</p>");
else $("#msg").html("<h4>" + title + "</h4>");

var samples = "http://picasaweb.google.com/data/feed/api/user/<span style="
font - weight: bold;
">USERID</span>/albumid/" + id + "?kind=photo&alt=rss&hl=en_US";

var options = {
displayTime: 2000,
transistionTime: 600,
linkTarget: google.feeds.LINK_TARGET_BLANK,
scaleImages: true
};
new GFslideShow(samples, "slideshow", options);
});
}
google.load("feeds", "1");
google.setOnLoadCallback(load);
</script>




Reference
  1. Interacting with Picasa Web Albums
  2. you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.
  3. Projection values: Feed URL "api" 與 "base"的差別,api參數提供了gphoto相關元素(包括我們需要的album id)
base
api

2008/06/10

Dynamic Feed Control Wizard - Put feeds on Your Web Page

6/10/2008 10:09:00 AM Posted by Unknown , , , , 1 comment

Google 現在推出了讓使用者可以在自己的網頁中加上 dynamic RSS AJAX feeds。在Blogger Draft中新增了可以嵌入Feeds的小裝置,但是一次只能載入一個Feed。而在Dynamic Rss AJAX Feeds中可讓使用者一次載入多個Feeds而達到連播的效果,並提供3種樣式選擇(Vertical、Vertical Stacked、Horizontal):


再輸入完Feeds Expression(Feeds搜尋的條件),可以搜尋多筆,中間以","相隔開,按下Preview之後便會產生Dynamic Feed,Dynamic Feed 左側顯示為搜尋的關鍵字(可在產出的代碼中修改)


最後一個動作,Generate Code。


//Skip...
function LoadDynamicFeedControl() {
var feeds = [{
title: '竹誌',
url: 'http://cage1016.blogspot.com/feeds/posts/default'
},
{
title: 'bamboobig',
// 在此可自訂顯示的Feed
url: 'http://bamboobig.blogspot.com/feeds/posts/default'
}];
var options = {
stacked: true,
horizontal: false,
title: "Hollywood News"
}

new GFdynamicFeedControl(feeds, 'feed-control', options);
}
// Load the feeds API and set the onload callback.
google.load('feeds', '1');
google.setOnLoadCallback(LoadDynamicFeedControl);
//Skip...

LiveDemo (Event News)

2008/05/29

Embedding Google Earth in Your Web Page

5/29/2008 09:16:00 PM Posted by Unknown , , 1 comment
Google Earth 於5/28 釋出 Google Earth Browser Plugin
所以現在想要使用Google Earth多了一種選擇
不一定要下載Google Earth

donwloading plugin

並於幾個小時之後也公開了Google Earth plug API
讓使用者可以把Google Earth直接嵌入到自己的網頁中


<html>
<head>
<title>Google</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=YourGoogleMapKey" type="text/javascript"></script>
<script src="http://www.google.com/jsapi?key=YourGoogleMapKey"></script>
<script type="text/javascript">
google.load("earth", "1");
google.load("maps", "2.99"); // For JS geocoder

var ge = null;
var geocoder;

function init() {
geocoder = new GClientGeocoder();
google.earth.createInstance("map3d", initCB, failureCB);
}

function initCB(object) {
ge = object;
ge.getWindow().setVisibility(true);
}

function failureCB(object) {
alert('load failed');
}

function submitLocation() {
var address = document.getElementById('address').value;
geocoder.getLatLng(
address,
function(point) {
if (point && ge != null) {
var la = ge.createLookAt('');
la.set(point.y, point.x, 100, ge.ALTITUDE_RELATIVE_TO_GROUND,
0, 0, 4000);
ge.getView().setAbstractView(la);
}
}
);
}

</script>
</head>
<body onload='init()' id='body'>
<div id='map3d_container' style='border: 1px solid silver; height: 500px;'>
<div id='map3d' style='height: 100%;'></div>
</div>
</body>
</html>


Live Demo簡單展示把Google Earth 嵌入到自己的網頁中

參考資料: