Below you will find pages that utilize the taxonomy term “CSharp”
Posts
'gRPC - Create C# gRPC server'
要建立 gRPC 的 Server,須先將 GRPC.Tools、GRPC.Core、Google.Protobuf 這三個 NuGet 套件加入參考。
... <ItemGroup> <PackageReference Include="Google.Protobuf" Version="3.7.0" /> <PackageReference Include="Grpc.Core" Version="1.20.0" /> <PackageReference Include="Grpc.Tools" Version="1.20.0" /> </ItemGroup> ... 然後設定從 Proto 檔產生需要的程式部分。
<ItemGroup> <Protobuf Include="../../proto/*.proto" GrpcServices="Server" /> <Content Include="@(Protobuf)" LinkBase="" /> </ItemGroup> 編譯後可在 obj 下看到產出的檔案。
接著開始實作 Service。
繼承產出的 Service 基底類別。
... public class HelloServiceImpl:HelloService.HelloServiceBase ... 並覆寫該服務的方法即可。
... public override Task<HelloResponse> SayHello(HelloRequest request, ServerCallContext context) { ... } ... 程式寫起來會像下面這樣 (這邊筆者只是簡單的將調用時送進來的人名做些加工回傳而已):
using System.Threading.Tasks; using Grpc.Core; public class HelloServiceImpl:HelloService.
read morePosts
'C# 8.0 - Target-typed new-expressions'
C# 8.0 的 Target-typed new-expressions 能讓開發人員在使用 new 關鍵字建立物件實體時省略帶入型別,編譯器編譯時會依照 Context 幫我們帶入。
以簡單的例子來說,假設已經宣告了變數 p 型別為 Point,那在用 new 關鍵字建立實體時就可以省略帶入 Point。
... Point p = new (1, 2); 反組譯看可以看到編譯器會幫我們在 new 關鍵字後面帶入正確的型別。
複雜一點的情境像是陣列元素的宣告也是支援。
... Point[] ps = { new (1, 2), new (2, 2) };
read morePosts
'C# 7.0 - Throw expressions'
C# 7.0 開始支援 Throw expressions。
三元運算中可以視需要直接丟出 exception。
... this.FirstName = firstName == null ? throw new ArgumentNullException(nameof(firstName)) : firstName; ... ?? 運算式中也可以直接丟出 exception。
... this.LastName = lastName ?? throw new ArgumentNullException(nameof(lastName)); ... Expression bodied member 也可以丟出 exception。
... public override string ToString() => throw new NotImplementedException(); ... 最後附上完整的測試範例:
class Program { static void Main(string[] args) { var person = new Person("Larry", "Nung"); Console.WriteLine(person.ToString()); } } struct Person { public string FirstName { get; set; } public string LastName { get; set; } public Person(string firstName, string lastName) { this.
read morePosts
'C# 7.0 - More expression bodied members'
C# 7.0 擴展了 Expression bodied。
開始支援建構子。
... class Program { ... public Program() => Console.WriteLine("Program()"); ... } ... 支援解構子。
... class Program { ... ~Program() => Console.WriteLine("~Program()"); ... } ... 支援 property accessors。
... private string _myProperty; public string MyProperty { get => _myProperty; set => _myProperty = value; } ... 支援 event accessors。
... public event EventHandler MyEvent { add => _myEvent += value; remove => _myEvent -= value; } .
read morePosts
'C# 7.0 - Deconstruction'
C# 7.0 新增 Deconstruction,可將 Tuple、結構、類別的成員拆解使用。
以 Tuple 為例,若想要將 Tuple 值拆解使用,可以用小括弧宣告出多個區域變數,並將 Value Tuple 指派過去,Value Tuple 的屬性值就會依序塞入這些區域變數。
(var v1, var v2) = GetTuple(); var (v1, v2) = GetTuple(); 若是結構或是類別,則要建一個 public 的 Deconstruct 方法,方法的參數用 out 將拆解出來的值依序傳出,編譯時編譯器就會自行幫我們調用 Deconstruct 方法將值拆解。
(var v1, var v2) = new MyClass(); ... class MyClass() { ... public void Deconstruct(out string v1, out string v2) { v1 = this.V1; v2 = this.V2; } } 若有需要 Deconstruct 也支援多載。
(var v1, var v2) = new MyClass(); .
read morePosts
'C# 7.0 - Tuple'
C# 7.0 新增了 Value Type 的 Tuple,因為是 Value Type,所以對 GC 的負擔會比較少。另外增加了一些語法糖,改進了本來 Tuple 類別可讀性不佳的問題。
使用上需先加入 System.ValueTuple 套件。
若不加入該套件編譯時會看到 System.ValueTuple is not defined or imported 的錯誤。
套件加入引用後我們可以看一下該套件的內容,可以看到有一堆泛型的 ValueTuple struct,裡面的成員屬性跟以往的 Tuple 一樣都是 Item1 ~ ItemN。
使用上可以直接建立 ValueTuple,然後在建立的同時指定其型態與值,在要取值的地方用 Item1 ~ ItemN 屬性來取值。
也可以用小括弧包住屬性值直接宣告。
但這樣的宣告方式跟舊的 Tuple 類別一樣有著可讀性不佳的問題,因此在用小括弧包住屬性值宣告的同時,我們將屬性名稱也一併指定,取值時就可以用指定的屬性名稱來取值。
編譯器在編譯時會自動幫你將程式轉換成 Item1 ~ ItemN。
若想要將 Tuple 值拆解使用,可以用小括弧宣告出多個區域變數,並將 Value Tuple 指派過去,Value Tuple 的屬性值就會依序塞入這些區域變數。
這些功能即使套用在方法的回傳值上也一樣適用。
Link Tackling Tuples: Understanding the New C# 7 Value Type - Our ComponentOne C# 7.0 – Tuples – CsharpStar Tuple deconstruction in C# 7 | Thomas Levesque’s .
read morePosts
C# 7.0 - Digit separators
以前在開發 C# 時,如果數值過大,在閱讀上會十分不易。
C# 7.0 以後提供了 Digit separators 功能,允許開發人員使用 _ 將數值做些分隔,有效解決了上述問題。最普遍的用法就是將數值做千分位分隔,像是下面這樣:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var values = new int[] { 1_000, 1_000_000, 0b1_000 }; foreach (var value in values) { Console.WriteLine(value.ToString()); } } } } {% img /images/posts/CSharp7DigitSeparators/1.png %}
Link C# 7 features preview · Anton Sizikov Exploring Visual Studio “15” Preview and Playing with C# 7 Test driving C# 7 features in Visual Studio “15” Preview » Thomas Levesque’s .
read morePosts
C# 7.0 - Binary literals
在程式開發時,有時我們會需要使用二進制的數值,像是在使用標有 FlagsAttribute 的列舉值做權限時就會用到。在 C 7.0# 前我們必需要使用十進制數值表示法,確保他是二進制的數值。
在 C# 7.0 後開始支援二進制數值表示法,使用上只需用 0b 當做前綴即可,像是 0 可以寫成 0b00、1 可以寫成 0b01、2 可以寫成 0b10、4 可以寫成 0b100,以此類推。
using System; namespace ConsoleApplication1 class Program { static void Main(string[] args) { var values = new int[] { 0b00, 0b01, 0b10, 0b100, 0b1000 }; foreach (var value in values) { Console.WriteLine(value.ToString()); } } } } {% img /images/posts/CSharp7Binaryliterals/1.png %}
Link A glance at C# vNext - CodeProject
read morePosts
C# 7.0 - Local functions
有時候我們在開發程式時,會碰到一些情境是需要建立個方法,但這個方法只有某個地方會用到,這時我們多半是用委派去做掉,但帶來的問題就是會有額外的記憶體耗費,而且無法被 inline 處理。
C# 7.0 後,我們可以改用 Local functions 功能去處理。使用方式很簡單,就是一般的方法宣告,只是是寫在方法裡面。像是:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { void SayHello(string name) { Console.WriteLine(string.Format("Hello~{0}", name)); } SayHello("Larry"); } } } 這邊也可以搭配使用 C# 6.0 的 Expression Bodied Members,程式碼會更為精簡。
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { void SayHello(string name) => Console.WriteLine(string.Format("Hello~{0}", name)); SayHello("Larry"); } } } 運行結果如下:
{% img /images/posts/CSharp7LocalFunctions/1.png %}
反組譯看一下:
{% img /images/posts/CSharp7LocalFunctions/2.
read morePosts
T4 Template - JsResource.tt
在撰寫 ASP.NET 時,.NET 程式部分可用 Resource 去做多語的部分,JavaScript 這邊雖然也有 L10N 的解決方案,但是若走不同的解決方案,難以避免有些詞彙會重複定義。
這邊筆者嘗試使用 T4 來解決這樣的問題。
<#@ template language="C#" debug="false" hostspecific="true"#> <#@ assembly name="System.Windows.Forms" #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Xml" #> <#@ assembly name="EnvDTE" #> <#@ assembly name="Microsoft.VisualStudio.OLE.Interop" #> <#@ assembly name="Microsoft.VisualStudio.Shell" #> <#@ assembly name="Microsoft.VisualStudio.Shell.Interop" #> <#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0" #> <#@ import namespace="System.Resources" #> <#@ import namespace="System.Diagnostics" #> <#@ import namespace="System.Collections" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.
read morePosts
T4 template - CultureNames.tt
.NET 在操作 Culture 時,免不了要帶入 CultureInfo 的 Name,多半是用 Hard code 的形式帶入,像是下面這樣:
... var currentThread = Thread.CurrentThread; currentThread.CurrentCulture = CultureInfo.GetCultureInfo("zh-tw"); ... {% img /images/posts/T4CultureNames/1.png %}
這邊筆者做了個 T4 Template,期望能解決這樣的問題。
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Globalization" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ output extension=".cs" #> namespace System.Globalization { public static class CultureNames { <# var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); var length = cultures.
read morePosts
CShell - A simply, yet powerful, C# scripting IDE
Cshell 是一 C# interactive tool,適合用於 C# 語言的學習或是用來做些簡單的小測試。
{% img /images/posts/Cshell/1.png %}
程式主檔可在 Github Project Page 下載。
{% img /images/posts/Cshell/2.png %}
下載完解壓點擊運行即可。
{% img /images/posts/Cshell/3.png %}
{% img /images/posts/Cshell/4.png %}
程式啟動後預設會幫我們含有兩個檔案,內含一些教學步驟,建議剛接觸的使用者可以先從這邊入手。
{% img /images/posts/Cshell/5.png %}
該工具雖然精簡,但該有的功能也都有,像是 Intellisense。
{% img /images/posts/Cshell/6.png %}
視窗版面的調整。
{% img /images/posts/Cshell/7.png %}
組件的參考等。
{% img /images/posts/Cshell/8.png %}
{% img /images/posts/Cshell/9.png %}
在使用上,它有提供些好用的內建命令,可輔助我們使用,有需要可以輸入 help 查閱。
{% img /images/posts/Cshell/10.png %}
像是 Describe 方法可回傳帶入的物件型別描述、ShowUsing 方法可查閱命名空間的引用狀況
{% img /images/posts/Cshell/11.png %}
ShowVars 方法可查閱區域變數的宣告狀況
read morePosts
C# 6.0 - Await in catch/finally
C# 6.0 以前 await 無法用在 catch/finally 區塊,C# 6.0 後開始支援。
using System; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Test(); System.Threading.Thread.Sleep(10000); } private static async void Test() { try { throw new Exception(); } catch { Console.WriteLine("Catch..."); await Task.Delay(500); } finally { Console.WriteLine("Finally..."); await Task.Delay(500); } } } }
read morePosts
C# 6.0 - Extension Add methods in collection initializers
C# 6.0 以前,集合類別可以像下面這樣透過 Collection Initializers 初始集合成員:
... var blogs = new List< Blog> { new Blog( "Level Up 1", "http://www.dotblogs.com.tw/larrynung" ), new Blog( "Level Up 2", "http://larrynung.github.io" ) }; ... {% endcodeblock%} <br/> 但無法像 VB 10 以後的版本一樣透過擴充方法客製處理 Collection Initializers 的動作,一直到 C# 6.0 才被加入 C# 內。 <br/> 只要為集合撰寫 Add 擴充方法即可客製處理 Collection Initializers,像是如果預期要讓 List<Blog> 的初始可以直接帶入 name 與 url,就會像下面這樣撰寫: ```c# ... public static class BlogExtension { public static void Add(this List<Blog> list, string name, string url) { list.
read morePosts
C# 6.0 - Parameterless constructors in structs
在 C# 6.0 以前,Struct 會自帶 Parameterless Constructors,且不允許我們自行實作,像是下面這樣的程式碼:
... public Blog() : this( string.Empty, string.Empty) { Console.WriteLine( "Blog.Ctor()..."); } public Blog(string name, string url) { this.Name = name; this.Url = url; } ... 運行在 C# 6.0 以前,編譯器就會告知錯誤:
{% img /images/posts/ParamlessStructConstructor/1.png %}
如果想要在 Parameterless Constructors 自行加些處理,像是用建構子鏈導到別的建構子去建構,在 C# 6.0 以前都沒辦法。
在 C# 6.0 以後,就比較沒有這樣的限制了,我們可以自行撰寫自己的 Paramless Constructor,加上自己想要的處理動作。唯一要注意的是需要透過 new 語法建立的才會觸發自己撰寫的 Paramless Constructor。
... var blog = default( Blog); DumpBlog(blog); blog = new Blog() { Name = "Larry Nung", Url = "http://larrynung.
read morePosts
C# 6.0 - Index initializers
以往我們在撰寫 C#,有 Object Initializer 與 Collection Initializer 可輔助我們作初始的動作,雖然可以初始大多數的資料,但在 Index 與 Event 這邊卻無法直接初始。
如果以 Dictionary 來說,因為他還是屬於集合的一種,所以仍舊可以像下面這樣透過 Collection Initializer 在初始的同時就將內容一併放入:
... var blog1 = new Dictionary<string , string >() { { "Name", "Level Up" }, { "Url", "http://larrynung.github.io/index.html" } }; ... 但並不是所有的情況下都可以用 Collection Initializer 來做 Index 的初始,所以在 C# 6.0 導入了 Index initializers,寫起來會像下面這樣,就像透過索引子塞值一般:
... var blog = new Dictionary<string , string >() { [ "Name"] = "Level Up" , [ "Url"] = "http://larrynung.github.io/index.html" }; .
read morePosts
C# 6.0 - String interpolation
以往在做比較簡單的字串串接,我們可能會用 + 運算符號進行串接,或是用 String.Format 帶入 Pattern 與要串接的字串去處理,像是下面這樣:
... Console.WriteLine((++idx).ToString("D2") + ". " + blog.Name + " (" + blog.Url + ")"); Console.WriteLine( String.Format( "{0:D2}. {1} ({2})", ++idx, blog.Name, blog.Url)); ... 在 C# 6.0 導入了 String Interpolation,可以像下面這樣簡化寫法:
... Console.WriteLine( "\{++idx, 5 :D2 }. \{blog.Name } (\{blog.Url ?? String.Empty})" ); ... 有點像是本來 String.Format 的 Pattern 內直接用斜線與大括號包住帶入運算式,且支援 optional alignment 與 format specifiers 的設定。
這邊來看個完整的使用範例:
using System; using System.Collections.Generic; public class Program { static void Main(string[] args) { var blog = new Blog { Name = "Level Up", Url = "http://larrynung.
read morePosts
Clr C# Heap Allocation Analyzer
Clr C# Heap Allocation Analyzer 是 Diagnostic Analyzers 的套件,功能上有點類似 ReSharper - Heap Allocation Viewer Extension,能對 Heap 的操作部分做些 Highlight。
這邊可先參閱一下影片的介紹:
該套件提供兩種安裝方式,一種是選擇安裝 VSIX,用 Extension Manager 搜尋安裝或是自 NuGet Gallery | Clr C# Heap Allocation Analyzer 1.0.0.5 下載安裝,好處是可以將效果套用至所有專案。
{% img /images/posts/HeapAllocationAnalyzer/1.png %}
一種則是用 NuGet By 專案安裝,好處是可以只套用至特定的專案。
{% img /images/posts/HeapAllocationAnalyzer/2.png %}
安裝完後,在程式編輯時即會呈現進行對應的分析,像是筆者這邊的程式即被偵測出有 Boxing 的動作。
{% img /images/posts/HeapAllocationAnalyzer/3.png %}
Link NuGet Gallery | Clr C# Heap Allocation Analyzer 1.0.0.5 Clr Heap Allocation Analyzer extension
read morePosts
C# 6.0 - Expression bodied members
Expression bodied members 是預計要在 C# 6.0 釋出的新功能,目前已可在 Visual Studio 14 中透過設定將功能開啟進行體驗,只要在方案檔中加上:
<LangVersion>experimental</LangVersion> 當撰寫簡單的成員方法或是屬性時,Expression bodied members 能讓我們將程式碼精簡。
在使用上就只要將屬性或方法的宣告後面直接接上 Lambda 表示式即可。
像是成員屬性的處理會像下面這樣,少了本來大括弧的區塊,也少了 Get 區塊。
... public string ID => Guid.NewGuid().ToString(); ... 如果是成員方法處理上也類似,只是本來大括弧區塊內的內容用 Lambda 取代。
... public override string ToString() => this.Name; ... 這邊可以看到用這樣的寫法可能會造成很難區別是屬性還是方法,使用上要特別注意小心,基本上差異只在於後面有沒有接小括弧區塊及方法的參數。
最後看個完整的範例:
using System; public class Program(string name) { public string ID => Guid.NewGuid().ToString(); public string Name { get; private set ; } = name; public override string ToString() => this.
read morePosts
C# 6.0 - Nameof expressions
Nameof expressions 是預計要在 C# 6.0 釋出的新功能,目前已可在 Visual Studio 14 CTP3 中透過設定將功能開啟進行體驗,只要在方案檔中加上:
<LangVersion>experimental</LangVersion> Nameof expressions 能讓開發人員輕易的在程式中取得變數或是類別名稱。
以往我們是無法取得變數名稱的,所以像是在撰寫參數檢查,當丟出的例外需要帶入參數名稱時,多半是自己填入字串帶入。但這樣的做法不是很恰當,因為拼錯時並不容易發現,且當重構參數名稱時很容易遺漏要配合修改。
至於類別名稱的取得,相較於變數名稱的取得是簡單了許多。但是名稱的取得需要 Runtime 進行解析,這樣的做法有時又多了一些無謂的耗費。
Nameof expressions 的出現能幫助開發人員解決這樣的問題,使用上只要叫用nameof,並帶入欲取得名稱的類別或變數即可。
nameof( 欲取得名稱的類別或變數 ) 這邊直接看個完整的使用範例:
using System; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var blog = new Blog { Name = "Level Up" , Url = "http://larrynung.github.io/" }; DumpBlogInfo(blog); DumpBlogInfo(null); } static void DumpBlogInfo(Blog blog) { Console.WriteLine( string.Format( "Dump data (Type is {0})..." , nameof(Blog ))); if (blog == null) throw new ArgumentNullException(nameof (blog)); Console.
read morePosts
C# 6.0 - Null propagation
— layout: post title: “C# 6.0 - Null propagation” date: 2014-08-21 00:03:00 comments: true tags: [CSharp, CSharp 6.0] keywords: “C#” description: “C# 6.0 - Null propagation”
read morePosts
C# 6.0 - Exception filters
Exception filters 是預計要在 C# 6.0 釋出的新功能,目前已可在 Visual Studio 14 中透過設定將功能開啟進行體驗,只要在方案檔中加上:
<LangVersion>experimental</LangVersion> 或是透過 .Net Fiddle 也可以,Compiler 那邊選取 Roslyn 就可以了。
Exception filters 能讓開發人員很容易的在攔截例外時順帶做些過濾的動作,藉此處理符合過濾條件的例外,且不對例外呼叫堆疊造成不良的影響。
以往我們必須要先將例外攔截,接著進行比對過濾,最後將符合的例外做對應的處理,不符合的例外繼續讓它向外擴出。但是這樣的作法會讓例外呼叫堆疊看不到實際發生的例外點,只看到重新擴出例外的點,造成除錯上的困難。
{% img /images/posts/ExceptionFilters/1.png %}
Exception filters 的出現能幫助開發人員解決這樣的問題。
它的語法很直覺,簡單來說就只是在 Try/Catch 的 Catch 後面加上 if 條件式進行過濾。
try {...} catch(Exception e) if (...) {...} 程式寫起來會像下面這樣:
反組譯看一下,可以看到 Exception filters 這邊會被編譯成 filter 區塊的部份,從 IL 這邊就直接支援。
{% img /images/posts/ExceptionFilters/2.png %}
這樣的寫法不僅直覺,且不會對例外呼叫堆疊造成不良的影響。
{% img /images/posts/ExceptionFilters/3.png %}
最後這邊做個新舊方法的測試比較:
可以看到效能的部份其實是差不多的,新語法感覺是沒有任何的效能優化。
read morePosts
C# 6.0 - Using static members
Using static members 是預計要在 C# 6.0 釋出的新功能,目前已可在 Visual Studio 14 中透過設定將功能開啟進行體驗,只要在方案檔中加上:
<LangVersion>experimental</LangVersion> 或是透過 .Net Fiddle 也可以,Compiler 那邊選取 Roslyn 就可以了。
Using static members 能讓開發人員更方便的對指定類別的靜態成員做存取。對於程式中有大量的靜態成員存取操作時特別好用。
使用上與 Namespace 的 Using 類似,只是後面帶的不是到 Namespace 而已,而是進一步再向下帶到 Class。用 Using 指定要存取的類別後,在程式中就可以直接存取該類別的靜態成員,就如同自身的成員一般。
以一個較完整的例子來看,程式寫起來會像下面這樣:
可以看到這邊程式的一開始就先使用 Using 引用 Console 類別,後續我們就可以在程式中直接存取 Console 類別的靜態成員,像是取用 Title 、或是呼叫 WriteLine 方法。
反組譯看一下,可以發現其實該語法也只是編譯器幫我們在編譯時做了些處理。
{% img /images/posts/UsingStaticMembers/1.png %}
read morePosts
C# 6.0 - Auto-property initializers
Auto-property initializers 是預計要在 C# 6.0 釋出的新功能,目前已可在 Visual Studio 14 中透過設定將功能開啟進行體驗,只要在方案檔中加上:
<LangVersion>experimental</LangVersion> 或是透過 .Net Fiddle 也可以,Compiler 那邊選取 Roslyn 就可以了。
Auto-property initializers 能讓開發人員在宣告 Auto-property 的同時就順道做初始的動作。不用另行在建構子中設定。也不再寫用回一般的 Property 寫法,然後在 Field 宣告時設定。
它的語法很直覺,簡單來說就是本來的 Auto-property 後面直接接上賦值的語法。像是:
public string Property { get; set; } = "Value"; 除了一般可讀可寫的 Property 外,唯讀的甚至是靜態的 Property 該語法也都支援。
以一個較完整的例子來看,程式寫起來會像下面這樣:
程式寫起來可以看到比以往精簡許多,運行後屬性也都有正確的賦值。
反組譯看一下,可以看到比較接近透過變數初始器去做賦值的動作,會在基底類別初始前宣告,也會標注 beforefieldinit。
{% img /images/posts/AutoPropertyInitializers/1.png %}
{% img /images/posts/AutoPropertyInitializers/2.png %}
read morePosts
.NET - A Simple Finite State Machine Solution
想要用實現有限狀態機的功能,看了一下網路上的解決方案以及 State Pattern,覺得都不怎麼適用,因此利用 Tuple 與 Dictionary 去實作了一個簡易又可重複使用的 State Machine:
public sealed class StateMachine<TState, TCommand> { #region Fields Dictionary<Tuple<TState, TCommand>, TState> _transitions; #endregion Fields #region Properties /// <summary> /// Gets the m_ transitions. /// </summary> /// <value> /// The m_ transitions. /// </value> private Dictionary<Tuple<TState, TCommand>, TState> m_Transitions { get { return _transitions ?? (_transitions = new Dictionary<Tuple<TState, TCommand>, TState>()); } } /// <summary> /// Gets the state of the current. /// </summary> /// <value> /// The state of the current.
read morePosts
.NET - Access Embeded Resource
Embeded Resource 可以將程式需要的檔案內嵌在程式組件內,會增加組件的大小,但是使用者看不到該檔案,也不會因為檔案位置錯誤造成程式出錯。當系統中存在有必要的檔案,且不希望讓使用者能夠輕易動到的話, 使用 Embeded Resource 是不錯的選擇。
要設定 Embedded Resource ,只要將檔案加入專案,然後在屬性視窗中將 Build Action 設為 Embeded Resource。
要取用時透過 Assembly.GetExecutingAssembly() 取得當前組件,然後叫用 GetManifestResourceStream() 並帶入 Resource Name 取得指定 Embeded Resource 的 Stream,最後再從 Stream 讀出我們所要的資料就可以了。
所以像是純文字檔,就可以像下面這樣處理:
private static string ReadAllTextFromEmbededResource(string resourceName) { var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } Link c# - How to read embedded resource text file - Stack Overflow How to read Embedded Resource in c# | Hadjloo’s Daily Notes 如何使用 Visual C# 內嵌和存取資源
read morePosts
ODP.NET - Oracle Data Provider for .NET
要用 C# 存取 Oracle,通常我們會使用 ODP.NET。
ODP.NET 目前有 x86、 x64 與 Managed 三個版本可供使用。
Managed 版本為純 .NET 的解決方案,具備位元適應性, 能兼容於 x86 與 x64 的環境,可不安裝 Oracle client 使用,只是目前尚未支援 UDT 操作。
x86 與 x64 版本的 ODP.NET 不具位元適應性,需依運行環境使用正確的組件,且需安裝對應的 Oracle client,或是將會用到的 Oracle client 組件一併發佈,使用起來較 Managed 的麻煩,但能使用完整的功能。
不論選用哪個版本做開發,使用前都需先將組件加入參考,這邊可直接透過 NuGet 安裝對應的套件。
{% img /images/posts/ODP.NET/1.png %}
{% img /images/posts/ODP.NET/2.png %}
{% img /images/posts/ODP.NET/3.png %}
{% img /images/posts/ODP.NET/4.png %}
組件載入後,程式撰寫起來跟一般的 ADO.NET 程式沒什麼兩樣。
首先要先建立資料庫的連線。
using(var conn = new OracleConnection(connstring)) { ... } 接著將建立的資料庫連線開啟。
read morePosts
WCF - Self hosting service
要 Self hosting WCF 的服務。首先要先將 System.ServiceModel 加入參考。
{% img /images/posts/WCFSelfHosting/1.png %}
接著在程式設計中建立 ServiceHost。建立的同時要指定欲運行的 Service 型態,以及要 Host 的位置。
var serviceUrl = "http://localhost:6525/ExecuteService"; var serviceUri = new Uri( serviceUrl ); using (var host = new ServiceHost (typeof(WcfServiceLibrary1. ExecuteService), serviceUri)) { ... } 再來要建立 ServiceMetadataBehavior 並對其做些對應的設定,像是啟用 HttpGet。
... var smb = new ServiceMetadataBehavior (); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; ... 將剛建立的 ServiceMetadataBehavior 加到 ServiceHost.Description.Behaviors。
... host.Description.Behaviors.Add(smb); ... 在開始需要服務時,叫用 ServiceHost 的 Open 方法啟用 WCF 服務。
read morePosts
T4 template - Auto generate ConnectionString's wrapper class
在 .Net 程式中要使用資料庫的連線字串,多半我們會將資料庫的連線字串設定在 Config 檔中,然後透過 ConfigurationManager.ConnectionStrings 帶入對應的 Key 去將之取出來使用。
用這樣的撰寫方式,連線字串名稱打錯無法立即的被意識到,連線字串名稱調動時也很容易漏改,造成系統運行時的錯誤。因此有的人會將連線字串這邊再包一層,透過這層物件的屬性去取得連線字串,將連線字串的修改都在這層處理,減少人為造成的錯誤。
然而這樣的做法並無法完全解決問題,因為多包的那層還是人工下去做的,仍舊是無法避免連線名稱鍵錯的問題,連線字串變動時仍是會有改錯的可能。故這邊筆者嘗試使用 T4 template,讀取專案的 config 檔,動態產生強型別物件,提供連線字串給系統使用。
首先我們要為專案加入一個 t4 template 檔。
然後將其程式碼替換成下面這樣。
<#@ template debug ="true" hostspecific="True" language= "C#" #> <#@ assembly name ="EnvDTE" #> <#@ assembly name ="System.Core.dll" #> <#@ assembly name ="System.Configuration" #> <#@ assembly name ="System.Xml" #> <#@ import namespace ="System.Collections.Generic" #> <#@ import namespace ="System.Configuration" #> <#@ import namespace ="EnvDTE" #> <#@ import namespace ="System.Xml" #> <#@ output extension =".
read morePosts
.NET 4.5 - Multicore JIT
以往我們的程式要增快啟動速度時,我們會使用 ngen 去產生原生映像檔,讓程式運行時改運行預先編譯過的原生映像檔,以減少 JIT 編譯的耗費。
然而 ngen 這種改善方案只適用於某些情境下,像是有安裝包的部署。並不是所有的情境都可以套用 ngen 這種改善方案。故在 .Net Framework 4.5 出現了 Multicore JIT 的概念,以並行編譯的方式來提升程式的啟動速度,預期可加速約 20% - 50% 。
微軟官方也有提供一些比較數據可供參考。
{% img /images/posts/MultiCoreJIT/1.png %}
{% img /images/posts/MultiCoreJIT/2.png %}
Multicore JIT 的運作原理主要是將運行分為兩種 Mode。一個是 Recording mode,於程式第一次運行時啟動,會將跟 Compile 要求的編譯紀錄到指定的 Profile 檔案。
{% img /images/posts/MultiCoreJIT/3.png %}
一個是 Plackback mode,會依照 Recording mode 所紀錄的 Profile 用另外一個 CPU 下去在背景編譯。
{% img /images/posts/MultiCoreJIT/4.png %}
以程式面來說,Asp.Net 4.5 與 Silverlight 5 這邊會自動啟用 Multicore JIT 功能,不需要做什麼特別的設定,如果有需要也可以修改 web.config 去將之關閉。
<system.web> <compilation profileGuidedOptimizations="None" /> </system.
read morePosts
WPF - Refresh / Update WPF controls
相信大家都知道若要釋放些資源去讓畫面得以更新,若不將運算處理切離主執行緒,我們可能會偷懶用 DoEvents 來做。然而, DoEvents 這個方法的功用只是釋放資源,而釋放出的資源為誰所用,這部分我們無法掌控。因此釋放出的資源可能會被拿去做不相干的處理,造成效能嚴重低落。
在 WinForm 的世界裡,這樣的問題比較好處理,因為有許多現成的方法可以指定特定元件去做更新,像是 Update、Refresh、或是 Invalidate。
在 WPF 的世界裡,我們沒現有的方法可以直接叫用,只能用些小技巧兜出類似的功能。像是將下面這段擴充方法加入…
public static class ExtensionMethods { private static Action EmptyDelegate = delegate() { }; public static void Refresh(this UIElement uiElement) { uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); } } 程式在撰寫時就可以像下面這樣直接透過 UI 元件觸發更新。
control.Refresh(); Link Refresh / Update WPF controls
read morePosts
Check if run as administrator
要判斷當前使用者是否具有管理者權限,我們可以先取得當前使用的 WindowsIdenty。
var wi = WindowsIdentity.GetCurrent(); 接著帶入剛取得的 WindowsIdenty,建立對應的 WindowsPrinciple。
var wp = new WindowsPrincipal(wi); 透過 WindowsPrinciple 的 IsInRole 方法判斷當前的使用者是否為 WindowsBuiltInRole.Administrator。
var isAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); 所以整個程式會像下面這樣 :
private bool IsRunAsAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); return wp.IsInRole(WindowsBuiltInRole.Administrator); } Link AntsCode: Running a ClickOnce Application as Administrator
read morePosts
Check empty folder with IsDirectoryEmplty Win32 API
在判斷目錄是否為空這邊,.NET 4.0 以前,很多人都會很直覺的去使用 Directory.GetFiles 、Directory.GetDirectories 、或 Directory.GetFileSystemEntries 方法,用個數判斷是否為空。
public bool IsDirectoryEmplty(string directory) { //return !Directory.GetFiles(directory).Any() && !Directory.GetDirectories(directory).Any(); return !Directory.GetFileSystemEntries(directory).Any(); } 用這樣的方式處理,必須等待所有檔案都找出來後回傳才能進行空目錄的判斷,效能十分的低落。
在 .NET 4.0 後可改用 Directory.EnumerateFiles 、Directory.EnumerateDirectories 、或 Directory.EnumerateFileSystemEntries 替代。
public bool IsDirectoryEmplty(string directory) { //return !Directory.EnumerateFiles(directory).Any() && !Directory.EnumerateDirectories(directory).Any(); return !Directory.EnumerateFileSystemEntries(directory).Any(); } 相較於 .NET 4.0 以前的處理方式,檔案變成找到就立刻回傳,因此我們找到一個檔案就可以將搜尋的動作中斷,效能問題獲得了改善。
雖然效能的問題解決了,不過像這樣的處理方式會受限於 .NET Framework 的版本,不是一個比較通用的解法。而且空目錄判斷這樣的動作其實跟前面提到的取得目錄大小一樣,用 Win32 API 去跟 OS 問多半是最快的方式。
以這邊來說,我們可以將之改用 IsDirectoryEmplty API 去處理。
[ DllImport("Shlwapi.dll" , EntryPoint = "PathIsDirectoryEmpty")] [ return: MarshalAs (UnmanagedType.Bool)] public static extern bool IsDirectoryEmplty([MarshalAs (UnmanagedType.
read morePosts
Remote desktop with Microsoft Terminal Services control
要使用.NET來開發具備遠端桌面功能的程式,我們可以使用 Microsoft Terminal Services control 這個 Com 元件來做。
首先將 Microsoft Terminal Servics control 這個 Com 元件加入工具箱,並將之拖曳至設計頁面擺放至適當的位置。
{% img /images/posts/MicrosoftTerminalServicesControl/1.png %}
然後接著進行程式的開發動作。
設定遠端桌面的 Server 位置。
設定Domain。
設定使用者名稱與密碼。
這邊的設定都很單純,只有密碼這塊設定需要特別的處理,需要叫用 GetOcx 方法取得 IMsTscNonScriptable 物件,再對其 ClearTextPassword 欄位設定。
該做的設定做完後,呼叫 Connect 方法就可以開始進行遠端桌面的連線。
若要斷開遠端桌面連線,可呼叫 Disconnect 方法。
另外連線的狀態可透過 Connected 欄位取得,欄位值是1時代表正在連線。所以在程式撰寫的時候我們可以在連線時進行連線狀態的確認,依此狀態決定是否要先將連線斷開。
最後附上完整的程式範例。
運行起來會像下面這樣:
{% img /images/posts/MicrosoftTerminalServicesControl/2.png %}
若有需要,範例程式也可至 larrynung / RDPDemo 這邊下載。
Link Remote Desktop using C#.NET - CodeProject
read morePosts
[.NET Resource]透過BoxCop偵測程式是否存在Boxing與UnBoxing
namespace ConsoleApplication25 { class Program { static void Main(string[] args) { Console.WriteLine(“Blog: {0}{1}Article count:{2}”, “Level Up”, Environment.NewLine, 549 ); } } }
read morePosts
[C#][Extension Method]Get directory size
namespace ConsoleApplication8 { class Program { static void Main(string[] args) { GetFolderSize(@“C:\Program Files”); GetDirSize(@“C:\Program Files”); DirSize(new DirectoryInfo(@“C:\Program Files”));
var sw = Stopwatch.StartNew(); Console.WriteLine(GetFolderSize(@"C:\Program Files")); Console.WriteLine(sw.ElapsedMilliseconds); sw.Stop(); sw.Reset(); sw.Start(); Console.WriteLine(GetDirSize(@"C:\Program Files")); Console.WriteLine(sw.ElapsedMilliseconds); sw.Stop(); sw.Reset(); sw.Start(); Console.WriteLine(DirSize(new DirectoryInfo(@"C:\Program Files"))); Console.WriteLine(sw.ElapsedMilliseconds); } static long GetDirSize(string path) { return (from item in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories) select new FileInfo(item).Length).Sum(); } static long GetFolderSize(string folder) // 取得資料夾大小 { return long.Parse((new Scripting.FileSystemObjectClass()).GetFolder(folder).Size.ToString()); } public static long DirSize(DirectoryInfo d) { long Size = 0; // Add file sizes.
read morePosts
[C#][Extension Method]String extension method(IsNull、IsNullOrEmpty、IsNullOrWhiteSpace、IsMatch)
namespace ConsoleApplication1 { public static class StringExtension { public static Boolean IsNull(this string str) { return str == null; }
public static Boolean IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } public static Boolean IsNullOrWhiteSpace(this string str) { return string.IsNullOrWhiteSpace(str); } public static bool IsMatch(this string str, string pattern) { if (str.IsNullOrEmpty()) throw new ArgumentNullException("str"); if (pattern.IsNullOrEmpty()) throw new ArgumentNullException("pattern"); return Regex.IsMatch(str, pattern); } } } namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string nullStr = null; string emptyStr = string.
read morePosts
[C#][JavaScript]WinForm與WebPage的JavaScript互通(一)
namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { webBrowser1.DocumentText = @"<script>function ShowAlert(alertMessage) {alert (alertMessage);}</script>"; } private void button1_Click(object sender, EventArgs e) { webBrowser1.Document.InvokeScript("ShowAlert", new object[] { "alert message..." }); } } }
namespace WindowsFormsApplication3 { [PermissionSet(SecurityAction.Demand, Name = “FullTrust”)] [ComVisible(true)] public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { webBrowser1.
read morePosts
[C#][JavaScript]WinForm與WebPage的JavaScript互通(二) - 動態加入並調用JavaScript
private void button1_Click(object sender, EventArgs e) { MessageBox.Show(webBrowser1.Document.InvokeScript("GetVar", new object[] { "executeCount" }).ToString()); } public void OnWebPageReady() { HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; HtmlElement script = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement; element.text = "function GetVar(varName) { return eval('(' + varName + ')'); }"; head.AppendChild(script); } }</pre></div> public void OnWebPageReady() { webBrowser1.Document.InvokeScript("ShowAlert", new object[] { "WebPage Ready..." }); HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; HtmlElement script = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement; element.text = "function GetJsonValue(json, member) { return eval('(' + json + '.
read morePosts
[C#][VB.NET]Path.GetTempFileName的IOException
namespace ConsoleApplication9 { class Program { static void Main(string[] args) { var sw = new Stopwatch(); for (int i = 1; i <= 65536; ++i) { sw.Start(); Console.WriteLine(String.Format("{0} {1}", Path.GetTempFileName(), sw.ElapsedMilliseconds.ToString())); sw.Stop(); sw.Reset(); } } } }
read morePosts
[C#][VB.NET]使用MFT Scanner遍巡USN Journal,快速找出磁碟內的所有檔案
public class MFTScanner { private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); private const uint GENERIC_READ = 0x80000000; private const int FILE_SHARE_READ = 0x1; private const int FILE_SHARE_WRITE = 0x2; private const int OPEN_EXISTING = 3; private const int FILE_READ_ATTRIBUTES = 0x80; private const int FILE_NAME_IINFORMATION = 9; private const int FILE_FLAG_BACKUP_SEMANTICS = 0x2000000; private const int FILE_OPEN_FOR_BACKUP_INTENT = 0x4000; private const int FILE_OPEN_BY_FILE_ID = 0x2000; private const int FILE_OPEN = 0x1; private const int OBJ_CASE_INSENSITIVE = 0x40; private const int FSCTL_ENUM_USN_DATA = 0x900b3;
read morePosts
[C#][VB.NET]自定義例外對話框
<pre> ExceptionDialog.ShowBugWindowOnError()</pre> <pre class="alt"> <span class="kwrd">End</span> Sub</pre> <pre><span class="kwrd">Imports</span> System.Threading</pre> <pre class="alt"><span class="kwrd">Imports</span> System.Text</pre> <pre> </pre> <pre class="alt"><span class="kwrd">Public</span> <span class="kwrd">Class</span> ExceptionDialog</pre> <pre> </pre> <pre class="alt"><span class="preproc">#Region</span> <span class="str">"Const"</span></pre> <pre> <span class="kwrd">Const</span> OpenDetailButtonText <span class="kwrd">As</span> <span class="kwrd">String</span> = <span class="str">"v 詳細資料"</span></pre> <pre class="alt"> <span class="kwrd">Const</span> CloseDetailButtonText <span class="kwrd">As</span> <span class="kwrd">String</span> = <span class="str">"^ 詳細資料"</span></pre> <pre><span class="preproc">#End Region</span></pre> <pre class="alt"> </pre> <pre> </pre> <pre class="alt"> </pre> <pre><span class="preproc">#Region</span> <span class="str">"Var"</span></pre> <pre class="alt"> <span class="kwrd">Private</span> _isDetailOpened <span class="kwrd">As</span> <span class="kwrd">Boolean</span></pre> <pre><span class="preproc">#End Region</span></pre> <pre class="alt"> </pre> <pre> </pre> <pre class="alt"> </pre> <pre><span class="preproc">#Region</span> <span class="str">"Public Shared Method"</span></pre> <pre class="alt"> </pre> <pre> <span class="rem">'***************************************************************************</span></pre> <pre class="alt"> <span class="rem">'Author: Larry Nung</span></pre> <pre> <span class="rem">'Date: 2009/4/9</span></pre> <pre class="alt"> <span class="rem">'Purpose: </span></pre> <pre> <span class="rem">'Memo: </span></pre> <pre class="alt"> <span class="rem">'***************************************************************************</span></pre> <pre> <span class="rem">''' <summary></span></pre> <pre class="alt"> <span class="rem">''' Shows the bug window on error.
read morePosts
[C#]Command Line Parser Library
[OptionArray("o", "output", HelpText = "The output files to generate.")] public string[] OutputFiles { get; set; } [OptionList("k", "keywords", Separator = ':', HelpText = "Specify keywords to search the text, separated by a colon.")] public List<string> Keywords { get; set; } [ValueList(typeof(List<string>), MaximumElements = 3)] public List<string> Items { get; set; } ... }</pre></div> [HelpOption] public string GetUsage() { ... } }</pre></div> help.AddPreOptionsLine(" "); help.AddPreOptionsLine("CommandLine parser library demo..."); help.AddPreOptionsLine(" "); help.
read morePosts
[C#]DateTime 與 ISO8601 格式字串的相互轉換
return sucessed ? new DateTime?(dt) : null; }</pre></div>
read morePosts
[C#]Decode Unicode Character
if (!match.Success) return string.Empty; var code = match.Groups["code"].Value; int value = Convert.ToInt32(code, 16); return ((char)value).ToString(); }</pre>
read morePosts
[C#]DropBox開發系列 - 使用DropNet上傳檔案至DropBox
... var selectedNode = treeView1.SelectedNode; if (selectedNode == null) return; var metaData = selectedNode.Tag as MetaData; if (metaData == null) return; if (!metaData.Is_Dir) { MessageBox.Show("Please select a folder first."); return; } if (tbxFile.Text.Length == 0) { MessageBox.Show("Please select a file to upload first."); return; } if (!File.Exists(tbxFile.Text)) { MessageBox.Show("File not found."); return; } m_DropNetClient.UploadFile(metaData.Path, Path.GetFileName(tbxFile.Text), File.ReadAllBytes(tbxFile.Text)); ...</pre></div> namespace DropNetDemo { public partial class Form1 : Form { #region Var private DropNetClient _dropNetClient; #endregion
read morePosts
[C#]DropBox開發系列 - 使用DropNet下載DropBox內存放的檔案
var metaData = selectedNode.Tag as MetaData; if(metaData == null) return; using (var saveFileDialog = new SaveFileDialog()) { saveFileDialog.FileName = metaData.Name; if(saveFileDialog.ShowDialog() == DialogResult.OK) { var fileData = m_DropNetClient.GetFile(metaData.Path); File.WriteAllBytes(saveFileDialog.FileName, fileData); } } ...</pre></div> namespace DropNetDemo { public partial class Form1 : Form { #region Var private DropNetClient _dropNetClient; #endregion
#region Private Property private DropNetClient m_DropNetClient { get { return _dropNetClient ?? (_dropNetClient = new DropNetClient(tbxAppKey.Text, tbxAppSecret.Text)); } set { _dropNetClient = value; } } #endregion public Form1() { InitializeComponent(); } private void SetSecretAndToken(string secret, string token) { Settings.
read morePosts
[C#]DropBox開發系列 - 使用DropNet進行DropBox的OAuth認證
... dialog.Controls.Add(browesr); dialog.ShowDialog(); ... }</pre></div> if (DoOAuth(callbackUrl, cancelCallbackUrl, size) == DialogResult.OK) { var accessToken = m_DropNetClient.GetAccessToken(); } ... private DialogResult DoOAuth(string callbackUrl, string cancelCallbackUrl, System.Drawing.Size size) { using (var dialog = new Form()) { var browesr = new WebBrowser() { Dock = DockStyle.Fill }; m_DropNetClient.GetToken(); var authUrl = m_DropNetClient.BuildAuthorizeUrl(); browesr.Navigated += (s, ex) => { var url = ex.Url.ToString(); if (url.Equals(callbackUrl)) { dialog.DialogResult = DialogResult.OK; } else if (url.Equals(cancelCallbackUrl)) { dialog.
read morePosts
[C#]DropBox開發系列 - 使用DropNet進行DropBox的二次登入
return; } ... if (DoOAuth(callbackUrl, cancelCallbackUrl, size) == DialogResult.OK) { var accessToken = m_DropNetClient.GetAccessToken(); Properties.Settings.Default.SECRET = accessToken.Secret; Properties.Settings.Default.TOKEN = accessToken.Token; Properties.Settings.Default.Save(); }</pre></div> namespace DropNetDemo { public partial class Form1 : Form { #region Var private DropNetClient _dropNetClient; #endregion
#region Private Property private DropNetClient m_DropNetClient { get { return _dropNetClient ?? (_dropNetClient = new DropNetClient(tbxAppKey.Text, tbxAppSecret.Text)); } set { _dropNetClient = value; } } #endregion public Form1() { InitializeComponent(); } private void SetSecretAndToken(string secret, string token) { Settings.
read morePosts
[C#]DropBox開發系列 - 使用DropNet遍巡DropBox內存放的檔案
FillTreeView(); return; } var callbackUrl = "https://www.dropbox.com/1/oauth/authorize"; var cancelCallbackUrl = "https://www.dropbox.com/home"; var size = new Size(1024, 600); if (DoOAuth(callbackUrl, cancelCallbackUrl, size) == DialogResult.OK) { var accessToken = m_DropNetClient.GetAccessToken(); Properties.Settings.Default.SECRET = accessToken.Secret; Properties.Settings.Default.TOKEN = accessToken.Token; Properties.Settings.Default.Save(); FillTreeView(); } }
private void FillTreeView() { treeView1.Nodes.Clear(); var metaData = m_DropNetClient.GetMetaData("/");
FillDirOrFileToTreeView(null, metaData); }
private void FillDirOrFileToTreeView(TreeNode parentNode, MetaData metaData) { if (metaData.Contents == null) return;
var nodes = (parentNode == null) ? treeView1.
read morePosts
[C#]Export PowerPoint file to photos
var ppt = application.Presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); var index = 0; var fileName = Path.GetFileNameWithoutExtension(file); foreach (Slide slid in ppt.Slides) { ++index; slid.Export(Path.Combine(outputPath, string.Format("{0}{1}.jpg", fileName, index)), "jpg", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); } ppt.Close(); application.Quit(); GC.Collect(); }</pre></div> void ConvertPptToJpg(string file, string outputPath) { Type t = Type.GetTypeFromProgID("PowerPoint.Application"); object o = Activator.CreateInstance(t); object p = t.InvokeMember( "Presentations", BindingFlags.Public | BindingFlags.GetProperty, null, o, null, null); Type t2 = p.GetType(); object ppt = t2.InvokeMember("Open", BindingFlags.Public | BindingFlags.
read morePosts
[C#]Json.NET - A high performance Json library
public String NickName { get; set; } public DateTime Birthday { get; set; } public int Age { get { return (int)((DateTime.Now - Birthday).TotalDays / 365); } } }</pre></div> Person Larry = new Person { Name = "Larry Nung", NickName = "蹂躪", Birthday = new DateTime(1980,4,19) }; var json = JsonConvert.SerializeObject(Larry, Formatting.Indented); ... var person = JsonConvert.DeserializeObject<Person>(json); ...</pre></div> public String NickName { get; set; } public DateTime Birthday { get; set; } public int Age { get { return (int)((DateTime.
read morePosts
[C#]Json.NET - Reducing Serialized JSON Size
public String NickName { get; set; } public DateTime Birthday { get; set; } public int Age { get { return (int)((DateTime.Now - Birthday).TotalDays / 365); } } }
Person Larry = new Person { Name = “Larry Nung”, Birthday = new DateTime(1980,4,19) };
var json = JsonConvert.SerializeObject(Larry, Formatting.Indented);
Console.WriteLine(json);
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public String NickName { get; set; } ... public bool ShouldSerializeNickName() { return !string.IsNullOrEmpty(NickName); } }</pre></div> protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.
read morePosts
[C#]Linq在使用Distinct去除重複資料時如何指定所要依據的成員屬性
/// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; set; } #endregion #region Public Method /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return Name; } #endregion</pre> public bool Equals(Person x, Person y) { return x.Name.Equals(y.Name); } public int GetHashCode(Person obj) { return obj.
read morePosts
[C#]ListBox如何偵測Item的新增、插入、與刪除
switch (m.Msg) { case LB_ADDSTRING: itemValue = Marshal.PtrToStringUni(m.LParam); OnItemAdded(EventArgs.Empty); break; case LB_INSERTSTRING: itemIndex = (int)m.WParam; itemValue = Marshal.PtrToStringUni(m.LParam); OnItemInserted(EventArgs.Empty); break; case LB_DELETESTRING: itemIndex = (int)m.WParam; OnItemDeleted(EventArgs.Empty); break; default: break; } base.WndProc(ref m); } </pre></div> namespace WindowsFormsApplication4 { public partial class Form1 : Form { class ListBoxEx : ListBox { #region Const private const int LB_ADDSTRING = 0x180; private const int LB_INSERTSTRING = 0x181; private const int LB_DELETESTRING = 0x182; #endregion
read morePosts
[C#]MEF開發系列 - Managed Extensibility Framework(MEF)的概念與簡介
public MainForm() { InitializeComponent(); var catalog = new DirectoryCatalog(Environment.CurrentDirectory, "*.dll"); var container = new CompositionContainer(catalog); container.ComposeParts(this); foreach (IModule module in Modules) { module.Host = this; 模組MToolStripMenuItem.DropDownItems.Add(module.Name, null, Module_Click).Tag = module; } } ... } }
read morePosts
[C#]PE檔案格式簡易介紹與PE檔案的檢測
typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER OptionalHeader; } IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;
// Verify file starts with "MZ" signature. if ((bytes[0] != 0x4d) || (bytes[1] != 0x5a)) { // Not a PE file. return false; } // OFFSET_TO_PE_HEADER_OFFSET = 0x3c s.Seek(0x3c, SeekOrigin.Begin); // read the offset to the PE Header uint offset = r.ReadUInt32(); // go to the beginning of the PE Header s.Seek(offset, SeekOrigin.Begin); bytes = r.ReadBytes(4); // Verify PE header starts with 'PE '.
read morePosts
[C#]Process.Exited事件觸發的執行緒會受Process.SynchronizingObject屬性設定的影響
namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { var process = Process.Start("calc.exe"); process.EnableRaisingEvents = true; process.Exited += new EventHandler(process_Exited); textBox1.Text = "Main Thread ID:" + Thread.CurrentThread.ManagedThreadId.ToString(); Console.Read(); } void process_Exited(object sender, EventArgs e) { MessageBox.Show("Process Thread ID:" + Thread.CurrentThread.ManagedThreadId.ToString()); } } }
namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
read morePosts
[C#]Set Windows 7 Progress Bar's State
#region DllImport [DllImport("user32.dll", CharSet = CharSet.Auto)] internal static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam); #endregion #region Private Method void SetPaused(ProgressBar progressBar) { SendMessage(progressBar.Handle, PBM_SETSTATE, PBST_PAUSE, 0); } void SetError(ProgressBar progressBar) { SendMessage(progressBar.Handle, PBM_SETSTATE, PBST_ERROR, 0); } void SetNormal(ProgressBar progressBar) { SendMessage(progressBar.Handle, PBM_SETSTATE, PBST_NORMAL, 0); } #endregion</pre></div> namespace WindowsFormsApplication3 { public partial class Form1 : Form { #region Const const int PBM_SETPOS = 0x402; const int PBM_GETPOS = 0x0408; const int PBM_SETSTATE = 0x410; const int PBST_PAUSE = 0x0003; const int PBST_ERROR = 0x0002; const int PBST_NORMAL = 0x0001; #endregion
read morePosts
[C#]仿照Chrome的Multi-process Architecture
var options = new Options(); ICommandLineParser parser = new CommandLineParser(); if (parser.ParseArguments(args, options)) { m_ReceiverHandel = (IntPtr)options.Handle; if (options.IsBrowser) { var browserTab = new WebBrowserPage() { StartPosition = FormStartPosition.Manual, Top = -3200, Left = -3200, Width = 0, Height = 0 }; browserTab.TextChanged += browserTab_TextChanged; Application.Run(browserTab); return; } } Application.Run(new MainForm()); }</pre> var host = new ApplicationHost() { File = Application.ExecutablePath, Arguments = string.Format("-b -h {0}", this.Handle), HideApplicationTitleBar = true, Dock = DockStyle.
read morePosts
[C#]使用BitmapDecoder快速取用圖檔內含的縮圖
public Image GetThumbnail(string file) { var decoder = BitmapDecoder.Create(new Uri(file), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); var frame = decoder.Frames.FirstOrDefault();
return (frame.Thumbnail == null) ? null : frame.Thumbnail.GetBitmap(); } …
namespace WindowsFormsApplication33 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
public Image GetThumbnail(string file) { var decoder = BitmapDecoder.Create(new Uri(file), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); var frame = decoder.Frames.FirstOrDefault(); return (frame.Thumbnail == null) ? null : frame.Thumbnail.GetBitmap(); } private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.
read morePosts
[C#]使用ExifLibrary簡易快速的擷取圖片的Exif資訊
namespace WindowsFormsApplication34 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void btnLoad_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { var photoFile = openFileDialog1.FileName; ExifFile exifFile = ExifFile.Read(photoFile); pbxThumbnail.Image = exifFile.Thumbnail.ToBitmap(); tbxMessage.Clear(); foreach (ExifProperty item in exifFile.Properties.Values) { tbxMessage.Text += string.Format("{0}:{1} “, item.Name, item.Value); } } } } }
read morePosts
[C#]使用Faker.Net輔助建立假的數據資料
namespace ConsoleApplication11 { class Program { static void Main(string[] args) { for (int i = 0; i < 3; ++i) { ShowFakeUserInfo(); Console.WriteLine(new String(’=’, 50)); } }
static void ShowFakeUserInfo() { Console.WriteLine(String.Format("User: {0}", Faker.Name.FullName())); Console.WriteLine(String.Format("Phone: {0}", Faker.Phone.Number())); Console.WriteLine(String.Format("Email1: {0}", Faker.Internet.Email())); Console.WriteLine(String.Format("Email2: {0}", Faker.Internet.FreeEmail())); Console.WriteLine(String.Format("Company: {0}", Faker.Company.Name())); Console.WriteLine(String.Format("Country: {0}", Faker.Address.Country())); } } }
read morePosts
[C#]使用FindFirstFile、FindNextFile API實做EnumerateFiles
[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData); [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] private static extern bool FindNextFile(IntPtr hndFindFile, ref WIN32_FIND_DATA lpFindFileData); [DllImport( "kernel32.dll" , SetLastError = true )] private static extern bool FindClose(IntPtr hndFindFile); [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto), BestFitMapping(false)] internal struct WIN32_FIND_DATA { public FileAttributes dwFileAttributes; public uint ftCreationTime_dwLowDateTime; public uint ftCreationTime_dwHighDateTime; public uint ftLastAccessTime_dwLowDateTime; public uint ftLastAccessTime_dwHighDateTime; public uint ftLastWriteTime_dwLowDateTime; public uint ftLastWriteTime_dwHighDateTime; public uint nFileSizeHigh; public uint nFileSizeLow; public int dwReserved0; public int dwReserved1; [MarshalAs(UnmanagedType.
read morePosts
[C#]使用InternetGetConnectedState API偵測目前電腦網路的連線狀態
namespace ConsoleApplication21 { class Program { [DllImport(“wininet”)] public static extern bool InternetGetConnectedState( ref uint lpdwFlags, uint dwReserved );
static void Main(string[] args) { uint flags = 0x0; var isNetworkAvailable = InternetGetConnectedState(ref flags, 0); Console.WriteLine(string.Format("Network available: {0} ({1})", isNetworkAvailable.ToString(), flags.ToString())); } } }
read morePosts
[C#]使用Microsoft Translator Soap API實作翻譯功能
if (String.IsNullOrEmpty(text)) return DEFAULT_DETECTED_LANG; const string DETECT_API_URI_PATTERN = "http://api.microsofttranslator.com/V2/Http.svc/Detect?appId={0}&text={1}"; const string MATCH_PATTERN = "<[^<>]*>([^<>]*)<[^<>]*>"; WebRequest req = WebRequest.Create(String.Format(DETECT_API_URI_PATTERN, APP_ID, text)); WebResponse resp = req.GetResponse(); string local = DEFAULT_DETECTED_LANG; using (StreamReader reader = new StreamReader(resp.GetResponseStream())) { local = reader.ReadToEnd(); local = Regex.Match(local, MATCH_PATTERN).Groups[1].Value; } return local; }</pre> if (!langs.Contains(lang)) lang = "en"; return client.Speak(APP_ID, tbxSource.Text, lang, "audio/wav", string.Empty); }</pre> var langNames = (from lang in langs.AsParallel() select new { Name = Client.
read morePosts
[C#]使用Mutex實現單一程式執行個體的注意事項
namespace WindowsFormsApplication10 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
Boolean bCreatedNew; //Create a new mutex using specific mutex name Mutex m = new Mutex(false, "myUniqueName", out bCreatedNew); if (bCreatedNew) Application.Run(new Form1()); } } }
//Create a new mutex using specific mutex name Mutex m = new Mutex(false, "myUniqueName", out bCreatedNew); GC.Collect(); if (bCreatedNew) Application.
read morePosts
[C#]使用Reflection檢查指定類別是否含有預設建構子
namespace ConsoleApplication17 { class Program { static void Main(string[] args) { Console.WriteLine(HasDefaultConstructor1<TestClass1>()); Console.WriteLine(HasDefaultConstructor2<TestClass1>());
Console.WriteLine(HasDefaultConstructor1<TestClass2>()); Console.WriteLine(HasDefaultConstructor2<TestClass2>()); } private static Boolean HasDefaultConstructor1<T>() { var type = typeof (T); foreach (var c in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)) { if (c.GetParameters().Length ==0) return true; } return false; } private static Boolean HasDefaultConstructor2<T>() { var type = typeof (T); return type.GetConstructor(Type.EmptyTypes) != null; } } internal class TestClass1 { public TestClass1() { } public TestClass1(int arg1) { } } internal class TestClass2 { public TestClass2(int arg1) { } } }
read morePosts
[C#]使用SharpShell實現Shell Icon Overlay功能
namespace ReadOnlyFileIconOverlayHandler { /// <summary> /// The ReadOnlyFileIconOverlayHandler is an IconOverlayHandler that shows /// a padlock icon over files that are read only. /// </summary> [ComVisible(true)] public class ReadOnlyFileIconOverlayHandler : SharpIconOverlayHandler { /// <summary> /// Called by the system to get the priority, which is used to determine /// which icon overlay to use if there are multiple handlers. The priority /// must be between 0 and 100, where 0 is the highest priority.
read morePosts
[C#]使用SHEmptyRecycleBin API清除資源回收桶
<td valign="top" width="200">No dialog box confirming the deletion of the objects will be displayed.</td> </tr> <tr> <td valign="top" width="200"><strong>SHERB_NOPROGRESSUI</strong></td> <td valign="top" width="200">No dialog box indicating the progress will be displayed.</td> </tr> <tr> <td valign="top" width="200"><strong>SHERB_NOSOUND</strong></td> <td valign="top" width="200">No sound will be played when the operation is complete.</td> </tr>
read morePosts
[C#]使用ShowCaret amp; HideCaret控制元件上的插入符號
[DllImport("user32.dll")] static extern bool HideCaret(IntPtr hWnd);</pre></div> namespace WindowsFormsApplication22 { public partial class Form1 : Form { [DllImport(“user32.dll”)] static extern bool ShowCaret(IntPtr hWnd);
[DllImport("user32.dll")] static extern bool HideCaret(IntPtr hWnd); public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { if (rbtnShowCaret.Checked) { ShowCaret(textBox1.Handle); } else { HideCaret(textBox1.Handle); } } } }
read morePosts
[C#]偵測系統Power狀態的改變以及是否進入Sleep mode
namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged); } void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) { textBox1.Text += e.Mode.ToString() + Environment.NewLine; } } }
namespace WindowsFormsApplication15 { public partial class Form1 : Form { private const int WM_POWERBROADCAST = 0x218; private const int PBT_APMSUSPEND = 0x4; private const int PBT_APMRESUMESUSPEND = 0x7; private const int PBT_APMRESUMEAUTOMATIC = 0x12; public Form1() { InitializeComponent(); }
read morePosts
[C#]取用.picasa.ini內存的現有資訊來做臉部偵測
rect64(3f845bcb59418507) break this number into 4 16-bit numbers by using substrings: ‘3f845bcb59418507’.substring(0,4) //“3f84” ‘3f845bcb59418507’.substring(4,8) //“5bcb” ‘3f845bcb59418507’.substring(8,12) // “5941” ‘3f845bcb59418507’.substring(12,16) // “8507” convert each obtained substring to an integer and divide it by the highest 16-bit number (2^16 = 65536), which should give 0 < results < 1. these are the relative coordinates of the crop rectangle (left,top,right,bottom): parseInt(“3f84”,16)/65536 //0.24810791015625 - left parseInt(“5bcb”,16)/65536 //0.3585662841796875 - top parseInt(“5941”,16)/65536 //0.3486480712890625 - right parseInt(“8507”,16)/65536 //0.
read morePosts
[C#]在.NET程式中要如何指定Windows的ClassName去接收視窗的訊息
protected override CreateParams CreateParams { get { base.CreateParams.ClassName = "test"; return base.CreateParams; } } }</pre></div> #region Delegate delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); #endregion #region DllImport /// <summary> /// Registers the class W. /// </summary> /// <param name="lpWndClass">The lp WND class.</param> /// <returns></returns> [DllImport("user32.dll", SetLastError = true)] static extern UInt16 RegisterClassW( [In] ref WNDCLASS lpWndClass ); /// <summary> /// Creates the window ex W. /// </summary> /// <param name="dwExStyle">The dw ex style.
read morePosts
[C#]如何使用TraceListener實作類似Visual Studio的輸出視窗
/// <summary> /// Initializes a new instance of the <see cref="ListBoxLogTraceListener"/> class. /// </summary> /// <param name="listBox">The list box.</param> public ListBoxLogTraceListener(ListBox listBox) { m_ListBox = listBox; } /// <summary> /// Writes the output to the OutputDebugString function and to the <see cref="M:System.Diagnostics.Debugger.Log(System.Int32,System.String,System.String)"/> method, followed by a carriage return and line feed ( ). /// </summary> /// <param name=“message”>The message to write to OutputDebugString and <see cref=“M:System.Diagnostics.Debugger.Log(System.Int32,System.String,System.String)”/>.</param> /// <PermissionSet> /// <IPermission class=“System.
read morePosts
[C#]如何使用Windows Shell做Zip檔的壓縮與解壓縮
public static void Compress(string sourceFolderPath, string zipFile) { if (!Directory.Exists(sourceFolderPath)) throw new DirectoryNotFoundException(); if (!File.Exists(zipFile)) File.Create(zipFile).Dispose(); ShellCopyTo(sourceFolderPath, zipFile); } public static void DeCompress(string zipFile, string destinationFolderPath) { if (!File.Exists(zipFile)) throw new FileNotFoundException(); if (!Directory.Exists(destinationFolderPath)) Directory.CreateDirectory(destinationFolderPath); ShellCopyTo(zipFile, destinationFolderPath); } </pre> public class ZipEntry { #region Private Property private FolderItem m_ShellItem { get; set; } private IEnumerable<ZipEntry> _entrys; #endregion #region Public Property /// <summary> /// Gets the name. /// </summary> /// <value>The name.
read morePosts
[C#]如何取出最近在Windows上所使用的文件檔案
return targetFile; } public static IEnumerable<string> GetRecentlyFiles() { var recentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Recent); return from file in Directory.EnumerateFiles(recentFolder) where Path.GetExtension(file) == ".lnk" select GetShortcutTargetFile(file); } }</pre></div> namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Clear(); foreach (var file in RecentlyFileHelper.GetRecentlyFiles()) { listBox1.Items.Add(file); } var recentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Recent); fileSystemWatcher1.Path = recentFolder; fileSystemWatcher1.Created += new System.IO.FileSystemEventHandler(fileSystemWatcher1_Created); } void fileSystemWatcher1_Created(object sender, System.
read morePosts
[C#]如何取得Process的Owner
if (processObj == null) throw new ArgumentException("Process not exists!"); var argList = new string[2]; int returnVal = Convert.ToInt32(processObj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { return string.Join(@"\", argList.Reverse().ToArray()); } return null; }</pre></div> if (processObj == null) throw new ArgumentException("Process not exists!"); var argList = new string[2]; int returnVal = Convert.ToInt32(processObj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { return string.Join(@"\", argList.Reverse().ToArray()); } return null; } }
read morePosts
[C#]如何在程式中內嵌其它應用程式
if (HideApplicationTitleBar) SetWindowLong(handle, GWL_STYLE, WS_VISIBLE);
SetParent(handle, this.Handle);
MoveWindow(handle, 0, 0, this.Width, this.Height, true); …
if (handle != IntPtr.Zero) MoveWindow(handle, 0, 0, this.Width, this.Height, true); }</pre>
read morePosts
[C#]如何解決在Vista以後開啟檔案FileSystemWatcher無法觸發LastAccess的問題
static void fw_Changed(object sender, FileSystemEventArgs e) { }</pre>
read morePosts
[C#]實作UDP Broadcast的傳送與接收
private static void BroadcastMessage(byte[] message, int port) { using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { sock.EnableBroadcast = true; sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); var iep = new IPEndPoint(IPAddress.Broadcast, port); sock.SendTo(message, iep); } }</pre></div> private void ReceiveBroadcastMessage(Action<EndPoint, byte[]> receivedAction, int port) { using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { var ep = new IPEndPoint(IPAddress.Any, port) as EndPoint; sock.Bind(ep);
while (true) { var buffer = new byte[1024]; var recv = sock.
read morePosts
[C#]將指定的檔案刪除並送到資源回收桶
#region Dllimport /// <summary> /// SHs the file operation. /// </summary> /// <param name="FileOp">The file op.</param> /// <returns></returns> [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp); #endregion #region Const public const int FO_DELETE = 3; public const int FOF_ALLOWUNDO = 0x40; public const int FOF_NOCONFIRMATION = 0x10; #endregion #region Public Static Method public static void DeleteFileToRecyclebin(string file, Boolean showConfirmDialog = false) { var shf = new SHFILEOPSTRUCT(); shf.
read morePosts
[C#]平行處理網路傳輸時因連線數不足發生連線Timeout的解決方案
namespace ConsoleApplication15 { class Program { public static string url = “https://www.google.com/images/srpr/logo3w.png"; private static List<WaitHandle> finished = new List<WaitHandle>(); public static void Main() { ServicePointManager.DefaultConnectionLimit = 200;
finished.Clear(); for (var idx = 0; idx < 5; ++idx ) { finished.Add(new ManualResetEvent(false)); Download(idx, url); } WaitHandle.WaitAll(finished.ToArray()); Console.WriteLine(“Done…”);
}
private static void Download(int idx, string url) { var wc = new WebClient(); wc.OpenReadCompleted += wc_OpenReadCompleted; wc.OpenReadAsync(new Uri(url), idx); } private static void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Console.
read morePosts
[C#]從PE檔中讀取組件資訊
/// <summary> /// AssemblyDetails is used in the update builder, wyBuild (http://wyday.com/wybuild/), /// to automagically detect .NET assemblies properties, namely: /// - if they are compiled with a Strong Name, /// - CPUVersion the assembly was compiled as, /// - .NET Framework the assembly was compiled for (.NET 2.0 or 4.0) /// </summary> public class AssemblyDetails { /// <summary> /// The CPUVersion the assembly was compiled with. /// </summary> public CPUVersion CPUVersion;
read morePosts
[C#]忽略在 HTTP 剖析期間發生的驗證錯誤
if (anInstance != null) { //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); if (aUseUnsafeHeaderParsing != null) { aUseUnsafeHeaderParsing.SetValue(anInstance, true); return true; } } } } return false; }</pre>
read morePosts
[C#]擷取Picasa資料庫(_.PMP)內現有的資料
var type = br.ReadInt16(); if (0x1332 != br.ReadInt16()) { throw new Exception("Incorrect format"); } if (0x00000002 != br.ReadInt32()) { throw new Exception("Incorrect format"); } if (type != br.ReadInt16()) { throw new Exception("Incorrect format"); } if (0x1332 != br.ReadInt16()) { throw new Exception("Incorrect format"); } var number = br.ReadInt32(); switch (type) { case 0x00: DumpStringField(br, number); break; case 0x01: Dump4ByteField(br, number); break; case 0x02: DumpDateField(br, number); break; case 0x03: DumpByteField(br, number); break; case 0x04: Dump8ByteField(br, number); break; case 0x05: Dump2ByteField(br, number); break; case 0x06: DumpStringField(br, number); break; case 0x07: Dump4ByteField(br, number); break; default: throw new Exception("Incorrect format"); } } } .
read morePosts
[C#]簡易的Backoff window實現類別
namespace ConsoleApplication12 { public class BackOff { #region Var private int _level; private Random _random; #endregion
#region Private Property private ReadOnlyCollection<int> m_BackOffWindows { get; set; } private Random m_Random { get { if (_random == null) _random = new Random(Guid.NewGuid().GetHashCode()); return _random; } } #endregion #region Public Property /// <summary> /// Gets or sets the level. /// </summary> /// <value>The level.</value> public int Level { get { return _level; } set { if (value <= 0) throw new Exception("Level value must be bigger than zero!
read morePosts
[C#]設定WebBrowser Control運行的User Agent版本
64 bit: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION
read morePosts
[C#]透過PerformanceCounter取得特定Process的CPU使用率
var instances = category.GetInstanceNames(); foreach (var instance in instances) { using (var counter = new PerformanceCounter(category.CategoryName, "ID Process", instance, true)) { int val = (int)counter.RawValue; if (val == pid) { return instance; } } } throw new ArgumentException("Invalid pid!"); }</pre> var lastUpdateTime = default(DateTime); m_UpdateTimePool.TryGetValue(pid, out lastUpdateTime); var interval = DateTime.Now - lastUpdateTime; if (interval.TotalSeconds > 1) { m_CpuUsagePool[pid] = (int)(m_CounterPool[pid].NextValue() / Environment.ProcessorCount); } return m_CpuUsagePool[pid]; }</pre> public static class ProcessExtension { #region Private Static Var private static Dictionary<int, PerformanceCounter> _counterPool; private static Dictionary<int, DateTime> _updateTimePool; private static Dictionary<int, int> _cpuUsagePool; #endregion
read morePosts
[Performance][C#]ToString V.S Enum.GetName
class Program { static void Main(string[] args) { var count = 1000000; Console.WriteLine("ToString: {0} ms", DoTest(count, () => { var temp = MyEnum.EnumItem1.ToString(); }).ToString()); Console.WriteLine("Enum.GetName: {0} ms", DoTest(count, () => { var temp = Enum.GetName(typeof(MyEnum), MyEnum.EnumItem1); }).ToString()); } static long DoTest(int count, Action action) { var sw = Stopwatch.StartNew(); for(int i = 0;i<count;++i) { action(); } return sw.ElapsedMilliseconds; } } } private static string InternalFormat(RuntimeType eT, object value) { if (eT.
read morePosts
[Visual Studio][C#]Visual Studio Achievements API
namespace AchievementsAPIDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private string GetHTMLSourceCode(string url) { HttpWebRequest request = (WebRequest.Create(url)) as HttpWebRequest; HttpWebResponse response = request.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(response.GetResponseStream())) { return sr.ReadToEnd(); } } private void Form1_Load(object sender, EventArgs e) { var obj = new VSAchievements.Achievement(GetHTMLSourceCode("http://channel9.msdn.com/achievements/visualstudio?json=true")); foreach (var achievement in obj.Achievements) { flowLayoutPanel1.Controls.Add(new PictureBox() { ImageLocation = achievement.IconSmall }); flowLayoutPanel1.Controls.Add(new Label() { Text = achievement.
read morePosts
FlickrNet開發系列- FlickrNet基本功能開發(一)
MessageBox.Show(string.Format( @“FullName: {0} UserId: {1} UserName: {2}”, user.FullName, user.UserId, user.UserName)); }
var photoSets = m_Flickr.PhotosetsGetList(userID); foreach (var photoSet in photoSets) { var pic = new PictureBox() { ImageLocation = photoSet.PhotosetThumbnailUrl, BorderStyle = BorderStyle.FixedSingle, SizeMode = PictureBoxSizeMode.AutoSize }; container.Controls.Add(pic); } var photos = m_Flickr.PhotosGetNotInSet(); foreach (var photo in photos) { var pic = new PictureBox() { ImageLocation = photo.ThumbnailUrl, SizeMode = PictureBoxSizeMode.AutoSize }; container.Controls.Add(pic); } form.Controls.Add(container); form.ShowDialog(); }</pre> foreach (var photo in photos) { var pic = new PictureBox() { ImageLocation = photo.
read morePosts
FlickrNet開發系列- FlickrNet基本功能開發(二)
for (int i = 0; i < photos.Count; ++i) { var photo = photos[i]; var pic = new PictureBox() { ImageLocation = photo.ThumbnailUrl, BorderStyle = BorderStyle.FixedSingle, SizeMode = PictureBoxSizeMode.AutoSize, Tag = photo }; container.Controls.Add(pic); pic.Click += (sender, e) => { photo = (sender as PictureBox).Tag as FlickrNet.Photo; var sizes = m_Flickr.PhotosGetSizes(photo.PhotoId); var hasLargePhoto = (from item in sizes where string.Equals(item.Label, "Large", StringComparison.CurrentCultureIgnoreCase) select item).Count() > 0; var dialog = new Form(); var photoBox = new PictureBox() { ImageLocation = hasLargePhoto ?
read morePosts
How to customize .NET 4.0's System.Runtime.Caching.ChangeMonitor
namespace CustomChangeMonitorDemo { public class ClipboardChangeMonitor : ChangeMonitor { #region Var private string _clipboardText; private Timer _timer; private string _uniqueID; #endregion
#region Private Property private string m_ClipboardText { get { return _clipboardText ?? string.Empty; } set { if (_clipboardText == value) return; _clipboardText = value; OnChanged(value); } } private System.Windows.Forms.Timer m_Timer { get { return _timer ?? (_timer = new System.Windows.Forms.Timer()); } } #endregion #region Public Property public override string UniqueId { get { return _uniqueID ?
read morePosts
How to use MetaWeblogSharp
return Login(connectionInfo); } private static Client Login(BlogConnectionInfo connectionInfo) { var client = new Client(connectionInfo); var blog = client.GetUsersBlogs().FirstOrDefault(); connectionInfo.BlogID = blog.BlogID; connectionInfo.BlogURL = blog.URL; return client; }</pre>
read morePosts
Recursive ContainerFromItem
if (dp != null) return dp; foreach (var item in itemsControl.Items) { var currentTreeViewItem = itemsControl.ItemContainerGenerator.ContainerFromItem(item); var childDp = ContainerFromItem(currentTreeViewItem as ItemsControl, value); if (childDp != null) return childDp; } return null; }</pre> public static class ItemsControlExtension { public static DependencyObject ContainerFromItem(this ItemsControl itemsControl, object value) { var dp = itemsControl.ItemContainerGenerator.ContainerFromItem(value);
if (dp != null) return dp; foreach (var item in itemsControl.Items) { var currentTreeViewItem = itemsControl.ItemContainerGenerator.ContainerFromItem(item); var childDp = ContainerFromItem(currentTreeViewItem as ItemsControl, value); if (childDp !
read morePosts
Use ResourceDictionary to do multi-language in WPF
private void ApplyMultiLanguageResource() { ApplyMultiLanguageResource(CultureInfo.CurrentCulture); } private void ApplyMultiLanguageResource(CultureInfo cultureInfo) { var cultureName = cultureInfo.Name; var resourceFile = string.Empty; try { resourceFile = @"StringResources." + cultureName + ".xaml "; } catch (Exception) { } if (string.IsNullOrEmpty(resourceFile)) resourceFile = @"StringResources.xaml"; var rd = Application.LoadComponent(new Uri(resourceFile, UriKind.Relative)) as ResourceDictionary; var existsRD = this.Resources.MergedDictionaries.Where(item => item.Source.OriginalString.Equals(resourceFile, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (existsRD != null) this.Resources.MergedDictionaries.Remove(existsRD); this.Resources.MergedDictionaries.Add(rd); } }</pre></div>
read morePosts
Use Windows Error Reporting(WER) to collect user-mode dumps
namespace ConsoleApplication46 { class Program { static void Main(string[] args) { var x = 1; var y = x - 1; var result = x / y; } } }
read morePosts
[C#][Control]BitsControl概念與簡易實做
int bitWith = width / 8; bit8.Width = bitWith; bit7.Width = bitWith; bit6.Width = bitWith; bit5.Width = bitWith; bit4.Width = bitWith; bit3.Width = bitWith; bit2.Width = bitWith; bit1.Width = bitWith; int bitHeight = flowLayoutPanel1.ClientSize.Height - bit8.Margin.Top * 2; bit8.Height = bitHeight; bit7.Height = bitHeight; bit6.Height = bitHeight; bit5.Height = bitHeight; bit4.Height = bitHeight; bit3.Height = bitHeight; bit2.Height = bitHeight; bit1.Height = bitHeight; }</pre> public void LoadBitsState(string hexValue) { LoadBitsState(Convert.ToInt32(hexValue, 16)); }</pre> namespace WindowsFormsApplication6 { public partial class BitsControl : UserControl { public BitsControl() { InitializeComponent(); }
read morePosts
[C#][Control]指撥開關控制項的概念與簡易實作
private SwitchState _state; public SwitchState State { get { return _state; } set { if (_state == value) return; _state = value; AdjustOnOffButton(); } } private void AdjustOnOffButton() { switch (State) { case SwitchState.On: OnOffButton.Dock = DockStyle.Top; break; case SwitchState.Off: OnOffButton.Dock = DockStyle.Bottom; break; default: break; } }</pre> private void OnOffButton_Click(object sender, EventArgs e) { Toggle(); }</pre> namespace WindowsFormsApplication3 { public partial class SwitchButton : UserControl {
public enum SwitchState { On, Off } private SwitchState _state; public SwitchState State { get { return _state; } set { if (_state == value) return; _state = value; AdjustOnOffButton(); } } public SwitchButton() { InitializeComponent(); State = SwitchState.
read morePosts
[C#][WPF]WPF程式接收視窗訊息
namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.SourceInitialized += new EventHandler(MainWindow_SourceInitialized); }
void MainWindow_SourceInitialized(object sender, EventArgs e) { IntPtr hwnd = new WindowInteropHelper(this).Handle; HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc)); } IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { //... } return IntPtr.Zero; } } }
read morePosts
[C#]Enable UAC Shield icons and run as administrator
#region Private Method private static bool AtLeastVista() { return (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6); } private static void SetButtonShield(Button btn, bool showShield) { if (!AtLeastVista()) return; btn.FlatStyle = FlatStyle.System; SendMessage(new HandleRef(btn, btn.Handle), BCM_SETSHIELD, IntPtr.Zero, showShield ? new IntPtr(1) : IntPtr.Zero); } #endregion</pre> public static class ButtonExtension { #region DllImport [DllImport(“shell32.dll”, EntryPoint = “#680”, CharSet = CharSet.Unicode)] private static extern bool IsUserAnAdmin();
[DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SendMessage(HandleRef hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); #endregion #region Const const int BCM_SETSHIELD = 0x0000160C; #endregion #region Private Method private static bool AtLeastVista() { return (Environment.
read morePosts
[.Net concept]使用方法與屬性時適時為其值做快取
//Calculate count.... ... return count; }
int count = myObj.Count; for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) ... } }
read morePosts
[C#].NET 4.5 New Feature - Regex match with timeout
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(2)); isMatch = IsMatch(input, pattern); Console.WriteLine(); isMatch = IsMatch(input, pattern, TimeSpan.FromSeconds(4)); } static Boolean IsMatch(string input, string pattern) { try { return Regex.IsMatch(input, pattern, RegexOptions.None); } catch (RegexMatchTimeoutException ex) { // handle exception Console.WriteLine("Match timed out!"); Console.WriteLine("- Timeout interval specified: " + ex.MatchTimeout); Console.WriteLine("- Pattern: " + ex.Pattern); Console.WriteLine("- Input: " + ex.Input); } return false; } static Boolean IsMatch(string input, string pattern, TimeSpan timeout) { try { return Regex.
read morePosts
[C#]RaiseEvent Extension Method (二)
public static void RaiseEvent(this object obj, EventHandler handler, Func<EventArgs> func) { if (handler == null) return; handler(obj, func()); } public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler, TEventArgs e) where TEventArgs : EventArgs { RaiseEvent(obj, handler, () => e); } public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler,Func<TEventArgs> func) where TEventArgs : EventArgs { if (handler == null) return; handler(obj, func()); } }</pre></div> namespace ConsoleApplication14 { class Program { static void Main(string[] args) { Person Larry = new Person(); Larry.
read morePosts
[C#][Linq]Linq to Wikipedia
private IQueryable<WikipediaKeywordSearchResult>KeyWordSearch(string keyWord) { return from item in (new WikipediaContext()).KeywordSearch where item.Keyword == keyWord select item; }</pre></div>
read morePosts
[C#]取得網卡的IPV6位置
namespace ConsoleApplication13 { class Program { static void Main(string[] args) { foreach (var ip in GetLocalIPV6IP()) { Console.WriteLine(ip); } }
private static IEnumerable<String> GetLocalIPV6IP() { return (from adapter in NetworkInterface.GetAllNetworkInterfaces() where adapter .NetworkInterfaceType == NetworkInterfaceType.Ethernet from AddressInfo in adapter.GetIPProperties().UnicastAddresses.OfType<UnicastIPAddressInformation>() where AddressInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 let ipAddress = AddressInfo.Address.ToString() select ipAddress); } } }
read morePosts
[.Net Concept]理解事件的宣告方式與用法
#region Event event NameChangingEventHandler NameChanging; event NameChangedEventHandler NameChanged; #endregion</pre> #region Event event EventHandler<FriendEventArgs> FriendAdded; #endregion
#region Protected Method protected void OnFriendAdded(FriendEventArgs e) { if (FriendAdded == null) return; FriendAdded(this, e); } #endregion
#region Public Method public void AddFriend(Person friend) { Friends.Add(friend); OnFriendAdded(new FriendEventArgs(friend.Name)); } #endregion
…
class FriendEventArgs : EventArgs { #region Var private String _name; #endregion
#region Property public String Name { get { if (_name == null) return String.
read morePosts
[C#]DictService
namespace DictServceDemo { public partial class Form1 : Form {
#region Var private DictService _dictService; #endregion #region Private Property public DictService m_DictService { get { if (_dictService == null) _dictService = new DictService(); return _dictService; } } #endregion #region Constructor public Form1() { InitializeComponent(); } #endregion #region Event Process private void Form1_Load(object sender, EventArgs e) { cbxDict.DisplayMember = "Name"; cbxDict.DataSource = m_DictService.DictionaryList(); cbxStrategy.DisplayMember = "Id"; cbxStrategy.DataSource = m_DictService.StrategyList(); } private void lbxResult_SelectedIndexChanged(object sender, EventArgs e) { if (cbxDict.
read morePosts
[C#]Stream.Write Extension Method
public static class StreamExtension { public static void Write(this Stream targetStream, byte[] buffer) { if (!targetStream.CanWrite) throw new ArgumentException(“targetStream”, “Unwritable stream”);
targetStream.Write(buffer, 0, buffer.Length); } public static void Write(this Stream targetStream, Stream sourceStream) { if (!targetStream.CanWrite) throw new ArgumentException("targetStream", "Unwritable stream"); if (sourceStream == null) throw new ArgumentNullException("sourceStream"); if (!sourceStream.CanRead) throw new ArgumentException("sourceStream", "Unreadable stream"); targetStream.Write(sourceStream, 1024, null); } public static void Write(this Stream targetStream, Stream sourceStream, int bufferSize, Action<object, System.
read morePosts
[C#][Linq]LINQ To WMI
foreach (Win32_UserAccount account in query) { Console.WriteLine(account.Name); } } }
read morePosts
[C#][Linq]BLinq - Linq To Bing
private IEnumerable<ImageSearchResult> SearchImages(string keyWord) { return from item in m_Bing.Images where item.Query == keyWord select item; }</pre>
read morePosts
[.Net Concept]理解並善用String pool
Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2))); Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3))); Console.WriteLine(string.Format("ReferenceEquals(str1, str4) = {0}", ReferenceEquals(str1, str4))); </pre></div> Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2))); Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3))); </pre></div> str2 = string.Intern(str2); str3 = string.Intern(str3); Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2))); Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3)));</pre></div> str1 = string.Intern(str1); Console.WriteLine(string.Format(@"String.IsInterned(str1) = {0}", String.IsInterned(str1) != null));</pre></div> private static void Test(int testCount, int stringLength) { NormalCompare1(string.Empty, string.Empty); NormalCompare2(string.
read morePosts
[C#]LevelUp.Lazy
namespace LazyDemo { class Program { static void Main(string[] args) { var count = 10; LevelUpLazy.Lazy<string>[] lazys = new LevelUpLazy.Lazy<string>[count]; for (int i = 0; i < count; i++) { lazys[i] = new LevelUpLazy.Lazy<string>(DoWork); }
lazys[3].ValueInited += new EventHandler(laz3_ValueInited); lazys[3].BeginInit();
lazys[2].BeginInit();
Stopwatch sw = Stopwatch.StartNew(); Console.WriteLine(“lazy1 result = {0}”, lazys[1].Value); Console.WriteLine(“lazy1 Elapsed Time = {0} ms”, sw.ElapsedMilliseconds);
sw.Restart(); Console.WriteLine(“lazy1 result = {0}”, lazys[1].Value); Console.WriteLine(“lazy1 Elapsed Time = {0} ms”, sw.
read morePosts
土豆視頻開發系列-依影集分類查詢
XmlNodeList nodes = xmlDom.SelectNodes(@"/result/results/AlbumInfo"); foreach (XmlNode node in nodes) { // Name = node.ChildNodes[1].InnerText // picUrl = node.ChildNodes[2].InnerText // … … } … }
read morePosts
[C#]取得檔案內容中的詳細資料
using System.Linq;
using System.Text;
using Shell32;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ViewDetailColumn();
Console.WriteLine(new string(’=’, 50));
var file = @“C:\Users\Public\Music\Sample Music\Kalimba.mp3”;
ViewDetailValue(file, “Album”);
ViewDetailValue(file, “Size”);
}
static IEnumerable<KeyValuePair<string, int>> GetDetailColumn()
{
ShellClass sh = new ShellClass();
Folder dir = sh.NameSpace(@“c:");
int idx = 0;
string columnName = dir.GetDetailsOf(0, idx);
do
{
yield return new KeyValuePair<string, int>(columnName, idx);
columnName = dir.GetDetailsOf(0, ++idx); } while (!
read morePosts
[C#]原子能委員會輻射監控非官方API
namespace LevelUp.RadiationAPI.Demo { public partial class Form1 : Form { private RadiationAgent _radiationAgent; private RadiationAgent m_RadiationAgent { get { if (_radiationAgent == null) { _radiationAgent = new RadiationAgent(); _radiationAgent.AutoUpdateInterval = 5000; _radiationAgent.EnableAutoUpdate = true; } return _radiationAgent; } }
public Form1() { InitializeComponent(); } private void UpdateRadiationValue() { listView1.Items.Clear(); listView1.BeginUpdate(); foreach (var data in m_RadiationAgent.RadiationDatas) { listView1.Items.Add(data.City).SubItems.AddRange(new string[] { data.RadiationValue.ToString(), data.State.ToString() }); } listView1.EndUpdate(); } private void timer1_Tick(object sender, EventArgs e) { UpdateRadiationValue(); } private void Form1_Load(object sender, EventArgs e) { UpdateRadiationValue(); m_RadiationAgent.
read morePosts
[C#]Everything SDK
namespace Everything { /// <summary> /// /// </summary> public class EverythingAPI { #region Const const string EVERYTHING_DLL_NAME = “Everything.dll”; #endregion
#region DllImport [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_SetSearch(string lpSearchString); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetMatchPath(bool bEnable); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetMatchCase(bool bEnable); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetMatchWholeWord(bool bEnable); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetRegex(bool bEnable); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetMax(int dwMax); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SetOffset(int dwOffset); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_GetMatchPath(); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_GetMatchCase(); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_GetMatchWholeWord(); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_GetRegex(); [DllImport(EVERYTHING_DLL_NAME)] private static extern UInt32 Everything_GetMax(); [DllImport(EVERYTHING_DLL_NAME)] private static extern UInt32 Everything_GetOffset(); [DllImport(EVERYTHING_DLL_NAME)] private static extern string Everything_GetSearch(); [DllImport(EVERYTHING_DLL_NAME)] private static extern StateCode Everything_GetLastError(); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_Query(); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_SortResultsByPath(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetNumFileResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetNumFolderResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetNumResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetTotFileResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetTotFolderResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern int Everything_GetTotResults(); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_IsVolumeResult(int nIndex); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_IsFolderResult(int nIndex); [DllImport(EVERYTHING_DLL_NAME)] private static extern bool Everything_IsFileResult(int nIndex); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_GetResultFullPathName(int nIndex, StringBuilder lpString, int nMaxCount); [DllImport(EVERYTHING_DLL_NAME)] private static extern void Everything_Reset(); #endregion #region Enum enum StateCode { OK, MemoryError, IPCError, RegisterClassExError, CreateWindowError, CreateThreadError, InvalidIndexError, InvalidCallError } #endregion #region Property /// <summary> /// Gets or sets a value indicating whether [match path].
read morePosts
[C#]More Effective C# 條款四十九: 考慮為大型物件使用弱引用
private static WeakReference m_ObjectCache { get { if (_objectCache == null) _objectCache = new WeakReference(null); return _objectCache; } } private static Object m_Cache { get { if (m_ObjectCache.Target == null) m_ObjectCache.Target = CreateBigObj(); return m_ObjectCache.Target; } } static void Main(string[] args) { Console.WriteLine(m_Cache); Console.WriteLine(m_Cache); GC.Collect(); Console.WriteLine(m_Cache); } ...</pre>
read morePosts
[C#]Effective C# 條款十七:盡量減少裝箱與拆箱
namespace ConsoleApplication18 { class Program { static void Main(string[] args) { Person p = new Person() { Name=“Larry”};
object o1 = (object)p; // boxing object o2 = p; // Implicit boxing ArrayList array = new ArrayList(); array.Add(p); //Implicit boxing //Unboxing Person p1 = (Person)o1; Person p2 = (Person)o2; p1.Name = "Larry1"; p2.Name = "Larry2"; Person p3 = (Person)array[0]; p3.Name = "Larry3"; Console.WriteLine(string.Format("p = {0}", p)); Console.WriteLine(string.Format("p1 = {0}", p1)); Console.
read morePosts
IEnumerable amp; IEnumerator介面的實作
PersonCollection persons = new PersonCollection ( new Person[]{new Person("Larry")}); foreach (Person person in persons) { Console.WriteLine(person.Name); } foreach (Person person in persons) { Console.WriteLine(person.Name); } } } public class Person { public string Name { get; set; } public Person(string name) { this.Name = name; } } public class PersonCollection : IEnumerable,IEnumerator { private Person[] _peoples; private int position = -1; public PersonCollection(Person[] list) { _peoples = list; } public bool MoveNext() { position++; return (position < _peoples.
read morePosts
[C#]Effective C# 條款十五:利用using和try/finally語句來清理資源.
conn.Open(); cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Dispose(); }</pre> conn.Open(); cmd.ExecuteNonQuery(); } finally { if (cmd != null) cmd.Dispose(); if (conn != null) conn.Dispose(); } }</pre>
read morePosts
[C#]Effective C# 條款十四:利用建構子鏈
public string FirstName { get; set; } public string LastName { get; set; } public SexType Sex { get; set; } public int Age { get; set; } public string Common { get; set; } public Person(string firstName , string lastName) { this.FirstName = firstName; this.LastName = lastName; } public Person(string firstName, string lastName,int age) { this.FirstName = firstName; this.LastName = lastName; this.Age = age; } }</pre> public Person(string firstName, string lastName) { Init(firstName, lastName, 0); } public Person(string firstName, string lastName, int age) { Init(firstName, lastName, age); } private void Init(string firstName, string lastName, int age) { this.
read morePosts
.NET 4.0 New Feature - System.Device.Location
GeoCoordinate location = watcher.Position.Location; if (location.IsUnknown) return; Console.WriteLine("Time: {0}", e.Position.Timestamp); Console.WriteLine("Longitude: {0}", location.Longitude); //經度 Console.WriteLine("Latitude: {0}", location.Latitude); //緯度 Console.WriteLine("Altitude: {0}", location.Altitude); //高度 Console.WriteLine("Course: {0}", location.Course); //角度 Console.WriteLine("Speed: {0}", location.Speed); //速度 CivicAddressResolver resolver = new CivicAddressResolver(); CivicAddress realLocation = m_addressResolver.ResolveAddress(location); if (realLocation.IsUnknown) return; Console.WriteLine("Address1: {0}", realLocation.AddressLine1); //實際地址 Console.WriteLine("Address2: {0}", realLocation.AddressLine2); Console.WriteLine("Building: {0}", realLocation.Building); //門牌號碼 Console.WriteLine("City: {0}", realLocation.City); //縣市 Console.WriteLine("CountryRegion: {0}", realLocation.CountryRegion); //國家 Console.WriteLine("PostalCode: {0}", realLocation.PostalCode); //郵遞區號 Console.WriteLine("StateProvince: {0}", realLocation.StateProvince); //省份 Console.
read morePosts
使用反射(Reflection)實現應用程式擴充元件機制
public IHost Host { get { return _host; } set { _host = value; } } public PlugInController(IHost host) { this.Host = host; } IModule GetModule(Assembly asm, string fullTypeName) { Type t = asm.GetType(fullTypeName); IModule module = null; if (!(t.IsNotPublic || t.IsAbstract)) { object objInterface = t.GetInterface("IModule", true); if (objInterface != null) { module = asm.CreateInstance(t.FullName) as IModule; module.Host = Host; return module; } } return null; } IModule GetModule(Assembly asm, Type moduleType) { return GetModule(asm, moduleType.
read morePosts
.Net 4.0 New Feature - SortedSet
int[] array = new int[setData1.Count]; setData1.CopyTo(array); foreach (var value in array) setData1.Add(value); System.Console.WriteLine("setData1"); System.Console.WriteLine(string.Join(",", setData1)); System.Console.WriteLine("setData2"); System.Console.WriteLine(string.Join(",", setData2)); System.Console.WriteLine("setData1 IsSubsetOf setData2"); System.Console.WriteLine(string.Join(",", setData1.IsSubsetOf(setData2))); System.Console.WriteLine("setData1 Overlaps setData2"); System.Console.WriteLine(string.Join(",", setData1.Overlaps(setData2))); System.Console.WriteLine("setData1 UnionWith setData2"); var setUnion = new SortedSet<int>(setData1); setUnion.UnionWith(setData2); System.Console.WriteLine(string.Join(",", setUnion)); System.Console.WriteLine("(setData1 UnionWith setData2) Reverse"); System.Console.WriteLine(string.Join(",", setUnion.Reverse())); System.Console.WriteLine("(setData1 UnionWith setData2) Min"); System.Console.WriteLine(string.Join(",", setUnion.Min)); System.Console.WriteLine("(setData1 UnionWith setData2) Max"); System.Console.WriteLine(string.Join(",", setUnion.Max)); System.Console.WriteLine("(setData1 UnionWith setData2) GetViewBetween({0},{1})", (setUnion.Min + setUnion.Max) / 2, setUnion.Max); System.Console.WriteLine(string.Join(",", setUnion.GetViewBetween((setUnion.Min + setUnion.
read morePosts
[.NET Concept]throw V.S throw ex
namespace ConsoleApplication6 { class Program {
static void Main() { TestThrow(); TestThrowEx(); } static void ThrowException() { throw new Exception(); } static void TestThrow() { try { try { ThrowException(); } catch (Exception) { throw; } } catch (Exception ex) { Console.WriteLine("TestThrow"); Console.WriteLine(ex.StackTrace); Console.WriteLine(new string('=',50)); } } static void TestThrowEx() { try { try { ThrowException(); } catch (Exception ex) { throw ex; } } catch (Exception ex) { Console.
read morePosts
.NET 4.0 New Feature - IObservablelt;Tgt; amp; IObserverlt;Tgt;
public Unsubscriber(List<IObserver<T>> observers, IObserver<T> observer) { this.m_Observers = observers; this.m_Observer = observer; } public void Dispose() { if (m_Observer != null && m_Observers.Contains(m_Observer)) { m_Observers.Remove(m_Observer); } } }</pre> public class Observable<T> : IObservable<T> { #region Class private class Unsubscriber : IDisposable { private List<IObserver<T>> m_Observers { get; set; } private IObserver<T> m_Observer { get; set; }
public Unsubscriber(List<IObserver<T>> observers, IObserver<T> observer) { this.m_Observers = observers; this.m_Observer = observer; } public void Dispose() { if (m_Observer !
read morePosts
.NET 4.0 New Feature - Environment.Is64BitProcess amp; Environment.Is64BitOperatingSystem
namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Console.WriteLine(“64位元作業系統: {0}",Environment.Is64BitOperatingSystem); Console.WriteLine(“64位元處理序: {0}”, Environment.Is64BitProcess); } } }
read morePosts
LINQ to CSV library
Read<T>(string fileName) Read<T>(string fileName, CsvFileDescription fileDescription) Read<T>(StreamReader stream) Read<T>(StreamReader stream, CsvFileDescription fileDescription)
[CsvColumn(Name = "LastName", FieldIndex = 1)] public String LastName { get; set; } [CsvColumn(Name = "Sex", FieldIndex = 2)] public String Sex { get; set; } [CsvColumn(Name = "Birthday", FieldIndex = 3)] public String Birthday { get; set; } public String Memo { get; set; } public override string ToString() { return string.Join(",", new string[] { FirstName, LastName, Sex, Birthday, Memo }); } }</pre> CsvContext cc = new CsvContext(); Person[] persons = new Person[] { new Person() { FirstName = "Larry", LastName = "Nung", Sex = "Boy", Birthday = "1980/04/19" } }; cc.
read morePosts
[C#][VB.NET]最大公因數 amp; 最小公倍數
private int LCM(int num1, int num2) { return num1 * num2 / GCD(num1, num2); }</pre></div> Private Function LCM(ByVal num1 As Integer, ByVal num2 As Integer) As Integer Return num1 * num2 / GCD(num1, num2) End Function</pre></div> namespace ConsoleApplication1 { class Program { private static int GCD(int num1, int num2) { int min = 0; int max = 0; int maxModMin = 0; min = Math.Min(num1, num2); max = Math.Max(num1, num2); maxModMin = max % min; return maxModMin > 0 ?
read morePosts
Linq To Excel Provider
using System.Linq; using System.ComponentModel;
[ExcelSheet(Name=“Sheet1”)] public class Person: INotifyPropertyChanged {
private double _id; private string _firstname; private string _lastname; private DateTime _birthdate; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } [ExcelColumn(Name="ID", Storage="_id")] public double ID { get { return _id;} set { _id = value; SendPropertyChanged("ID"); } } [ExcelColumn(Name="FirstName", Storage="_firstname")] public string FirstName { get { return _firstname;} set { _firstname = value; SendPropertyChanged("FirstName"); } } [ExcelColumn(Name="LastName", Storage="_lastname")] public string LastName { get { return _lastname;} set { _lastname = value; SendPropertyChanged("LastName"); } } [ExcelColumn(Name="BirthDate", Storage="_birthdate")] public DateTime BirthDate { get { return _birthdate;} set { _birthdate = value; SendPropertyChanged("BirthDate"); } } }
read morePosts
Linq To Excel
//自己可自行加要過濾的條件,這邊只是示範 var linq = from item in excel.Worksheet(sheetName) select item; ...</pre> //這邊會取使用Sheet1的工作表內容去做查詢動作 var linq = from item in excel.Worksheet() select item; ...</pre> var linq = from item in excel.Worksheet<Blogger>(sheetName) where item.Sex==SexType.Boy select item; ...</pre> namespace ConsoleApplication1 { class Blogger { public int ID { get; set; } public String FirstName { get; set; } public String LastName { get; set; } public SexType Sex { get; set; } public int Age { get; set; } public String Blog { get; set; }
read morePosts
.NET 4.0 New Feature - Environment.SpecialFolder
CDBurning C:\Documents and Settings[User Account]\Local Settings\Application Data\Microsoft\C D Burning
CommonAdminTools C:\Documents and Settings\All Users\「開始」功能表\程式集\系統管理工具
CommonDocuments C:\Documents and Settings\All Users\Documents
CommonMusic C:\Documents and Settings\All Users\Documents\My Music
CommonOemLinks
CommonPictures C:\Documents and Settings\All Users\Documents\My Pictures
CommonStartMenu C:\Documents and Settings\All Users\「開始」功能表
CommonPrograms C:\Documents and Settings\All Users\「開始」功能表\程式集
CommonStartup C:\Documents and Settings\All Users\「開始」功能表\程式集\啟動
CommonDesktopDirectory C:\Documents and Settings\All Users\桌面
CommonTemplates C:\Documents and Settings\All Users\Templates
CommonVideos C:\Documents and Settings\All Users\Documents\My Videos
Fonts C:\WINDOWS\Fonts
MyVideos
NetworkShortcuts C:\Documents and Settings[User Account]\NetHood
read morePosts
.NET 4.0 New Feature - Environment.FailFast
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { Environment.FailFast(“A castrophic failure has occured.”, new DivideByZeroException ()); } catch (Exception) { Console.WriteLine(“catch…”); } finally { Console.WriteLine(“finally…”); } } } }
read morePosts
.NET 4.0 New Feature - System.Runtime.Caching
namespace CacheItemPolicyDemo { class Program { static void Main(string[] args) { ContentProvider textFile = new ContentProvider(); Stopwatch sw = new Stopwatch(); while (true) { sw.Reset(); sw.Start(); Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine(textFile.Content); sw.Stop(); Console.WriteLine(“Elapsed Time: {0} ms”, sw.ElapsedMilliseconds); Console.WriteLine(new string(’=’, 50)); Console.ReadLine(); } } }
public class ContentProvider { public String Content { get { const string CACHE_KEY = "Content"; string content = m_Cache[CACHE_KEY] as string; if (content == null) { CacheItemPolicy policy = new CacheItemPolicy(); policy.
read morePosts
.NET 4.0 New Feature - Stream.CopyTo
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (MemoryStream sourceStream = new MemoryStream(512)) { using (StreamWriter sw = new StreamWriter(sourceStream)) { sw.WriteLine(“Test Stream.CopyTo”); sw.Flush();
sourceStream.Seek(0, SeekOrigin.Begin); using (FileStream targetStream = new FileStream("Test.Txt", FileMode.Create)) { sourceStream.CopyTo(targetStream); } } } } } }
read morePosts
.NET 4.0 New Feature - String.Concat
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { String[] stringCollection = { “123”, “456”, “789” }; int[] intCollection = { 123, 456, 789 }; Object[] objCollection = { 123, “456”, 789.0f }; float[] floatCollection = { 123.0f, 456.0f, 789.0f };
ShowValue<String>("stringCollection", stringCollection); ShowValue<int>("intCollection", intCollection); ShowValue<Object>("objCollection", objCollection); ShowValue<float>("floatCollection", floatCollection); } static void ShowValue<T>(string title, IEnumerable<T> values) { Console.WriteLine("{0}: {1}", title, string.Concat<T>(values)); } } }
read morePosts
.NET 4.0 New Feature - String.IsNullOrWhiteSpace
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] values = { null, String.Empty, “ABCDE”, new String(’ ‘, 20), " “, new String(’\u2000’, 10), };
Console.WriteLine(new String('=', 50)); Console.WriteLine("IsNullOrWhiteSpaceDemo..."); IsNullOrWhiteSpaceDemo(values); Console.WriteLine(new String('=', 50)); Console.WriteLine("MSDNCustomIsNullOrWhiteSpaceDemo..."); MSDNCustomIsNullOrWhiteSpaceDemo(values); Console.WriteLine(new String('=', 50)); Console.WriteLine("CustomIsNullOrWhiteSpaceDemo..."); CustomIsNullOrWhiteSpaceDemo(values); } public static void IsNullOrWhiteSpaceDemo(string[] values) { foreach (string value in values) Console.WriteLine("String.IsNullOrWhiteSpace({0}): {1}", value, String.IsNullOrWhiteSpace(value)); } public static void MSDNCustomIsNullOrWhiteSpaceDemo(string[] values) { foreach (string value in values) Console.
read morePosts
.NET 4.0 New Feature - String.Join
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { String[] stringCollection = { “123”, “456”, “789” }; int[] intCollection = { 123, 456, 789 }; Object[] objCollection = { 123, “456”, 789.0f }; float[] floatCollection = { 123.0f, 456.0f, 789.0f };
ShowValue<String>("stringCollection", stringCollection); ShowValue<int>("intCollection", intCollection); ShowValue<Object>("objCollection", objCollection); ShowValue<float>("floatCollection", floatCollection); } static void ShowValue<T>(string title, IEnumerable<T> values) { Console.WriteLine("{0}: {1}", title, string.Join(",", values)); } } }
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { String[] stringCollection = { “123”, “456”, “789” }; int[] intCollection = { 123, 456, 789 }; Object[] objCollection = { 123, “456”, 789.
read morePosts
.NET 4.0 New Feature - Tuple
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var var1 = Tuple.Create(1, 2, 1); var var2 = Tuple.Create(1, 1, 2);
Console.WriteLine("Var1 : {0}", var1); Console.WriteLine("Var2 : {0}", var2); Console.WriteLine("Var1 == Var2 : {0}", var1 == var2); Console.WriteLine("Var1.Equals(Var2) : {0}", var1.Equals(var2)); Console.WriteLine("(Var1 as IComparable).CompareTo(Var2) : {0}", (var1 as IComparable).CompareTo(var2)); Console.WriteLine(); Console.WriteLine("Original Array..."); var tupeArray = new Tuple<int, int, int>[] { var1, var2 }; foreach (var item in tupeArray) Console.
read morePosts
使用C#呼叫VB.NET的CallByName函式
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DataTable dt = new DataTable(); … foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dt.Columns) { Versioned.CallByName(obj, dc.ColumnName, CallType.Set, dr(dc.ColumnName)); } } } } }
read morePosts
Brahma Command Line Parser
/* Simple commandline argument parser written by Ananth B. http://www.ananthonline.net */ static class CommandLine { public class Switch // Class that encapsulates switch data. { public Switch(string name, Action<IEnumerable<string>> handler, string shortForm) { Name = name; Handler = handler; ShortForm = shortForm; }
public Switch(string name, Action<IEnumerable<string>> handler) { Name = name; Handler = handler; ShortForm = null; } public string Name { get; private set; } public string ShortForm { get; private set; } public Action<IEnumerable<string>> Handler { get; private set; } public int InvokeHandler(string[] values) { Handler(values); return 1; } } /* The regex that extracts names and comma-separated values for switches in the form (<switch>[="value 1",value2,.
read morePosts
Linq to GPU (Brahma)
// Create a data-parallel array and fill it with data var data = new DataParallelArray<float>(computationProvider, new[] { 0f, 1f, 2f, 3f, 4f, 5f, 6f }); // Compile the query CompiledQuery query = computationProvider.Compile<DataParallelArray<float>> ( d => from value in d select value * 2f ); // Run the query on this data IQueryable result = computationProvider.Run(query, data); // Print out the results foreach (float value in result) Console.WriteLine(value); // Get rid of all the stuff we created computationProvider.
read morePosts
使用Extension Method計算漢字筆畫
public static int GetStrokesNumber(this char c) { String hex = BitConverter.ToString(Encoding.GetEncoding("Big5").GetBytes(new char[] { c })).Replace("-", string.Empty); for (int i = 0; i < _strokesNumberData.Length; ++i) { for (int j = 0; j < _strokesNumberData[i].Length; j += 2) { if (hex.CompareTo(_strokesNumberData[i][j]) >= 0 && hex.CompareTo(_strokesNumberData[i][j + 1]) <= 0) return i+1; } } return 0; } }</pre></div> Module CharExtension
Private _strokesNumberData As String()() = { _ New String() {"A440", "A441"}, _ New String() {"A442", "A453", "C940", "C944"}, _ New String() {"A454", "A47E", "C945", "C94C"}, _ New String() {"A4A1", "A4FD", "C94D", "C95C"}, _ New String() {"A4FE", "A5DF", "C95D", "C9AA"}, _ New String() {"A5E0", "A6E9", "C9AB", "C959"}, _ New String() {"A6EA", "A8C2", "CA5A", "CBB0"}, _ New String() {"A8C3", "AB44", "CBB1", "CDDC"}, _ New String() {"AB45", "ADBB", "CDDD", "D0C7", "F9DA", "F9DA"}, _ New String() {"ADBC", "B0AD", "D0C8", "D44A"}, _ New String() {"B0AE", "B3C2", "D44B", "D850"}, _ New String() {"B3C3", "B6C3", "D851", "DCB0", "F9DB", "F9DB"}, _ New String() {"B6C4", "B9AB", "DCB1", "E0EF", "F9D6", "F9D8"}, _ New String() {"B9AC", "BBF4", "E0F0", "E4E5"}, _ New String() {"BBF5", "BEA6", "E4E6", "E8F3", "F9DC", "F9DC"}, _ New String() {"BEA7", "C074", "E8F4", "ECB8", "F9D9", "F9D9"}, _ New String() {"C075", "C24E", "ECB9", "EFB6"}, _ New String() {"C24F", "C35E", "EFB7", "F1EA"}, _ New String() {"C35F", "C454", "F1EB", "F3FC"}, _ New String() {"C455", "C4D6", "F3FD", "F5BF"}, _ New String() {"C3D7", "C56A", "F5C0", "F6D5"}, _ New String() {"C56B", "C5C7", "F6D6", "F7CF"}, _ New String() {"C5C8", "C5C7", "F6D6", "F7CF"}, _ New String() {"C5F1", "C654", "F8A5", "F8ED"}, _ New String() {"C655", "C664", "F8E9", "F96A"}, _ New String() {"C665", "C66B", "F96B", "F9A1"}, _ New String() {"C66C", "C675", "F9A2", "F9B9"}, _ New String() {"C676", "C67A", "F9BA", "F9C5"}, _ New String() {"C67B", "C67E", "F9C6", "F9DC"}} <Extension()> _ Public Function GetStrokesNumber(ByVal c As Char) As Integer Dim hex As [String] = BitConverter.
read morePosts
.NET 4.0 New Feature - Generic Lazy class
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Lazy<Boolean> lazy = new Lazy<Boolean>(() => { Console.WriteLine(“Initializing…”); System.Threading.Thread.Sleep(10000); Console.WriteLine(“Initialized…”); return true; });
Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated); Stopwatch sw = Stopwatch.StartNew(); Console.WriteLine("result = {0}", lazy.Value); //Console.WriteLine("result = {0}", lazy.ToString()); Console.WriteLine("Elapsed Time = {0} ms", sw.ElapsedMilliseconds); Console.WriteLine(new string('=', 50)); Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated); sw.Restart(); Console.WriteLine("result = {0}", lazy.Value); //Console.WriteLine("result = {0}", lazy.ToString()); Console.WriteLine("Elapsed Time = {0} ms", sw.ElapsedMilliseconds); } } }
read morePosts
[C#]使用WM_SYSCOMMAND訊息控制螢幕模式切換
const int SC_MONITORPOWER = 0xF170; const int WM_SYSCOMMAND = 0x0112; ... SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER , -1); SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER , 1); SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER , 2); </pre></div> <p> </p> <p>這邊為方便後續使用,將程式整理成類別,有需要的自行取用。</p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:c3cd5a55-1615-41d4-9ccd-45dd058acb8b" class="wlWriterSmartContent"><pre name="code" class="c#"> public static class MonitorControler { [DllImport(“user32.dll”)] private static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
const int SC_MONITORPOWER = 0xF170; const int WM_SYSCOMMAND = 0x0112; //const int SC_SCREENSAVE = 0xF140; public enum MonitorMode : int { MONITOR_ON = -1, MONITOR_STANBY = 1, MONITOR_OFF } public static void ChangeMonitorState(MonitorMode mode) { SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, (int)mode); } public static void MonitorOff() { ChangeMonitorState(MonitorMode.
read morePosts
.NET 4.0 New Feature - 程式碼合約(Code Contracts) (三) Contract.Assert Contract.Assume
public static int CalculateSomeValues() { Contract.Ensures(Contract.Result<int>() > 0); return 1; }</pre></div> <p> </p> <p>由於在CalculateSomeValues函式內,已經用後置條件去驗證了函式回傳值,因此在Main裡面的Contract.Assert就可以確定x變數一定會滿足驗證條件,故整個程式在做靜態分析時是會通過驗證的。</p> <p> </p> <p>而若今天我們的函式並未用後置條件去確保有正確的函式回傳值的話,這樣的程式在Contract.Assert那段就會被檢查出有問題。因為回傳值不確定,這個Assert在靜態分析中就無法被驗證,也就無法確定x變數一定會大於零。 </p> <p><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="398" height="244" src="\images\posts\17802\image_thumb_2.png" /></a> </p> <p><a href="http://files.dotblogs.com.tw/larrynung/1009/.NET4.0NewFeatureCodeContracts_B520/image_4.png"><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="447" height="129" src="\images\posts\17802\image_thumb_1.png" /></a></p> <p> </p> <p>這時若仍不想為函式加入後置方法,讓整個驗證更為嚴謹的話,可以使用Contract.Assume來做驗證的動作。</p> <p><a href="http://files.dotblogs.com.tw/larrynung/1009/.NET4.0NewFeatureCodeContracts_B520/image_8.png"><img style="border-bottom: 0px; border-left: 0px; border-top: 0px; border-right: 0px" border="0" alt="image" width="404" height="247" src="\images\posts\17802\image_thumb_3.png" /></a></p> <p><a href="http://files.
read morePosts
.NET 4.0 New Feature - 程式碼合約(Code Contracts) (二) 三大合約
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(MyProperty >= 0); }
public int MyProperty { get; set; }
[ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(MyProperty >= 0); } 這邊我們來反組譯了解一下其運作原理,反組譯後可發現Code Contract偷偷的幫我們在裡面造了兩個私有欄位<MyProperty>k_backingField與$evaluatingInvariant$。 <img alt="" src="\images\posts\17516
read morePosts
[C#]使用Win32 API為編輯框與下拉方塊加上提示字串
const int EM_SETCUEBANNER = 0x1501; private string _cueText; [Localizable(true)] public string CueText { get { if (_cueText == null) return string.Empty; return _cueText; } set { _cueText = value; updateCue(); } } private void updateCue() { SendMessage(this.Handle, EM_SETCUEBANNER, 0, CueText); } }</pre></div>
read morePosts
[Linq]Linq程式逐步執行與偵錯
foreach (var item in linq) { Console.WriteLine(item); } }</pre></div> For Each item In linq Console.WriteLine(item) Next End Sub</pre>
read morePosts
[Extension Method]使用擴充方法來做二維陣列排序
T[] tempArray = new T[count]; for (int idx = 0; idx < count; ++idx) { tempArray[idx] = array[idx, d2Idx]; } Array.Sort(tempArray); for (int idx = 0; idx < count; ++idx) { T tempValue = tempArray[idx]; for (int idx2 = idx+1; idx2 < count; ++idx2) { if (array[idx2, d2Idx].Equals(tempValue)) { array.Swap(idx, d2Idx, idx2, d2Idx); int d2Idx2 = (d2Idx == 0) ? 1 : 0; array.Swap(idx, d2Idx2, idx2, d2Idx2); } } } } public static void Swap<T>(this T[,] array, int idx1, int idx2, int targetIdx1, int targetIdx2) { T temp; temp = array[targetIdx1, targetIdx2]; array[targetIdx1, targetIdx2] = array[idx1, idx2]; array[idx1, idx2] = temp; } 使用上呼叫Sort方法,並傳入要排序依據的索引即可。
read morePosts
[C#]用Stopwatch計算累計耗費時間的注意事項
for (int i = 1; i <= count; i++) { sw.Reset(); sw.Start(); string guid = Guid.NewGuid().ToString(); sw.Stop(); total += sw.ElapsedMilliseconds; } Console.WriteLine(total); sw.Reset(); for (int i = 1; i <= count; i++) { sw.Start(); string guid = Guid.NewGuid().ToString(); sw.Stop(); } Console.WriteLine(sw.ElapsedMilliseconds); }</pre></div> for (int i = 1; i <= count; i++) { sw.Reset(); sw.Start(); System.Threading.Thread.Sleep(10); sw.Stop(); total += sw.ElapsedMilliseconds; } Console.WriteLine(total); sw.Reset(); for (int i = 1; i <= count; i++) { sw.
read morePosts
[C#][VB.NET]FullScreen the winform
static class FullScreenExtension { #region Struct struct FullScreenData { public FormBorderStyle FormBorderStyle { get; set; } public FormWindowState WindowState { get; set; }
public FullScreenData(FormBorderStyle formBorderStyle, FormWindowState windowState):this() { this.FormBorderStyle = formBorderStyle; this.WindowState = windowState; } } #endregion #region Var private static Dictionary<Form, FullScreenData> _fullScreenDataPool; #endregion #region Private Property private static Dictionary<Form, FullScreenData> m_FullScreenDataPool { get { if (_fullScreenDataPool == null) _fullScreenDataPool = new Dictionary<Form, FullScreenData>(); return _fullScreenDataPool; } } #endregion #region Public Method public static void FullScreen(this Form frm) { if (m_FullScreenDataPool.
read morePosts
[Performance][C#]絕對值的取得
namespace WindowsFormsApplication35 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
static int ABS1(int value) { return value < 0 ? -value : value; } static int ABS2(int value) { return Math.Abs(value); } private void button1_Click(object sender, EventArgs e) { int count = (int)numericUpDown1.Value; int value = -1; textBox1.AppendText("Count: " + count.ToString() + Environment.NewLine); Stopwatch sw = Stopwatch.StartNew(); for (int idx = 0; idx < count; ++idx) ABS1(value); sw.
read morePosts
[Performance][C#]String.Empty V.S ldquo;rdquo;
Console.Clear(); int count = 1000000000; for (int idx = 0; idx < 3; ++idx) { EmptyString1(count); EmptyString2(count); EmptyString3(count); Console.WriteLine(); } } private static void EmptyString1(int count) { String test; Stopwatch sw = Stopwatch.StartNew(); for (int idx = 0; idx < count; ++idx) { test = ""; } sw.Stop(); Console.WriteLine("EmptyString1: " + sw.ElapsedMilliseconds.ToString()); } private static void EmptyString2(int count) { String test; Stopwatch sw = Stopwatch.StartNew(); for (int idx = 0; idx < count; ++idx) { test = string.
read morePosts
[Performance][C#]同時判斷多個字串是否為數值型態
sw.Reset(); sw.Start(); for (int idx = 0; idx < testCount; ++idx) { IsNumeric2_1(values); } sw.Stop(); Console.WriteLine("Method2-1: " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); for (int idx = 0; idx < testCount; ++idx) { IsNumeric2_2(values); } sw.Stop(); Console.WriteLine("Method2-2: " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); for (int idx = 0; idx < testCount; ++idx) { IsNumeric3(values); } sw.Stop(); Console.WriteLine("Method3: " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); for (int idx = 0; idx < testCount; ++idx) { IsNumeric4(values); } sw.
read morePosts
[C#]透過API移除表單的控制功能表方塊中的功能表項目
const Int32 MF_BYPOSITION = 1024;//&H400 public enum SystemMenuItemType { Restore, Move, Size, Min, Max, Seperator, Close } public static void RemoveSystemMenuItem(Form form, SystemMenuItemType menuItem) { RemoveMenu(GetSystemMenu(form.Handle.ToInt32(), 0),(int)menuItem, MF_BYPOSITION); } public static void RemoveRestoreSystemMenuItem(Form form) { RemoveSystemMenuItem(form, SystemMenuItemType.Restore); } public static void RemoveMoveSystemMenuItem(Form form) { RemoveSystemMenuItem(form, SystemMenuItemType.Move); } public static void RemoveSizeSystemMenuItem(Form form) { RemoveSystemMenuItem(form, SystemMenuItemType.Size); } public static void RemoveMinSystemMenuItem(Form form) { RemoveSystemMenuItem(form, SystemMenuItemType.Min); } public static void RemoveMaxSystemMenuItem(Form form) { RemoveSystemMenuItem(form, SystemMenuItemType.
read morePosts
[C#]Effective C# 條款十一: 優先採用foreach迴圈
foreach (int i in foo) Console.WriteLine(i.ToString()); for (int index = 0; index < len; index++) Console.WriteLine(foo[index].ToString()); for (int index = 0; index < foo.Length; index++) Console.WriteLine(foo[index].ToString()); }</pre>
read morePosts
[C#]Effective C# 條款九: 理解幾個相等判斷之間的關係
//兩個有一個為空=>return false; if ((left == null) || (right == null)) return false; //透過left.Equals判斷是否相等 return left.Equals(right); }
//檢查是否與自身是相同物件 if (object.ReferenceEquals(this, obj)) return true; //檢查是否型態相等 if (this.GetType() != obj.GetType()) return false; //比較內容是否相等 return CompareMembers(this, obj); }</pre> //檢查是否與自身是相同物件 if (object.ReferenceEquals(this, obj)) return true; //檢查是否型態相等 if (this.GetType() != obj.GetType()) return false; //叫用基底類別的Equals方法 if(!base.Equals(obj)) return false; //比較內容是否相等 return CompareMembers(this, obj); }</pre>
read morePosts
[C#]Effective C# 條款八: 確保0為值類型的有效狀態
struct Person { public String Name; public Sex Sex; public Person(String name, Sex sex) { this.Name = name; this.Sex = sex; } }</pre> struct Person { public String Name; public Sex Sex; public Person(String name, Sex sex) { this.Name = name; this.Sex = sex; } }</pre>
read morePosts
[C#]Effective C# 條款七: 將值類型盡可能實現為具有常量性與原子性的類型
public string Line { get { return _line; } set { _line = value; } } public string City { get { return _city; } set { _city = value; } } public string State { get { return _state; } set { ValidateState(value); _state = value; } } public int ZipCode { get { return _zipCode; } set { ValidateZip(value); _zipCode = value; } } ... }</pre> public string Line { get { return _line; } } public string City { get { return _city; } } public string State { get { return _state; } } public int ZipCode { get { return _zipCode; } } public Address(string line,string city,string state,int zipCode) { _line = line; _city = city; _state = state; _zipCode = zipCode; ValidateState(state); ValidateZip(zipCode); } }</pre> public PhoneList(Phone[] ph) { _phones = ph; } .
read morePosts
[C#]Effective C# 條款六: 明辨值類型與參考類型的使用場合
MyData data= GetData();
MyData data= GetData();
IMyInterface data= GetData();
C var = new C();
public void Pay(BankAccount b) { b.Balance -= _salary; } }
public void Pay(BankAccount b) { b.Balance -= _salary; } }
read morePosts
[C#]Effective C# 條款四: 使用ConditionalAttribute替代#if條件編譯
[Conditional(“B”)] static void DoIfAandB() { // Code to execute when both A and B are defined… } static void HelloWord() { Console.WriteLine("Hello~"); } static void SayHello1() { #if DEBUG HelloWord(); #endif }
[System.Diagnostics .Conditional ("DEBUG")] static void SayHello2() { HelloWord(); }</pre> private static void Main(string[] args) { HelloWord(); SayHello1(); //SayHello2被編譯器拿掉 } private static void SayHello1() { //內容被編譯器拿掉 } [Conditional("DEBUG")] private static void SayHello2() { HelloWord(); } }
read morePosts
[C#]使用DebuggerDisplayAttribute自訂除錯監看訊息
[System.Diagnostics.DebuggerDisplay("Name = {Name}, Year = {Year}")] class Person { [System.Diagnostics.DebuggerDisplay("Name = {Name}")] string Name { get; set; } int Year { get; set; } public Person(string name, int year) { this.Name = name; this.Year = year; } }</pre></div>
read morePosts
[C#]使用GetSystemPowerStatus API查看目前電源使用狀態
<td valign="top" width="499">表示目前充電狀態。 <br />1為High(66%以上電力)、2為Low(33%以上電力)、4為Critical(5%以下電力)、8為Charging、128為NoBattery、255為UnKnow</td> </tr> <tr> <td valign="top" width="200">BatteryFullLifeTime</td> <td valign="top" width="499">表示充滿電力可使用多久時間(-1為不詳)。</td> </tr> <tr> <td valign="top" width="200">BatteryLifePercent</td> <td valign="top" width="499">表示電力剩餘多少百分比,其正常值為0~100,255為電力不詳。</td> </tr> <tr> <td valign="top" width="200">BatteryLifeTime</td> <td valign="top" width="499">表示剩餘電力可使用多久時間(-1為不詳)。</td> </tr> <tr> <td valign="top" width="200">ACLineStatus</td> <td valign="top" width="499">表示電源狀態。 <br />0為offline、1為online、255為unknow。</td> </tr> namespace Battery { [Flags] public enum BatteryChargeStatus : byte { High = 1, Low = 2, Critical = 4, Charging = 8, NoSystemBattery = 128, Unknown = 255 }
read morePosts
[C#][VB.NET].NET 4.0 Barrier Class
Module Module1
Private sync As Barrier Sub Main(ByVal args() As String) sync = New Barrier(3) Dim charlie = New Thread(Sub() DriveToBoston("Charlie", TimeSpan.FromSeconds(1))) charlie.Start() Dim mac = New Thread(Sub() DriveToBoston("Mac", TimeSpan.FromSeconds(2))) mac.Start() Dim dennis = New Thread(Sub() DriveToBoston("Dennis", TimeSpan.FromSeconds(3))) dennis.Start() charlie.Join() mac.Join() dennis.Join() Console.ReadKey() End Sub Sub DriveToBoston(ByVal name As String, ByVal timeToGasStation As TimeSpan) Console.WriteLine("[{0}] Leaving House", name) ' Perform some work Thread.Sleep(timeToGasStation) Console.WriteLine("[{0}] Arrived at Gas Station", name) ' Need to sync here sync.
read morePosts
[C#]C# 4.0 動態繫結 (Dynamic Lookup)
namespace ConsoleApplication16 { class Program { static void Main(string[] args) { dynamic[] ds = new dynamic[2]; ds[0] = new System.Windows.Forms.TextBox(){Name=“TextBox”}; ds[1] = new Person() { Name = “Larry” }; foreach (dynamic d in ds) { Console.WriteLine(d.Name); } } } class Person { public string Name { get; set; } } } 由於不用把型態從Object轉回匿名型別,因此動態繫結也可以用在匿名型別上,真的方便許多,看來以後若要偷懶直接傳遞匿名型別也可以了(不建議也不鼓勵濫用)。 using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ConsoleApplication19 { class Program { static void Main(string[] args) { dynamic d = new { Name = “Larry” }; Console.
read morePosts
[C#]利用FlowLayoutPanel控制項合併大量圖片
namespace WindowsFormsApplication5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK ) { listBox1.Items.Clear(); listBox1.Items.AddRange(openFileDialog1.FileNames); } } private void button2_Click(object sender, EventArgs e) { flowLayoutPanel1.Controls.Clear(); foreach(string file in listBox1.Items){ flowLayoutPanel1.Controls.Add(new PictureBox() { Image = new Bitmap(file), SizeMode = PictureBoxSizeMode.AutoSize, Margin=new Padding(0)}); } } private void button3_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { Bitmap b = new Bitmap(flowLayoutPanel1.
read morePosts
[C#]C# 4.0 選擇性參數 (Optional Parameters)
Sub SayHello(Optional ByVal name As String = "無名氏") Console.WriteLine("Hello~My name is " & name) End Sub</pre> static void SayHello(String name = "無名氏") { Console.WriteLine("Hello~My name is " + name); }</pre> namespace SayHello { class Program { static void Main(string[] args) { SayHello(); SayHello(name:“Larry”); SayHello(“Larry”); } static void SayHello() { Console.WriteLine(“Hi~”); } static void SayHello(object name) { Console.WriteLine(“Hi~My name is” + name.ToString()); } static void SayHello(String name = “無名氏”) { Console.
read morePosts
[C#][VB.NET]擴充方法 (Extension Method)
public static class EnumExtension { public static string GetName(this Enum e) { return Enum.GetName(e.GetType(), e); } } class Program { static void Main(string[] args) { Console.WriteLine(Grade.APlus.GetName()); } }</pre></div> Enum Grade APlus A B C D End Enum
Module Module1 Sub Main() Console.WriteLine(Grade.APlus.GetName) End Sub End Module
Module EnumExtension <Extension()> _ Public Function GetName(ByVal e As [Enum]) As String Return [Enum].GetName(e.GetType, e) End Function End Module
class Program { static void Main(string[] args) { string str = null; Console.
read morePosts
[Performance][C#]StringBuilder與String.Join串接字串時的效能比較
namespace ConsoleApplication17 { class Program { static void Main(string[] args) { int testTimes = 10; int dataCount = 1000000; GoTest(dataCount, testTimes); }
static void GoTest(int dataCount,int testTimes) { //Let JIT compiler precompiler Test1(1); Test2(1); //Test performance Stopwatch sw; long[] elapsedTimes = new long[testTimes]; Console.WriteLine("String.Join..."); for (int i = 0; i < testTimes; i++) { sw = Stopwatch.StartNew(); Test1(dataCount); elapsedTimes[i] = sw.ElapsedMilliseconds; Console.WriteLine("Elapsed Time: " + elapsedTimes[i]); } Console.WriteLine("Average Elapsed Time: " + elapsedTimes.
read morePosts
[C#][VB.NET]彩色濾鏡
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]反轉圖片顏色
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]彩色圖片轉為黑白圖片
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]壓縮.NET程式的記憶體用量
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#]HashSet 集合型別
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]Isolated Storage 隔離儲存區
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[Control][C#]WebCamPictureBox Control
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[Performance][C#]List V.S SortedList
<pre><span class="kwrd">using</span> System.Collections.Generic;</pre> <pre class="alt"><span class="kwrd">using</span> System.ComponentModel;</pre> <pre><span class="kwrd">using</span> System.Data;</pre> <pre class="alt"><span class="kwrd">using</span> System.Drawing;</pre> <pre><span class="kwrd">using</span> System.Linq;</pre> <pre class="alt"><span class="kwrd">using</span> System.Text;</pre> <pre><span class="kwrd">using</span> System.Windows.Forms;</pre> <pre class="alt"><span class="kwrd">using</span> System.Collections;</pre> <pre><span class="kwrd">using</span> System.Diagnostics;</pre> <pre class="alt"> </pre> <pre><span class="kwrd">namespace</span> HashTableVSSortedList</pre> <pre class="alt">{</pre> <pre> <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> Form1 : Form</pre> <pre class="alt"> {</pre> <pre> <span class="kwrd">public</span> Form1()</pre> <pre class="alt"> {</pre> <pre> InitializeComponent();</pre> <pre class="alt"> }</pre> <pre> </pre> <pre class="alt"> <span class="kwrd">private</span> <span class="kwrd">void</span> button1_Click(<span class="kwrd">object</span> sender, EventArgs e)</pre> <pre> {</pre> <pre class="alt"> button1.
read morePosts
[.NET Concept][C#][VB.NET].NET兩個表單間的資料互通
Public Class Form2 … Public MainForm As Form1 … ‘Form2透過Form1傳進的物件參考控制Form1 MainForm.Value = Me.NumericUpDown1.Value … End Class
read morePosts
[C#][VB.NET]自定義.NET WindowForm表單介面(二)
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]使用AxWindowsMediaPlayer撥放多媒體
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]使用AxMediaPlayer撥放多媒體
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[.NET Concept][C#][VB.NET]四捨六入五成雙
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .
read morePosts
[C#][VB.NET]XML序列化私有欄位
#Region “Enum” Enum SexType Boy Girl End Enum #End Region
#Region “Var” Private _name As String Private _year As Integer Private _sex As SexType Private _friendNames As New List(Of String) #End Region
#Region “Property” Public Property Name() As String Get If String.IsNullOrEmpty(_name) Then Return String.Empty End If Return _name End Get Set(ByVal value As String) _name = value End Set End Property
Public Property Year() As Integer Get Return _year End Get Set(ByVal value As Integer) _year = value End Set End Property Public Property Sex() As SexType Get Return _sex End Get Set(ByVal value As SexType) _sex = value End Set End Property #End Region
read morePosts
[C#][VB.NET]自製桌面小玩意
Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove If PictureBox1.Capture = True Then '如果滑鼠按著拖曳 '設定新的視窗位置 Me.Top = e.Y + nOldWndTop - nClickY Me.Left = e.X + nOldWndLeft - nClickX '更新紀錄的視窗位置 nOldWndLeft = Me.Left nOldWndTop = Me.Top End If End Sub</pre></div><p> </p><p>C#</p><p> </p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f0c57834-e54e-4456-896a-5ebc58634d32" class="wlWriterSmartContent"><pre class="c#" name="code"> private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
read morePosts
[C#][VB.NET]自定義.NET WindowForm表單介面
Private Sub pnlTitleBar_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pnlTitleBar.MouseMove If pnlTitleBar.Capture = True Then '如果滑鼠按著拖曳 '設定新的視窗位置 Me.Top = e.Y + nOldWndTop - nClickY Me.Left = e.X + nOldWndLeft - nClickX '更新紀錄的視窗位置 nOldWndLeft = Me.Left nOldWndTop = Me.Top End If End Sub</pre></div><p> </p><p>C#</p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0d2adec9-5189-493d-821d-1272f208c5e0" class="wlWriterSmartContent"><pre class="c#" name="code"> private void pnlTitleBar_MouseDown(object sender, MouseEventArgs e) { //紀錄滑鼠點選時的視窗位置與滑鼠點選位置 nOldWndLeft = this.
read morePosts
[C#][VB.NET]設定.NET透明表單
Abstract Introduction Form.Opacity屬性設定不透明度 Form.TransparencyKey屬性設定透明的顏色 Form.Opacity VS Form.TransparencyKey Conclusion Introduction 在.NET WinForm程式中,要設定透明表單有兩種方式。一種是用Form.Opacity屬性來設定表單的不透明度,一種則是用Form.TransparencyKey屬性來設定表單上視為透明的顏色。本篇將會對兩種方法做個簡單的介紹,並針對兩者做點小小的比較。
Form.Opacity屬性設定不透明度 以Form.Opacity屬性為例,該屬性值所設定的是0~1之間的雙精度浮點數(Double),用以表示表單的不透明度比例。如下圖所示,該值越小越透明、越大則越不透明。
完整範例如下:
VB.NET
C#
Form.TransparencyKey屬性設定透明的顏色 要用Form.TransparencyKey屬性來設定表單透明度,只須把該屬性設為欲透明的顏色,則當表單上存在著被設為透明色的顏色區塊時,該顏色區塊就會被視為是透明的。用該方法設定的透明效果跟用Form.Opacity的方法是不同的。該方法的透明是完全的透明(透明度100%),且若用滑鼠點選在表單中透明的區塊上,滑鼠的點選動作會穿透目前的表單點選到目前表單下方的視窗,而Form.Opacity的透明除非是設為完全透明,不然無法穿透目前的表單。
**P.S.**Form.Opacity = 0 雖然也可以完全穿透目前表單,但是表單上面的元件也會跟著透明。
Form.Opacity VS Form.TransparencyKey 可調整透明度比例 點選表單透明區塊可穿透表單 可設定表單一部份為透明區塊,只會影響跟設定相同顏色的區塊 點選表單不完全透明區塊(Form.Opacity != 0)不可穿透表單 透明度會影響整個表單上的元件 不可調整透明度比例 Conclusion 本篇介紹了WinForm中改變表單透明度的兩種方法。雖然兩種方法都可以達到透明表單的效果,但在實際的應用上,我個人覺得用Form.TransparencyKey來設定表單透明度較為實用。雖此方法無法調整透明程度,但是其所具備的穿透透明區塊與可透明表單中部分區塊的特性,大幅增加了應用上的彈性。
read morePosts
[C#][VB.NET].NET捷徑(ShortCut)控制
Function GetLnkWorkingDirectory(ByVal shortCutFile As String) As String Return GetLnkObj(shortCutFile).WorkingDirectory End Function
Function GetLnkPath(ByVal shortCutFile As String) As String Return GetLnkObj(shortCutFile).Path End Function C# private String GetLnkArguments(string shortCutFile) { return GetLnkObj(shortCutFile).Arguments; }
private String GetLnkWorkingDirectory(string shortCutFile) { return GetLnkObj(shortCutFile).WorkingDirectory; }
private String GetLnkPath(string shortCutFile) { return GetLnkObj(shortCutFile).Path; } 這邊須注意的是,使用此方法建立捷徑時,若捷徑檔不存在於指定位置,則須先建立個空的捷徑檔案,才可取得ShellLinkObject物件。VB.NET If Not My.Computer.FileSystem.FileExists(shortCutFile) Then File.Create(shortCutFile).Close() End If C# if (!My.Computer.FileSystem.FileExists(shortCutFile)) { File.Create(shortCutFile).Close(); } 取得ShellLinkObject物件後,捷徑的建立與寫入也就只是設定對應的屬性值後呼叫Save方法。VB.NET lnkObj = GetLnkObj(shortCutFile) With lnkObj .Arguments = arguments .
read more