Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Get files name in batch Windows Batch : get filename using [%%~ni] Linux Shell Script : get filename using [awk, sed] windows sample : rename all *.htm file to ... Translating 2.0 <html> <head>     <title>Translation 2.0</title>     <meta http-equiv="content-type" content="text...
Stats
Group operation: create, grant permission and add member using client object model
public void Main(string[] args)
{
    var siteCollectionUrl = "http://your_site_url";
    var member = "domain\\account";

    using (var ctx = new ClientContext(siteCollectionUrl))
    {
        var web = ctx.Web;
        ctx.Load(web, w => w.ServerRelativeUrl);
        ctx.ExecuteQuery();

        // Create a new group named 'Contact'
        var groupInfo = new GroupCreationInformation();
        groupInfo.Title = "Contact";
        groupInfo.Description = string.Format(@"Use this group to grant people full control permissions to the SharePoint site: {0}", groupInfo.Title);
        var group = web.SiteGroups.Add(groupInfo);
        ctx.Load(group);
        ctx.ExecuteQuery();

        // Set group properties
        group.OnlyAllowMembersViewMembership = false;
        group.AllowMembersEditMembership = true;
        group.Update();
        ctx.ExecuteQuery();

        // Grant group permission
        var fullControlPermission = web.RoleDefinitions.GetByName("Full Control");
        var roleBinding = new RoleDefinitionBindingCollection(ctx);
        roleBinding.Add(fullControlPermission);
        web.RoleAssignments.Add(group, roleBinding);
        ctx.ExecuteQuery();

        // Add new member to group
        var u = web.EnsureUser(member);
        ctx.Load(u);
        ctx.ExecuteQuery();
        var userInfo = new UserCreationInformation();
        userInfo.Email = u.Email;
        userInfo.Title = u.Title;
        userInfo.LoginName = u.LoginName;
        group.Users.Add(userInfo);
        ctx.ExecuteQuery();
    }
}
Get file type icon path
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
        var reportItem = properties.ListItem;
        // icon
        var icon = SPUtility.MapToIcon(properties.Web, reportItem["URL Path"].ToString(), "", IconSize.Size16);
        var iconPath = string.Format("/_layouts/15/images/{0}", icon);

        // do something
}
Sublime Text hotkeys
編輯
Ctrl + X 刪除行
Ctrl + Enter 插入下一行
Ctrl + Shift + Enter 插入前一行
Ctrl + Shift + ↑ 往上移動一行
Ctrl + Shift + ↓ 往下移動一行
Ctrl + L 選取整行
Ctrl + D 選取單字(可重複選取相同的)
Alt + F3 選取所有已選取的單字
Ctrl + M 跳到最近的括弧
Ctrl + Shift + M 選取括弧內的所有文字
Ctrl + K + K 刪除游標後方所有文字
Ctrl + K + Backspace 刪除游標前方所有文字
Ctrl + ] 向內縮排(通常使用Tab)
Ctrl + [ 向外縮排(通常使用Shift + Tab)
Ctrl + Shift + D 複製行
Ctrl + J 與下一行結合為同一行
Ctrl + / 註解與移除註解
Ctrl + Shift + / 區域註解
Ctrl + Y 回覆上一步,沒有上一步時重複上個動作
Ctrl + Shift + V 貼上並符合縮排
Ctrl + U 軟回覆(包括選取動作)
導覽/Goto Anything
Ctrl + P 快速開啟檔案
Ctrl + R 快速到達符號(function, class, etc...)
Ctrl + G 快速到達某一行
Ctrl + ; 快速到達變數
通用
Ctrl + Shift + P 命令提示符(包含所有命令)
Ctrl + K + B 切換側欄
Ctrl + Shift + Alt + P 切換狀態列
搜尋/取代
Ctrl + F 搜尋
Ctrl + H 取代
Ctrl + Shift + F 檔案間搜尋
分頁
Ctrl + Shift + T 還原最後關閉的分頁
Ctrl + PgUp 換到上一個分頁
Ctrl + PgDown 換到下一個分頁
Ctrl + Tab 切換上一個分頁
Alt + [NUM] 切換到第[NUM]個分頁
切割視窗
Alt + Shift + (2, 3, 4) 垂直分割(2, 3, 4)個視窗
Alt + Shift + 1 回覆到預設
Alt + Shift + 5 水平垂直分割
Alt + Shift + (8, 9) 水平分割(2, 3)個視窗
書籤
Ctrl + F2 切換書籤
F2 到下一個書籤
Shift + F2 到上一個書籤
Ctrl + Shift + F2 清除書籤
文字操作
Ctrl + K + U 轉換為大寫
Ctrl + K + L 轉換為小寫
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);
    }
}
Permission Levels, SPBasePermissions, PermissionMask bit, and default assignments
enum bit Group Enum Name Name in browser Description R C D FC
12 12 List ManageLists Manage Lists Create and delete lists, add or remove columns in a list, and add or remove public views of a list. FC
10 9 List CancelCheckout Override Checkout Discard or check in a document which is checked out to another user. D FC
3 2 List AddListItems Add Items Add items to lists, add documents to document libraries, and add Web discussion comments. C D FC
4 3 List EditListItems Edit Items Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries. C D FC
5 4 List DeleteListItems Delete Items Delete items from a list, documents from a document library, and Web discussion comments in documents. C D FC
2 1 List ViewListItems View Items View items in lists, documents in document libraries, and view Web discussion comments. R C D FC
6 5 List ApproveItems Approve Items Approve a minor version of a list item or document. D FC
7 6 List OpenItems Open Items View the source of documents with server-side file handlers. R C D FC
8 7 List ViewVersions View Versions View past versions of a list item or document. R C D FC
9 8 List DeleteVersions Delete Versions Delete past versions of a list item or document. C D FC
32 40 List CreateAlerts Create Alerts Create e-mail alerts. R C D FC
13 13 List ViewFormPages View Application Pages View forms, views, and application pages, and enumerate lists. R C D FC
23 26 Site ManagePermissions Manage Permissions Create and change permission levels on the Web site and assign permissions to users and groups. FC
19 22 Site ViewUsageData View Usage Data View reports on Web site usage. FC
21 24 Site ManageSubwebs Create Subsite Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.  FC
28 31 Site ManageWeb Manage Web Site Grant the ability to perform all administration tasks for the Web site as well as manage content. Activate, deactivate, or edit properties of Web site scoped Features through the object model or through the user interface (UI). When granted on the root Web site of a site collection, activate, deactivate, or edit properties of site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site collection scoped Features through the UI, you must be a site collection administrator. FC
16 19 Site AddAndCustomizePages Add and Customize Pages Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services–compatible editor. D FC
17 20 Site ApplyThemeAndBorder Apply Theme and Border Apply a theme or borders to the entire Web site. D FC
18 21 Site ApplyStyleSheets Apply Style Sheets Apply a style sheet (.css file) to the Web site. D FC
22 25 Site CreateGroups Create Groups Create a group of users that can be used anywhere within the site collection. FC
24 27 Site BrowseDirectories Browse Directories Enumerate files and folders in a Web site using Microsoft Office SharePoint Designer 2007 and WebDAV interfaces. C D FC
20 23 Site CreateSSCSite Use Self-Service Site Creation Create a Web site using Self-Service Site Creation.
15 18 Site ViewPages View Pages View pages in a Web site. R C D FC
34 63 Site EnumeratePermissions Enumerate Permissions Enumerate permissions on the Web site, list, folder, document, or list item. FC
25 28 Site BrowseUserInfo Browse User Information View information about users of the Web site. R C D FC
31 39 Site ManageAlerts Manage Alerts Manage alerts for all users of the Web site. FC
30 38 Site UseRemoteAPIs Use Remote Interfaes Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access the Web site. R C D FC
29 37 Site UseClientIntegration Use Client Integration Features Use features that launch client applications; otherwise, users must work on documents locally and upload changes.  R C D FC
14 17 Site Open Open Allow users to open a Web site, list, or folder to access items inside that container. R C D FC
33 41 Site EditMyUserInfo Edit Personal User Information Allows a user to change his or her user information, such as adding a picture. C D FC
11 10 Personal ManagePersonalViews Manage Personal Views Create, change, and delete personal views of lists. C D FC
26 29 Personal AddDelPrivateWebParts Add/Remove Personal Web Parts Add or remove personal Web Parts on a Web Part Page. C D FC
27 30 Personal UpdatePersonalWebParts Update Personal Web Parts Update Web Parts to display personalized information. C D FC
1 0 EmptyMask EmptyMask Has no permissions on the Web site. Not available through the user interface.
35 1 FullMask FullMask Has all permissions on the Web site. Not available through the user interface.

From: http://techtrainingnotes.blogspot.tw/2010/01/sharepoint-permission-levels.html

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;
        }
    }
}
ADOMD.NET, Query data from cube
Add assembly: Microsoft.AnalysisServices.AdomdClient.dll
string ReturnCommandUsingCellSet()
{
    //Create a new string builder to store the results
    System.Text.StringBuilder result = new System.Text.StringBuilder();

    //Connect to the local server
    using (AdomdConnection conn = new AdomdConnection("Data Source=localhost;"))
    {
        conn.Open();

        //Create a command, using this connection
        AdomdCommand cmd = conn.CreateCommand();
        cmd.CommandText = @"
                      WITH MEMBER [Measures].[FreightCostPerOrder] AS 
                            [Measures].[Reseller Freight Cost]/[Measures].[Reseller Order Quantity],  
                            FORMAT_STRING = 'Currency'
                      SELECT 
                            [Geography].[Geography].[Country].&[United States].Children ON ROWS, 
                            [Date].[Calendar].[Calendar Year] ON COLUMNS
                      FROM [Adventure Works]
                      WHERE [Measures].[FreightCostPerOrder]";

        //Execute the query, returning a cellset
        CellSet cs = cmd.ExecuteCellSet();

        //Output the column captions from the first axis
        //Note that this procedure assumes a single member exists per column.
        result.Append("\t");
        TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples;
        foreach (Tuple column in tuplesOnColumns)
        {
            result.Append(column.Members[0].Caption + "\t");
        }
        result.AppendLine();

        //Output the row captions from the second axis and cell data
        //Note that this procedure assumes a two-dimensional cellset
        TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples;
        for (int row = 0; row < tuplesOnRows.Count; row++)
        {
            result.Append(tuplesOnRows[row].Members[0].Caption + "\t");
            for (int col = 0; col < tuplesOnColumns.Count; col++)
            {
                result.Append(cs.Cells[col, row].FormattedValue + "\t");
            }
            result.AppendLine();
        }
        conn.Close();

        return result.ToString();
    } // using connection
}