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... Simple Web snapshot import java.util.Date; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.graphics.GC; import org.e... Tired of Hibernate? Try JDBI in your code JDBI Quick sample ICategoryDAO.java : create a data access interface (implement is not required) package com.prhythm.erotic.task.data....
Blog Archive
Stats
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
}
ROBOCOPY: Robust File Copy for Windows
-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows
-------------------------------------------------------------------------------

  Started : Wednesday, December 25, 2013 11:26:07 AM
              Usage :: ROBOCOPY source destination [file [file]...] [options]

             source :: Source Directory (drive:\path or \\server\share\path).
        destination :: Destination Dir  (drive:\path or \\server\share\path).
               file :: File(s) to copy  (names/wildcards: default is "*.*").

::
:: Copy options :
::
                 /S :: copy Subdirectories, but not empty ones.
                 /E :: copy subdirectories, including Empty ones.
             /LEV:n :: only copy the top n LEVels of the source directory tree.

                 /Z :: copy files in restartable mode.
                 /B :: copy files in Backup mode.
                /ZB :: use restartable mode; if access denied use Backup mode.
                 /J :: copy using unbuffered I/O (recommended for large files).
            /EFSRAW :: copy all encrypted files in EFS RAW mode.

  /COPY:copyflag[s] :: what to COPY for files (default is /COPY:DAT).
                       (copyflags : D=Data, A=Attributes, T=Timestamps).
                       (S=Security=NTFS ACLs, O=Owner info, U=aUditing info).


               /SEC :: copy files with SECurity (equivalent to /COPY:DATS).
           /COPYALL :: COPY ALL file info (equivalent to /COPY:DATSOU).
            /NOCOPY :: COPY NO file info (useful with /PURGE).
            /SECFIX :: FIX file SECurity on all files, even skipped files.
            /TIMFIX :: FIX file TIMes on all files, even skipped files.

             /PURGE :: delete dest files/dirs that no longer exist in source.
               /MIR :: MIRror a directory tree (equivalent to /E plus /PURGE).

               /MOV :: MOVe files (delete from source after copying).
              /MOVE :: MOVE files AND dirs (delete from source after copying).

     /A+:[RASHCNET] :: add the given Attributes to copied files.
     /A-:[RASHCNET] :: remove the given Attributes from copied files.

            /CREATE :: CREATE directory tree and zero-length files only.
               /FAT :: create destination files using 8.3 FAT file names only.
               /256 :: turn off very long path (> 256 characters) support.

             /MON:n :: MONitor source; run again when more than n changes seen.
             /MOT:m :: MOnitor source; run again in m minutes Time, if changed.

      /RH:hhmm-hhmm :: Run Hours - times when new copies may be started.
                /PF :: check run hours on a Per File (not per pass) basis.

             /IPG:n :: Inter-Packet Gap (ms), to free bandwidth on slow lines.

                /SL :: copy symbolic links versus the target.

            /MT[:n] :: Do multi-threaded copies with n threads (default 8).
                       n must be at least 1 and not greater than 128.
                       This option is incompatible with the /IPG and /EFSRAW options.
                       Redirect output using /LOG option for better performance.

 /DCOPY:copyflag[s] :: what to COPY for directories (default is /DCOPY:DA).
                       (copyflags : D=Data, A=Attributes, T=Timestamps).

           /NODCOPY :: COPY NO directory info (by default /DCOPY:DA is done).

         /NOOFFLOAD :: copy files without using the Windows Copy Offload mechanism.

::
:: File Selection Options :
::
                 /A :: copy only files with the Archive attribute set.
                 /M :: copy only files with the Archive attribute and reset it.
    /IA:[RASHCNETO] :: Include only files with any of the given Attributes set.
    /XA:[RASHCNETO] :: eXclude files with any of the given Attributes set.

 /XF file [file]... :: eXclude Files matching given names/paths/wildcards.
 /XD dirs [dirs]... :: eXclude Directories matching given names/paths.

                /XC :: eXclude Changed files.
                /XN :: eXclude Newer files.
                /XO :: eXclude Older files.
                /XX :: eXclude eXtra files and directories.
                /XL :: eXclude Lonely files and directories.
                /IS :: Include Same files.
                /IT :: Include Tweaked files.

             /MAX:n :: MAXimum file size - exclude files bigger than n bytes.
             /MIN:n :: MINimum file size - exclude files smaller than n bytes.

          /MAXAGE:n :: MAXimum file AGE - exclude files older than n days/date.
          /MINAGE:n :: MINimum file AGE - exclude files newer than n days/date.
          /MAXLAD:n :: MAXimum Last Access Date - exclude files unused since n.
          /MINLAD:n :: MINimum Last Access Date - exclude files used since n.
                       (If n < 1900 then n = n days, else n = YYYYMMDD date).

                /XJ :: eXclude Junction points. (normally included by default).

               /FFT :: assume FAT File Times (2-second granularity).
               /DST :: compensate for one-hour DST time differences.

               /XJD :: eXclude Junction points for Directories.
               /XJF :: eXclude Junction points for Files.

::
:: Retry Options :
::
               /R:n :: number of Retries on failed copies: default 1 million.
               /W:n :: Wait time between retries: default is 30 seconds.

               /REG :: Save /R:n and /W:n in the Registry as default settings.

               /TBD :: wait for sharenames To Be Defined (retry error 67).

::
:: Logging Options :
::
                 /L :: List only - don't copy, timestamp or delete any files.
                 /X :: report all eXtra files, not just those selected.
                 /V :: produce Verbose output, showing skipped files.
                /TS :: include source file Time Stamps in the output.
                /FP :: include Full Pathname of files in the output.
             /BYTES :: Print sizes as bytes.

                /NS :: No Size - don't log file sizes.
                /NC :: No Class - don't log file classes.
               /NFL :: No File List - don't log file names.
               /NDL :: No Directory List - don't log directory names.

                /NP :: No Progress - don't display percentage copied.
               /ETA :: show Estimated Time of Arrival of copied files.

          /LOG:file :: output status to LOG file (overwrite existing log).
         /LOG+:file :: output status to LOG file (append to existing log).

       /UNILOG:file :: output status to LOG file as UNICODE (overwrite existing log).
      /UNILOG+:file :: output status to LOG file as UNICODE (append to existing log).

               /TEE :: output to console window, as well as the log file.

               /NJH :: No Job Header.
               /NJS :: No Job Summary.

           /UNICODE :: output status as UNICODE.

::
:: Job Options :
::
       /JOB:jobname :: take parameters from the named JOB file.
      /SAVE:jobname :: SAVE parameters to the named job file
              /QUIT :: QUIT after processing command line (to view parameters).
              /NOSD :: NO Source Directory is specified.
              /NODD :: NO Destination Directory is specified.
                /IF :: Include the following Files.

Reference: ROBOCOPY

MKLINK: Creates a directory symbolic link
MKLINK [[/D] | [/H] | [/J]] Link Target                                    
                                                                           
        /D      Creates a directory symbolic link.  Default is a file      
                symbolic link.                                             
        /H      Creates a hard link instead of a symbolic link.            
        /J      Creates a Directory Junction.                              
        Link    specifies the new symbolic link name.                      
        Target  specifies the path (relative or absolute) that the new link
                refers to.                                                 

Reference : Mklink

Related : junction

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"}
Active site feature
public void Main(string[] args)
{
    var siteCollectionUrl = "http://your_site_url";
    var featureId = "379c069c-c650-451c-8887-aaaf91bf5df8";
 
    using (var ctx = new ClientContext(siteCollectionUrl))
    {
        var web = ctx.Web;
        // activate feature
        ctx.Load(web);
        ctx.Load(web.Features);
        ctx.ExecuteQuery();
        web.Features.Add(new Guid(featureId), false, FeatureDefinitionScope.Site); ;
        ctx.ExecuteQuery();
    }
}
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
}
Error on RenderAction - No route in the route table matches the supplied values
Application works fine on develop machine and staging server. When deploy to production, there was some route error occurs on RenderAction.
Here is the Rounte config:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}/{*filePath}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Although the id parameter is not required in this rounting. I've tried use code bellow and error occurs
@{Html.RenderAction("ListPart", "Store");}

@{Html.RenderAction("ListPart", "Store", new { id = UrlParameter.Optional });}
Finally, I add a really value to solve it.
@{Html.RenderAction("ListPart", "Store", new { id = 0 });}
Action results
  • ActionResult

    Encapsulates the result of an action method and is used to perform a framework-level operation on behalf of the action method.
    public ActionResult Index()
    {
        return Show();
    }
    
    public ActionResult Show()
    {
        return View();
    }
    
  • ContentResult

    Represents a user-defined content type that is the result of an action method.
    public ActionResult Index()
    {
        return Content("Represents a user-defined content type that is the result of an action method.", "text/plain", System.Text.Encoding.UTF8);
    }
  • EmptyResult

    Represents a result that does nothing, such as a controller action method that returns nothing.
    public ActionResult Index()
    {
        return new EmptyResult();
    }
  • FileContentResult

    Sends the contents of a binary file to the response.
    public ActionResult Index()
    {
        //return new FileContentResult(Buffer, "application/pdf");
        return File(Buffer, "application/pdf");
    }
  • FilePathResult

    Sends the contents of a file to the response.
    public ActionResult Index()
    {
        return File(Server.MapPath("~/doc/sample.pdf"), "application/pdf");
    }
  • FileStreamResult

    Sends binary content to the response by using a Stream instance.
    public ActionResult Index()
    {
        using (var ms = new System.IO.MemoryStream())
        {
            TempImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            //return new FileStreamResult(ms, "image/png") { FileDownloadName = "logo.png" };
            return File(ms, "image/png", "logo.png");
        }
    }
  • HttpNotFoundResult

    Defines an object that is used to indicate that the requested resource was not found.
    public ActionResult Index()
    {
        return HttpNotFound("Page not fould");
    }
  • HttpStatusCodeResult

    Provides a way to return an action result with a specific HTTP response status code and description.
    public ActionResult Index()
    {
        return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
    }
  • HttpUnauthorizedResult

    Represents the result of an unauthorized HTTP request.
    public ActionResult Index()
    {
        return new HttpUnauthorizedResult("Please sign in");
    }
  • JavaScriptResult

    Sends JavaScript content to the response.
    public ActionResult Index()
    {
        return JavaScript("alert(new Date());");
    }
  • JsonResult

    Represents a class that is used to send JSON-formatted content to the response.
    public ActionResult Index()
    {
        return Json(new { Message = "Represents a class that is used to send JSON-formatted content to the response." });
    }
  • PartialViewResult

    Represents a base class that is used to send a partial view to the response.
    public ActionResult Index()
    {
        return PartialView();
    }
  • RedirectResult

    Controls the processing of application actions by redirecting to a specified URI.
    public ActionResult Index()
    {
        //return Redirect("/Product");  // 302
        return RedirectPermanent("/Product");  // 301
    }
    Redirect and RedirectPermanent
  • RedirectToRouteResult

    Represents a result that performs a redirection by using the specified route values dictionary.
    public ActionResult Index()
    {
        //return RedirectToAction("Show");
        //return RedirectToActionPermanent("Show");
        //return RedirectToRoute(new { action = "Show" });
        return RedirectToRoute(new { action = "Show" });
    }
  • ViewResult

    Represents a class that is used to render a view by using an IView instance that is returned by an IViewEngine object.
    public ActionResult Index()
    {
        return View();
    }
Action attributes
  • AcceptVerbsAttribute

    Represents an attribute that specifies which HTTP verbs an action method will respond to.
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index() { return View(); }
    [AcceptVerbs("get", "post")]
    public ActionResult Index() { return View(); }
  • ActionFilterAttribute

    Represents the base class for filter attributes.
    public class PermissionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
        }
    }
  • ActionMethodSelectorAttribute

    Represents an attribute that is used to influence the selection of an action method.
    public class RequestSourceFilterAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            throw new NotImplementedException();
        }
    }
  • ActionNameAttribute

    Represents an attribute that is used for the name of an action.
    [ActionName("Substitute")]
    public ActionResult Index() { return View(); }
  • ActionNameSelectorAttribute

    Represents an attribute that affects the selection of an action method.
    public class RequestSourceFilterAttribute : ActionNameSelectorAttribute
    {
        public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
        {
            throw new NotImplementedException();
        }
    }
  • AllowHtmlAttribute

    Allows a request to include HTML markup during model binding by skipping request validation for the property. (It is strongly recommended that your application explicitly check all models where you disable request validation in order to prevent script exploits.)
    [AllowHtml]
    public ActionResult Index() { return View(); }
  • AsyncTimeoutAttribute

    Represents an attribute that is used to set the timeout value, in milliseconds, for an asynchronous method.
    [AsyncTimeout(1000000)] // In milliseconds.
    public ActionResult Index() { return View(); }
  • AuthorizeAttribute

    Represents an attribute that is used to restrict access by callers to an action method.
    [Authorize(Users = "Betty, Johnny", Roles = "Admin, Super User")]
    public ActionResult Index() { return View(); }
    public class ApplicationAuthorizaeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return base.AuthorizeCore(httpContext);
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
        protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
        {
            return base.OnCacheAuthorization(httpContext);
        }
    }
  • ChildActionOnlyAttribute

    Represents an attribute that is used to indicate that an action method should be called only as a child action.
    [ChildActionOnly]
    public ActionResult Index() { return View(); }
    @{Html.RenderAction("Index");}
  • FilterAttribute

    Represents the base class for action and result filter attributes.
    public class BaseFileter : FilterAttribute
    {
        public override bool IsDefaultAttribute()
        {
            return base.IsDefaultAttribute();
        }
        public override bool Match(object obj)
        {
            return base.Match(obj);
        }
    }
  • HandleErrorAttribute

    Represents an attribute that is used to handle an exception that is thrown by an action method.
    [HandleError(Master = "Site", View = "Error", ExceptionType = typeof(NullReferenceException))]
    public ActionResult Index() { return View(); }
  • HttpDeleteAttribute

    Represents an attribute that is used to restrict an action method so that the method handles only HTTP DELETE requests.
    [HttpDelete]
    public ActionResult Index() { return View(); }
  • HttpGetAttribute

    Represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests.
    [HttpGet]
    public ActionResult Index() { return View(); }
  • HttpPostAttribute

    Represents an attribute that is used to restrict an action method so that the method handles only HTTP POST requests.
    [HttpPost]
    public ActionResult Index() { return View(); }
  • HttpPutAttribute

    Represents an attribute that is used to restrict an action method so that the method handles only HTTP PUT requests.
    [HttpPut]
    public ActionResult Index() { return View(); }
  • NonActionAttribute

    Represents an attribute that is used to indicate that a controller method is not an action method.
    [NonAction]  // Prevent called from url
    public void InnerCall() { Response.Write("Hello InnerCall"); Response.End(); }
  • OutputCacheAttribute

    Represents an attribute that is used to mark an action method whose output will be cached.
    [OutputCache(Duration = 60, VaryByParam = "page")]
    public ActionResult Index() { return View(); }
  • RequireHttpsAttribute

    Represents an attribute that forces an unsecured HTTP request to be re-sent over HTTPS.
    [RequireHttps]
    public ActionResult Index() { return View(); }
  • SessionStateAttribute

    Specifies the session state of the controller.
    [SessionState(System.Web.SessionState.SessionStateBehavior.Required)]
    public ActionResult Index() { return View(); }
  • ValidateInputAttribute

    Represents an attribute that is used to mark action methods whose input must be validated.
    [ValidateInput(false)]
    public ActionResult Index() { return View(); }