2012年2月17日 星期五

AJAX學習筆記

市面上常用的瀏覽器很多

設計一個AJAX網站

為了讓所有使用者都可以正常瀏覽

就需要判別目前使用的瀏覽器

用其所定義的XMLHttpRequest物件

if (window.XMLHttpRequest)
{// 如果是 Mozilla, Safari,...
  http_request = new XMLHttpRequest();
} 
else if (window.ActiveXObject)
{// 如果是 IE
  try
  {// IE 又分成新版和舊版的,其處理方式也不同
   // 新版的 IE
    http_request = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
    try
    {// 舊版的 IE
      http_request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) {}
  }
}



建立好XMLHttpRequest物件之後

開始跟web server要資料

http_request.open("GET/POST", "資源URL", true/false);
http_request.send([參數]);

參數說明:
open()
一、GET/POST是看web server支援情況
二、資源只可存取於同一個web server,指定其完整的URL
三、是否非同步,true可在資源傳送完成前執行其他動作

send()
GET直接帶null
http_request.send(null);

如果用POST
需定義MIME類型及URL參數
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send("[id1]=[value1]&[id2]=[value2]&[id3]=[value3]&...");



既然是非同步

那麼在發送我們要哪些資源前

需要先做好"完成資源傳送"的事件處理函數

http_request.onreadystatechange = function()
{
  // 要執行的事件函數
};



可以用readyState得知送出的http_request處理狀況
0 未初始化:未呼叫open()
1 載入中:未呼叫send()
2 載入完成:server以接收,可以取得content header
3 資源傳送中:可以取得部分傳送完成的資源
4 完成:資源已傳送完成

以及states得知處理結果
請檢視HTTP Status Codes ( 狀態碼 )

if (http_request.readyState == 4)
{
  if (http_request.status == 200)
  {
    // 可以依照我們的需求來處理資源了
  }
  else
  {
    // 自行決定要如何處理錯誤的情形
  }
}



資源都傳送完成了

就可以開始接收與處理資源

http_request 提供兩種方式來存取資料:
http_request.responseText:回傳的資料為字串,需利用字串的處理函數。
http_request.responseXML :回傳的資料為XMLDocuemnt,可利用JavaScript的DOM APIs來存取這份XML物件。

回aspnet目錄
回html目錄
回C#目錄
回首頁

2012年2月16日 星期四

直接連接SQL MDF檔

在資料庫上建資料表

再連結資料庫使用是非常基本用法

但是如果設計與SERVER是不同台電腦時

不可能每次修改資料庫都重新匯入進去

時間上浪費許多


這邊需要安裝相對應的SQL Server 200X Express

2008 R2
SQLEXPR_x64_CHT.exe
SQLEXPR_x86_CHT.exe
SQLEXPR32_x86_CHT.exe

2008
SQLEXPRWT_x64_CHT.exe
SQLEXPRWT_x86_CHT.exe

2005
SQLEXPR_CHT.EXE

再配合

上一篇SqlConnection.ConnectionString 屬性


其中一項參數
AttachDbFilename
-或-
Extended Properties
-或-
Initial File Name

簡單來說

這是用來設定想要連接的資料庫相對或絕對路徑


但是要注意

1.
該台SERVER還是要安裝SQL SERVER

而且需要支援指定的MDF版本

2.
此時的Data Source是要設定此SERVER上SQL的資料庫掛載位置


參數解說:

<add name="ConnectionString" connectionString="Data Source=[SQL位置];AttachDbFilename=[MDF位置];Initial Catalog=[SQL名稱];Integrated Security=True" providerName="System.Data.SqlClient"/>

[SQL位置]:要掛載在哪個SQL伺服器上(.\SQLSERVER)


[MDF位置]:欲掛載的資料庫,可用絕對位置(C:\MyData\Data.mdf)或網頁App_Data目錄內(|DataDirectory|\Data.mdf)


[SQL名稱]:掛載後的資料庫名稱


在掛載時,切記版本不可高於電腦SQL SERVER所能支援的版本

當掛載不支援會顯示

舉個範例
顯示問題:因為版本為 661。這個伺服器支援 655 及更早的版本。不支援降級路徑。
這是將  SQL Server 2008 R2 版本的資料庫,佈署、附加到 SQL Server 2008 版本的環境上。
程式設計師的開發環境,安裝的是 SQL Server 2008 R2 版本,但是客戶端伺服器機器是:SQL Server 2008 版本。
基本上,在新版本 SQL Server 上的資料庫,是沒辦法直接使用附加、還原的方式,將資料庫搬移到舊版本的 SQL Server 上。


也提醒各位:
SQL Server 2008 R2 與 SQL Server 2008 是不同的版本;SQL Server 2008 R2 是目前最新的版本。

較新版本的資料庫是無法在舊版上使用的。

以下提供查詢 SQL Server 以及資料庫的版本資訊之方式:
USE master
GO
SELECT SERVERPROPERTY('ProductVersion') AS'執行個體的版本'
 SERVERPROPERTY('ProductLevel') AS'執行個體的版本層級',
 DATABASEPROPERTYEX('master','Version') AS'資料庫的內部版本號碼'


以下是已知的各 SQL Server 所用的資料庫版本號:
SQL Server 2005     :database version 611
SQL Server 2008     :database version 655
SQL Server 2008 R2:database version 661

若是將 SQL Server 2008 版本的資料庫,附加到 SQL Server 2008 R2 版本上。
也就是說:
將舊版的資料庫,附加到新版本的 SQL Server 上,將會看到以下類似的訊息:

將資料庫 'DB1' 從版本 655 轉換為目前版本 661。
資料庫 'DB1' 正在執行從版本 655 升級到版本 660 的步驟。
資料庫 'DB1' 正在執行從版本 660 升級到版本 661 的步驟。
--
Converting database 'DB1' from version 655 to the current version 661.
Database 'DB1' running the upgrade step from version 655 to version 660.
Database 'DB1' running the upgrade step from version 660 to version 661.

回aspnet目錄
回sql目錄
回首頁

2012年2月10日 星期五

HTTP Status Codes ( 狀態碼 )

最近因為大量擷取網路資料,需要利用 Http Request 類別擷取資料,在這期間不斷切換 Proxy server ( 代理伺服器 ),但是會碰到一些 Http Status Codes,除了 200 - 成功 之外,其他都看不懂,所以 google 了一下,列出 Http Status Codes 供大家參考。

HTTP CODES - 100-101

100 - Continue ( 繼續 )
Tells the client that the first part of the request has been received and that it should continue with the rest of the request or ignore if the request has been fulfilled.

101 - Switching Protocols ( 切換通訊協定 )
Tells the client that the server will switch protocols to that specified in the Upgrade message header field during the current connection.



HTTP CODES 200-206

200 - OK ( 確定。 用戶端要求成功 )
The request sent by the client was successful.

201 - Created ( 已建立 )
The request was successful and a new resource was created.

202 - Accepted ( 已接受 )
The request has been accepted for processing, but has not yet been processed.

203 - Non-Authoritative Information ( 非授權資訊 )
The returned meta information in the entity-header is not the definitive set as available from the origin server.

204 - No Content ( 無內容 )
The request was successful but does not require the return of an entity-body.

205 - Reset Content ( 重設內容 )
The request was successful but the User-Agent should reset the document view that caused the request.

206 - Partial Content ( 部分內容 )
The partial GET request has been successful.



HTTP CODES 300-307

300 - Multiple Choices
The requested resource has multiple possibilities, each with different locations.

301 - Moved Permanently ( 要求的網頁已經永久改變網址 )
The resource has permanently moved to a different URI.

302 - Found ( 物件已移動,並告知移動過去的網址 )
The requested resource has been found under a different URI but the client should continue to use the original URI.

303 - See Other ( 通知 Client 連到另一個網址去查看上傳表單的結果(POST 變成 GET),當使用程式作網頁轉向時,會回應此訊息 )
The requested response is at a different URI and should be accessed using a GET command at the given URI.

304 - Not Modified ( 未修改 )
The resource has not been modified since the last request.

305 - Use Proxy ( 要求的網頁必須透過 Server 指定的 proxy 才能觀看 ( 透過 Location 標頭 ) )
The requested resource can only be accessed through the proxy specified in the location field.

306 - No Longer Used ( (未使用) 此代碼僅用來為了向前相容而已 )
Reserved for future use.

307 - Temporary Redirect ( 暫時重新導向 )
The resource has temporarily been moved to a different URI. The client should use the original URI to access the resource in future as the URI may change.



HTTP CODES 400-417

400 - Bad Request ( 錯誤的要求 )
The syntax of the request was not understood by the server.

401 - Not Authorised ( 拒絕存取 )
The request needs user authentication

402 - Payment Required
Reserved for future use.

403 - Forbidden ( 禁止使用 )
The server has refused to fulfill the request.

404 - Not Found ( 找不到 )
The document/file requested by the client was not found.

405 - Method Not Allowed ( 用來存取這個頁面的 HTTP 動詞不受允許 (方法不受允許) )
The method specified in the Request-Line is not allowed for the specified resource.

406 - Not Acceptable ( 用戶端瀏覽器不接受要求頁面的 MIME 類型 )
The resource requested is only capable of generating response entities which have content characteristics not specified in the accept headers sent in the request.

407 - Proxy Authentication Required ( 需要 Proxy 驗證 )
The request first requires authentication with the proxy.

408 - Request Timeout
The client failed to sent a request in the time allowed by the server.

409 - Conflict
The request was unsuccessful due to a conflict in the state of the resource.

410 - Gone
The resource requested is no longer available and no forwarding address is available.

411 - Length Required
The server will not accept the request without a valid Content-Length header field.

412 - Precondition Failed ( 指定條件失敗 )
A precondition specified in one or more Request-Header fields returned false.

413 - Request Entity Too Large ( 要求的實體太大 )
The request was unsuccessful because the request entity is larger than the server will allow.

414 - Request URI Too Long ( 要求 URI 太長 )
The request was unsuccessful because the URI specified is longer than the server is willing to process.

415 - Unsupported Media Type ( 不支援的媒體類型 )
The request was unsuccessful because the entity of the request is in a format not supported by the requested resource for the method requested.

416 - Requested Range Not Satisfiable ( 無法滿足要求的範圍 )
The request included a Range request-header field, and not any of the range-specifier values in this field overlap the current extent of the selected resource, and also the request did not include an If-Range request-header field.

417 - Expectation Failed ( 執行失敗 )
The expectation given in the Expect request-header could not be fulfilled by the server.



HTTP CODES 500-505

500 - Internal Server Error ( 內部伺服器錯誤 )
The request was unsuccessful due to an unexpected condition encountered by the server.

501 - Not Implemented ( 標頭值指定未實作的設定 )
The request was unsuccessful because the server can not support the functionality needed to fulfill the request.

502 - Bad Gateway ( Web 伺服器在作為閘道或 Proxy 時收到無效的回應 )
The server received an invalid response from the upstream server while trying to fulfill the request.

503 - Service Unavailable ( 服務無法使用。 這是 IIS 6.0 專用的錯誤碼 )
The request was unsuccessful to the server being down or overloaded.

504 - Gateway Timeout ( 閘道逾時 )
The upstream server failed to send a request in the time allowed by the server.

505 - HTTP Version Not Supported ( 不支援的 HTTP 版本 )
The server does not support or is not allowing the HTTP protocol version specified in the request.

引用: HTTP Status Codes
網頁開發人員應了解的 HTTP 狀態碼


回目錄
回首頁

2012年2月5日 星期日

ASP.NET 讓上一頁無效

ASP.NET 中,送出資料後轉移頁面,若回上一頁沒有做任何處理,則可以再次的送出表單。

參考網址:讓Browser的「上一頁」無效(網頁已過期)

解決方法:

if (!this.IsPostBack)
{
    //# 設定此頁面不留Cache,讓上一頁無法回來。
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    //## 初始化畫面。
    ......
}

回目錄
回首頁


ASP.NET 避免重新整理頁面資料被重複送出

最近做了一個頁面,遇到一個有與金額處理的頁面,當按鈕按下,資料送出並顯示結果,頁面在同一頁,如果此時按下重新整理,資料會再度的被送出。



解決的方法請參考以下網址:ASP.NET 如何避免頁面重新整理時重複送出

我這裡在再簡單註記一下解決流程:

1. 建立一個類別 BasePage.cs,首先繼承 System.Web.UI.Page,接著在其中新增幾個函式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


/// <summary>
/// BasePage 的摘要描述
/// </summary>
public class BasePage : System.Web.UI.Page
{
    public BasePage() 
    { this.PreRender += new EventHandler(Page_PreRender); }

    /// <summary>
    /// 設置戳記
    /// </summary>
    private void SetActionStamp()
    {
        Session["actionStamp"] = Server.UrlEncode(DateTime.Now.ToString());
    }

    void Page_PreRender(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetActionStamp();
        }

        ClientScript.RegisterHiddenField("actionStamp", 
            Session["actionStamp"].ToString());
    }

    /// <summary>
    /// 取得值,指出網頁是否經由重新整理動作回傳 (PostBack)
    /// </summary>
    protected bool IsRefresh
    {
        get
        {
            if (HttpContext.Current.Request["actionStamp"] as string == 
            Session["actionStamp"] as string)
            {
                SetActionStamp();
                return false;
            }

            return true;
        }
    }
}

2. 最後在要使用的頁面上繼承這個類別,例如:

public partial class Default : BasePage
{
    .....
    .....
}

3. 接著可以利用 this.IsRefresh 判斷這個頁面是否經由重新整理而來。

回目錄
回首頁