2007年4月25日 星期三

(Flex)AS3 字串處理輔助類別

MSN SpaceGoogle DocGoogle Blog啪啦資訊科技
Chui-Wen Chiu(Arick)
2007.04.26 建立

Flex 2.0 雖然已經又內建一個 StringUtil 類別,該類別提供一些字串常用的輔助函數,可惜太過於陽春只有下面幾個
1. trim:去除字串前後空白字元
2. trimArrayElements:將字串以指定分隔字元進行分割,並將分割後的字串去除前後空白。
3. isWhitespace:檢查是否為空白字元
4. substitute:格式化輸出,類似 C# 的 String.Format()


目前 Macromedia 釋出一個包在 com.chewtinfoil.utils Package 中的 StringUtils 類別提供更多的字串處理功能,如下:
afterFirst
adterLast
beginsWith
beforeFirst
beforeLast
between
block
capitalize
contains
countof
editDistance
endsWith
hasText
isEmpty
isNumeric
padLeft
padRight
properCase
quote
remove
removeExtraWhiteSpace
reverse
reverseWords
similarity
stripTags
swapCase
trim
trimLeft
trimRight
wordCount
truncate


一個簡單的測試範例

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="358" height="202">
<mx:Script >
<![CDATA[
import com.chewtinfoil.utils.StringUtils;
import mx.controls.Alert;
// 擷取指定字串第一次出現之後的字串
private function btnafterFirst():void{
Alert.show( '-->' + StringUtils.afterFirst("Hello, My Name is Arick", "is ") + '<--');// -->Arick<--
}

// 截去指定字串最後出現以後的字串
private function btnafterLast():void{
Alert.show( '-->' + StringUtils.afterLast("Hello, My Name is Arick", "i") + '<--'); // -->ck<--
}

// 檢驗字串開頭是否符合指定字串
private function btnbeginsWith():void{
Alert.show(StringUtils.beginsWith("Chui-Wen Chiu", "Chui-Wen").toString()); // -->ck<--
}

// 取得從開頭到指定字串第一次出現位址以前的字串
private function btnbeforeFirst():void{
Alert.show('-->'+StringUtils.beforeFirst("Chui-Wen Chiu", "Chiu") + '<--'); // -->Chui-Wen <--
}

// 取得從開頭到指定字串最後一次出現位址以前的字串
private function btnbeforeLast():void{
Alert.show('-->'+StringUtils.beforeLast("Chui-Wen Chiu", "i") + '<--'); // -->Chui-Wen Ch<--
}

// 是否含指定字串
private function btncontains():void{
Alert.show('-->'+StringUtils.contains("Chui-Wen Chiu", "i").toString() + '<--'); // -->true<--
}

// 計算指定字元出現次數
private function countOf():void{
Alert.show('-->'+StringUtils.countOf("Chui-Wen Chiu", "i") + '<--'); // -->2<--
}



// 檢查字串結尾是否符合指定字串
private function endsWith():void{
Alert.show('-->'+StringUtils.endsWith("c:\notepad.exe", ".exe").toString() + '<--'); // -->true<--
}


// 檢查是否為 NULL 或字傳長度為 0
private function isEmpty():void{
Alert.show(StringUtils.isEmpty("Chui-Wen Chiu").toString()); // false
}

// 是否為數值樣式字串
private function isNumeric():void{
Alert.show(StringUtils.isNumeric("12E5").toString() ); // true
}

// 以指定字元填補左側字元達到指定的字串長度
private function padLeft():void{
Alert.show(StringUtils.padLeft(".123", "0", 5) ); // 0.123
}

// 以指定字元填補右側字元達到指定的字串長度
private function padRight():void{
Alert.show(StringUtils.padRight("123.", "0", 6)); // 123.00
}

// 字串開頭大寫,其他字母皆為小寫
private function properCase():void{
Alert.show('-->'+StringUtils.properCase("Chui-Wen Chiu") + '<--'); // -->Chui-wen chiu<--
}

//
private function quote():void{
Alert.show('-->'+StringUtils.quote("Chui-Wen Chiu") + '<--'); // -->"Chui-Wen Chiu"<--
}

// 移除定的字串
private function remove():void{
Alert.show('-->'+StringUtils.remove("Chui-Wen Chiu", "i") + '<--'); // -->Chu-Wen Chu<--
}

// 字串反轉
private function reverse():void{
Alert.show('-->'+StringUtils.reverse("Chui-Wen Chiu") + '<--'); // -->uihC neW-iuhC<--
}

// 以單字為單位反轉
private function reverseWords():void{
Alert.show('-->'+StringUtils.reverseWords("Chui-Wen Chiu") + '<--'); // -->ChiuChui-Wen<--
}

// 移除 < 開頭 > 結尾的字串
private function stripTags():void{
Alert.show('-->'+StringUtils.stripTags("<html><body style = 'color:red'>Chui-Wen Chiu</body></html>") + '<--'); // -->Chui-Wen Ch<--
}

// 大小寫互轉
private function swapCase():void{
Alert.show('-->'+StringUtils.swapCase("Chui-Wen Chiu") + '<--'); // -->chui-Wen Chiu<--
}

// 去除字串前後空白字元
private function trim():void{
Alert.show('-->'+StringUtils.trim(" Chui-Wen Chiu ") + '<--'); // -->Chui-Wen Ch<--
}

// 去除字串左側空白字元
private function trimLeft():void{
Alert.show('-->'+StringUtils.trimLeft(" Chui-Wen Chiu ") + '<--'); // -->Chui-Wen Ch<--
}

// 去除字串右側空白字元
private function trimRight():void{
Alert.show('-->'+StringUtils.trimRight(" Chui-Wen Chiu ") + '<--'); // -->Chui-Wen Ch<--
}

// 計算單字數量
private function wordCount():void{
Alert.show('-->'+StringUtils.wordCount("Hello, My name is Arick.") + '<--'); // -->Chui-Wen Ch<--
}


// 擷取指定長度並加上後綴字
private function truncate():void{
Alert.show('-->'+StringUtils.truncate("Chui-Wen Chiu", 3) + '<--'); // -->Chu...<--
}

]]>
</mx:Script>
<mx:Button x="10" y="10" label="afterFirst" click="btnafterFirst()"/>
<mx:Button x="10" y="30" label="afterLast" click="btnafterLast()"/>
<mx:Button x="10" y="50" label="beginsWith" click="btnbeginsWith()"/>
<mx:Button x="10" y="70" label="beforeFirst" click="btnbeforeFirst()"/>
<mx:Button x="10" y="90" label="beforeLast" click="btnbeforeLast()"/>
<mx:Button x="10" y="130" label="contains" click="btncontains()"/>
<mx:Button x="10" y="150" label="countOf" click="countOf()"/>
<mx:Button x="10" y="110" label="endsWith" click="endsWith()"/>
<mx:Button x="239" y="10" label="isEmpty" click="isEmpty()"/>
<mx:Button x="239" y="30" label="isNumeric" click="isNumeric()"/>
<mx:Button x="239" y="50" label="padLeft" click="padLeft()"/>
<mx:Button x="239" y="70" label="padRight" click="padRight()"/>
<mx:Button x="239" y="90" label="properCase" click="properCase()"/>
<mx:Button x="239" y="110" label="quote" click="quote()"/>
<mx:Button x="239" y="130" label="remove" click="remove()"/>
<mx:Button x="121.5" y="150" label="reverse" click="reverse()"/>
<mx:Button x="121.5" y="170" label="reverseWords" click="reverseWords()"/>
<mx:Button x="121.5" y="10" label="stripTags" click="stripTags()"/>
<mx:Button x="121.5" y="30" label="swapCase" click="swapCase()"/>
<mx:Button x="121.5" y="50" label="trim" click="trim()"/>
<mx:Button x="121.5" y="70" label="trimLeft" click="trimLeft()"/>
<mx:Button x="121.5" y="90" label="trimRight" click="trimRight()"/>
<mx:Button x="121.5" y="110" label="wordCount" click="wordCount()"/>
<mx:Button x="121.5" y="130" label="truncate" click="truncate()"/>
</mx:Application>

補充:
Flex 2.0 使用上述類別可能會有一些警告訊息,你可以忽略不理,或嘗試進行下面的修改:
Line 256:新增var j:uint;
Line 272: 將 var j:uint 改為 j=0
Line 277: 將 var j:uint=1改為j=1
Line 638: 改成 public static function truncate(p_string:String, p_len:uint = 0, p_suffix:String = "..."):String {
Line 640: 改成 if (p_len == 0) { p_len = p_string.length; }

檔案下載:
[1] AS3 String Utils


參考資料:
[1] http://www.gskinner.com/blog/archives/2007/04/free_extension.html


2007年4月22日 星期日

(Flex) 使用 ShareObject 類別
Chui-Wen Chiu(Arick)
MSN SpaceGoogle DocGoogle Blog
2007.04.22

測試環境:
1. Windows XP Pro
2. Flex Builder 2.0.1

ShareObject 類別允許你將小量資料儲存在用戶端電腦。ShareObject 有點類似瀏覽器的 Cookie。應用程式只能存取屬於自己的資料,且應用程式必須和資料同屬於同一個網域(Domain)。但是這個資料並不能傳送到伺服器端。

ShareObject 提供下面的方法

clear()

從 ShareObject 中清空所有的資料,並從檔案磁碟刪除 ShareObject 檔案。

flush()

將 ShareObject 直接寫入用戶端的檔案

getLocal()

回傳 ShareObject 所在的 Domain。假如不存在,這個方法會在用戶端建立一個新的 ShareObject

getSize()

Gets the size of the SharedObject file, in bytes. The default size limit is 100 KB, although it can be larger if the client allows it.


屬性:

data

(唯讀)儲存在 ShareObject 中的資料

onStatus

當 ShareObject 發生警告、錯誤或其他訊息時會觸發這個事件


建立 ShareObject 的語法如下:
SharedObject.getLocal("objectName" [, pathname]): SharedObject
下面是簡單的範例:
public var mySO:SharedObject;
mySO = SharedObject.getLocal("preferences");

上述如果在 local 端執行,Flash Player 會產生 preferences.sol 到下面路徑
c:/Documents and Settings/username/Application Data/Macromedia/Flash Player/#SharedObjects/一串數字/localhost/應用程式路徑/SWF 檔名/
以我的情況來說,我的帳號是 Administrator,SWF 放在 "C:Documents and SettingsAdministrator.MYCHAT-1A793BE7My DocumentsFlex Builder 2Examplebin",preferences.sol 會存放到下面路徑
C:Documents and SettingsAdministrator.MYCHAT-1A793BE7Application DataMacromediaFlash Player#SharedObjects96FX85HWlocalhostDocuments and SettingsAdministrator.MYCHAT-1A793BE7My DocumentsFlex Builder 2ExamplebinExample.swf
註:上述路徑和文件所述有出入,不知道是否為文件錯誤。
註:如果你只有執行上述的 getLocal 並不會立即產生 *.sol,你可以在後面加上一行 mySO.flush() 利即將資料寫入檔案。
註:如果程式是在網路上執行,則路徑結構會變為
c:/Documents and Settings/username/Application Data/Macromedia/Flash Player/#SharedObjects/一串數字/web_domain/應用程式路徑/SWF 檔名/ 
如:
C:Documents and SettingsAdministrator.MYCHAT-1A793BE7Application DataMacromediaFlash Player#SharedObjects96FX85HWwww.box.netstaticflashbox_explorer.swf
註:假如 getLocal 沒有提供 sol 名稱,則會使用 undefined.sol
註:預設情況 ShareObject 在每個網域只能儲存 100KB,如果超過時,Flash Player 會要求使用者允許儲存超過 100KB 的資料
註:也可以使用 getLocal 的第二個參數來指定儲存位置,但必須是目前網域的子目錄
註:可以一次建立多個 ShareOjbect

存取 ShareObject 資料的方法很簡單,只要透過 data 屬性,後面接需要儲存的變數名稱,如下:
// 寫入資料
mySO.data.name = "Chui-Wen Chiu";
mySO.data.age = 27;

// 讀取資料
trace( mySO.data.name )

SharedObject 範例:紀錄登出時間

點一下 Log out 在重新載入 Flash 會看到上次登入時間
<?xml version="1.0"?>
<!-- lsos/WelcomeMessage.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initApp()">
<mx:Script><![CDATA[
public var mySO:SharedObject;
[Bindable]
public var welcomeMessage:String;

public function initApp():void {
mySO = SharedObject.getLocal("mydata");
if (mySO.data.visitDate==null) {
welcomeMessage = "Hello first-timer!"
} else {
welcomeMessage = "Welcome back. You last visited on " +
getVisitDate();
}
}

private function getVisitDate():Date {
return mySO.data.visitDate;
}

private function storeDate():void {
mySO.data.visitDate = new Date();
mySO.flush();
}

private function deleteLSO():void {
// Deletes the SharedObject from the client machine.
// Next time they log in, they will be a 'first-timer'.
mySO.clear();
}

]]></mx:Script>
<mx:Label id="label1" text="{welcomeMessage}"/>
<mx:Button label="Log Out" click="storeDate()"/>
<mx:Button label="Delete LSO" click="deleteLSO()"/>
</mx:Application>

參考資料:
[1] Flex2 Developer's Guide

2007年4月21日 星期六

演算法問題1-5:等值首尾和(Java版本)
MSN SpaceGoogle DocGoogle Blog
Chui-Wen Chiu(Arick)
2007.04.21

有人在問 演算法問題1-5:等值首尾和 的 Java 版本怎麼寫,其實語法差不多,改完後的樣子也差不多如下(演算法1-1也差不多就不改了):

/**
* JDK 1.6
*
* Headtail.java
*
* javac Headtail.java
*/
public class Headtail {
public static void main(String[] args) {
int f[] = {3, 6, 2, 1, 4, 5, 2};

System.out.println( headtail(f) ); // 3
}
public static int headtail(int f[]){
if (f.length <= 0){
return 0;
}
int count = 1; // 整個陣列的和一定相同
int i = 0;
int j = f.length-1;
int lv = f[i];
int rv = f[j];
while(i.LENGTH-1 j="" &&=""> 0){ // 邊界值,兩側最後一個值不用測試,因為累加到最後一定相等
if (lv <= rv){
if (lv == rv){
++count;
}
if (i .LENGTH-1){>
lv += f[++i];
}else{
rv += f[--j];
}
continue;
}

if (lv > rv){
if (j >1){
rv += f[--j];
}else{
lv += f[++i];
}
}
}
return count;
}
}
補充:
剛剛才發現 MSN Space 處理 < 符號有問題,會把部份內容過濾調,所以,可看 Googe DOC 避免此問題。
Flex 2.0 使用 .NET Web Service 簡單測試

Chui-Wen Chiu(Arick)
MSN SpaceGoogle DocGoogle Blog
2007.04.21

測試環境:
1. Windows XP Pro
2. Visual Studio 2005 Team Edition
3. Flex Builder 2.0.1

1. 建立簡單的 .NET Web Services
a. 啟動 Visual Studio 2005
b. File | New | Project | ASP.NET Web Service Application,名稱使用 mydata
c. 產生的程式碼如下:
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;

namespace mydata
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
d. Web Services 不是重點,所以上述程式不需要修改,直接執行即可啟動 Web Services,如下:


2. 建立 Flex 程式使用 Web Services
a. 啟動 Flex Builder,新增 Flex Project
b. 輸入下面的程式碼
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
width="335" height="115">
<mx:Script>
<![CDATA[
import mx.rpc.AbstractOperation;
import mx.controls.Alert;

private function btnGo_click():void{
ws.getOperation("HelloWorld").send();
}

private function load():void{
mx.controls.Alert.show("WSDL Loaded");
}

// 取用 Service 失敗時呼叫
private function fault(target:AbstractOperation):void{
mx.controls.Alert.show("fault: " + target);
}

// 取用 Service 成功時呼叫
private function result(target:AbstractOperation):void{
mx.controls.Alert.show("result: " + target.lastResult );
}
]]>
</mx:Script>
<mx:Button x="10" y="10" label="Button" click="btnGo_click();"/>
<mx:WebService
id="ws"
load = "load()"
useProxy = "false"
wsdl="http://localhost:4921/Service1.asmx?wsdl">

<mx:operation name="HelloWorld"
fault="fault( ws.getOperation('HelloWorld') );"
result="result( ws.getOperation('HelloWorld') );"
>

</mx:operation>
</mx:WebService>
</mx:Application>

上述透過 <mx:WebService> 取得 .NET Web Service,wsdl 屬性設定 Web Services 的 WSDL 連結,load 屬性設定 Web Services 載入完成後觸發事件。<mx:operation> 設定 Web Service 操作,name 設定 Service 名稱,fault 設定操作失敗觸發的事件, result 設定操作完成觸發的事件。<mx:WebService> 提供 getOperation 方法取得 AbstractOperation,透過 AbstractOperation 的 send() 取得服務運算結果。



執行結果

圖1、Web Services 載入完成畫面


圖2、取用 HelloWorld Service 畫面


參考資料:
[1] http://blog.xuite.net/ticore/blog2/4611760

2007年4月17日 星期二

(C++) 模擬 CoCreateInstance( ),不用註冊 COM 即可使用

Chui-Wen Chiu(Arick)
MSN SpaceGoogle DocGoogle Blog
2007.04.18

lallous 在[1]發表了透過模擬 CoCreateInstance() 方式直接使用未註冊的 COM,CoCreateInstance 函數的用途在透過 Registry 找出 DLL 所在位置並載入系統,然後呼叫 DllGetClassObject( ) 取得類別工廠(Class Factory),透過類別工廠產生你需要的 IID 實體。所以只要能夠模擬出上述這些動作即可免除註冊 COM 步驟,除非 COM 元件還需要在 Registry 中註冊其他使用資料。

因此[1]提出下面的程式片段
HRESULT __stdcall MyCoCreateInstance(
LPCTSTR szDllName,
IN REFCLSID rclsid,
IUnknown* pUnkOuter,
IN REFIID riid,
OUT LPVOID FAR* ppv)
{
HRESULT hr = REGDB_E_KEYMISSING;
// 載入 COM DLL
HMODULE hDll = ::LoadLibrary(szDllName);
if (hDll == 0)
return hr;

typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID rclsid, IN REFIID riid, OUT LPVOID FAR* ppv);

// 檢查是否具有取得 Class Factory 的 Function
pDllGetClassObject GetClassObject = (pDllGetClassObject)::GetProcAddress(hDll, "DllGetClassObject");
if (GetClassObject == 0)
{
::FreeLibrary(hDll);
return hr;
}

IClassFactory *pIFactory;
// 取得 Class Factory
hr = GetClassObject(rclsid, IID_IClassFactory, (LPVOID *)&pIFactory);

if (!SUCCEEDED(hr))
return hr;

// 建立指定 IID 的實體
hr = pIFactory->CreateInstance(pUnkOuter, riid, ppv);
pIFactory->Release();

return hr;
}
上述片段的使用方式:
// 1. 以一般 CoCreateInstance 建立 COM
hr = CoCreateInstance(CLSID_DOT, NULL, CLSCTX_ALL,
IID_IDOT, (LPVOID *)&pIDOT);

if (hr == REGDB_E_CLASSNOTREG)
{
// 2. 假如未註冊,呼叫模擬的 CoCreateInstance
hr = MyCoCreateInstance(_T("WinGraphViz.dll"), CLSID_DOT, NULL, IID_IDOT, (LPVOID *)&pIDOT);
}

if (FAILED(hr))
{
cout << "CoCreateInstance Failed: " << hr << "nn";
return -1;
}

參考資料:
[1] http://www.codeproject.com/useritems/Emul_CoCreateInstance.asp



2007年4月16日 星期一

[Apollo] 不使用標準是窗外框,自行處理視窗拖拉、縮小和關閉

Chui-Wen Chiu(Arick)
MSN SpaceGoogle DocGoogle Blog
2007.04.17

[1] 提出一個不具有醜醜的 Windows 視窗,且能夠自由的拖拉視窗範例,整個範例的關鍵在於自訂 Application 類別,如果你打開 CustomChrome.mxml 你將會發現他的根節點是 <pixelbox:ApolloApplicationClass>,這個延伸 Application 的類別定義在 com.pixelbox.view.ApolloApplicationClass,這個類別主要再建立完 Application 之後就將相關控制項的事件進行監聽,並進行相對應處理,如下:

// 當 Application 建立完成時
public function creationCompleteHandler():void
{
// 建立相關的事件監聽,包含視窗的拖拉(controlBar)、縮小按鈕(minimizeBtn和關閉程式按鈕(closeBtn)
this.controllBar.addEventListener( MouseEvent.MOUSE_DOWN, applicationDragHandler );
this.minimizeBtn.addEventListener( MouseEvent.MOUSE_UP, onMinimize );
this.closeBtn.addEventListener( MouseEvent.MOUSE_UP, onClose );
}

然後將這三個事件委託給 stage.window 處理,如下:
// 視窗拖曳
public function applicationDragHandler(event:MouseEvent):void
{
stage.window.startMove();
}

// 視窗關閉
private function onClose(evt:MouseEvent):void
{
stage.window.close();
}

// 視窗最小化
private function onMinimize(evt:MouseEvent):void
{
stage.window.minimize();
}

上述的動作已經使得 Flex 的標題列(controlBar)可以拖拉,而且可以縮小和關閉視窗。然後設定CSS 移除預設的 Window 樣式,
 Application
{
background-color: "";
background-image: "";
padding: 0px;
}

最後一步是將 Apollo 預設的作業系統視窗移除,這個可以透過 Apollo 設定檔來完成,修改 CustomChrome-app.xml 的
<rootContent systemChrome="none" transparent="true" visible="true">[SWF reference is generated]</rootContent>

systemChrome 設為 none 可將是窗外框移除, transparent 可以讓程式具有透空效果。



檔案下載:
[1] 原始 AIR 檔
[2] 原始碼

參考資料:
[1] http://www.pixelbox.net/2007/04/16/apollo-custom-chrome-example/
[2] http://www.pixelbox.net/2007/04/13/no-chrome-in-apollo/


2007年4月11日 星期三

[JS]Ext 的 XmlReader 測試

MSN SpaceGoogle DocGoogle Blog
Chui-Wen Chiu(Arick)
2007.04.11 建立

測試環境:

1. Windows XP Pro + SP2

2. IE 6.0

3. Javascript Library

3.1 Ext 1.0a

3.2 Prototype 1.5.0

Ext 1.0 提供了 XmlReader 物件,可將 XML Document 轉換成 Array,下面是一個簡單的測試範例,因為使用了 IE 專屬的 XMLDOM 所以此範例無法運作於 Firefox 中。如果 XML 是放在遠端機器上,可搭配 HttpProxy 物件使用,如此可同時用於 IE 和 Firefox。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=big5"/>
<meta name="author" content="Chui-Wen Chiu">
<script type="text/javascript" src="../prototype.js"></script>
<script type="text/javascript" src="../../yui-utilities.js"></script> <script type="text/javascript" src="../../ext-yui-adapter.js"></script> <!-- ENDLIBS -->
<script type="text/javascript" src="../../ext-all-debug.js"></script>

<script type = 'text/javascript'>
<!--//
Ext.onReady(function(){
// 1. 產生 XmlReader
// 下面的參數主要的意思是將 XML 中的 <Item> 標籤轉換成陣列
// 陣列中的每一筆資料代表一筆紀錄,每一筆紀錄使用 <ASIN>xxx</ASIN> 為識別碼
// 將 <Item> 標籤的數量放置在 totalRecords
// 每一筆紀錄的欄位分別抓取 <Item> 標籤下的 <Author>, <Title>, <Manufacturer>, <ProductGroup> 等標籤

var xr = new Ext.data.XmlReader({
record: 'Item', // XML 標籤
id: 'ASIN', // 紀錄識別碼對應 XML 的標籤
totalRecords: '@total' // 取得 record 欄位指定標籤(<Item>)的數量,如果未指定該欄位,則 Record 物件的 totalRecords 屬性將直接取用 <item> 標籤數量,一般情況兩個值應該都一樣
},
// 要讀取的欄位定義
[
{
name: 'Author',
mapping: 'ItemAttributes > Author'
},
'Title',
'Manufacturer',
'ProductGroup'
]
);
// 2. 產生一個 XML Document
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var xmlStr = '
<?xml version="1.0" encoding="big5"?>
<Items>
<Item>
<ASIN>0446354732</ASIN>
<DetailPageURL>http://www.amazon.com/gp/</DetailPageURL>
<ItemAttributes>
<Author>中文作者</Author>
<Manufacturer>Warner Books</Manufacturer>
<ProductGroup>Book</ProductGroup>
<Title>Nothing Lasts Forever</Title>
</ItemAttributes>
</Item>
</Items>
';
xmlDoc.loadXML(xmlStr);

// 3. 將 XML Document 轉換成 Array
var rs = xr.readRecords(xmlDoc);

// 4. 取得資料筆數
var count = rs.totalRecords;
$('lblCount').innerText = count;

var out = '';
for(var i = 0; i< count; ++i){
// 5. 取得每一筆紀錄,型態為 Record 物件
var r = rs.records[i];

// Record 有兩個重要屬性
// id: Item 的識別碼
// data: 欄位陣列
// 上述兩個屬性都依據 XmlReader 建構子的兩個參數所決定

out += r.id + '=>' + [r.data['Author'], r.data['Title'] , r.data['Manufacturer'] , r.data['ProductGroup'] ].join(',') + '<br/>';
}
$('divRecord').innerHTML = out;

});
//-->
</script>
</head>
<body>
<div>
<label>Total:</label><label id = 'lblCount' style = 'color: red'></label>
<div id ='divRecord'>
</div>
</div>

</body>
</html>

參考資料:

[1] http://extjs.com/

2007年4月8日 星期日

[C#]壓縮過長的路徑字串

MSN SpaceGoogle DocGoogle Blog
Chui-Wen Chiu(Arick)
2007.04.09 建立

.NET 2.0 的 TextRendar.MeasureText() 用來量測字串,但是他可以接收 TextFormatFlags.PathEllipsis 參數,該參數可以將過長字串的中間部份以 ... 取代,具體的實作如下:

private void button1_Click(object sender, EventArgs e) {
textBox2.Text = CompactString(textBox1.Text, textBox2.Width , textBox2.Font );
}

public static String CompactString(String str, int Width, Font fnt) {
String result = String.Copy(str);
TextRenderer.MeasureText(result, fnt, new System.Drawing.Size(Width, 0), TextFormatFlags.PathEllipsis | TextFormatFlags.ModifyString);
return result;
}



參考資料
[1] http://www.codeproject.com/useritems/NewPathCompactPath.asp

搜尋此網誌