ASP.NET MVC 單元測試系列 (7):Visual Studio Unit Test

The Will Will Web | ASP.NET MVC 單元測試系列 (7):Visual Studio Unit Test

透過 Visual Studio 裡的整合開發環境 (IDE) 結合單元測試開發是再便利不過的了,在 Visual Studio 開發工具中已經內建一套 Visual Studio Unit Testing 框架 (Framework),可以方便協助你開發各式單元測試或整合測試的程式,工欲善其事、必先利其器,要善用他就必須先瞭解他,否則還是會事倍功半的,本篇文章會著重在 Visual Studio Unit Test 框架的概要介紹與快速上手的注意事項。

Subversion on CentOS

HowTos/Subversion – CentOS Wiki

Subversion isn’t just for coders and programmers…I know because I’m not one. I’ve begun to use it lately for many things, such as, backing up Nagios configurations, documents, and pretty much anything text based. I don’t know why I didn’t start using it sooner, but none the less, here I am. This document quickly explains how to install, configure, and use subversion locally, as well as across Apache on a network. For complete and complex configurations and installations seek the documentation provided. There is plenty of well written documentation on the subject, that far exceeds my knowlegde of the tool. This just helps get you started quickly, for those like me that just like to jump in head first into new things.

Snippet Saturday: limit() function

Flash 程式設計
很多Action Script的語法

Snippet Saturday: limit() function | dispatchEvent() Blog™

Snippet Saturday: limit() function
Posted on March 5, 2011 by Mims H Wright

So I’m sitting on a bunch of pretty useful code and I’m not sure how to share it with people. I could create a massive library that combines all the miscellaneous bits into a single, poorly documented library, but after looking at the Flash Game Dojo’s wiki, I’m starting to believe more strongly in the idea of releasing code in smaller pieces that achieve a particular function. So, I’m going to try to kick off this idea of #SnippetSaturday. I’m sure I won’t manage to post something every week but I’ll do my best. If you’ve got a blog or just twitter, I’d encourage you to join in too!

Anyway, here’s my first contribution. It’s a simple little function that limits a number between an upper and lower limit.

[VBNET] 抓取網頁部分內容

[VBNET] 抓取網頁部分內容 « 鄭子璉

很多網頁砍站軟體支援續傳、多線下載,多線下載觀念比較簡單,就是同一個檔利用多緒分別抓某個部分,再用二進位檔存取方式將抓得的結果直接寫入指定的範圍即可。

要知道怎樣做,可以先看規格書:
HTTP 1.0: RFC2068 14.36 節 Range
HTTP 1.1: RFC2616 14.35 節 Range

也就是說在 通訊協定中,檔頭加入:
Range: bytes=開始-結束
省略開始時,從 0 開始,省略結束時,自動抓到結尾。

我是認為寫程式前,應該先了解低階運作方式,通訊協定自然就是利用命令提示字元測試,例如輸入:
telnet tlcheng.twbbs.org 80
GET / HTTP/1.0
Range: bytes=100-199
傳回:
HTTP/1.1 206 Partial Content
Content-Length: 100
Content-Type: text/html
Content-Location: http://192.168.2.10/index.htm
Content-Range: bytes 100-199/3162
Last-Modified: Thu, 16 Oct 2008 08:32:25 GMT
Accept-Ranges: bytes
ETag: “e2437db7692fc91:1518″
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Thu, 16 Oct 2008 17:08:55 GMT
Connection: close
-equiv="Page-Exit" content="RevealTrans(Duration=0.5,Transition=23)">
憸函此蝘凵?撽ⓗ??毡<br />遺失與主機的連線。<br />C:><br />由上可知,很明確的傳回指定的範圍。<br /> <br />我們可以選擇的類別有 WebClient / WebRequest / HttpWebRequest ,在屬性 Headers 中的註解有提到:<br /><br />WebHeaderCollection 類別通常是經由 WebRequest.Headers 或 WebResponse.Headers 來存取。某些通用標頭會視為受限制的,並會直接由 API 公開 (例如,Content-Type) 或是由系統保護,而且無法變更。 </blockquote>

[Java]利用URLConnection檢查網站狀態

[Java]利用URLConnection檢查網站狀態 | 聰明的生活2

[Java]利用URLConnection檢查網站狀態
public class TestURLStatus {
    public static void main(String args[]) {
        try {
            java.net.URL url = new java.net.URL(
                    "http://tw.yahoo.com/123123");
            java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url
                    .openConnection();
            uc.setRequestProperty("User-agent", "IE/6.0");
            uc.setReadTimeout(30000);// 設定timeout時間
            uc.connect();// 連線
            System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
            int status = uc.getResponseCode();
            System.out.println(status);
            switch (status) {
            case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
                System.out.println("連線網址逾時!");
                break;
            case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
                System.out.println("連線網址禁止!");
                break;
            case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
                System.out.println("連線網址錯誤或不存在!");
                break;
            case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
                System.out.println("連線網址不存在!");
                break;
            case java.net.HttpURLConnection.HTTP_OK:
                System.out.println("OK!");
                break;

            }

        } catch (java.net.MalformedURLException e) {
            System.out.println("網址格式錯誤!!!");
            e.printStackTrace();
        } catch (java.io.IOException e) {
            System.out.println("連線有問題!!!!!!");
            e.printStackTrace();
        }
    }
}
原始碼如下:

java HttpURLConnection來實作get及post動作

java HttpURLConnection來實作get及post動作 | 聰明的生活2

java HttpURLConnection來實作get及post動作

private org.apache.log4j.Logger logger;

  public WebModule() {
    logger = org.apache.log4j.Logger.getLogger(this.getClass());
  }

  public boolean doPost(String sURL, String data, String cookie,
      String referer, String charset) {

    boolean doSuccess = false;
    java.io.BufferedWriter wr = null;
    try {

      URL url = new URL(sURL);
      HttpURLConnection URLConn = (HttpURLConnection) url
          .openConnection();

      URLConn.setDoOutput(true);
      URLConn.setDoInput(true);
      ((HttpURLConnection) URLConn).setRequestMethod("POST");
      URLConn.setUseCaches(false);
      URLConn.setAllowUserInteraction(true);
      HttpURLConnection.setFollowRedirects(true);
      URLConn.setInstanceFollowRedirects(true);

      URLConn
          .setRequestProperty(
              "User-agent",
              "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) "
                  + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)");
      URLConn
          .setRequestProperty("Accept",
              "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
      URLConn.setRequestProperty("Accept-Language",
          "zh-tw,en-us;q=0.7,en;q=0.3");
      URLConn.setRequestProperty("Accept-Charse",
          "Big5,utf-8;q=0.7,*;q=0.7");
      if (cookie != null)
        URLConn.setRequestProperty("Cookie", cookie);
      if (referer != null)
        URLConn.setRequestProperty("Referer", referer);

      URLConn.setRequestProperty("Content-Type",
          "application/x-www-form-urlencoded");
      URLConn.setRequestProperty("Content-Length", String.valueOf(data
          .getBytes().length));

      java.io.DataOutputStream dos = new java.io.DataOutputStream(URLConn
          .getOutputStream());
      dos.writeBytes(data);

      java.io.BufferedReader rd = new java.io.BufferedReader(
          new java.io.InputStreamReader(URLConn.getInputStream(),
              charset));
      String line;
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

      rd.close();
    } catch (java.io.IOException e) {
      doSuccess = false;
      logger.info(e);

    } finally {
      if (wr != null) {
        try {
          wr.close();
        } catch (java.io.IOException ex) {
          logger.info(ex);
        }
        wr = null;
      }
    }

    return doSuccess;
  }

  public boolean doGet(String sURL, String cookie, String referer,
      String charset) {
    boolean doSuccess = false;
    BufferedReader in = null;
    try {
      URL url = new URL(sURL);
      HttpURLConnection URLConn = (HttpURLConnection) url
          .openConnection();
      URLConn
          .setRequestProperty(
              "User-agent",
              "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) "
                  + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)");
      URLConn
          .setRequestProperty("Accept",
              "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
      URLConn.setRequestProperty("Accept-Language",
          "zh-tw,en-us;q=0.7,en;q=0.3");
      URLConn.setRequestProperty("Accept-Charse",
          "Big5,utf-8;q=0.7,*;q=0.7");

      if (cookie != null)
        URLConn.setRequestProperty("Cookie", cookie);
      if (referer != null)
        URLConn.setRequestProperty("Referer", referer);
      URLConn.setDoInput(true);
      URLConn.setDoOutput(true);
      URLConn.connect();
      URLConn.getOutputStream().flush();
      in = new BufferedReader(new InputStreamReader(URLConn
          .getInputStream(), charset));

      String line;
      while ((line = in.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      doSuccess = false;
      log.out.println(e);
      e.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (java.io.IOException ex) {
          logger.info(ex);
        }
        in = null;

      }
    }

    return doSuccess;

 

C# HttpWebRequest實作POST來取得網頁內容

C# HttpWebRequest實作POST來取得網頁內容 | 聰明的生活2

C# HttpWebRequest實作POST來取得網頁內容

 

程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace yslifes
{
    class WebModule
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(WebModule));
        //回傳的網頁內容
        private StringBuilder buff;
        //記錄Session及Cookie,如果登入時Session將一直存在
        private static CookieContainer cookie = null;
        public WebModule()
        {
            buff = new StringBuilder();
            cookie = new CookieContainer();

        }
        //取得網頁內容
        public string getContent()
        {
            return buff.ToString();
        }
        //做post事件
        public bool doPost(string sUrl, string data, string referer)
        {
            bool dosuccess = false;
            HttpWebRequest URLConn = null;
            try
            {
                //URL連線
                URLConn = (HttpWebRequest)WebRequest.Create(sUrl);
                //連線最大等待時間
                URLConn.Timeout = 10000;
                URLConn.Method = "POST";
                //設定Header模擬瀏覽器
                URLConn.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) "
                          + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)";
                URLConn.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                URLConn.Headers.Set("Accept-Language",
                    "zh-tw,en-us;q=0.7,en;q=0.3");
                URLConn.Headers.Set("Accept-Charse",
                    "Big5,utf-8;q=0.7,*;q=0.7");
                //設定referer
                if (referer != null)
                {

                    URLConn.Referer = referer;
                }
                //純文字傳送,使用application/x-www-form-urlencoded
                //如需傳送檔案,則需用multipart/form-data
                URLConn.ContentType = "application/x-www-form-urlencoded";
                //自動從導
                URLConn.AllowAutoRedirect = true;

                if (data == null)
                    data = "";
                logger.Debug(data);
                //把要傳送的資料變成binary
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                URLConn.ContentLength = bytes.Length;

                //設定Cookie,Session
                URLConn.CookieContainer = cookie;

                //送出post資料
                if (data.Length > 0)
                {
                    Stream oStreamOut = URLConn.GetRequestStream();
                    oStreamOut.Write(bytes, 0, bytes.Length);
                    //oStreamOut.Close();
                }

                //取回回傳內容
                string html = (new StreamReader(URLConn.GetResponse().GetResponseStream())).ReadToEnd();
                buff.Clear();
                buff.Append(html);

                dosuccess = true;
            }
            catch (Exception ex)
            {
                logger.Info(ex.StackTrace);

            }
            finally
            {
                try
                {
                    if (URLConn != null)
                    {
                        URLConn.GetResponse().Close();
                        URLConn.GetRequestStream().Close();
                    }
                }
                catch (Exception exx)
                {
                    logger.Debug(exx.StackTrace);

                }
            }

            return dosuccess;

        }
    }

    class Program
    {

        static void Main(string[] args)
        {

            System.IO.FileInfo f = new System.IO.FileInfo("log4net.config");
            log4net.Config.XmlConfigurator.Configure(f);

            ILog logger = LogManager.GetLogger(typeof(Program));

            WebModule module = new WebModule();
            module.doPost("http://localhost:8080/test/MyData.jsp", "test=123", null);
            Console.WriteLine("解答:"+module.getContent());

            module.doPost("http://localhost:8080/test/MyData.jsp", "test=456", null);
            Console.WriteLine("解答:" + module.getContent());
            Console.ReadLine();

        }
    }
}

log4net的使用可以參考Log4net Visual Studio版的log4j