2013年2月26日 星期二

Facebook OAuth use Javascript API


一些 Facebook Javascript API 簡單與常用的功能

開發前需先至 Facebook Develope 申請並取得APP ID

並參考本頁面 Login without Javascript SDK 架設基本環境


    //facebook api 初始化設定
    window.fbAsyncInit = function () {
        FB.init({
            appId: 'your facebook app ip', //facebook app id
            channelUrl: ' localhots/channel.html', // Channel.html 位置
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });
    };

    //載入 facebook jssdk
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));

    //facebook javascript 登入
    function login() {
        FB.login(function (response) {
            if (response.authResponse) {
                FB.api('/me', 'GET', function (response) {
                    console.log(response.name);    //取得使用者名稱
                    consoel.log(response.email);    //取得使用者 Email 
                    console.log(response.id);    //取得使用者 facebook id
                });
            } else {
                alert('登入失敗');
            }
        }, { scope: "email,user_groups,publish_stream,publish_checkins" });
        //scope為要求取得使用者的 permission 
        //EX: email:取得使用者 Email
        //    user_groups: 使用者社團資料
        //    user_about_me: 使用者關於我
        //    user_photos: 使用者相片
        //    publish_stream: 使用者發文權限
        //more: http://developers.facebook.com/docs/reference/login/#permissions
    }

    //使用者登出
    function logout() {
        FB.logout(function (response) {
            // user is now logged out
        });
    }

    //取得目前登入狀態
    function getLoginStatus() {
        FB.getLoginStatus(function (response) {
            console.log('logout');
            console.log(response);
        });
    }

    //取得使用者資料
    function getUserData() {

        //使用者資料        
        FB.api('/me','GET', function (response) {
            console.log('me:');
            console.log(response);
            console.log('Hello ' + response.name);
        });

        //使用者縮圖
        FB.api('/me/picture', 'GET', function (response) {
            if (response) {
                console.log('picture:');
                console.log(response);
            } else {
                alert("Error");
            }
        })

        //有使用者在內的照片
        FB.api('/me/photos', 'GET', function (response) {
            if (response) {
                console.log('photos:');
                console.log(response);
            } else {
                alert("Error");
            }
        })

        //使用者好友資料
        FB.api('/me/friends','GET',function (response) {
            if (response) {
                console.log('friends:');
                console.log(response);
            } else {
                alert("Error");
            }
        });

        //社團資料 (需開啟 user_groups permission)
        FB.api('/me/groups', 'GET', function (response) {
            if (response) {
                console.log('groups:');
                console.log(response);
            } else {
                alert("Error");
            }
        });     
    }

    //使用者發文(需開啟 publish_stream permission)
    function publish(){
        FB.api('/me/feed', 'post', { message: 'facebook api' }, function (response) { 
            //{message:'發文內容'}
            if (!response || response.error) {
                alert('Error');
            } else {
                alert('Post ID: ' + response.id);
            }
        });
    }

    //使用者打卡(需開啟 publish_checkins permission)
    function Checkins() {
        var data = {    
            "place" : "117464364938130",    //打卡位置ID
            "coordinates" : JSON.stringify({    //打卡位置至經緯度
                'latitude' : 40.7798027,
                'longitude' : -73.9481371,
            })
        };
        FB.api('me/checkins',data,'POST', function (response) {
            if (response) {
                console.log('checkins success');
                console.log(response);    
            } else {
                alert('Error');
            }
        })
    }

2013年1月24日 星期四

Javascript XML(DOM) & JSON 解析




//JSON 解析

var json = '{"a":1,"b":2,"c":3}';

var job = JSON.Parse(json);    //字串轉物件

console.log(job.a);    //1

var jobtostring = JSON.stringify(job);    //物件轉字串

console.log(jobtostring);    //"{"a":1,"b":2,"c":3}"


//XML(DOM)解析 

var xml = ' +
11 +
22 +
33 +
44 +
55 +
66 +
';

var xmlparse = new  DOMParser();    //宣告解析XML物件

var xmlobj = xmlparse.parseFromString(xml,'text/xml');    //字串轉物件

console.log(xmlobj);    //DOM object

console.log(xmlobj.getElementsByTagName('a')[0]);    //DOM object

console.log(xmlobj.getElementsByTagName('Company')[0].childNodes[0].childNodes[0].nodeValue);    //1

var serializer = new XMLSerializer();    //宣告XML序列化物件

console.log(serializer.serializeToString(xmlobj));    //物件轉字串




2012年9月1日 星期六

C# Creat Write Read File


class Program
{

    static void Main(string[] args)
    {

        string dir = "c:\\";

        //設定資料夾路徑

        string folder = "myFolder";

        //設定資料夾名稱

        string file = "mytext.txt";

        //設定檔案名稱

        string path = System.IO.Path.Combine(dir,folder);

        //路徑加入資料夾名稱

        if (!System.IO.Directory.Exists(path))

        {

            //判斷資料夾是否存在

            System.IO.Directory.CreateDirectory(path);

            //建立資料夾

            System.Console.WriteLine("CreateDirectory Success");

        }

        path = System.IO.Path.Combine(path,file);

        //路徑加入檔案名稱

        if (!System.IO.File.Exists(path))

        {

            //判斷檔案是否存在

            using (StreamWriter sw = System.IO.File.CreateText(path))

            {

                //新增檔案並寫入資料

                sw.Write("hello", Encoding.UTF8);

                sw.Close();

            }

            System.Console.WriteLine("CreateFile Success");

        }

        else

        {

            using (StreamReader sr = System.IO.File.OpenText(path))

            {

                //開啟檔案並讀取資料

                System.Console.WriteLine(sr.ReadToEnd());

                sr.Close();

            }

        }

    Console.ReadKey();

    }

}

2012年8月20日 星期一

C# Send Mail (SmtpClient)

class Program
{
    
    static void Main(string[] args)

    {

        try

        {

            SmtpClient mySmtp = new SmtpClient("stmp host",smtp port);

            //定義smtp的連接(smtp 網址,smtp port(預設25))

            mySmtp.Credentials = new System.Net.NetworkCredential("account", "password");

            //設定寄件者的認證(帳號,密碼)

            MailMessage msgMail = new MailMessage();

            //定義電子郵件

            msgMail.From = new MailAddress("account@smtp host");

            //寄件者

            msgMail.To.Add("account@smtp host");

            //收件者

            msgMail.Subject = "mail subject";

            //主旨

            msgMail.SubjectEncoding = System.Text.Encoding.UTF8;

            //主旨的編碼

            msgMail.IsBodyHtml = true;

            //設定郵件內容採用HTML格式

            msgMail.Body = "mail content";

            //設定郵件內容

            msgMail.BodyEncoding = Encoding.UTF8;

            //內容編碼               

            mySmtp.Send(msgMail);

            //發送mail

            Console.WriteLine("send success");

        }

        catch (Exception e)

        {

            Console.WriteLine(e.ToString());

        }

        Console.ReadKey();

    }

}

2012年8月14日 星期二

C# Socket Sample(Client-server)



Server 端:
namespace lf.socket.clientserver
{

    class Server

    {

        static void Main(string[] args)

        {

            IPEndPoint ipont = new IPEndPoint(IPAddress.Any, 20);

            //將IP位址和Port宣告為服務的連接點(所有網路介面卡 IP,20 Port)

            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //宣告一個Socket通訊介面(使用IPv4協定,通訊類型,通訊協定)

            newsock.Bind(ipont);

            //建立本機連線   

            newsock.Listen(10);

            //偵測連接(最大連接數)

            while (true)

            { 

                Socket client = newsock.Accept();

                //宣告一個Socket等於新建立的連線

                IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;

                //宣告一個連接點為socket端的連接點

                System.Console.WriteLine("Client End Point = " + clientip);

                //印出遠端IP位址

                SocketListener listener = new SocketListener(client);

                //宣告一個監聽類別SocketListener監聽client訊息

                Thread thread = new Thread(new ThreadStart(listener.run));

                //宣告一個執行序去跑SocketListener監聽事件

                thread.Start();           

            }

        }

    }



    public class SocketListener

    {

        private Socket socket;

        public SocketListener(Socket socket)

        {

            this.socket = socket;

            //建構元取得遠端socket連線

        }

        public void run()

        {

            while (true)

            {

                byte[] data = new byte[1024];

                //定義一個資料緩衝區接收長度最大為(1024)

                int len = socket.Receive(data);

                //接收資料至緩衝區中並回傳成功街收位元數

                if (len == 0) break;

                //若成功接收位元數為0則跳出迴圈

                System.Console.WriteLine(Encoding.UTF8.GetString(data,0,len));

                //印出編碼後的資料(資料,起始位置,長度)

            }

            socket.Close();

        }

    }

}


Client 端:
namespace lf.socket.clientserver

{

    class Client

    { 

        static void Main(string[] args)

        {

            IPEndPoint ipont = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 20);

            //將IP位址和Port宣告為服務的連接點(Server Ip,20 Port)

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //宣告一個Socket通訊介面(使用IPv4協定,通訊類型,通訊協定)

            server.Connect(ipont);

            //建立至遠端主機的連接

            while (true)

            {

                string input = Console.ReadLine();

                //接收輸入字串

                if (input == "exit")break;

                //若輸入exit則跳出迴圈

                byte[] data = Encoding.UTF8.GetBytes(input);

                //將字串以UTF8編碼存入緩衝區

                server.Send(data);

            }

            server.Shutdown(SocketShutdown.Both);

            //關閉遠端的傳送與接收

            server.Close();

            //關閉連接

            System.Console.Write("Disconnecting from server...");

            System.Console.ReadKey();

        }

    }

}