Saturday, June 06, 2009 - 文章

WCF不定期壞掉

寫WCF好一陣子,常常在WCF程式碼完全沒更動的情況下,WCFName.svc忽然傳回以下錯誤。

Could not load file or assembly 'App_Web_9wddxbri, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

我後來試出最簡單的解法是在WCFName.svc.cs隨便加一個空白再存檔,觸發ASP.NET Web Site Project重新編譯後,問題就可解決。(我猜IISReset或Restart Web Application都有同樣效果,但這樣做最快)

今天忽然鋸箭鋸得有點煩,就找了一下根治的方法。在ScottGu的Blog找到這篇文章,看起來這是ASP.NET的Bug,不過我只有在跑.svc時才會遇到。懶得安裝Hotfix,於是修改了<compilation batch="false"></compilation>,試跑了幾天,果真就再也沒發生找不到Assembly的錯誤。

只是,取消批次編譯應該或多或少會降低效能,安裝Hotfix或Patch,設法修正Bug應該還是最佳的解決方案。

CODE-在.NET中模擬WHERE X IN ('A',’B’,’C’)的邏輯

你是不是有遇過這種邏輯需求: if (x == “A” || x == “B” || x == “C” || x == “D” ….),x滿足其中任一即可。當可能選項很多時,程式碼就會又臭又長,此時不免有個念頭,如果可以像SQL寫成WHERE X IN ('A', 'B', 'C', 'D' ...)多好?

我慣用的做法是借用.NET 2.0的System.Collections.Generic的List<string>,其中有個Contains()方法可產生類似效果:
【2009-06-06更新】感謝大估補充,其實Array.IndexOf(Array, string)就可以提供相同的比對功能,可省去動用List<string>的步驟,寫法上更簡潔。我又再次抛磚引玉,賺到了。
【2009-06-07更新】賺翻了,丟了顆小石頭,結果掉出鑽石來!! chicken大給了個絕佳的點子,bool WhereIn(x, "A", "B", "C"),詳見留言區。(註: 再次證明本站的留言比貼文精彩,建議可以長期訂閱哦!)

using System;
using System.Collections.Generic;
 
public class CSharpLab
{
    private static string getTestResult(
                    List<string> lst, string target)
    {
        bool test = lst.Contains(target);
        string result = 
            string.Format("[{0}] {1} in ('{2}')!",
            target, test ? "is" : "is not",
            string.Join("','", lst.ToArray()));
        return result;
    }
 
    public static void Test()
    {
        List<string> lst = 
            new List<string>("A,B,C,D,E,F".Split(','));
        string x = "X";
        Console.WriteLine(getTestResult(lst, x));
        lst.Add("X");        
        Console.WriteLine(getTestResult(lst, x));
    }
}

執行結果為: (程式碼可以複製到Mini C# Lab中直接執行)

[X] is not in ('A','B','C','D','E','F')!
[X] is in ('A','B','C','D','E','F','X')!

很簡單吧! 整篇的關鍵只在lst.Contains()那一列,其餘的部分都是為了舖陳這個梗而灑的花瓣(XD)...

順道一提,上面的程式碼裡有幾個我常用的小技巧:

  • string.Split(char)可以將一個逗號分隔的字串轉成string[]
  • new List<string>(string[])可以直接將字串陣列轉成List<string>
  • List<string>.ToArray()可以匯出string[]
  • string.Join(string, string[])可以將字串陣列用指定的分隔文字再組成一個字串。用"','"間隔,前後加上"('"及"')",就搞出('A','B’,…,’X’)囉! (不過我偷懶沒避開無元素的情境,會變成(''))

類似的情境,如果大家有不一樣的解法,歡迎提出來交流。

Posted 06 June 2009 06:26 AMJeffrey | 8 comment(s)
Filed under:

搜尋

Go

<June 2009>
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
 
RSS
【工商服務】
最新回應

Tags 分類檢視
關於作者

一個醉心技術又酷愛分享的Coding魔人,十年的IT職場生涯,寫過系統、管過專案, 也帶過團隊,最後還是無怨無悔地選擇了技術鑽研這條路,近年來則以做一個"有為的中年人"自許。

文章典藏
其他功能

這個部落格


BlogLook Score and Rank

Syndication