Popular Posts
Activate IIS GIZP compress 1. Set metabase editable for editing. 2. Add a new extension for gzip. 3. Edit the file c:\windows\system32\inetsrv\MetaBase.xml Add file... Sublime Text hotkeys 編輯 Ctrl + X 刪除行 Ctrl + Enter 插入下一行 Ctrl + Shift + Enter 插入前一行 Ctrl + Shift + ↑ 往上移動一行 C... Tomcat GET encoding edit server.xml : <Connector     URIEncoding="UTF-8"     connectionTimeout="20000"     port="8080"     prot...
Stats
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Add file to google drive
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SyncDump
{
    class Program
    {
        /// <summary>
        /// 存取權限
        /// </summary>
        static string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
        static string ApplicationName = "Drive Uploader";

        static void Main(string[] args)
        {
            // 檢查輸入參數
            if (args.Length < 1)
            {
                Console.WriteLine("No target file argument!");
                return;
            }

            // 要上傳的檔案
            string dumpPath = args[0];
            string dumpName = System.IO.Path.GetFileName(dumpPath);

            // 載入驗證資訊
            GoogleCredential credential;
            using (var stream = new System.IO.FileStream("client_secret.json", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream);
            }

            // 建立 service
            DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential.CreateScoped(Scopes),
                ApplicationName = ApplicationName
            });
            
            // 進行上傳
            insertFile(
                service,
                dumpName,
                dumpName,
                System.Configuration.ConfigurationManager.AppSettings["drive.folder.id"],
                "application/oct-stream",
                dumpPath
            );
        }

        /// <summary>
        /// 新增檔案
        /// </summary>
        /// <param name="service">Drive API service instance.</param>
        /// <param name="title">Title of the file to insert, including the extension.</param>
        /// <param name="description">Description of the file to insert.</param>
        /// <param name="parentId">Parent folder's ID.</param>
        /// <param name="mimeType">MIME type of the file to insert.</param>
        /// <param name="filename">Filename of the file to insert.</param><br>  /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns>
        private static File insertFile(DriveService service, string title, string description, string parentId, string mimeType, string filename)
        {
            // 檔案資訊
            File body = new File();
            body.Title = title;
            body.Description = description;
            body.MimeType = mimeType;

            // 設定上傳位置
            if (!string.IsNullOrEmpty(parentId))
            {
                body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } };
            }

            // 檔案內容
            byte[] byteArray = System.IO.File.ReadAllBytes(filename);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            try
            {
                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
                request.Upload();

                File file = request.ResponseBody;

                Console.WriteLine("{0:yyyy/MM/dd HH:mm:ss} File {1} is uploaded to drive", DateTime.Now, file.Title);

                return file;
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return null;
            }
        }
    }
}
Override Response Content-Type with OutputCache

Response content-type will be set as text/html on OutputCache is assigned, even if there is an assignment inside action.

HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [OutputCache(Duration = 60)]
        public ActionResult NavigationScript()
        {
            Response.ContentType = "application/javascript";
            return View();
        }
    }
}
Result

Custom a attribute and change content type after output cache processed.

ResponseHeaderAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Filter
{
    public class ResponseHeaderAttribute : ActionFilterAttribute
    {
        public string ContentType { get; set; }
        public System.Text.Encoding ContentEncoding { get; set; }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (!string.IsNullOrWhiteSpace(ContentType)) filterContext.HttpContext.Response.ContentType = ContentType;
            if (ContentEncoding != null) filterContext.HttpContext.Response.ContentEncoding = ContentEncoding;
        }
    }
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Filter;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [OutputCache(Duration = 60, Order = 1)]
        [ResponseHeader(ContentType = "application/javascript", Order = 2)]
        public ActionResult NavigationScript()
        {
            return View();
        }
    }
}
Result
[Json.net] Convert enum to string
[JsonConverter(typeof(StringEnumConverter))]
public enum Gender
{
    [EnumMember(Value = "man")]
    Male,
    [EnumMember(Value = "woman")]
    Femail,
    [EnumMember(Value = "unknown")]
    Unknown
}
CORS in Asp.net MVC Web API v2

Step 1.

Install cors from NeGet

Step 2.

Enable cors in config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebSample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.EnableCors();
        }
    }
}

Step 3

Add cors attribute to your controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using WebSample.Models;

namespace WebSample.Controllers.Api
{
    public class JobController : ApiController
    {
        [EnableCors(origins: "*", headers: "*", methods: "GET")]
        public Message Get()
        {
            return new Message
            {
                ID = 2,
                Content = "Job"
            };
        }
    }
}

Step 4

Test x-domain request
Math Captcha
public class MathCaptcha
{
    public static MathCaptcha Generate(int degree = 3)
    {
        if (degree < 2) degree = 2;

        var verifier = new MathCaptcha();
        var rdm = new Random(unchecked((int)DateTime.Now.Ticks));
        var nums = new decimal[] {
            rdm.Next(1, (int)Math.Pow(10, degree)),
            rdm.Next(1, (int)Math.Pow(10, degree)),
            rdm.Next(1, (int)Math.Pow(10, degree))
        };
        nums = nums.OrderBy(n => n).ToArray();

        while (true)
        {
            if ((decimal)Math.Pow(10, degree) - 1 <= nums[0] * nums[1])
            {
                nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
            }
            else if ((decimal)Math.Pow(10, degree - 1) >= nums[0] * nums[1])
            {
                nums[0] = Math.Ceiling(nums[0] * (decimal)(rdm.NextDouble() + 1));
            }
            else
            {
                break;
            }
            nums = nums.OrderBy(n => n).ToArray();
        }

        if (rdm.NextDouble() > 0.5)
        {
            while (degree != Math.Abs(nums[0] * nums[1] + nums[2]).ToString().Length)
            {
                nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
            }

            if (rdm.NextDouble() > 0.7)
            {
                verifier.Text = string.Format("{0}x{1}+{2}", nums[0], nums[1], nums[2]);
                verifier.Answer = nums[0] * nums[1] + nums[2];
            }
            else
            {
                verifier.Text = string.Format("{2}+{0}x{1}", nums[0], nums[1], nums[2]);
                verifier.Answer = nums[2] + nums[0] * nums[1];
            }
        }
        else
        {
            while (degree != Math.Abs(nums[0] * nums[1] - nums[2]).ToString().Length)
            {
                nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
            }

            if (nums[0] * nums[1] - nums[2] > 0)
            {
                verifier.Text = string.Format("{0}x{1}-{2}", nums[0], nums[1], nums[2]);
                verifier.Answer = nums[0] * nums[1] - nums[2];
            }
            else
            {
                verifier.Text = string.Format("{2}-{0}x{1}", nums[0], nums[1], nums[2]);
                verifier.Answer = nums[2] - nums[0] * nums[1];
            }
        }

        return verifier;
    }

    public string Text { get; private set; }
    public decimal Answer { get; private set; }

    private MathCaptcha() { }

    public byte[] GetImageData(System.Drawing.Imaging.ImageFormat format)
    {
        var ms = new System.IO.MemoryStream();
        CaptchaImage.Save(ms, format);
        ms.Close();
        return ms.ToArray();
    }

    public Bitmap CaptchaImage
    {
        get
        {
            var w = Text.Length * 13;
            var h = 25;
            var rdm = new Random();
            var bmp = new Bitmap(w, h);
            var graphic = Graphics.FromImage(bmp);
            var font = new Font("Verdana", 14, FontStyle.Italic);

            for (int i = 1; i <= 10; i++)
            {
                graphic.DrawLine(GetPen(i), rdm.Next(w), 0, rdm.Next(w), h);
            }

            graphic.DrawString(Text, font, Brushes.Black, 0, 0);
            for (int i = 0; i <= 50; i++)
            {
                int RandPixelX = rdm.Next(0, w);
                int RandPixelY = rdm.Next(0, h);
                bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);
            }

            return bmp;
        }
    }

    #region Get brush color
    protected Pen GetPen(int i)
    {
        Pen PenLine = new Pen(Brushes.Red, 1);
        switch (i)
        {
            case 1:
                PenLine = new Pen(Brushes.Red, 1);
                break;
            case 2:
                PenLine = new Pen(Brushes.BlueViolet, 1);
                break;
            case 3:
                PenLine = new Pen(Brushes.GreenYellow, 1);
                break;
            case 4:
                PenLine = new Pen(Brushes.Gold, 1);
                break;
            case 5:
                PenLine = new Pen(Brushes.MediumBlue, 1);
                break;
            case 6:
                PenLine = new Pen(Brushes.MintCream, 1);
                break;
            case 7:
                PenLine = new Pen(Brushes.Pink, 1);
                break;
            case 8:
                PenLine = new Pen(Brushes.Purple, 1);
                break;
            case 9:
                PenLine = new Pen(Brushes.HotPink, 1);
                break;
            case 10:
                PenLine = new Pen(Brushes.Chocolate, 1);
                break;
        }
        return PenLine;
    }
    #endregion
}
Serialize object without null field/member in .net web api
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    public class MemberController : ApiController
    {
        // GET api/member/5
        public Member Get(int id)
        {
            return new Member()
            {
                ID = id,
                FirstName = "Bruce"
            };
        }
    }

    [DataContract]
    public class Member
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember(EmitDefaultValue = false)]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string FirstName { get; set; }
        [DataMember(EmitDefaultValue = false)]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string LastName { get; set; }
        [DataMember(EmitDefaultValue = false)]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public DateTime? Birthday { get; set; }
    }
}
Serialize object without null field/member to xml/json
class Program
{
    static void Main(string[] args)
    {
        var m = new Member()
        {
            ID = 3,
            FirstName = "Bruce"
        };
        var dto = new MemberDTO()
        {
            ID = 3,
            FirstName = "Bruce"
        };

        // Serialize to xml format
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(Member));
        var sw = new System.IO.StringWriter();
        xs.Serialize(sw, m);
        Console.WriteLine("Serialize object to xml");
        Console.WriteLine(sw);

        // Serialize to xml format without null value
        xs = new System.Xml.Serialization.XmlSerializer(typeof(MemberDTO));
        sw = new System.IO.StringWriter();
        xs.Serialize(sw, dto);
        Console.WriteLine("Serialize dto-object to xml");
        Console.WriteLine(sw);

        Console.WriteLine("Serialize object to json");
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(m));
        Console.WriteLine("Serialize dto-object to json");
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(dto));

        Console.Read();
    }
}

public class Member
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? Birthday { get; set; }
}

public class MemberDTO
{
    public int ID { get; set; }
    [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string FirstName { get; set; }
    [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string LastName { get; set; }
    [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public DateTime? Birthday { get; set; }

    #region
    public bool ShouldSerializeFirstName()
    {
        return !string.IsNullOrWhiteSpace(FirstName);
    }
    public bool ShouldSerializeLastName()
    {
        return !string.IsNullOrWhiteSpace(LastName);
    }
    public bool ShouldSerializeBirthday()
    {
        return Birthday.HasValue;
    }
    #endregion
}
Result:
Serialize object to xml
<?xml version="1.0" encoding="utf-16"?>
<Member xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ID>3</ID>
  <FirstName>Bruce</FirstName>
  <Birthday xsi:nil="true" />
</Member>
Serialize dto-object to xml
<?xml version="1.0" encoding="utf-16"?>
<MemberDTO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ID>3</ID>
  <FirstName>Bruce</FirstName>
</MemberDTO>
Serialize object to json
{"ID":3,"FirstName":"Bruce","LastName":null,"Birthday":null}
Serialize dto-object to json
{"ID":3,"FirstName":"Bruce"}
Quickly get first and last day of month
public static class DateTimeExtension
{
    public static DateTime FirstDayOfMonth(this DateTime bsaeDate)
    {
        //return new DateTime(bsaeDate.Year, bsaeDate.Month, 1);
        return bsaeDate.AddDays(-bsaeDate.Day + 1);
    }

    public static DateTime LastDayOfMonth(this DateTime baseDate)
    {
        //return new DateTime(baseDate.Year, baseDate.Month + 1, 1).AddDays(-1);
        return baseDate.AddMonths(1).AddDays(-baseDate.AddMonths(1).Day);
    }
}
Quick array compare
string[] array1 = { "A", "B", "C", "D" };
string[] array2 = { "B", "C", "D", "E" };
string[] array3 = { "C", "D", "A", "B" };
string[] array4 = { "A", "B", "C", "D" };

Console.WriteLine("1 Equals 2 : {0}", array1.Equals(array2));  // false
Console.WriteLine("1 Equals 3 : {0}", array1.Equals(array3));  // false
Console.WriteLine("1 Equals 4 : {0}", array1.Equals(array4));  // false

Console.WriteLine("1 SequenceEqual 2 : {0}", array1.SequenceEqual(array2));  // false
Console.WriteLine("1 SequenceEqual 3 : {0}", array1.SequenceEqual(array3));  // false
Console.WriteLine("1 SequenceEqual 4 : {0}", array1.SequenceEqual(array4));  // true

Console.WriteLine("1 Except 2 : {0}", !array1.Except(array2).Any());  // false
Console.WriteLine("1 Except 3 : {0}", !array1.Except(array3).Any());  // true
Console.WriteLine("1 Except 4 : {0}", !array1.Except(array4).Any());  // true
SmtpClient, change authentication type of credential
using (var client = new SmtpClient())
{
    client.UseDefaultCredentials = false;
    client.Host = setting.Host;
    client.Port = setting.Port;
    client.EnableSsl = setting.EnableSsl;

    CredentialCache cache = new CredentialCache();
    // authentication type:  gssapi, ntlm, WDigest, login
    cache.Add(setting.Host, setting.Port, "login", new NetworkCredential(setting.UserName, setting.Password));
    client.Credentials = cache;

    using (var message = new MailMessage())
    {
        var body = System.IO.File.ReadAllText("content.email");

        message.From = new MailAddress(setting.Sender);
        message.ReplyToList.Add(new MailAddress(setting.Email));
        message.To.Add(new MailAddress(setting.Receiver));
        message.IsBodyHtml = true;
        message.Body = body;
        message.Subject = setting.Subject;
        message.BodyEncoding = Encoding.UTF8;
        message.SubjectEncoding = Encoding.UTF8;

        try { client.Send(message); }
        catch (Exception ex)
        {
            Log.Write(ex);
        }
    }
}
Zxing: generate QR code
var code = "Hello, QRCode";
var hints = new Dictionary();
hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.Add(EncodeHintType.MARGIN, 2);

var qrWriter = new QRCodeWriter();
var result = qrWriter.encode(code, BarcodeFormat.QR_CODE, 200, 200, hints);

var writer = new BarcodeWriter() { Format = BarcodeFormat.QR_CODE };
var bitmap = writer.Write(result);

var ms = new System.IO.MemoryStream();
var img = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap());
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Close();

System.IO.File.WriteAllBytes("qrcode.png", ms.ToArray());
Snapshot using WebBrowser
class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        var image = Capture("http://www.yahoo.com", 1024, 768);
        image.Save("aa.png", System.Drawing.Imaging.ImageFormat.Png);
    }

     
    static Image Capture(string url, int width, int height)
    {
        using (WebBrowser wb = new WebBrowser())
        {
            // skip script error
            wb.ScriptErrorsSuppressed = true;
            wb.ScrollBarsEnabled = false;
            wb.AllowNavigation = true;
            // Set the size of the WebBrowser control
            wb.Width = width;
            wb.Height = height;
            ServicePointManager.ServerCertificateValidationCallback
                = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =>
                {
                    return true;
                });


            if (width == -1)
            {
                // Take Screenshot of the web pages full width
                wb.Width = wb.Document.Body.ScrollRectangle.Width;
            }

            if (height == -1)
            {
                // Take Screenshot of the web pages full height
                wb.Height = wb.Document.Body.ScrollRectangle.Height;
            }

            wb.Navigate(url);
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            System.Threading.Thread.Sleep(5000);
            wb.Update();

            // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            return bitmap;
        }
    }
}
Catpture webpage snapshot by form control
[STAThread]
static Image Capture(string url, int width, int height)
{
    WebBrowser wb = new WebBrowser();

    wb.Navigate(url);
    wb.ScrollBarsEnabled = false;
    wb.ScriptErrorsSuppressed = false;

    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Application.DoEvents();
    }

    // Set the size of the WebBrowser control
    wb.Width = width;
    wb.Height = height;

    if (width == -1)
    {
        // Take Screenshot of the web pages full width
        wb.Width = wb.Document.Body.ScrollRectangle.Width;
    }

    if (height == -1)
    {
        // Take Screenshot of the web pages full height
        wb.Height = wb.Document.Body.ScrollRectangle.Height;
    }

    // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
    Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
    wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
    wb.Dispose();

    return bitmap;
}
explicit, implicit and operator
public class Name
{
    /// <summary>
    /// The implicit keyword is used to declare an implicit user-defined type conversion operator.
    /// Use it to enable implicit conversions between a user-defined type and another type, 
    /// if the conversion is guaranteed not to result in a loss of data.
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static implicit operator Name(string name)
    {
        return new Name(name);
    }

    /// <summary>
    /// The explicit keyword declares a user-defined type conversion operator that must be 
    /// invoked with a cast
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static explicit operator string(Name name)
    {
        return name.Content;
    }

    /// <summary>
    /// Use the operator keyword to overload a built-in operator or to provide a user-defined 
    /// conversion in a class or struct declaration.
    /// </summary>
    /// <param name="n1"></param>
    /// <param name="n2"></param>
    /// <returns></returns>
    public static Name operator +(Name n1, Name n2)
    {
        return n1.Content + n1.Content;
    }

    string Content;

    public Name(string name)
    {
        Content = name;
    }

    public override string ToString()
    {
        return Content;
    }
}

class Program
{
    public static void Main(string[] args)
    {
        Name n1 = new Name("Bruce");
        Console.WriteLine(n1);  // output: Bruce

        Name n2 = "Bruce";      // auto cast
        Console.WriteLine(n2);  // output: Bruce

        string n3 = (string)n1; // manual cast
        Console.WriteLine(n3);  // output: Bruce

        Console.WriteLine(n1 + n2);  // output: BruceBruce
    }
}
reference: explicit, implicit, operator
new operator/modifier/constraint

new Operator Used to create objects and invoke constructors.

// Create objects and invoke constructors
Class1 obj  = new Class1();

// Create instances of anonymous types
var employee = new { EmpID = 3, Name = "Bruce", Gender = Gender.Male};

// invoke the default constructor for value types
int i = new int();

// invoke the default constructor for value types with default value
int i = 0;

new Modifier Used to hide an inherited member from a base class member.

class ParentClass
{
    public int x = 5;
    public void Work()
    {
        for (int i = 0; i < x; i++) Console.WriteLine("Parent work : " + i);
    }
    public decimal Caculate()
    {
        return x + x;
    }
}

class ChildClass : ParentClass
{
    public new int x;
    public new void Work()
    {
        for (int i = 0; i < x; i++) Console.WriteLine("Child work : " + i);
    }
    public new decimal Caculate()
    {
        return base.x + this.x;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ParentClass p = new ParentClass();
        p.Work();
        // Parent work : 0
        // Parent work : 1
        // Parent work : 2
        // Parent work : 3
        // Parent work : 4
        Console.WriteLine(p.Caculate());
        // 10

        Console.WriteLine("================");

        ChildClass c = new ChildClass() { x = 3 };
        c.Work();
        // Child work : 0
        // Child work : 1
        // Child work : 2
        Console.WriteLine(c.Caculate());
        // 8
    }
}

new Constraint Used to restrict types that might be used as arguments for a type parameter in a generic declaration.

class MyCollection<T> where T : new()
{
    // Type T must have a public parameterless constructor
}

class MyCollection2<T> : IEnumerable<T> where T : IDisposable, new()
{
    // Type T implements IDisposable and must have a public parameterless constructor,
    // the new() constraint must at last
}
C# 4.0's New Features
Named and Optional Parameters
public class Person
{
    public Person(string name, string gender = "Unknow", int age = 18) { }
}

var p1 = new Person("Bruce");  // only primary parameter
var p2 = new Person("Bruce", "Male");  // one optional parameter
var p3 = new Person("Bruce", "Male", 20);  // all parameters
var p4 = new Person("Bruce", age: 20);  // specified optional parameters

Dynamic Support
dynamic foo = 123;
foo = "foo";

dynamic p = new System.Dynamic.ExpandoObject();
p.age = 20;
p.name = "bruce";
Capitalize First Letters Of Words
string str = "EXTERNAL";
str = new string(str.Select((c, index) => index == 0 ? char.ToUpper(c) : char.ToLower(c)).ToArray());
Console.WriteLine(str);
// output: External
Batch insert using SqlDataAdapter
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["JobHunter"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
    conn.Open();

    #region
    string JobID = Guid.NewGuid().ToString();
    HashSet<string> JobCategory = new HashSet<string>(new string[] { 
       "Windows 8標準搭載のセキュリティ Windows Defenderとは - トレンドマイクロ",
        "Windows 8対応 パスワードマネージャー Modern UI版 - トレンドマイクロ",
        "Windows 8にもマルウェア対策は必須 - トレンドマイクロ",
        "Windows 8にもWeb脅威対策は必須 - トレンドマイクロ",
        "Windows 8でも、面倒なパスワード入力はしない。 - トレンドマイクロ",
        "Windows 8 最新のセキュリティにも対応 - トレンドマイクロ",
        "Windows 8 もウイルスバスタークラウドで安心! border=",
        "Windows 8 のセキュリティ対策もウイルスバスター クラウド - トレンドマイクロ",
        "Windows 8 Modern UI向け無料アプリ Windows ストアアプリ",
        "Windows 8 Modern UI向け Windows ストアアプリ - トレンドマイクロ",
        "Windows 8 Modern UI向け 3種類のWindows ストアアプリ - トレンドマイクロ"
    });
    #endregion

    using (System.Data.SqlClient.SqlDataAdapter adapter 
        = new System.Data.SqlClient.SqlDataAdapter(@"select top 0 * from JobCategory", conn))
    {
        // add insert command
        adapter.InsertCommand = new SqlCommand(@"insert into JobCategory values(@JobID, @CategoryName);", conn);
        adapter.InsertCommand.Parameters.Add("@JobID", SqlDbType.VarChar, 50, "JobID");
        adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 50, "CategoryName");
        adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;

        DataTable dt = new DataTable();
        adapter.Fill(dt);

        foreach (string name in JobCategory)
        {
            dt.Rows.Add(JobID, name);
        }

        // one-time update
        adapter.UpdateBatchSize = 0;
        adapter.Update(dt);
    }
}
Linq paging
var lqData = (from data in cl.AsQueryable<JobData>()
              select data).Skip(pageIndex * pageSize).Take(pageSize);
Regex.Replace by group value
string content = @"<div><img src=""loading.gif"" title=""loading""></div>";
content = System.Text.RegularExpressions.Regex.Replace(content, @"<img(.+?)>", delegate(System.Text.RegularExpressions.Match match)
{
    return string.Format(@"<img{0}/>", match.Groups[1].Value);
});