2010年12月28日 星期二

Spring MVC Demo

最近研究了一下 Spring MVC 的架構

大該了解基本的用法

在此分享 Spring MVC Demo 程式

DemoWeb 架構以
Spring MVC + Hibernate + Annotation
為主架構, 是目前業界還滿流行的架構之一, 如果前端想使用JQuery也是沒問題
的, 至於後端 DB 的話因為是使用 Hibernate 做為 ORM, 所以基本上並不會有
Databases Dependency 的問題, 只要找到相關 DB 的 JDBC 就可以切換了

請點選下載 DemoWeb 程式
或至 DemoWeb (github) 下載程式

開發工具為 SpringSource Tool Suite

DemoWeb 所用的 Databases 目前有二種, 可任選其中一種作測試
1. 設定 SQLite (DemoWeb程式預設)
  a. 將 DemoWeb 下載解壓後, 資料夾下有一個 SQLite DB 檔 demowebdb.db3
  b. 將 demowebdb.db3 檔放至 C:\DemoWebDB\ 資料夾下就可以了

2. 設定 MySQL
  a. 將 DemoWeb 下載解壓後, 資料夾下有一個 demowebdb_schema.sql
  b. 執行此 SQL 檔後, 將會建立 demowebdb
  c. 開啟 WEB-INF\jdbc.properties 檔, 更改 MySQL 登入的 UserName 跟
      Password 參數
# MySQL Setting
datasource.mysql.driverClassName=com.mysql.jdbc.Driver
datasource.mysql.dialect=org.hibernate.dialect.MySQLDialect
datasource.mysql.demowebdb.url=jdbc:mysql://localhost:3306/demowebdb?useUnicode=true&characterEncoding=UTF-8
datasource.mysql.demowebdb.username=xxxxx
datasource.mysql.demowebdb.password=xxxxx
...
   d. 開啟 WEB-INF\spring\appServlet\servlet-context.xml 檔, 更改
       DataSource 的參數, 先找到以下區段
...
<beans:bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
  <beans:property name="driverClass" value="${datasource.sqlite.driverClassName}"/>
  <beans:property name="jdbcUrl" value="${datasource.sqlite.demowebdb.url}"/>
  <beans:property name="user" value="${datasource.sqlite.demowebdb.username}"/>
  <beans:property name="password" value="${datasource.sqlite.demowebdb.password}"/>
</beans:bean>
...
      修改成
...
<beans:bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
  <beans:property name="driverClass" value="${datasource.mysql.driverClassName}"/>
  <beans:property name="jdbcUrl" value="${datasource.mysql.demowebdb.url}"/>
  <beans:property name="user" value="${datasource.mysql.demowebdb.username}"/>
  <beans:property name="password" value="${datasource.mysql.demowebdb.password}"/>
</beans:bean>
...

    再來就是執行程式作測試啦!!!!

2010年12月21日 星期二

Serializing Python Objects

此篇文章主要說用Python的Pickle module功能

1. 序列化(Serialization)
    將Python Object序列化時, 可使用pickle module的dumps方法
    ex.
>>> import pickle
>>> x = {'name':'allen', 'sex':'boy'}
>>> xs = pickle.dumps(x)
>>> xs
"(dp0\nS'name'\np1\nS'allen'\np2\nsS'sex'\np3\nS'boy'\np4\ns."

2. 反序列化(Deserialize)
    將序列化後的資料反序列化時, 可使用pickle module的loads方法
    ex.
>>> xsa = pickle.loads(xs)
>>> xsa
{'name': 'allen', 'sex': 'boy'}

3. 序列化(Serialization)至檔案
    如果要將 Python Object 序列化後資料儲存至檔案時,
    可使用 pickle module 的 dump 方法
    ex.
>>> import pickle
>>> x = {'name':'allen', 'sex':'boy'}
>>> f = open('c:/pyreadfile.txt', 'wb')
>>> pickle.dump(x, f)
>>> f.close()

4. 檔案反序列化(Deserialize)
    如果要將序列化的檔案反序列化時,
    可使用 pickle module 的 load 方法
    ex.
>>> f = open('c:/pyreadfile.txt', 'rb')
>>> a = pickle.load(f)
>>> f.close()
>>> print a
{'name': 'allen', 'sex': 'boy'}

參考網站
Saving a Python dict to a file using pickle
[python] 不錯的玩意, pickle與 shelve

2010年11月29日 星期一

Python 2.7 Connect MySQL

依序下載程式安裝
1. Python 2.7
2. SetupTools 2.7
3. MySQL-python 1.2.3 for windows and python 2.7

測試 Connect MySQL 是否可運作
1. 開啟 Python 2.7 IDLE
2. 編輯測試程式
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost", user="xxxx", passwd="xxxx", db="xxxx")
>>> cursor = db.cursor()
>>> cursor.execute("select * from system_user")
2L
>>> result = cursor.fetchall()
>>> for record in result :
        print record[0]


USERE00000000000000000001
USERE00000000000000000002
>>>

2010年10月25日 星期一

Android XmlRpc Remote Service Problem

測試 Android 系統使用 XmlRpc 呼叫遠端的服務時遇到二個問題

1. java.net.SocketExeption: Permission denied
2. localhost connection refused

第一個問題是因為在Android Application中沒有開啟 Internet 使用權限
解決方法是在 Manifest檔內加上
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
就可以正常運作

第二個問題是因為在 Android Simulator 把自己作為 localhost 了,
所以如果在程式中寫 localhost 要連至本機的 Server 將會出現此問題
如果要連至本機的 Server 就必需將 IP 設為 10.0.2.2


參考網站
java.net.SocketException:Permission denied
localhost connection refused

2010年10月12日 星期二

JDBC for Sqlite DB

1. 下載必要的Jar檔
     sqlite-jdbc-3.7.2 可至 Xerial 下載使用

2. 建立好Sqlite DB後, 將Sqlite的DB檔放至某處 (ex. C:\test.db)

3. 用以下的程式碼測試


String url = "jdbc:sqlite://C:\\test.db";
try {
  Class.forName("org.sqlite.JDBC");
  Connection con = DriverManager.getConnection(url);
  String query = "select * from test_T";
  Statement stmt = con.createStatement();
  con = DriverManager.getConnection(url);
  ResultSet rs = stmt.executeQuery(query);
  while (rs.next()) {
    out.print(rs.getString("Id")+"&nbsp;"+rs.getString("Password")+"<br/>");
  }
  rs.close();
  stmt.close();
} catch (Exception e) {
  e.printStackTrace();
  out.print(e.getMessage());
}


p.s. 記得 import 相關的 class 檔
ex.
import java.sql.Connection;
import java.sql.*;
import org.sqlite.JDBC;

以上是一個簡易的Sqlite連線

2010年9月26日 星期日

Mac OS Server 服務的相關 Port

Remote Login (SSH) - 22
Screen Sharing Service (VNC) - 5900
AddressBook Service - 8800, 8843
iChat Service - 5222, 5223, 5060, 5269, 7777
Mail Service (SMTP, IMAP, POP) - 25, 110, 143, 587, 993, 995
Web Service - 80, 443
VPN Service (L2TP) - 500, 1701, 4500
VPN Service (PPTP) - 1723
File Sharing Service (AFP, SMB) - 548, 139

參考URL
http://support.apple.com/kb/TS2963

2010年9月16日 星期四

Setting Debugging PHP with Xdebug

1. download xdebug 

2. copy xdebug's dll to php\ext\ (ex. C:\Program Files\PHP\ext)

3. modify php.ini add xdebug define (if xdebug's dll name is php_xdebug-2.0.5-5.2.dll)
    zend_extension_ts="C:\Program Files\PHP\ext\php_xdebug-2.0.5-5.2.dll"
    xdebug.remote_enable=1 
    xdebug.remote_handler=dbgp 
    xdebug.remote_host=127.0.0.1 
    xdebug.remote_port=9000 
    xdebug.remote_mode=req 
    xdebug.idekey=default 
    xdebug.remote_log="c:\tmp\xdebug\xdebug.log" 
    xdebug.show_exception_trace=0 
    xdebug.show_local_vars=9 
    xdebug.show_mem_delta=0 
    xdebug.trace_format=0 
    xdebug.profiler_enable  = 1 
    xdebug.profiler_output_dir ="c:\tmp\xdebug"

4. Make sure you create the folder c:\tmp\xdebug\

5. restart apache

6. look phpinfo()
  















Reference URL : http://www.webcheatsheet.com/php/debug_php_with_xdebug.php

2010年9月4日 星期六

設定Input只能輸入數值


在Script Tag之中加入限制的方法

<Script>

...

$(function() 
{
$('#InputID').bind('keypress', filterWithOutNumber)
});



//限制只能輸入數值的方法
function filterWithOutNumber(e) 
{
if(e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
return false;
else
return true;
}

...

</Script>

<body>
<Input type="text" id="InputID"></Input>
</body>


2010年8月12日 星期四

How to Delete a Windows Service

Command 語法如下
    sc delete [ServiceName]

Ex.
    sc delete "GlassfishService"

2010年7月27日 星期二

c3p0 的屬性設定

acquireIncrement 
    當Connection Pool中的連線用盡時所批次新增Connection的數量. Default: 3

acquireRetryAttempts 

    定義從Databases取新Connection時失敗後重覆嘗試次數. Default: 30


acquireRetryDelay 
    兩次連接中間隔時間, 單位毫秒. Default: 1000


autoCommitOnClose 
    Connection Close時預設將所有未Commit的交易RollBack. Default: false


automaticTestTable
    c3p0將建立一個名為Test的空資料表, 並使用其自帶的查詢語句進行測試.
    如果定義了這個參數那麼屬性preferredTestQuery將被忽略. 無法在此Test
    資料表進行任何作業, Test只提供c3p0測試使用. Default: null


breakAfterAcquireFailure
    取Connection失敗將會引起所有等待Connection Pool來取Connection的
    Thread拋出異常.但是Databases仍有效保留, 並在下次調用getConnection()
    的時候繼續嘗試取得Connection, 如果設為true, 那麼在嘗試取Connection
    失敗後該DataSource將申明已斷開並永久關閉. Default: false


checkoutTimeout
    從Connection Pool等待取得新的Connection的時間, 超過此時間後, 將拋
    出SQLException, 如設為0則無限期等待. 單位毫秒. Default: 0


connectionTesterClassName
    通過實現Connection Tester或QueryConnectionTester的類別來測試
    Connection. 類別名稱需為全路徑. 
    Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester


factoryClassLocation
    指定c3p0 Libraries的路徑, 如果在Local端就無需設定, 預設null即可, 
    Default: null


forceIgnoreUnresolvedTransactions
    Strongly disrecommended. Setting this to true may lead to 
    subtle and bizarre bugs. 


idleConnectionTestPeriod
    設定每多少秒檢查所有Connection Pool中的閒置Connection. 
    Default: 0


initialPoolSize
    初始化時建立多少Connection, 值應在minPoolSize與maxPoolSize之間
    , Default: 3


maxIdleTime
    最大閒置時間, 每多少秒內未使用Connection則丟棄. 若為0則永不丟棄. 
    Default: 0


maxPoolSize
    Connection Pool中保留最大Connection Count. Default: 15


maxStatements
    JDBC的標準參數, 用來控制Datasource內加載的PreparedStatements
    數量. 如果maxStatements與maxStatementsPerConnection均為0, 
    則暫存被關閉. Default: 0


maxStatementsPerConnection
    定義Connection Pool內單個Connection所擁有的最大暫存statements
    數. Default: 0


numHelperThreads
    c3p0是非同步操作的, 緩慢的JDBC操作通過幫助程式完成. 擴展這些操作
    可以有效的提升性能通過Thread實現多個操作同時被執行. Default: 3


overrideDefaultUser
    當用戶調用getConnection()時使用root用戶成為去取Connection的用戶.
    主要用於Connection Pool 連接非c3p0的Datasource. Default: null


overrideDefaultPassword
    與overrideDefaultUser參數對應使用的一個參數. Default: null


password
    密碼. Default: null


preferredTestQuery
    定義所有Connection測試都執行的測試語法, 注意:測試的表必須在初始
    Datasource的時候就存在. Default: null


propertyCycle
    用戶修改系統配置參數執行前最多等待的秒數, Default: 300


testConnectionOnCheckout
    如果設為true那麼在每個Connection Commit的時候都將驗證有效性. 建
    議使用idleConnectionTestPeriod或automaticTestTable等方法來提升
    連接測試的性能Default: false


testConnectionOnCheckin
    如果設為true那麼在取得連接的同時將驗證連接的有效性. Default: false


user
    用戶名. Default: null

2010年6月7日 星期一

Setting Access Log for Tomcat

打開 Tomcat 下的 Server.xml
新加入二個 Tag

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="combined" resolveHosts="false"/>

<Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="localhost_log." suffix=".txt" timestamp="true"/>

重新啟動 Tomcat

瀏覽 Tomcat 網站後

在 log forder 下將會出現 access log file

2010年5月27日 星期四

MySQL 資料庫備份與復原

備份作業

語法 mysqldump -u [帳號] -p [資料庫名稱] > [備份檔案名稱]
Ex.
    mysqldump -u root -p smilelight > smilelightdb.sql

復原作業

語法 mysql -u [帳號] -p [資料庫名稱] < [備份檔案名稱]
Ex.
    mysql -u root -p smilelight < smilelightdb.sql

2010年5月24日 星期一

Import Sql File For Mysql

匯入Sql File的語法

cmd 下輸入
mysql -p -u root smilelight < smilelight.sql

Enter後輸入密碼
就會開始執行Sql File的指令

2010年5月4日 星期二

開發佈署 Windows Service 程式

A. 建立 Windows Service Project
B. 建立 Windows Service Project Install 
C. 建立安裝佈署程式 


A. 建立 Windows Service Project 
A-1. 建立 → 專案
A-2. 專案類型選擇 Windows 服務
A-3. 在專案中的Service1.cs上按滑鼠右鍵, 點選檢視程式碼(C)
A-4. 程式碼中的OnStart方法內輸入
        EventLog.WriteEntry(“啟動了Service”);
A-5. 程式碼中的OnStop 方法內輸入
        EventLog.WriteEntry(“停止了Service”); 
















B. 建立 Windows Service Project Install 
B-1. Service1.cs的設計頁面中按滑鼠右鍵, 加入安裝程式
B-2. 在專案中將會新增一個ProjectInstaller.cs檔案,
        開啟ProjectInstaller.cs設計頁面
B-3. 點選 serviceProcessInstaller1元件的屬性頁中,
        將account屬性設為LocalSystem
B-4. 點選 serviceInstaller1元件的屬性頁中, ServiceName
        為服務的名稱,如果想要在開機時自動啟動Service的
        話, 請將StartType更改為Automatic

















C. 建立安裝佈署程式 
C-1. 檔案 → 加入 → 新增專案
C-2. 選擇安裝和部屬類中的安裝專案
C-3. 新增的安裝佈署專案中按滑鼠右鍵 → 加入 → 專案輸出
C-4. 下拉選單中選擇一開始建立的Service Project, 再選擇主
         要輸出, 按下確定
C-5. 安裝佈署專案中按滑鼠右鍵 → 檢視 → 自訂動作
C-6. 自訂動作中按滑鼠右鍵 → 加入自訂動作 → 應用程式資
         料夾 → 確定
C-5. 建置安裝佈署專案
C-6. 建置成功後, 安裝佈署專案中按滑鼠右鍵 → 安裝
C-7. 安裝成功後, 至服務中將會看見剛剛建立完成的Service,
         將它啟動
C-8. 至事件檢視器中將可看見剛剛程式碼中寫到EventLog的訊息


2010年4月6日 星期二

Mantis's upload file to disk and setting max size

要讓Mantis有upload的機制有以下幾個地方要修改

1. mantis 的config_inc.php 檔
    新增以下參數
   // 開啟upload 機制
   $g_allow_file_upload = ON; 
   // 設定上傳最大檔案容量, 20M
   $g_max_file_size = 20000000; 
   // 設定上傳型態, 預設是DATABASE
   // 可設定成 DATABASE, DISK, FTP 三種型態
   $g_file_upload_method = DISK;

2. php.ini 的設定
   ;script最大執行時間
   max_execution_time = 300 ; 
   ;最大上傳檔案容量
   upload_max_filesize = 20M ; 
   ;post可接受最大容量
   post_max_size= 20M;

3. 設定mantis內project的檔案上傳路徑
   先在mantis web site中新增一個upload資料夾
   再到mantis內編輯project的檔案上傳路徑
   









4. 完成以上設定, 將可以上傳檔案至mantis中

參考網站


Image.save 發生 "在 GDI+ 中發生泛型錯誤" 解決方法

一開始在載入圖檔時, 如果是用以下的方式載入的話, 檔案會被鎖定
    Image image = Image.FromStream(fileStream);
而之後想要另存此圖檔時將發生 "在 GDI+ 中發生泛型錯誤"

解決辦法是用以下方式載入圖檔
    Image image = Image.FromFile(filePath);
此方法能解決無法另存新檔的問題

參考網站
http://blog.miniasp.com/post/2009/05/A-generic-error-occurred-in-GDI-plus.aspx
http://social.msdn.microsoft.com/Forums/zh-TW/233/thread/8b3f6406-7ae4-46d0-865c-fed7243f9189

2010年3月19日 星期五

Devexpress's XtraGrid 客制顯示圖檔

1. 設定要顯示圖檔的欄位屬性
    FieldName 設為 "Image" 或其它值, 只要與其它的欄位值不相同就好
    UnboundType 設為 Object
    ColumnEdit 選擇 RepositoryItemPictureEdit 元件 (支援 Image 顯示)

2. 設定 XtraGrid 的 CustomUnboundColumnData Event Method

3. 在 CustomUnboundColumnData Method 內做處理
    Ex.
if (e.Column.FieldName == "Image" && e.IsGetData) { GridView view = sender as GridView; //取資料列欄位Path值 string path = (string)view.GetRowCellValue(e.RowHandle, "Path"); //取資料列欄位PhotoName值 string photoName = (string)view.GetRowCellValue(e.RowHandle, "PhotoName"); string photoNamePath = path + photoName; if (!Images.ContainsKey(photoNamePath)) { Image img = Image.FromFile(photoNamePath); Images.Add(photoNamePath, img); } e.Value = Images[photoNamePath];               }
4. 此方式將可以客制欄位的輸出值

2010年3月16日 星期二

Create Databases Command For MySql

利用 Command 建立 Databases

CREATE DATABASE [DatabasesName]
DEFAULT CHARACTER
SET utf8
COLLATE utf8_general_ci;

Ex.
  CREATE DATABASE TaipeiPotoAssociation
  DEFAULT CHARACTER
  SET utf8
  COLLATE utf8_general_ci;

2010年3月8日 星期一

Flex HttpService Cache 資料問題

最近因為Flex HttpService Cache困擾了很久
因為Cache的關係, 在Flex第一次 load 之後, 就不會再到後端 Server load 資料
會以第一次取回的資料做處理
目前找到比較好的解決方法
暫時在Url裡傳入一個隨機產生變數

Ex.
var _random:String=(Math.floor(Math.random()*10000000*10)>>0).toString();
        
authService = new HTTPService();
authService.url = "UserInfoAction.action";
authService.method = "POST";
authService.useProxy = false;
authService.resultFormat = "e4x";
var parameters:* =
{
  "random": _random
}      
authService.addEventListener(ResultEvent.RESULT, handleResult);      
authService.send(parameters); 
這樣子基本上可以先暫時解決 HttpService Cache 的問題

2010年3月3日 星期三

Use Servlet Download File

Source Code Refrence :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      
request.setCharacterEncoding("UTF-8");

String filename = (String)request.getParameter("filename");
String original_filename = (String)request.getParameter("original_filename");
                ServletOutputStream op = response.getOutputStream();
                ServletContext context  = getServletConfig().getServletContext();
                String realFileNamePath = context.getRealPath(filename);
    
File f = new File(realFileNamePath);
                int length = 0;
  
                response.setContentType("application/octet-stream");
                response.setContentLength( (int)f.length() );
                response.setHeader( "Content-Disposition",
                                                      "attachment; filename=\"" + original_filename + "\"" );

               byte[] bbuf = new byte[1024];
               DataInputStream in = new DataInputStream(new FileInputStream(f));

               while ((in != null) && ((length = in.read(bbuf)) != -1))
               {
                     op.write(bbuf,0,length);
               }

               in.close();
               op.flush();
               op.close();
}

2010年3月2日 星期二

Tomcat Setting Server.xml's URIEncoding

like









let tomcat can parse UTF-8 URL

2010年2月25日 星期四

MySQL Like SQL Server With Nolock Use

  • Session Scope
          SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
          SELECT * FROM TABLE_NAME ;
          SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
  • Global Scope
          SET GLOBAL TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

  • Isolation Level Variables
          SELECT @@global.tx_isolation;
          SELECT @@tx_isolation;

2010年2月24日 星期三

將中文(UTF-8) 寫入MySQL DB for Java Servlet

1. get request parameter before set Encode
    request.setCharacterEncoding("UTF-8");

2. add connection string parameter
    useUnicode=true&characterEncoding=UTF-8
  
    Ex.
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/demo?
               useUnicode=true&characterEncoding=UTF-8", "userid", "password");

2010年2月8日 星期一

How about send sample mail use telnet

1. telnet smtp server








2. enter command step
    a. HELO <domain>
    b. MAIL FROM:<address>
    c. RCPT TO:<address>
    d. DATA
    e. SUBJECT:<mail title>
     f. <mail body>
    g. CRLF period CRLF
    h. QUIT

2010年2月5日 星期五

取得Web Site在Server端真正的路徑

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
   ...
   ServletContext context = getServletContext();
   String path = context.getRealPath("/");
   ...
}

2010年2月2日 星期二

Create Enterprise Architect Database

1. Create New Database







































2. Execute EA SQL Script
    download file : EA Database SQL Script




















3. Check EA DataBase Table List






















4. Create EA New Project

































5. Tools -> Data Management -> Select Project Transfer...















6. Select EAP to DBMS



















7. Select EAP File



















8. Select Database Connect





















9. Click Transfer Button



















10. Input Database Connect Password