Parallel 平行運算 ConcurrentStack

在 .Net 3.5 之前所提供的 Collections 不是 thread-safe 的,必須使用.Net 4.0 ,System.Collections.Concurrent Namespace 下的泛型。

錯誤寫法

List<string> testData = new List<string>();
List<string> resultData = new List<string>();
Parallel.For(0, testData.Count() - 1, (i, loopState) =>
{
    resultData.Add(testData[i]);
});

  2011-11-29      ez      .NET
DEBUG 模式才顯示文字

利用 #if DEBUG,並在區段中加入要顯示的文字,將 web.config 的 debug mode 設定為 true,就可以輸出資料,再將 debug mode 設定為 false,就可以隱藏資料!

#if DEBUG
Response.Write("要輸出的資訊");
#endif

  2011-11-29      ez      .NET
Stopwatch 計算耗費時間

DateTime的時間單位最小為秒,如果要到毫秒就必須使用Stopwatch,可以用來計算程式執行時間!

static void Main(string[] args)
{
	Stopwatch sw = new Stopwatch();
	sw.Start();
	for (int i = 1; i <= 10; i++)
	{
		System.Threading.Thread.Sleep(1000);
	}
	sw.Stop();
	Console.WriteLine(sw.ElapsedMilliseconds);
}

  2011-11-29      ez      .NET
判斷是否為日期

可以用來判斷用戶日期格式是否輸入錯誤!

/// <summary>
/// 判斷是否為日期
/// </summary>
public static bool IsDate(object obj)
{
    DateTime date;

    return DateTime.TryParse(obj.ToString(), out date);
}

  2011-11-29      ez      .NET
判斷是否為數字

可以用來判斷用戶是否輸入錯數值!

/// <summary>
/// 判斷是否為數字
/// </summary>
public static bool IsNumeric(object obj)
{
    double retNum;
    bool Result = Double.TryParse(obj.ToString(), System.Globalization.NumberStyles.Any
                        , System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);

    return Result;
}

  2011-11-28      ez      .NET
利用擴充方法加強字串分割

第一個參數加入this,就可以在對應型態的變數使用此擴充方法,在底層寫了這個靜態方法後,就可以像原本的分割一樣用str.Split(",")的方式執行字串分割。

public static string[] Split(this string Text, string Separator, StringSplitOptions SSO = StringSplitOptions.None)
{
            return Text.Split(new string[] { Separator }, SSO);
}

  2011-11-28      ez      .NET
判斷字串中是否有非英數字的字元

判斷字串中是否有非英文及數字的字元,可以用來判斷用戶是否輸入中文字!

/// <summary>
/// 判斷字串中是否有非英數文字
/// </summary>
public static bool ContainUnicode(string Text)
{
    return (Text.ByteCount() > Text.Length);
}

/// <summary>
/// 取得字串的位元數
/// </summary>
public static int ByteCount(this string Text)
{
    return System.Text.Encoding.UTF8.GetByteCount(Text);
}

  2011-11-28      ez      .NET
ZIP壓縮處理

SharpZipLib 官方網站下載:http://www.icsharpcode.net/OpenSource/SharpZipLib/ or SharpZipLib 0.86 壓縮檔案

Compress("C:\\ziproute", "C:\\ziproute.zip", 5);
// 傳入參數: 來源路徑, 目的壓縮檔名(.zip), 壓縮比( 0=僅儲存, 9=最高壓縮比 )
public static void Compress(string dir, string zipFileName, int level)
{
    string[] filenames = Directory.GetFiles(dir);
    byte[] buffer = new byte[4096];

    using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
    {
        // 設定壓縮比
        s.SetLevel(level);

        // 逐一將資料夾內的檔案抓出來壓縮,並寫入至目的檔(.ZIP)
        foreach (string filename in filenames)
        {
            ZipEntry entry = new ZipEntry(filename);
            s.PutNextEntry(entry);

            using (FileStream fs = File.OpenRead(filename))
                StreamUtils.Copy(fs, s, buffer);
        }
    }
}

  2011-11-28      ez      .NET