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... Change the AppDomain's Base Directory and Environment Directory // Update AppDomain's Base Directory string root_path = "c:\\temp\\"; AppDomain.CurrentDomain.SetData("APPBASE", roo... Word break tag : <wbr/> (HTML5) The  HTML  <wbr>  tag  is  used  defines  a  potential  line  break  point  if  needed.  This  stands  for  Word  BReak. This  is  u...
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"}