2009年11月25日 星期三

Sqlite with C# 在資料庫新增字串

這次試者將 RSS 下載下來的資料透過 System.Data.SQLite.dll 儲存到SQLite中 , 但是 會遇到一個問題就是 文章中會包涵 單引號(') 在用 sql的 insert 指令就會有問題


目前只想到一個方法就是吧字串存成 BLOB 的方式來避免錯誤

舉例說明比較容易

假設我要輸入一組 文字 如 文章標題,內容

標題: Tuck's incoming class gives back to the Upper Valley
內容: Before the academic year officially started, the incoming class of 2011 at the Tuck School of Business at Dartmouth was busy working on consulting projects for organizations in the Upper Valley. As part of Community Outreach Day (COD), all first-year students donated half a day during orientation week to work on solving a variety of issues facing local nonprofits.

將 標題的文字存成 一個 string 叫 title
內容 的文字存成 另一個 string 叫 contant

在將string 轉成 byte array 便可以 blob 方式 存入 資料庫

/// Translation string to byte array
byte[] bTitle = Encoding.ASCII.GetBytes(title);
byte[] bContant = Encoding.ASCII.GetBytes(contant);

轉貼 C# 文字轉成日期方法

有時候利用網路上取得的資料,但時間格式常常不是想要的格式,在這個時候就可以利用這個方法將說明時間的字串轉換為date 的格式

這時可以用 DateTime.ParseExact 的方法


主要有三個變數
s
型別:System.String
字串,包含要轉換的日期和時間。
format
型別:System.String
格式規範,定義 s 的所需格式。
provider
型別:System.IFormatProvider
物件,提供關於 s 的文化特性特定格式資訊。

如想要吧 這個字串
Tue, 10 Nov 2009 13:54:20 EST

轉成 DateTime 格式
以下是範例code




/// 宣告 格式資訊
CultureInfo provider = CultureInfo.InvariantCulture;
/// 時間字串
string pubDate="Tue, 10 Nov 2009 13:54:20 EST";
/// 轉換成DateTime 格式
DateTime x = DateTime.ParseExact(pubDate, "ddd, dd MMM yyyy HH':'mm':'ss 'EST'", provider);




詳細說明可以參考 MSDN

2009年11月12日 星期四

使用 Google protrol to get the google api in C# with Google Site data api

在這個範例 中 使用 Google protocol 去取得 google site data 的資訊

所使用的語言是 C#, java的版本之前在其他文章有寫過


Http Post requset with java:
使用 java http post 取得 google account (AuthSub)

Http Get request with java:
使用 java http Get( by AuthSub) 取得 google document list





主要分成3個部份

1. SetProxyServer (有經過proxy 才要設 )
code 如下

/**
* @name SetProxyServer
*
* Set the Proxy Server if have Proxy Server
*
* @param req [in] - the http web request
*/
public void SetProxyServer(HttpWebRequest req)
{

IWebProxy iProxy = WebRequest.DefaultWebProxy;

/// potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;
req.Proxy = iProxy;
}






2.
取得 google api 的要驗證碼( 使用 http post), 這裡我是使用client login的方法

輸入以下三種資訊
Account: google 帳號
Password: google 帳號的密碼
Service Type: google api 的 類型 這裡使用 google site 類型為 "jotspot" (其他類型 )

code 如下



/**
* @name GetGoogleLoginAuth
*
* Get the google client login auth token
*
* @param Account [in] - the google account
* @param Password [in] - the google account password
* @param ServiceType [in] - the google api type
*
* @return the google client login auth
*/
public string GetGoogleLoginAuth(string Account, string Password, string ServiceType)
{
/// Declare the return valure
string GoogleLoginAuth="";

/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");

/// Set proxy
this.SetProxyServer(req);

/// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string strNewValue = "accountType=HOSTED_OR_GOOGLE"+
"&Email=" + Account +
"&Passwd=" + Password +
"&service=" + ServiceType +
"&source=Gulp-CalGulp-1.05";

/// Set the request value
req.ContentLength = strNewValue.Length;


/// Write the request
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();


/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();


/// Split string and set token
/// there are tree type in the return value
/// SID, LSID and Auth
string[] parts = strResponse.Split('=');

/// Save the auth token, auth token is in last part of string parts[]
GoogleLoginAuth = parts[parts.Length - 1];

/// Close the stream reader
stIn.Close();


return GoogleLoginAuth;
}




3. RetrievalContentFeed , 利用 http get 取得google site 的資訊
主要實做 google guide 的範例

輸入兩個 資訊
a. url: http(s)://sites.google.com/feeds/content/site/siteName

site 網域名稱 如 example.com
siteName 網頁名稱 如 myCoolSite

b. token 剛取得的 auth token


附註:
要 傳送出以下的訊息
GET /feeds/content/site/siteName HTTP/1.1
Host: sites.google.com
GData-Version: 1.0
Authorization: GoogleLogin auth= yourAuthToken

在c # 這裡是用 HttpWebRequest.Headers.Add 來附加訊息
此外 Host 不需在設定, 因為 會從 url 取得
所以要附加的資訊就只有
GData-Version 和 Authorization

看下面的code 會更瞭解, code 如下


/**
* @name RetrievalContentFeed
*
* Get the google client login auth token
*
* @param URL [in] - the google api Url
* @param Token [in] - the google client login token
*
*
* @return Content Feed
*/
public string RetrievalContentFeed(string URL, string Token)
{
/// Declare the return valure
string Feed = "";

/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://sites.google.com/feeds/content/hh-mud.com/touch-teach");

/// Set proxy
this.SetProxyServer(req);

/// Set values for the request back
req.Method = "GET";

/// Set the Head value
req.Headers.Add("GData-Version:1.0");
req.Headers.Add("Authorization: GoogleLogin auth=" + Token);


/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
Feed = stIn.ReadToEnd();

stIn.Close();

return Feed;
}


2009年11月11日 星期三

轉貼java sock 範例

透過 socket 可以讓兩台電腦達成連線並且互相傳訊訊息

在範例中 利用java建立
有兩個部份
server 端
client 端

client 透過連線可以和server 端溝通


直接轉貼範例

永遠的UNIX- Java做一個最簡單的Socket通話程序

2009年10月28日 星期三

心得 Silverlight Demo From Msdn

由於 Msdn 提供的教學影片是利用 silverlight 結合 javascript 及 asp.net 的方法來執行 silverlight 的事件, 但現在本人以 visual stdio 2008 的開發平台來實做這個 demo 似乎有點 多此一舉

所以以下 就以 C# 的方式 來編譯那些事件

範例網址



這個範例大致解說如下, 建立四個圖片物件, 分別有三種事件 ,
滑鼠移入物件: onMouseEnter()將所選圖片 透明度增加(預設0.65), 圖片作部份位移
滑鼠移出物件: onMouseLeave()還原位置及透明度
點選物件: onClick()開啟網頁




在 C# 的 code 如下

onMouseEnter()

由於 C# 定義較 javascript 嚴謹,所以要將sender 給予 Image的型態, (因為確定是由Image 所發生的物件 )



void onMouseEnter(Object sender, RoutedEventArgs e)
{
Image img = (Image)sender;
img.Opacity = 1;
Canvas.SetTop(img, Canvas.GetTop(img) + 3);
Canvas.SetLeft(img, Canvas.GetLeft(img) + 3);
}



onMouseLeave()

原理同onMouseEnter()


void onMouseLeave(Object sender, RoutedEventArgs e)
{

Image img = (Image)sender;
img.Opacity = 0.65;
Canvas.SetTop(img, Canvas.GetTop(img) - 3);
Canvas.SetLeft(img, Canvas.GetLeft(img) - 3);
}


onClick()

在C# 使用javascript 的 window 物件, 必須要using "System.Windows.Browser"
但是沒有像javascript那麼齊全, 例如就不能使用 window.open 這個方法, 但是可以利用
Window.Eval 的方式來執行出來javascript的程式
下面就利用 eval 的方式 執行出window.open來打開新網頁


void onClick( object sender, RoutedEventArgs e)
{

Image img = (Image)sender;

switch (img.Name)
{

case "p1":

HtmlPage.Window.Eval("window.open('http://www.google.com.tw/);");

break;
case "p2":
HtmlPage.Window.Eval("window.open('http://tw.yahoo.com/');");
break;

case "p3":
HtmlPage.Window.Eval("window.open('http://www.pchome.com.tw/');");
break;

case "p4":
HtmlPage.Window.Eval("window.open('http://tw.msn.com/');");
break;

default:

break;

}

}


2009年10月23日 星期五

Sliver light Demo2 輸入數字新增物件至Silverlight Canvas

在這個例子中, 試者修改畫布物件, 輸入數目, 變會在 canvas 上顯示多少個橢圓形

步驟可以參考

DEMO 網址

a. Index.html

在這裡有 3個 function

1. ShowTheEllipse: 執行建立物件的動作
2. ClearCanvase: 清除 Silverlight Canvas 的物件
3. addEllipse: 新增物件到
Silverlight Canvas 上

code 如下



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title> Sliver Light Test 1</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="SL2.js"></script>
<script type="text/javascript" src="index.js"></script>


<script type="text/javascript">


/// the canvas top
var top = 0;


function ShowTheEllipse() {

// Get the inpute Value
var GetValue = document.getElementById('txtInput').value;


if (GetValue >= 0 && GetValue !="") {

// Get the XAML Object
var SlControl = document.getElementById('SilverlightPlugIn');

// Claer the objevt in the canvas
ClearCanvase();


// Add the object in the canvas
for (var i = 0; i < GetValue; i++) {

var xaml = SlControl.content.createFromXaml(' <Ellipse Width="20" Height="15" Fill="Azure"/>');

addEllipse(xaml);

}



}
else{

alert("Error, must enter the number");
}


}


// Clear the objevt in the canvas
function ClearCanvase() {

// Get the XAML Object
var SlControl = document.getElementById('SilverlightPlugIn');

var itemsContainer = SlControl.content.findName('Root');
itemsContainer.children.clear();

top = 0;

}



// Add the Ellipse object
function addEllipse(xaml) {

// Get the XAML Object
var SlControl = document.getElementById('SilverlightPlugIn');

// Set the Canvas top
xaml["Canvas.Top"] = top;
var itemsContainer = SlControl.content.findName('Root');
itemsContainer.children.insert(0, xaml);
top += 20;
}

</script>
</head>
<body>

<input id="txtInput" type="text" />

<input id="ShowSilverlight" type="button" value="Enter the number to show the Ellipse in the seliverlight Canvase" onclick="ShowTheEllipse()"/>


<div id="SilverlightPlugInHost">
<br />
<br />
<script type="text/javascript">
createSilverlight();
</script>
</div>




</body>
</html>







b. 主要的js 檔 呼叫 xaml 物件 , 如 index.js




function createSilverlight() {
var scene = new AdBanner.Scene();
Silverlight.createObjectEx({
source: 'SL2.xaml',
parentElement: document.getElementById('SilverlightPlugInHost'),
id: 'SilverlightPlugIn',
properties: {
width: '300',
height: '300',
background: 'LightBlue',
isWindowless: 'false',
version: '1.0'
},
events: {
onError: null,
onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
},
context: null
});
}

if (!window.Silverlight)
window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);
}
}




c. Xaml 檔 , 定義 silverlight 物件的顯示 , 如 SL2.xaml

別忘了命名 ,在這裡將 Canvas 命名為 Root


<Canvas xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Root">


</Canvas>



d. X.Xaml.js , 定義 silverlight 物件的方法, 如若在visual stdio 上 ,新增 XAML檔就會一起建立,如 SL2.js


if (!window.AdBanner)
window.AdBanner = {};

AdBanner.Scene = function() {
}

AdBanner.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement) {
this.plugIn = plugIn;
}
}





2009年10月22日 星期四

Sliver light Demo1 使用javascript 改變 silverlight 物件

以下這個例子包含我從創建簡單的slight 專案開始,這個專案是將html 輸入的文字秀到 silverlight 的畫布上

DEMO 網址

開啟專案的步驟

1. 建立專案,選擇 Sliverlight Application or Sliverlight Navigation Application

Sliverlight Application : 空白的 專案

Sliverlight Navigation Application : 在專案中已有先建立簡單的 瀏覽器的表框



2.

雖然原本有樣本可以使用(預設範例是 C# 或 VB 的方式),但以下使用自行增加檔案來使用 javascript 執行 XAML


所以就 新增物件如下




3.

新增html:


在 Web 選項中選擇 HTML Page, 如圖




JS 檔 : Web 選項中選擇 : javascript File

xaml 檔 : Sliverlight 選項中選擇 : SilverlightJScript Page



4.
設定 執行首頁, 在檔案上按右鍵,選 Set Start Page





5.

在 html 用 javascript 使用 silverlight 必須包含以下幾個 檔案 的設定


a. Index.html

b. 主要的js 檔 呼叫 xaml 物件 , 如 SL1.js

c. Xaml 檔 , 定義 silverlight 物件的顯示 , 如 SL1.xaml

d. X.Xaml.js , 定義 silverlight 物件的方法, 如 SL1.xaml.js



code 如下

a. Index.html

在這裡必須引用 幾個JS 檔 包含 Silverlight.js, SL1.js ,SL1.xaml.js


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title> Sliver Light Test 1</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="SL1.js"></script>
<script type="text/javascript" src="SL1.xaml.js"></script>


<script type="text/javascript">

function changeText() {
// Get the inpute Value
var GetValue = document.getElementById("txtInput").value;
// Get the XAML Object
var SlControl = document.getElementById("SilverlightPlugIn");
// Get the Object SLText in the XAML file
var SLText = SlControl.content.findName("SLText");
// Change the ext
SLText.Text = GetValue;
}

</script>
</head>
<body>

<input id="txtInput" type="text" />

<input id="ShowSilverlight" type="button" value="Show in Silverlight Canvas" onclick="changeText()"/>


<div id="SilverlightPlugInHost">
<br />
<br />
<script type="text/javascript">
createSilverlight();
</script>
</div>

</body>
</html>





b. SL1.js



function createSilverlight() {
var scene = new AdBanner.Scene();
Silverlight.createObjectEx({
source: 'SL1.xaml',
parentElement: document.getElementById('SilverlightPlugInHost'),
id: 'SilverlightPlugIn',
properties: {
width: '300',
height: '300',
background: 'LightBlue',
isWindowless: 'false',
version: '1.0'
},
events: {
onError: null,
onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
},
context: null
});
}

if (!window.Silverlight)
window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);
}
}




c. SL1.xaml



<Canvas xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<TextBlock x:Name="SLText" Width="67" Height="23.2" Canvas.Left="29"
Canvas.Top="10" Foreground="#FFEFEFEF" Text="Enter and show" />


</Canvas>




d. SL1.xaml.js



if (!window.AdBanner)
window.AdBanner = {};

AdBanner.Scene = function() {
}

AdBanner.Scene.prototype =
{
handleLoad: function(plugIn, userContext, rootElement) {
this.plugIn = plugIn;
}
}

Eclipse4sl( silverlight develop with eclipse)

雖說 silver light 也可以在純文字下開發, 但少了IDE 偵錯 功能還是有點不方便,

所以除了 在 visual studio 2008 上開發之外, 也可以透過 eclipse 上的外掛來編譯 XAML 檔 及開發

安裝方式如下 (參考來源

1. 安裝 jdk 1.0.5.11以上
2. eclipse 3.4 以上 的IDE
3. .net Framework 3.5以上
4. silverlight 2 以上 的 Runtime
5. silverlight 2 以上 的 SDK
6. eclipse 中新增 Silverlight4sl 外掛(網址是 http://www.eclipse4sl.org/update/



但目前安裝後僅有顯示XAML 的編輯工具, 但編輯畫面沒有顯示出來....

Silver light 開發環境設定

Silverlight 是MS 所提供的一種 網頁開發的技術,提供了許多在繪圖及網頁互動上的一些技術使網頁內容更為豐富。

Microsoft Silverlight 的 WIKI

安裝步驟可以參考

其實只要安裝 第一點的
Silverlight 的開發人員 工具在加上 visual stdio 2008 更新到sp1
就可以在 visual stdio 2008 進行開發

補充, 其他只是讓開發更豐富的工具


第二點 Expression Blend 是一種提供圖形介面的操作方式,但是這裡只有試用版,若要使用必須額外購買



第三點 的 Deep Zoom 是一種快速瀏覽影像的工具 介紹



2009年10月19日 星期一

Google Calendar的小工具 介紹

除了 google calendar api 外, google 在 calendar 還提供了一些相關的應用

包含

Calendar Gadgets

這裡還可細分兩種

Event Gadgets
在google calendar 上加入小圖示,點入小圖示之後可以開啟一個小視窗可以包含 圖片、網頁或 gadget

如圖

建立的方法有三種,這裡都有詳細的介紹

使用 Calendar Event Gadget Creator
使用 the iCalendar Format
使用 the Google Calendar data API

Sidebar Gadgets
開發 Gadget 在 google calendar 的右邊, 範例的功能有 世界時鐘、顯示年曆等等
說明網站在這邊, 不過開發 Gadget 又要另一種的方式了


CalDAV

CalDAV 是一種行事曆同步協定,可以使其他行事曆 (如 Apple iCal、Mozilla Sunbird) ) 交換Google calendar 的資料。

Publishing Tools

透過這個小工具可以在網頁上鑲入google calendar
在網頁上(如blogger)中新增calendar 事件

2009年10月9日 星期五

在html 中 克服 ie 無法讀取 svg 的 library (SVG Web)

SVG 是XML的一種可以用來顯示圖片,詳細的說明可以參照以下的網址


但可惜的是目前 IE 系列的瀏覽器還沒支援顯示SVG 的功能,
所幸可以透過安裝library 來解決這個問題



安裝及使用library 的步驟很簡單

1. 下載 library

2. 注意必須架在 HTTP server 上才可以正常執行,如IIS、 apache,不能直接用
檔案開啟

3. 引用library (複製 library 的 src 資料夾 )
  • <script src="src/svg.js" data-path="src" ></script>
  • src/svg.js js 檔相對於首頁的位置
  • src 相關的library

4. 引用 SVG 在 ie 和 非 ie 有不同用法, 其中 sample.svg 只是檔名


用法1

<!--[if IE]>
<object src="sample.svg"classid="image/svg+xml"
width="200" height="200"
id="mySVGObject">
<![endif]-->
<!--[if !IE]>-->
<object data="sample.svg" type="image/svg+xml"
width="200" height="200"
id="mySVGObject">
<!--<![endif]-->
</object>



用法 2

<object type="image/svg+xml" data="sample.svg" width="200" height="200">
<param name="mySVG" value="
sample.svg"/>

2009年10月7日 星期三

轉貼 HTML 教學網址 錨點(anchor)

錨點(anchor) 可以提供一個 超連結,連到同一份 html 的不同位置, 在撰寫 bloger 中若有大量的文章可以使用這個方法,方面文件的整理及搜尋


使用說明轉貼 鋼鐵之翼

2009年9月28日 星期一

Google Calendar Api query constrain

在使用google calendar api 中, 其實有以個預設的查詢限制,

舉例來說,若想要查詢其中一本日曆的事件, 但一次查最多只有25筆
如 : http://www.google.com/calendar/feeds/default/private/full
解果只會傳回最新的25筆資料


但 若要查詢所有的資料的話,可以設定 max-results 的數量, 將他設定一個很大的值
如,可以將url 改為
http://www.google.com/calendar/feeds/default/private/full?max-results=200



見 google 常見問題 How do I retrieve more than 25 results in an event feed?

Google Calendar api in javascript

之前將 google calendar 試過了 .net 和 java 上應用, 現在來試試 javascript 。

在是的過程中發現了幾項限制

1. 必須要架在server 上
可以用 apache 或 iis 的方法, 我這裡是用 eclipse + google app engine 的方式 ,之後在上傳到 google app engine 上

2. 在網頁上要至少放一個圖檔
這個限制有點奇怪,不過不放的話會有一個 「An image of the same domain is required on this page for authenticated reads and all writes.」的錯誤 (參考 Geoffrey's 有人QWERTY絮語

之後照者 Google Calendar APIs and Tools 的教學即可

以下是我寫得 範例

2009年9月17日 星期四

Upload image to the picasa web album

在 C# 要使用 picasa web album data api , 在下在完 google api 後, 記得 include 以下的 dll

  • Google Data API Access Control Library
  • Google Data API Core Library
  • Google Data API Extansions Library
  • Google Data API Picasa Library

這個範例輸入 以下資訊就可以上傳 圖片到picasa,不同於google 官方範例是從檔案路徑讀取檔案在上傳 ,這裡 傳入一個 BitmapImage 即可取得 圖片的資料


註 1、 Image Type
  • image/bmp
  • image/gif
  • image/jpeg
  • image/png
註 2、 Picasa Web Albums Data API - C# delelper's guide

Code 如下





/**
* @Name UpLoadImageToWebAlbum
*
* Upload photo to the the picasa web album,
* In there, using the StreamSource get the photo byte array
*
* @param Account [in] - the google accpount
* @param Password [in] - the google accpount's password
* @param AlbumUri [in] - the google picasa web album uri
* @param PhotoID [in] - the photo id
* @param Image [in] - the image which want upload
*
*/
public void UpLoadImageToWebAlbum(string Account, string Password, string AlbumUri, String PhotoID, BitmapImage Image)
{


/// Set Service
PicasaService service = new PicasaService("UploadImag");

/// Set Account and Password
service.setUserCredentials(Account, Password);


/// Set Uri
Uri postUri = new Uri(AlbumUri);


/// Set proxy
GDataRequestFactory requestFactory = (GDataRequestFactory)service.RequestFactory;
IWebProxy iProxy = WebRequest.DefaultWebProxy;
WebProxy myProxy = new WebProxy(iProxy.GetProxy(postUri));

///potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialCache.DefaultCredentials;

myProxy.UseDefaultCredentials = true;
requestFactory.Proxy = myProxy;


/// Insert photo
/// service.Insert(the album uri, image's StreamSource, image type , the image name );
service.Insert(postUri, Image.StreamSource, "image/png", "" + PhotoID);

///Insert Pic

/// Close stream
Image.StreamSource.Close();

MessageBox.Show("OK");



}



Get picasa web album Photo list in album by c#

在 C# 要使用 picasa web album data api , 在下在完 google api 後, 記得 include 以下的 dll

  • Google Data API Access Control Library
  • Google Data API Core Library
  • Google Data API Extansions Library
  • Google Data API Picasa Library



這個範例輸入 帳號、密碼及 AlbumUri 就可以取得 在這個相簿裡的 所有的photo 資料

註1、 AlbumUri 可以見上一篇 取得的 FeedUri
註2、 entry.Content.AbsoluteUri 就是實際存放相片的位址




/**
* @Name GetPhotoListInAlbum
*
* Get album list from the picasa web album
*
* @param Account [in] - the google accpount
* @param Password [in] - the google accpount's password
* @param AlbumUri [in] - the google picasa web album uri
*
*/
public void GetPhotoListInAlbum(string Account, string Password, string AlbumUri)
{


/// Set Service
PicasaService service = new PicasaService("Get_Album_List");

/// Set Account and Password
service.setUserCredentials(Account, Password);

/// Set Query
PhotoQuery query = new PhotoQuery(AlbumUri);


/// Set proxy
GDataRequestFactory requestFactory = (GDataRequestFactory)service.RequestFactory;

IWebProxy iProxy = WebRequest.DefaultWebProxy;

WebProxy myProxy = new WebProxy(iProxy.GetProxy(query.Uri));

///potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialCache.DefaultCredentials;
myProxy.UseDefaultCredentials = true;
requestFactory.Proxy = myProxy;


/// Get feed
PicasaFeed feed = service.Query(query);


/// Get Album count
int count = feed.Entries.Count;
Console.WriteLine(count);


foreach (PicasaEntry entry in feed.Entries)
{
/// Get album title
string title = entry.Title.Text;
Console.WriteLine(title);

/// Get the image uri
string uri = entry.Content.AbsoluteUri;
Console.WriteLine(uri);
}

}



Get picasa web album list by c#

在 C# 要使用 picasa web album data api , 在下在完 google api 後, 記得 include 以下的 dll

  • Google Data API Access Control Library
  • Google Data API Core Library
  • Google Data API Extansions Library
  • Google Data API Picasa Library
下面這個 例子 就是 輸入 google 帳號和密碼後就可以取得所有的相簿清單

註1 、 其中要注意的就是 query 的用法, 預設 可以使用 "default" 來取得自己的相簿清單
但是可以取代成其他使用者,用這語法來找到你想知道的人的相簿(僅限於他公開或分享給你的)


例如 朋友的帳號為 xxxxx@gmail.com
FriendAccountName = "xxxxx";

語法可以 轉成
AlbumQuery query = new AlbumQuery(PicasaQuery.CreatePicasaUri(FriendAccountName));


註2 、 取得後 entry.FeedUri 可以取得 相簿的 uri 位址, 可利用這個位址取得在這相簿所有的圖片資訊

code 如下




/**
* @Name GetAlbumList
*
* Get album list from the picasa web album
*
* @param Account [in] - the google accpount
* @param Password [in] - the google accpount's password
*
*
*/
public void GetAlbumList(string Account, string Password)
{


/// Set Service
PicasaService service = new PicasaService("Get_Album_List");

/// Set Account and Password
service.setUserCredentials(Account, Password);

/// Set Query , default is the account user,
/// "default" can chang other user name to get other album (if that user set public or share with you)
AlbumQuery query = new AlbumQuery(PicasaQuery.CreatePicasaUri("default"));


/// Set proxy
GDataRequestFactory requestFactory = (GDataRequestFactory)service.RequestFactory;

IWebProxy iProxy = WebRequest.DefaultWebProxy;

WebProxy myProxy = new WebProxy(iProxy.GetProxy(query.Uri));

// /potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialCache.DefaultCredentials;
myProxy.UseDefaultCredentials = true;
requestFactory.Proxy = myProxy;


/// Get feed
PicasaFeed feed = service.Query(query);


/// Get Album count
int count = feed.Entries.Count;
Console.WriteLine(count);


foreach (PicasaEntry entry in feed.Entries)
{
/// Get album title
string title = entry.Title.Text;
Console.WriteLine(title);

/// Get Album feed uri , by this uri can get the photo information in this album
string Uri = entry.FeedUri;
Console.WriteLine(Uri);

}

}



2009年9月16日 星期三

圖片存取 in sqlite by C# 2

之前有寫過

圖片存取 in sqlite by C#


這一篇,但那一篇的作法試從檔案中讀取圖片資料在存入sqlite的資料庫中的;

不同於那篇文章, 現在修改了一部分,能夠讀取畫面中的圖像的byte array
(在此是用C# WPF的語法)

GetImageSourceByte function 說明︰
傳入一個 ImageSource ,利用 PngBitmapEncoder 的方式將ImageSource 轉成一個 Stream 並存入 MemoryStream 中; 最後在從 MemoryStream 取得資料存到 byte array中,

參考 定義




/**
* @Name GetImageSourceByte
*
* Get the ImageSource Byte array, which can save in database as BLOB type
*
* @param EventImage [in] - image to save
* @return the image byte array
*
*/
public byte[] GetImageSourceByte(ImageSource EventImage)
{
byte[] MyData = null;

/// new a JpegBitmapEncoder and add r into it
PngBitmapEncoder e = new PngBitmapEncoder();
e.Frames.Add(EventImage as BitmapFrame);

/// new memoryStream
MemoryStream ms = new MemoryStream();

/// Save to memory
e.Save(ms);

/// Re set the position, or read the memory from the last position
///ms.Seek(0, SeekOrigin.Begin);
/// Or set position
ms.Position = 0;

MyData = new byte[ms.Length];
ms.Read(MyData, 0, System.Convert.ToInt32(ms.Length));

ms.Close();

return MyData;

}




這裡說明一下 如何取得 傳入要傳的 ImageSource
參考 定義



/// Get bound of the visual
/// g is the WPF visual object, such as "grid","canvas", "Image", ...
Rect b = VisualTreeHelper.GetDescendantBounds(g);

/// new a RenderTargetBitmap with actual size of c
RenderTargetBitmap r = new RenderTargetBitmap((int)b.Width, (int)b.Height, 96, 96, PixelFormats.Pbgra32);

/// Render visual
r.Render(g);

/// Create BitmapFrame as ImageSource
BitmapFrame BitF= BitmapFrame.Create(r);

/// Get Byte[]
byte[] Img = GetImageSourceByte(BitF);




在此感謝 James 的指點

2009年9月15日 星期二

C# BinaryWriter and BinaryReader 應用

一個簡單的應用,不過現在還用不太到,先寫起來作個紀錄

Code 大概是這樣, 將一段字串和一個圖片檔一起存到一個 txt 的 file , 在從file 裡面讀出之前存入的字串和圖片

兩個 function
1. SaveFileByBinaryWrite
2. LoadFileByBinaryReader


Code 如下


SaveFileByBinaryWrite :


/**
* @name SaveFileByBinaryWrite
*
* Save the file by using BinaryWrite method,
* the file include sample description and the image source binary array
*
*
* @param ImgFileRoot [in] - the image file path
* @param Description1 [in] - sample description 1
* @param Description2 [in] - sample description 2
* @param newFile [in] - the new file path
*
*/
public void SaveFileByBinaryWrite(string ImgFileRoot, string Description1, string Description2, string NewFile)
{

/// Open FIleStream to transform image to byte array "MyData"
FileStream FsImageSource = new FileStream(ImgFileRoot, FileMode.OpenOrCreate, FileAccess.Read);
byte[] MyData = new byte[FsImageSource.Length];
FsImageSource.Read(MyData, 0, System.Convert.ToInt32(FsImageSource.Length));
FsImageSource.Close();


/// Open fileStream to write the information to the txt file
FileStream fs = new FileStream(NewFile, FileMode.CreateNew);

/// Open BinaryWriter
BinaryWriter bw = new BinaryWriter(fs);

/// Write information
bw.Write(Description1);
bw.Write(Description2);

/// Set the next write start position
/// In there , set 300
bw.Seek(300, SeekOrigin.Begin);

/// Write byte array MyData begin MyData[0] and length is MyData.Length
bw.Write(MyData, 0, MyData.Length);


/// Close the BinaryWriter and fileStream
bw.Close();
fs.Close();

}




LoadFileByBinaryReader:


/**
* @name LoadFileByBinaryReader
*
* Load the file by using BinaryRead method,
* the file include sample description and the image source binary array
*
*
* @param FileRoot [in] - the file path
*
*
* @return the BitmapImage to shw the image
*
*/
public BitmapImage LoadFileByBinaryReader(string FileRoot)
{

/// Set the Description Length
int DescriptionLength = 300;

/// Open FIleStream to transform image to byte array "MyData"
FileStream fs = new FileStream(FileRoot, FileMode.OpenOrCreate, FileAccess.Read);

/// Open BinaryReader read the FileStream
BinaryReader br = new BinaryReader(fs);

/// Declare the description char array
/// In there length is 300
char[] CharDescripion = new char[DescriptionLength];

/// Write the binary array in CharDescripion , start position 0 and length 300
br.Read(CharDescripion, 0, DescriptionLength);

/// Declare the string dscription
string Descripion = "";


/// Write the Char information to the string Descripion
for (int i = 1; i < DescriptionLength ; i++)
/// when no file break

if (CharDescripion[i] == '\0')
break;
Descripion = Descripion + CharDescripion[i];
}

/// Declare the byte array to get the image
byte[] MyData = new byte[fs.Length - DescriptionLength];

/// Get the ByteLength
int ByteLength = System.Convert.ToInt32(fs.Length - DescriptionLength);
/// Write the binary array in MyData, start position 0 and length ByteLength fs.Read(MyData, 0, ByteLength);
/// Close FIleStream
fs.Close();
/// Put the image byte[] to MemoryStream
MemoryStream ms = new MemoryStream(MyData);
/// Declare BitmapImage Bi
BitmapImage
Bi = new BitmapImage();
Bi.BeginInit();
/// Set Bi source from MemoryStream
Bi.StreamSource = ms;
Bi.EndInit();
return Bi;
}

2009年9月11日 星期五

轉貼 從網路取得圖片 儲存 成 Byte[] by C #

資料來源

http://bytes.com/topic/c-sharp/answers/235707-save-image-url


這裡有用到 BinaryReader. ReadBytes(count )的 function 可以參考MSDN的說明

http://msdn.microsoft.com/zh-tw/library/system.io.binaryreader.readbytes%28VS.80%29.aspx


其中 count 表示要讀取的位元組數目, 此範例 設 500000,
實際圖片轉換成byte[]必須比這個數目小,否則會lose 資料,
儲存完成 範例的 byte[] b 會依據實際的大小作調整

Code 如下




static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}




還有將byte[] 儲存成image 的函式




static public void WriteBytesToFile(string fileName, byte[] content)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write(content);
}
finally
{
fs.Close();
w.Close();
}

}


2009年9月10日 星期四

Get Image form Web by C#

以下範例 簡單的說明c# 取得位在網路上圖片的方法, 並將圖片暫存成 BitmapImage


ImgSource 為一個url string 如 "http://lh3.ggpht.com/_aUxwb_torSg/SZ5FjN1UkzI/AAAAAAAAAds/0FM7vPHF0Ho/showBorder.png"

Code 如下


public BitmapImage GetImagefromWeb(string ImgSource)
{
/// Declare BitmapImage Bi
BitmapImage Bi = new BitmapImage();

/// Create the requests.
WebRequest requestPic = WebRequest.Create(ImgSource);

/// Se proxy
/// if web request by proxy
IWebProxy iProxy = WebRequest.DefaultWebProxy;

/// Get potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;

/// Set proxy
requestPic.Proxy = iProxy;


/// Get response
WebResponse responsePic = requestPic.GetResponse();



Bi.BeginInit();

/// Set Bi source from Stream
Bi.StreamSource = responsePic.GetResponseStream();

Bi.EndInit();



return Bi;

}

圖片存取 in sqlite by C#

儲存圖片在資料庫中 可以將圖片轉成一種 blob type 的資料型態, 在儲存在資料庫中。

Blob 的相關用法用很多, 如以下的例子 是用 java 存取 mysql 為例
http://caterpillar.onlyfun.net/Gossip/HibernateGossip/BlobClob.html

在這裡,將使用 C# 將圖片儲存在 sqlite 上

這裡參考了 這一篇文章 http://sqlite.phxsoftware.com/forums/p/324/1329.aspx#1329

我的範例大致描述一下


此範例有使用 System.Data.SQLite; library , 如何使用 見

C sharp or .Net 使用sqlite 設定




有四個物件在視窗上

名稱 函式 說明
---------------------------------------------------------
CreateDB CreateDB_Click 建立資料庫
SaveToDB Save_Click 將圖片儲存在資料庫
LoadImageFromDB Load_Click 將圖片重資料庫讀出
imageExample null 顯示圖片的物件


顯示畫面如下



若 資料庫 及圖片以儲存 按下 LoadImageFromDB 就會重資料庫讀取檔案並顯示




CODE 如下





using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Data.SQLite;
using System.IO;
using System.Data;


namespace SQLiteBlobTest
{

/// Interaction logic for Window1.xaml

public partial class Window1 : Window
{

/// Set Database Root
string DataBaseRoot = Directory.GetCurrentDirectory() + "\\TestBlobDB.db";

public Window1()
{
InitializeComponent();
}



/**
* @name CreateDataBase
*
* Create Database "TestBlobDB.db",
*
*
* Must import System.Data.SQLite or it not work
* @param DataBaseRoot [in] the data base root
*
*/
public static void CreateDataBase(string DataBaseRoot)
{

/// Creat Database
SQLiteConnection.CreateFile(DataBaseRoot);

/// Open Database and set password
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Close connect
cnn.Close();

}



/**
* @name CreateBlobTable
*
* Create table whcih hava two column
* Name , type is nvarchar(40) , to record the name
* Image , type is BLOB , to record the image with byte[]
*
* Must import System.Data.SQLite or not work
* @param DataBaseRoot [in] the data base root
*/
public void CreateBlobTable(string DataBaseRoot)
{

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot );

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

/// Set commend to create table
cmd.CommandText = "CREATE TABLE [BlobTable] (Name nvarchar(40), Image BLOB)";

/// Execute the command, iF have exist show error message
cmd.ExecuteNonQuery();

/// Close connect
cnn.Close();
}



/**
* @name CheckDataBaseExist
*
* Check database exist or not
*
* @param DataBaseRoot [in] the data base root
* @return True if exist, otherwise false
*
*/
public Boolean CheckDataBaseExist(string DataBaseRoot)
{

/// Set return value
Boolean ExistOrNot;

/// Check file is exits
if (File.Exists(DataBaseRoot))
{
ExistOrNot = true;
}
else
{
ExistOrNot = false;
}

return ExistOrNot;
}





/**
* @name CreateDB_Click
*
* When click this button , it will create database and table
*
*
*/
private void CreateDB_Click(object sender, RoutedEventArgs e)
{

/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Flag id database exist
bool FlagIsDBExist = CheckDataBaseExist(DataBaseRoot);


if (FlagIsDBExist)
{
MessageBox.Show("The Database is already exist");
}
else
{
/// Create database and table "BlobTable"
CreateDataBase(DataBaseRoot);
CreateBlobTable(DataBaseRoot);
}

}




/**
* @name Save_Click
*
* When click this button , it will save the image from cumputer to the database
*
*
*/
private void Save_Click(object sender, RoutedEventArgs e)
{


/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;



/// Open FIleStream to transform image to byte array "MyData"
/// @"C:\20090908002chiachunchuang.jpg" is your image root
FileStream fs = new FileStream(@"C:\20090908002chiachunchuang.jpg", FileMode.OpenOrCreate, FileAccess.Read);
byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();


/// Set commend to save the date to database
cmd.CommandText = "INSERT INTO BlobTable VALUES( 'Test', @blobdata)";
/// When using blob type using the commend to let db save blob type
cmd.Parameters.AddWithValue("@blobdata", MyData);

/// Execute the command
cmd.ExecuteNonQuery();

/// Close connect
cnn.Close();

}


/**
* @name Load_Click
*
* When click this button , it get the image from database and show on windows
*
*
*/
private void Load_Click(object sender, RoutedEventArgs e)
{

/// Declare the byte[] to record the image imformation
byte[] MyData=null;

/// Set Database Root
string DataBaseRoot = this.DataBaseRoot;

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + DataBaseRoot);

/// Open connect
cnn.Open();

/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

/// Set commend to get value
cmd.CommandText = "Select * from BlobTable";

/// CommandBehavior -> using System.Data;
/// Read all information
using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{

while (dr.Read())
{
/// Get the value from db
MyData = (Byte[])dr.GetValue(1);

}
}


cnn.Close();



/// Put the image byte[] to MemoryStream
MemoryStream ms = new MemoryStream(MyData);

/// Declare BitmapImage Bi
BitmapImage Bi = new BitmapImage();

Bi.BeginInit();

/// Set Bi source from MemoryStream
Bi.StreamSource = ms;

Bi.EndInit();

/// Set the imageExample's source and it will show on windows
imageExample.Source = Bi;


}





}






}



2009年9月4日 星期五

C sharp 使用 httpRequest 取得 google Auth token

直接使用Google api 來登入 Google 的服務 雖然很方便, 但是每用一次就必須重新驗證一次, 若有要使用很多服務的話也是一件蠻麻煩的事。

所以 Google 提供了一種 ClientLogin 方式的驗證, 讓使用者只要取得一次驗證碼, 之後就不必一直作驗證的動作

以下 是官方的 說明網站

java 範例之前寫過了 見 使用 java http post 取得 google account (AuthSub)

這裡就說明 C# 的方法

輸入 帳號、 密碼即可

會得到 strResponse 如圖, 但我們只要 auth 的驗證碼就好



所以在此用 Split('=') 的方法找出 需要的字串



/**
* @name GetGoogleAuth
*
* Get Google Auth code
* @return string Auth
*/
public string GetGoogleAuth(string Account, string Password)
{
string Auth="";

try
{
/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");

/// Set proxy
SetProxyServer(req);

/// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string strNewValue = "accountType=HOSTED_OR_GOOGLE&Email=" + Account +
"&Passwd=" + Password +
"&service=cl&source=Gulp-CalGulp-1.05";
req.ContentLength = strNewValue.Length;


/// Write the request
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();

/// Do the request to get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();

/// Split string and set token
string[] parts = strResponse.Split('=');

/// Save the Auth Token
/// Auth Token id in the last string
GoogleAuthToken= parts[parts.Length - 1];

stIn.Close();
Auth = GoogleAuthToken;
}
catch
{
Auth = "";
}

return Auth;

}




/**
* @name SetProxyServer
*
* Set the Proxy Server if have Proxy Server
*
*/
public void SetProxyServer(HttpWebRequest req)
{

IWebProxy iProxy = WebRequest.DefaultWebProxy;
/// potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;
req.Proxy = iProxy;
}

2009年8月26日 星期三

Sqlite 檢查 table是否存在

語法如下



SELECT count(*) FROM sqlite_master WHERE type='table' and name='" + TableName+ "'";


這裡的 name 後面接的就是 table name

查詢後會顯示數目, 0表示沒有, 1 表示有, 應該不會有一樣名稱的table 所以只有 0 或 1
兩種


sqlite_master 還有其他的用法

2009年8月14日 星期五

Android BMI DEMO 心得

看了一下 深入淺出android 的 BMI 範例,稍微寫一下心得及結構整理一下 如下圖


2009年8月12日 星期三

C sharp 取得現在檔案位置

用一個簡單的語法就可以取得現在檔案的位置


Directory.GetCurrentDirectory();




也可以使用來取得執行檔案的位置
System.Windows.Forms.Application.StartupPath

兩者的差異
GetCurrentDirectory 會取得現在的資料夾位置,如果是用捷徑的話,就會回傳捷徑所在的資料夾

StartupPath 都是會回傳 程式確切的資料夾位置


詳細可見

http://www.huanghengxu.com/Html/Article/207.htm

2009年8月10日 星期一

C sharp or .Net 使用sqlite : 6(end) update data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

關於其他的SQL 語法,可以參考

update語法 大致如下

UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]
javascript:void(0)



以下是簡單的例子,將id=1 的欄位 取代乘 5



public void UpdateExampleTable(SQLiteCommand cmd)
{

try
{
/// Set drop table command
cmd.CommandText = "Update [tbl] set id=1 where id=5";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("update OK");
}
catch
{
MessageBox.Show("update Error");
}


}


這應該是相關的最後一篇

C sharp or .Net 使用sqlite : 5 delete data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

關於其他的SQL 語法,可以參考

在SQL 相關刪除的語法有3個

delete 刪除特定欄位在某個table

DELETE FROM employee WHERE id = 100;

truncate 刪除所有欄位在某個table

TRUNCATE TABLE employee;

但 SQLite 沒有 truncate 但可以用
DELETE FROM employee 的語法達成同樣效果

drop 刪除整個table


DROP TABLE employee;


以下例子,顯示相關SQLite語法

例一 刪除 table tbl 中 id =3的欄位


public void DeleteExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Delete command
cmd.CommandText = "DELETE FROM [tbl] where id=3";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("delete OK");
}
catch
{
MessageBox.Show("delete Error");
}

}




例二 刪除 table tbl 所有的欄位達成 truncate 的效果



public void DeleteExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Delete command
cmd.CommandText = "DELETE FROM [tbl]";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("delete OK");
}
catch
{
MessageBox.Show("delete Error");
}

}


例三 刪除 table tbl (drop)


public void DROPExampleTable(SQLiteCommand cmd)
{

try
{
/// Set drop table command
cmd.CommandText = "DROP TABLE [table]";
/// Execute the command, iF have not exist show error message
cmd.ExecuteNonQuery();
MessageBox.Show("Drop OK");
}
catch
{
MessageBox.Show("Drop Error");
}


}

C sharp or .Net 使用sqlite : 4 select data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help


以下例子,查詢資料利用Messageshow的方式顯示查詢結果

由於此例只有兩欄,所以就只有 get 0 和 get 1




public void GetDataFromAccountTable(SQLiteCommand cmd)
{
// Set command
cmd.CommandText = "SELECT * FROM [tbl]";

/// CommandBehavior -> using System.Data;
/// Read all information
using (SQLiteDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
/// Read information by each record
/// GetValue(by index), the index is begin 0 to the number of Field-1
while (dr.Read())
{
MessageBox.Show("第"+ dr.GetValue(0)+" 條:" + dr.GetValue(1));
}
}




}

2009年8月6日 星期四

C sharp or .Net 使用sqlite : 3 Insert data

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help


以下例子,將資料寫入前一篇定義的table中

簡單的 Insert data function , 是利用一個for loop 一次輸入 5 筆資料
如下




public void InserDataInAccountTableTest(SQLiteCommand cmd)
{

try
{
for (int i = 0; i < 5; i++){
/// Set Commend
cmd.CommandText = string.Format("INSERT INTO [tbl] VALUES ({0}, 'Test{1}')", i,i);

/// Execute Commend

cmd.ExecuteNonQuery();
}
}
catch{ MessageBox.Show("insert Error");
}
}

C sharp or .Net 使用sqlite :2 Login DB and 新增Table

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteCommand 的變數定義自行參考 SQLite.Net 的 Help

簡單的 login and 新增 table function 如下




public void LoginSqliteDatabase()
{

/// Set Database Root
string DatabaseRoot = "c:\\test.db";

/// Set Database Password
string DB_Password = "password";

/// Open Database
/// Version is sqlite version
SQLiteConnection cnn = new SQLiteConnection("Data Source="+ DatabaseRoot+";"+ "Version = 3; Password ="+DB_Password);

/// Open connect
cnn.Open();


/// Define SQLite Command object
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;

CreatExampleTable(cmd);


}


注意 login 若沒有設定密碼的話,也可以換為以下指令
SQLiteConnection cnn = new SQLiteConnection("Data Source="+ DatabaseRoot+";");




public void CreatExampleTable(SQLiteCommand cmd)
{

try
{
/// Set Creat table command
cmd.CommandText = "create table tbl(one, two)";
/// IF have exist show error message
cmd.ExecuteNonQuery();

}
catch
{
Console.WriteLine("error");
}


}


注意 creat table 指令也可以換為以下格式,定義更多資訊
cmd.CommandText = "CREATE TABLE [tbl] (int, teo nvarchar(20))";

2009年8月5日 星期三

C sharp or .Net 使用sqlite : 1 新增資料庫

步驟主要參考 守望轩-Sqlite数据库的加密

require download System.Data.SQLite 及設定, 可見 C sharp or .Net 使用sqlite 設定

SQLiteConnection的變數定義可參考

簡單的function 如下



public void CreatSqliteDatabase()
{
/// Set Database Root
string DatabaseRoot = "c:\\test.db";

/// Set Database Password
string DB_Password = "password";

/// Check file is exits
/// File.Exists() -> using System.IO;
if (File.Exists(DatabaseRoot))
{
MessageBox.Show("Already exists.");
}
else
{
/// Creat table
SQLiteConnection.CreateFile(DatabaseRoot);

/// Open Database
SQLiteConnection cnn = new SQLiteConnection("Data Source="+DatabaseRoot);

/// Open connect
cnn.Open();

/// Set default Password
cnn.ChangePassword(DB_Password);
}
}

C sharp or .Net 使用sqlite 設定

要在C# 或 .net 環境下使用Sqlite,必須安裝額外的DLL

System.Data.SQLite

SQLite.NET.0.21_x68_dll.zip

下載後,開啟專案

選擇 Project -> Add Reference 好可以 使用 他定義好得函數

使用不同的dll 有不同的 include 方法

  • System.Data.SQLite
using System.Data.SQLite
  • SQLite.NET.0.21_x68_dll.zip
using Finisar.SQLite


此外轉貼上一些例子和教學

為了說明方便,之後文章都以System.Data.SQLite 為例說明

Google Doc Presentation 插入投影片

雖然google Document 是蠻好用的一個工具,但是說真的要在線上編輯還倒是蠻不習慣的,本人我還是習慣在傳統的PPT上編輯在上傳檔案,不過presentation 沒有像 spreadsheet有上傳新版本的功能....,要編輯還算是有些麻煩。

不過在 Presentation 上有一個 插入slide 的功能,可以讓在本機編輯好得投影片,整合在網路上的檔案

步驟如下

1. 點選insert , insert slides


2. 點選insert , insert slides
右側一攔選擇要插入的檔案位置,從在google doc的檔案選取,或由電腦上傳


2-1 由電腦上傳的話要注意 現在不支援pptx的格式


2-2 選擇好了後按的upload



3-1. 選擇要插入的檔案,slide 左下角可以勾選


3-2. 第一頁可以點選全選




雖然還是有點麻煩,但是如果之前有設分享的話就不用重新在設一遍

期待之後可以直接上傳新版本吧...

2009年7月30日 星期四

Google Blogger 縮排技巧


每次用Google blogger 在排版上都會有種困擾,在此提供一個小技巧

就是利用Google Site (協作平台) 的編輯器 修改, 雖然都是google 的 不過 google site 的編寫平台就比較方便

舉例說明 我要將以下的html 程式碼貼到blogger


若是直接貼的話會有以下的錯誤

1. "<" , ">" 是 html 保留字元
2. 縮排會跑掉



而利用google site 步驟如下

1. 打開google site , 在編輯頁面上貼上想要貼的程式碼



2. 點選html標籤,接者google site 編輯器 會自動幫你轉碼





3. 最後將剛才轉好得html碼貼到blogger就好了

結果如下:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"><head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Google Earth JavaScript API Example</title>

</head>

<body   >



<div id="map"  ></div>

<div id="photo" >

     <img id="city-photo" src="" height="100%" width="100%"  /> </div>



  <style>

    #news {background-image: url(Pic/Title.jpg);

           height:100px;

           background-position : right;

           }

  </style>

<div id="news" name="news" ">load...  </div>



</body></html>




雖然還是有點麻煩,但比我之前用純文字加html編輯好用的多

2009年7月28日 星期二

Google Api in .Net 實做

以下我是用 VS2008 和 win XP 為環境做的簡單程式


基本上照這裡的步驟就OK 了, 教學網址


流程
1. 下載 Google Data API Setup.msi .NET Client Library 現在是(1.4.0.2 )
2. 開啟新專案, 這裡我是用 WPF 的專案, 不過沒有差別,基本上都是用C#寫(.CS檔)
3. Add Reference 如圖

4. 選擇Browse tag , 尋找Google api SDK 的路徑 , 預設都會將相關的DLL在 C:\Program Files\Google\Google Data API SDK\Redist


5. 選擇要引用的DLL, 這裡要用的有 Google.GData.Client.dll, Google.GData.Extensions.dll 這兩個DLL , 此外, 因為是以 Calendar 為範例 所以也要引用 Google.GData.Calendar.dll

6. 引用完這些DLL , 但還會無法執行,因為驗證沒過,所以 必須還要在引用 Google.GData.AccessControl.dll


在這個簡單例子我是用這個 UI , 按一下 click me 就會顯示google Calendar 的日曆清單


code 如下

//-------------------------------------------------------
// Window1.xaml.cs
//-------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;

namespace WPFGoogle
{

/// Interaction logic for Window1.xaml

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}


void button_Click(object sender, RoutedEventArgs e)
{

CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("Your@gmail.com", "YourPassword");

CalendarQuery query = new CalendarQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/allcalendars/full");

String Temp;

CalendarFeed resultFeed = myService.Query(query);

/// Get calnedars List
Temp = "Your calendars:\n";
foreach (CalendarEntry entry in resultFeed.Entries)
{
Temp = Temp + entry.Title.Text + "\n";

}

/// Show the Message
MessageBox.Show(Temp);


}

}
}


萬一需要設定 proxy 則 必須 修改 code 如下

//-------------------------------------------------------
// Window1.xaml.cs
//-------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;

using System.Net;

namespace WPFGoogle
{

/// Interaction logic for Window1.xaml

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}


void button_Click(object sender, RoutedEventArgs e)
{

CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("Your@gmail.com", "YourPassword");

CalendarQuery query = new CalendarQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/allcalendars/full");


/// Set proxy

GDataRequestFactory requestFactory = (GDataRequestFactory)myService.RequestFactory;

IWebProxy iProxy = WebRequest.DefaultWebProxy;

WebProxy myProxy = new WebProxy(iProxy.GetProxy(query.Uri));

// /potentially, setup credentials on the proxy here

myProxy.Credentials = CredentialCache.DefaultCredentials;

myProxy.UseDefaultCredentials = true; requestFactory.Proxy = myProxy;





String Temp;

CalendarFeed resultFeed = myService.Query(query);

Temp = "Your calendars:\n";
/// Get calnedars List
foreach (CalendarEntry entry in resultFeed.Entries)
{
Temp = Temp + entry.Title.Text + "\n";

}

/// Show the Message
MessageBox.Show(Temp);


}

}
}