2009年5月10日 星期日

ASP.NET Web Site 使用Trace.WriteLine()無效??

ASP.NET 有提供追蹤的功能, 你在網頁是會這樣寫:
Trace.Write("category","message")

這個實際上是System.Web.TraceContext類別. 它當然不會有問題.

這裡說的是System.Diagnostics 命名空間中的Trace 類別.
當你在網頁中撰寫Trace.WriteLine() 的指令時, 會發現無效, 不管是不是在除錯模式下, 它無法被列印出來.

這是因為Visual Studio的Web Site 專案模式, 對於網頁的編譯動作並沒有將TRACE 定義編譯進來, 所以Trace 指令會無效.

因此, 必須修改Web.config 的<system.codedom> 中的 <compiler ...
要加上 compilerOptions, VB 與 C# 的參數不同.
VB
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warninglevel="4" compilerOptions="/d:TRACE=TRUE" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

C#
<compiler language="c#;cs;csharp" extension=".cs" warninglevel="4" compilerOptions="/d:TRACE" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

預設System.Diagnostics.Trace 會輸出到Visual Studio 的Output Window, 可是大部份的情況會想讓他輸出的檔案或事件檢視器, 你可以再加上以下設定:
<configuration> <system.diagnostics> <trace autoflush="true" >
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener, system version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="c:\myListener.log" />
<add name="MyEventListener" type="System.Diagnostics.EventLogTraceListener, system version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="MyConfigEventLog"/>
</listeners>
</trace>
</system.diagnostics>

另一個問題:
如何ASP.NET 的Trace.Write("category","message") 功能也可以像System.Diagnostics的Trace 一樣可以輸出到檔案或事件記錄檔呢?
答案很簡單:
<configuration>
<system.web>
<trace enabled="true" writeToDiagnosticsTrace="true" />
<system.web>
<configuration>

當然要能成功的輸出必須設定compilerOptions 及 listener

2009年5月2日 星期六

List 的 其他排序選擇

List 有提供 Sort 方法, 當你呼叫它時, 它會根據項目的型別裡實作的IComparable介面的CompareTo方法排序.

同學問到了, 如果我想提供其他的排序方式, 怎麼寫?

可以在項目的型別裡加上新的比較方法:
Shared Function EmpSortByName(ByVal emp1 As Employee, ByVal emp2 As Employee) As Integer
Return emp1.Name.CompareTo(emp2.Name)
End Function

然後在呼叫Sort 方法時指定這個Delegate
Dim employees As New List(Of Employee)
employees.Add(New Employee(101, "Anita", #7/1/1999#))
employees.Add(New Employee(201, "Andy", #7/1/1998#))
employees.Add(New Employee(301, "Lisa", #1/1/2009#))
employees.Add(New Employee(102, "Mary", #7/1/2000#))
employees.Sort(AddressOf Employee.EmpSortByName)