Delphi 使用superobject分析JSON

ResizedImage600199-RADJson
http://superobject.googlecode.com

https://github.com/hgourvest/superobject

Delphi從2009才開始支援JSON格式,先前的版本需使用第三方函式庫才能解決。這邊提供不錯的SuperObject給大家。

使用方式很簡單,例如從台北市政府資料開放平台取得臺北市公廁點位資訊

[json]
[{“unit”:”台北市政府環境保護局”,”title”:”公廁坐落:士林官邸”,”dep_content”:”座數:8,特優級:2,優等級:6,普通級:0,加強級:0,無障礙設施”,”address”:”臺北市士林區福林路60號”,”lng”:”121.530152″,”lat”:”25.094898″,”modifydate”:”2013-03-25T17:58:20+08:00″},{“unit”:”台北市政府環境保護局”,”title”:”公廁坐落:天母公園”,”dep_content”:”座數
:1,特優級:0,優等級:1,普通級:0,加強級:0″,”address”:”臺北市士林區中山北路七段219號邊”,”lng”:”121.530071″,”lat”:”25.125855″,”modifydate”:”2015-08-06T00:00:00+08:00″}]
[/json]
[pascal]
uses superobject, supertypes, superxmlparser;

var vjson: Isuperobject;
vitem:Tsuperarray;
i,j:integer;
s:string;
begin
vjson:= so(‘[{"unit":"台北市政府環境保護局","address":"臺北市士林區福林路60號"},{"unit":"台北市政府環境保護局","address":"臺北市士林區中山北路七段219號邊"}]’);
vitem:=vjson.AsArray;
for i:=0 to vitem.Length-1 do begin
memo2.Lines.Add(vitem[i][‘unit’].AsString+’ ‘+vitem[i][‘address’].AsString);
end;
end;
[/pascal]

那如果格式如下
[json]
{“zoo”:”壽山動物園”,”animals”:[{“name”:”猴子”,”years”:”12″},{“name”:”猩猩”,”years”:”5″}]}
[/json]
[pascal]
var vjson: Isuperobject;
vitem:Tsuperarray;
i:integer;
begin
vjson:= so(‘{"zoo":"壽山動物園","animals":[{"name":"猴子","years":"12"},{"name":"猩猩","years":"5"}]}’);
memo2.lines.add(vjson[‘zoo’].asstring);
vitem:= vjson[‘animals’].AsArray;
for i:=0 to vitem.Length -1 do begin
memo1.Lines.Add(vitem[i][‘name’].AsString+’ ‘+vitem[i][‘years’].AsString );
end;
[/pascal]

Delphi XE8使用Microsoft Azure Translator微軟線上翻譯服務

在微軟的Microsoft Azure Marketplace有許多不錯的資料可以應用,今天就分享如果利用XE8搭配Microsoft Translator線上翻譯服務來做翻譯。
一、註冊Azure帳戶

點選 https://datamarket.azure.com/dataset/bing/microsofttranslator 上的登入,使用個人。然後依照步驗註冊就好。
tran002

二、訂閱服務
進入 https://datamarket.azure.com/dataset/bing/microsofttranslator ,點選2000000字元數/月的免費方案註冊。

tran001

tran004

 

tran005 tran006
三、註冊程式
程式中需要client_id跟client_secret ,所以到 https://datamarket.azure.com/developer/applications 註冊程式。

client_id就是用戶端識別碼

client_secret就是用戶端密碼

tran007
四、開始建立程式

新增一個Blank Application

001

接著在上面增加三個元件,TRESTClient、TRESTRequest跟TRESTResponse。重新命名為RESTClientAuthToken、RESTRequestAuthToken跟RESTResponseAuthToken.

002

 

RESTClientAuthToken的BaseURL設定 https://datamarket.accesscontrol.windows.net/v2

003

 

RESTRequestAuthToken的Method改為rmPOST、然後Resource設為OAuth2-13(參考 https://msdn.microsoft.com/en-us/library/hh454950.aspx)

 

004

 

然後在Params增加四個參數如下

 

005

 

在畫面上增加3個label、3個edit以及一個button

 

006

加上程式碼

[pascal]
var
token: string;
begin
RESTRequestAuthToken.Params.ParameterByName(‘client_secret’).Value := EditClient_Secret.Text;
RESTRequestAuthToken.Params.ParameterByName(‘client_id’).Value := EditClient_ID.Text;
RESTRequestAuthToken.Execute;
if RESTResponseAuthToken.GetSimpleValue(‘access_token’,token) then
begin
EditToken_value.Text := token;
end;
[/pascal]

取得Token值後我們可以開始進行翻譯,參考的文件為(https://msdn.microsoft.com/en-us/library/ff512387.aspx),一樣增加三個元件,TRESTClient、TRESTRequest跟TRESTResponse。重新命名為RESTClientTranslate、RESTRequestTranslate跟RESTResponseTranslate.。

RESTClientTranslate的BaseURL設為 http://api.microsofttranslator.com/v2/Http.svc

007

 

接著在RESTRequestTranslate的Resource設為Translate?text={text}&from={from}&to={to}

 

008

一樣在裡面增加四個Params,from跟to需要對應相關的語言代碼(參考https://msdn.microsoft.com/en-us/library/hh456380.aspx

009

在畫面上增加combobox二個,以及二個memo及button。

011

 

開啟view→LiveBindings Designer,將RESTRequestTranslate中的Params.text指到Memo1的Text(輸入),然後RESTResponseTranslate.的Content指向Memo2的Text(輸出)。

010

 

最後補上翻譯的程式碼如下。

[pascal]
RESTRequestTranslate.Params.ParameterByName(‘Authorization’).Value := ‘bearer ‘+EditToken_value.Text;
RESTRequestTranslate.Params.ParameterByName(‘from’).Value := cbFrom.Selected.Text;
RESTRequestTranslate.Params.ParameterByName(‘to’).Value := cbToo.Selected.Text;
RESTRequestTranslate.Execute;
[/pascal]

番外篇:
語音的部份(參考 https://msdn.microsoft.com/en-us/library/ff512420.aspx)
增加一個RESTRequestPlay,然後設定Resource為 speak?text={text}&language={language}&to={to}&format=audio/mp3&options=MinSize 。
三個Param為 Authorization、text、language
以及增加mediaplayer。
程式如下

[pascal]
var
MS: TMemoryStream;
TempFile: string;
begin
RESTRequestPlay.Params.ParameterByName(‘Authorization’).Value := ‘bearer ‘+EditToken_value.Text;
RESTRequestPlay.Params.ParameterByName(‘language’).Value := RESTRequestTranslate.Params.ParameterByName(‘to’).Value;
RESTRequestPlay.Params.ParameterByName(‘text’).Value := RESTResponseTranslate.Content;
RESTRequestPlay.Execute;
MS := TMemoryStream.Create;
try
MS.WriteData(RESTResponsePlay.RawBytes,Length(RESTResponsePlay.RawBytes));
TempFile := TPath.ChangeExtension(TPath.GetTempFileName,’.mp3′);
MS.SaveToFile(TempFile);
MediaPlayer1.FileName := TempFile;
MediaPlayer1.Play;
finally
MS.Free;
end;
end;
[/pascal]

API參考

https://msdn.microsoft.com/en-us/library/dd576287.aspx

程式碼下載

https://drive.google.com/file/d/0BxMN7KkA7p3NZlU5clItaGxiMzQ/view?usp=sharing

原文:
http://blogs.embarcadero.com/stephenball/2015/06/30/using-azure-translator-services-with-delphi/

 

CodeIgniter3.0將Session寫入DB

[sql]
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
PRIMARY KEY (id),
KEY `ci_sessions_timestamp` (`timestamp`)
);
[/sql]
修改 application/config/config.php
[php]
$config[‘sess_driver’] = ‘database’;
$config[‘sess_save_path’] = ‘ci_sessions’;
[/php]

讓資料庫密碼加上鹽(Salt)值

以往許多人喜歡在資料庫的密碼欄使用明碼儲存,但站在資訊安全角度來說不是挺安全的,可以產生一個Salt值後,增加安全性。
[php]
// 隨機產生一組長度為10的Salt值
$salt = substr(md5(uniqid(rand(), true)), 0, 10);
// 存入資料庫的密碼欄,使用Salt值加上md5雜湊後存回資料庫
$new_password = md5(md5($old_password.$salt));
[/php]
使用者登入後,先從資料庫讀出salt值,接著再一樣加上salt值加上md5後比對就可以了!

CodeIgniter使用PHPExcel製作Excel

1 下載PHPExcel,將PHPExcel解壓縮到Application的third_party目錄下
2 在libraries目錄下新增 excel.php
[php]
<?php
if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);

require_once APPPATH."/third_party/PHPExcel.php";

class Excel extends PHPExcel {
public function __construct() {
parent::__construct();
}
}
?>
[/php]
使用
[php]
function createexcel(){
// 產生php 範例
$this->load->library(‘excel’);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue(‘A1’, ‘中文’);
$objPHPExcel->getActiveSheet()->setCellValue(‘B2’, ‘許’);
$objPHPExcel->getActiveSheet()->setCellValue(‘C3’, ‘test3’);
$objPHPExcel->getActiveSheet()->setCellValue(‘D3’, ‘test4’);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007’);

header(‘Content-Type: application/vnd.ms-excel’);
header(‘Content-Disposition: attachment;filename="excel_report_’ . date(‘ymd’) . ‘.xls"’);
// header(‘Content-Disposition: attachment; filename="file.xls"’);
header(‘Cache-Control: max-age=0’);

$objWriter->save(‘php://output’);

}
[/php]

Embarcadero RAD Studio XE8, Delphi XE8, and C++ Builder XE8 Update 1 正式發佈

這次更新分為二種版本,分為有買維護合約且有效期的以及沒有買維護合約的版本。差別如下~

 

General Update 1 Feature and Fix List

This update is provided to XE8 customers without an Update Subscription

Click here for the download.

  • Community toolbar
  • iOS 8 simulator fix
  • Several files missing from the initial XE8 delivery

Subscription Update 1 Features and Fix List

This update is provided to active Update Subscription customers

Click here for the download.

  • Community toolbar
  • Favorites in welcome page
  • Fast search of Bluetooth LE devices
  • iOS 8 simulator support
  • Improved robustness of IDE productivity features
  • Improvements in multi-device previews

延伸連結

Fix List for XE8 Update 1:
http://edn.embarcadero.com/article/44470

PHP透過curl上傳xml給API

[php]

<?php
$xml_data ='<?xml version="1.0" encoding="UTF-8"?>
<FILE>
<HEAD>
<FILEDESC>ORDER</FILEDESC>
</HEAD>
<CONTENT>
<DATA>
<ID>XXXX</ID>
<MEMO>XXXXXXX</MEMO>
</DATA>
</CONTENT>
</FILE>
‘;

$URL = "http://apisite";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type: text/xml’));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
[/php]

CodeIgniter發送台灣簡訊範例

[php]
<?php
$username = "xxx"; // 帳號
$password = "xxx"; // 密碼
$mobile = "09xxxxxxxx"; // 電話
$message = "測試簡訊"; // 簡訊內容
$MSGData = "";

$msg = "username=".$username."&password=".$password."&mobile=".$mobile."&message=".urlencode($message)."&drurl=".urlencode("http://xxxx.com.tw/admin/drul/");
$num = strlen($msg);

// 打開 API 閘道
$fp = fsockopen ("api.twsms.com", 80);
if ($fp) {
$MSGData .= "POST /smsSend.php HTTP/1.1\r\n";
$MSGData .= "Host: api.twsms.com\r\n";
$MSGData .= "Content-Length: ".$num."\r\n";
$MSGData .= "Content-Type: application/x-www-form-urlencoded\r\n";
$MSGData .= "Connection: Close\r\n\r\n";
$MSGData .= $msg."\r\n";
fputs ($fp, $MSGData);
$Tmp ="";
// 取出回傳值
while (!feof($fp)) $Tmp.=fgets($fp,128);
$temp2 = explode(PHP_EOL, $Tmp);
// 關閉閘道
fclose ($fp);
/*
0 傳送完成:HTTP/1.1 200 OK
1 Date: Wed, 03 Jun 20xx 09:31:36 GMT
2 Server: Apache
3 X-Powered-By: PHP/5.2.12
4 Connection: close
5 Transfer-Encoding: chunked
6 Content-Type: text/html
7
8 51
9 <smsResp><code>00000</code><text>Success</text><msgid>188xxxx69</msgid></smsResp>
10 0
*/
$xml = simplexml_load_string($temp2[9]);
$xmldata = json_decode( json_encode($xml) , 1);
echo "傳送完成:".$Tmp."<br/>".$xmldata[‘msgid’];
} else {
echo "您無法連接 TwSMS API Server";
}
$this->load->view(‘welcome_message’,$data);

}

public function drul(){
$this->load->database();
$inputdata = $this->input->get(‘xml’);
$xml = simplexml_load_string($inputdata);
$xmldata = json_decode( json_encode($xml) , 1);
$arraystring =print_r($xmldata);
$this->msg=$arraystring;

$dbvalue = array(
‘sms_msg’=> $xmldata[‘msgid’]."status=".$xmldata[‘statustext’],
‘id’ =>$xmldata[‘code’],
‘ip’ => $this->input->ip_address(),
);
$this->db->insert(‘drul’,$dbvalue );
$data = array(
‘message’ => $xmldata[‘msgid’]
);
$this->load->view(‘welcome_message’,$data);
}
[/php]

CodeIgniter超簡易發信

[php]
$email_config = Array(
‘mailtype’ => ‘html’

);
$this->load->library(’email’,$email_config);
$this->email->from(‘superlevin@gmail.com’, ‘林壽山’); //寄件者
$this->email->to(‘123@gmail.com’); // 收件者
//$this->email->cc(‘123cc@gmail.com’); // 副本
//$this->email->bcc(‘123bcc@gmail.com’); // 密件副本

$this->email->subject(‘成功通知信’); // 主旨
$this->email->message(‘<b>報名成功</b>’); //內容
$this->email->send();
[/php]