Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... 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... set/remove cookie using applet jdk/jre 1.4 later, the library is included in plugin.jar file. import java.applet.Applet; import java.util.ArrayList; import java.util.Date;...
Stats
CORS in Asp.net MVC Web API v2

Step 1.

Install cors from NeGet

Step 2.

Enable cors in config
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web.Http;
  5.  
  6. namespace WebSample
  7. {
  8.     public static class WebApiConfig
  9.     {
  10.         public static void Register(HttpConfiguration config)
  11.         {
  12.             // Web API configuration and services
  13.  
  14.             // Web API routes
  15.             config.MapHttpAttributeRoutes();
  16.  
  17.             config.Routes.MapHttpRoute(
  18.                 name: "DefaultApi",
  19.                 routeTemplate: "api/{controller}/{id}",
  20.                 defaults: new { id = RouteParameter.Optional }
  21.             );
  22.  
  23.             config.EnableCors();
  24.         }
  25.     }
  26. }

Step 3

Add cors attribute to your controller
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using System.Web.Http.Cors;
  8. using WebSample.Models;
  9.  
  10. namespace WebSample.Controllers.Api
  11. {
  12.     public class JobController : ApiController
  13.     {
  14.         [EnableCors(origins: "*", headers: "*", methods: "GET")]
  15.         public Message Get()
  16.         {
  17.             return new Message
  18.             {
  19.                 ID = 2,
  20.                 Content = "Job"
  21.             };
  22.         }
  23.     }
  24. }

Step 4

Test x-domain request
Math Captcha
  1. public class MathCaptcha
  2. {
  3.     public static MathCaptcha Generate(int degree = 3)
  4.     {
  5.         if (degree < 2) degree = 2;
  6.  
  7.         var verifier = new MathCaptcha();
  8.         var rdm = new Random(unchecked((int)DateTime.Now.Ticks));
  9.         var nums = new decimal[] {
  10.             rdm.Next(1, (int)Math.Pow(10, degree)),
  11.             rdm.Next(1, (int)Math.Pow(10, degree)),
  12.             rdm.Next(1, (int)Math.Pow(10, degree))
  13.         };
  14.         nums = nums.OrderBy(=> n).ToArray();
  15.  
  16.         while (true)
  17.         {
  18.             if ((decimal)Math.Pow(10, degree) - 1 <= nums[0] * nums[1])
  19.             {
  20.                 nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
  21.             }
  22.             else if ((decimal)Math.Pow(10, degree - 1) >= nums[0] * nums[1])
  23.             {
  24.                 nums[0] = Math.Ceiling(nums[0] * (decimal)(rdm.NextDouble() + 1));
  25.             }
  26.             else
  27.             {
  28.                 break;
  29.             }
  30.             nums = nums.OrderBy(=> n).ToArray();
  31.         }
  32.  
  33.         if (rdm.NextDouble() > 0.5)
  34.         {
  35.             while (degree != Math.Abs(nums[0] * nums[1] + nums[2]).ToString().Length)
  36.             {
  37.                 nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
  38.             }
  39.  
  40.             if (rdm.NextDouble() > 0.7)
  41.             {
  42.                 verifier.Text = string.Format("{0}x{1}+{2}", nums[0], nums[1], nums[2]);
  43.                 verifier.Answer = nums[0] * nums[1] + nums[2];
  44.             }
  45.             else
  46.             {
  47.                 verifier.Text = string.Format("{2}+{0}x{1}", nums[0], nums[1], nums[2]);
  48.                 verifier.Answer = nums[2] + nums[0] * nums[1];
  49.             }
  50.         }
  51.         else
  52.         {
  53.             while (degree != Math.Abs(nums[0] * nums[1] - nums[2]).ToString().Length)
  54.             {
  55.                 nums[2] = Math.Ceiling(nums[2] * (decimal)rdm.NextDouble());
  56.             }
  57.  
  58.             if (nums[0] * nums[1] - nums[2] > 0)
  59.             {
  60.                 verifier.Text = string.Format("{0}x{1}-{2}", nums[0], nums[1], nums[2]);
  61.                 verifier.Answer = nums[0] * nums[1] - nums[2];
  62.             }
  63.             else
  64.             {
  65.                 verifier.Text = string.Format("{2}-{0}x{1}", nums[0], nums[1], nums[2]);
  66.                 verifier.Answer = nums[2] - nums[0] * nums[1];
  67.             }
  68.         }
  69.  
  70.         return verifier;
  71.     }
  72.  
  73.     public string Text { get; private set; }
  74.     public decimal Answer { get; private set; }
  75.  
  76.     private MathCaptcha() { }
  77.  
  78.     public byte[] GetImageData(System.Drawing.Imaging.ImageFormat format)
  79.     {
  80.         var ms = new System.IO.MemoryStream();
  81.         CaptchaImage.Save(ms, format);
  82.         ms.Close();
  83.         return ms.ToArray();
  84.     }
  85.  
  86.     public Bitmap CaptchaImage
  87.     {
  88.         get
  89.         {
  90.             var w = Text.Length * 13;
  91.             var h = 25;
  92.             var rdm = new Random();
  93.             var bmp = new Bitmap(w, h);
  94.             var graphic = Graphics.FromImage(bmp);
  95.             var font = new Font("Verdana", 14, FontStyle.Italic);
  96.  
  97.             for (int i = 1; i <= 10; i++)
  98.             {
  99.                 graphic.DrawLine(GetPen(i), rdm.Next(w), 0, rdm.Next(w), h);
  100.             }
  101.  
  102.             graphic.DrawString(Text, font, Brushes.Black, 0, 0);
  103.             for (int i = 0; i <= 50; i++)
  104.             {
  105.                 int RandPixelX = rdm.Next(0, w);
  106.                 int RandPixelY = rdm.Next(0, h);
  107.                 bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);
  108.             }
  109.  
  110.             return bmp;
  111.         }
  112.     }
  113.  
  114.     #region Get brush color
  115.     protected Pen GetPen(int i)
  116.     {
  117.         Pen PenLine = new Pen(Brushes.Red, 1);
  118.         switch (i)
  119.         {
  120.             case 1:
  121.                 PenLine = new Pen(Brushes.Red, 1);
  122.                 break;
  123.             case 2:
  124.                 PenLine = new Pen(Brushes.BlueViolet, 1);
  125.                 break;
  126.             case 3:
  127.                 PenLine = new Pen(Brushes.GreenYellow, 1);
  128.                 break;
  129.             case 4:
  130.                 PenLine = new Pen(Brushes.Gold, 1);
  131.                 break;
  132.             case 5:
  133.                 PenLine = new Pen(Brushes.MediumBlue, 1);
  134.                 break;
  135.             case 6:
  136.                 PenLine = new Pen(Brushes.MintCream, 1);
  137.                 break;
  138.             case 7:
  139.                 PenLine = new Pen(Brushes.Pink, 1);
  140.                 break;
  141.             case 8:
  142.                 PenLine = new Pen(Brushes.Purple, 1);
  143.                 break;
  144.             case 9:
  145.                 PenLine = new Pen(Brushes.HotPink, 1);
  146.                 break;
  147.             case 10:
  148.                 PenLine = new Pen(Brushes.Chocolate, 1);
  149.                 break;
  150.         }
  151.         return PenLine;
  152.     }
  153.     #endregion
  154. }
ROBOCOPY: Robust File Copy for Windows
  1. -------------------------------------------------------------------------------
  2.    ROBOCOPY     ::     Robust File Copy for Windows
  3. -------------------------------------------------------------------------------
  4.  
  5.   Started : Wednesday, December 25, 2013 11:26:07 AM
  6.               Usage :: ROBOCOPY source destination [file [file]...] [options]
  7.  
  8.              source :: Source Directory (drive:\path or \\server\share\path).
  9.         destination :: Destination Dir  (drive:\path or \\server\share\path).
  10.                file :: File(s) to copy  (names/wildcards: default is "*.*").
  11.  
  12. ::
  13. :: Copy options :
  14. ::
  15.                  /:: copy Subdirectories, but not empty ones.
  16.                  /:: copy subdirectories, including Empty ones.
  17.              /LEV::: only copy the top n LEVels of the source directory tree.
  18.  
  19.                  /:: copy files in restartable mode.
  20.                  /:: copy files in Backup mode.
  21.                 /ZB :: use restartable mode; if access denied use Backup mode.
  22.                  /:: copy using unbuffered I/(recommended for large files).
  23.             /EFSRAW :: copy all encrypted files in EFS RAW mode.
  24.  
  25.   /COPY:copyflag[s] :: what to COPY for files (default is /COPY:DAT).
  26.                        (copyflags : D=Data, A=Attributes, T=Timestamps).
  27.                        (S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
  28.  
  29.  
  30.                /SEC :: copy files with SECurity (equivalent to /COPY:DATS).
  31.            /COPYALL :: COPY ALL file info (equivalent to /COPY:DATSOU).
  32.             /NOCOPY :: COPY NO file info (useful with /PURGE).
  33.             /SECFIX :: FIX file SECurity on all files, even skipped files.
  34.             /TIMFIX :: FIX file TIMes on all files, even skipped files.
  35.  
  36.              /PURGE :: delete dest files/dirs that no longer exist in source.
  37.                /MIR :: MIRror a directory tree (equivalent to /E plus /PURGE).
  38.  
  39.                /MOV :: MOVe files (delete from source after copying).
  40.               /MOVE :: MOVE files AND dirs (delete from source after copying).
  41.  
  42.      /A+:[RASHCNET] :: add the given Attributes to copied files.
  43.      /A-:[RASHCNET] :: remove the given Attributes from copied files.
  44.  
  45.             /CREATE :: CREATE directory tree and zero-length files only.
  46.                /FAT :: create destination files using 8.3 FAT file names only.
  47.                /256 :: turn off very long path (> 256 characters) support.
  48.  
  49.              /MON::: MONitor source; run again when more than n changes seen.
  50.              /MOT::: MOnitor source; run again in m minutes Time, if changed.
  51.  
  52.       /RH:hhmm-hhmm :: Run Hours - times when new copies may be started.
  53.                 /PF :: check run hours on a Per File (not per pass) basis.
  54.  
  55.              /IPG::: Inter-Packet Gap (ms), to free bandwidth on slow lines.
  56.  
  57.                 /SL :: copy symbolic links versus the target.
  58.  
  59.             /MT[:n] :: Do multi-threaded copies with n threads (default 8).
  60.                        n must be at least 1 and not greater than 128.
  61.                        This option is incompatible with the /IPG and /EFSRAW options.
  62.                        Redirect output using /LOG option for better performance.
  63.  
  64.  /DCOPY:copyflag[s] :: what to COPY for directories (default is /DCOPY:DA).
  65.                        (copyflags : D=Data, A=Attributes, T=Timestamps).
  66.  
  67.            /NODCOPY :: COPY NO directory info (by default /DCOPY:DA is done).
  68.  
  69.          /NOOFFLOAD :: copy files without using the Windows Copy Offload mechanism.
  70.  
  71. ::
  72. :: File Selection Options :
  73. ::
  74.                  /:: copy only files with the Archive attribute set.
  75.                  /:: copy only files with the Archive attribute and reset it.
  76.     /IA:[RASHCNETO] :: Include only files with any of the given Attributes set.
  77.     /XA:[RASHCNETO] :: eXclude files with any of the given Attributes set.
  78.  
  79.  /XF file [file]... :: eXclude Files matching given names/paths/wildcards.
  80.  /XD dirs [dirs]... :: eXclude Directories matching given names/paths.
  81.  
  82.                 /XC :: eXclude Changed files.
  83.                 /XN :: eXclude Newer files.
  84.                 /XO :: eXclude Older files.
  85.                 /XX :: eXclude eXtra files and directories.
  86.                 /XL :: eXclude Lonely files and directories.
  87.                 /IS :: Include Same files.
  88.                 /IT :: Include Tweaked files.
  89.  
  90.              /MAX::: MAXimum file size - exclude files bigger than n bytes.
  91.              /MIN::: MINimum file size - exclude files smaller than n bytes.
  92.  
  93.           /MAXAGE::: MAXimum file AGE - exclude files older than n days/date.
  94.           /MINAGE::: MINimum file AGE - exclude files newer than n days/date.
  95.           /MAXLAD::: MAXimum Last Access Date - exclude files unused since n.
  96.           /MINLAD::: MINimum Last Access Date - exclude files used since n.
  97.                        (If n < 1900 then n = n days, else n = YYYYMMDD date).
  98.  
  99.                 /XJ :: eXclude Junction points. (normally included by default).
  100.  
  101.                /FFT :: assume FAT File Times (2-second granularity).
  102.                /DST :: compensate for one-hour DST time differences.
  103.  
  104.                /XJD :: eXclude Junction points for Directories.
  105.                /XJF :: eXclude Junction points for Files.
  106.  
  107. ::
  108. :: Retry Options :
  109. ::
  110.                /R::: number of Retries on failed copies: default 1 million.
  111.                /W::: Wait time between retries: default is 30 seconds.
  112.  
  113.                /REG :: Save /R:n and /W:in the Registry as default settings.
  114.  
  115.                /TBD :: wait for sharenames To Be Defined (retry error 67).
  116.  
  117. ::
  118. :: Logging Options :
  119. ::
  120.                  /:: List only - don't copy, timestamp or delete any files.
  121.                  /X :: report all eXtra files, not just those selected.
  122.                  /V :: produce Verbose output, showing skipped files.
  123.                 /TS :: include source file Time Stamps in the output.
  124.                 /FP :: include Full Pathname of files in the output.
  125.              /BYTES :: Print sizes as bytes.
  126.  
  127.                 /NS :: No Size - don't log file sizes.
  128.                 /NC :: No Class - don't log file classes.
  129.                /NFL :: No File List - don't log file names.
  130.                /NDL :: No Directory List - don't log directory names.
  131.  
  132.                 /NP :: No Progress - don't display percentage copied.
  133.                /ETA :: show Estimated Time of Arrival of copied files.
  134.  
  135.           /LOG:file :: output status to LOG file (overwrite existing log).
  136.          /LOG+:file :: output status to LOG file (append to existing log).
  137.  
  138.        /UNILOG:file :: output status to LOG file as UNICODE (overwrite existing log).
  139.       /UNILOG+:file :: output status to LOG file as UNICODE (append to existing log).
  140.  
  141.                /TEE :: output to console window, as well as the log file.
  142.  
  143.                /NJH :: No Job Header.
  144.                /NJS :: No Job Summary.
  145.  
  146.            /UNICODE :: output status as UNICODE.
  147.  
  148. ::
  149. :: Job Options :
  150. ::
  151.        /JOB:jobname :: take parameters from the named JOB file.
  152.       /SAVE:jobname :: SAVE parameters to the named job file
  153.               /QUIT :: QUIT after processing command line (to view parameters).
  154.               /NOSD :: NO Source Directory is specified.
  155.               /NODD :: NO Destination Directory is specified.
  156.                 /IF :: Include the following Files.

Reference: ROBOCOPY

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

Reference : Mklink

Related : junction

Serialize object without null field/member in .net web api
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Runtime.Serialization;
  8. using System.Web.Http;
  9.  
  10. namespace WebApplication1.Controllers
  11. {
  12.     public class MemberController : ApiController
  13.     {
  14.         // GET api/member/5
  15.         public Member Get(int id)
  16.         {
  17.             return new Member()
  18.             {
  19.                 ID = id,
  20.                 FirstName = "Bruce"
  21.             };
  22.         }
  23.     }
  24.  
  25.     [DataContract]
  26.     public class Member
  27.     {
  28.         [DataMember]
  29.         public int ID { get; set; }
  30.         [DataMember(EmitDefaultValue = false)]
  31.         [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  32.         public string FirstName { get; set; }
  33.         [DataMember(EmitDefaultValue = false)]
  34.         [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  35.         public string LastName { get; set; }
  36.         [DataMember(EmitDefaultValue = false)]
  37.         [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  38.         public DateTime? Birthday { get; set; }
  39.     }
  40. }
Serialize object without null field/member to xml/json
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.         var m = new Member()
  6.         {
  7.             ID = 3,
  8.             FirstName = "Bruce"
  9.         };
  10.         var dto = new MemberDTO()
  11.         {
  12.             ID = 3,
  13.             FirstName = "Bruce"
  14.         };
  15.  
  16.         // Serialize to xml format
  17.         var xs = new System.Xml.Serialization.XmlSerializer(typeof(Member));
  18.         var sw = new System.IO.StringWriter();
  19.         xs.Serialize(sw, m);
  20.         Console.WriteLine("Serialize object to xml");
  21.         Console.WriteLine(sw);
  22.  
  23.         // Serialize to xml format without null value
  24.         xs = new System.Xml.Serialization.XmlSerializer(typeof(MemberDTO));
  25.         sw = new System.IO.StringWriter();
  26.         xs.Serialize(sw, dto);
  27.         Console.WriteLine("Serialize dto-object to xml");
  28.         Console.WriteLine(sw);
  29.  
  30.         Console.WriteLine("Serialize object to json");
  31.         Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(m));
  32.         Console.WriteLine("Serialize dto-object to json");
  33.         Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(dto));
  34.  
  35.         Console.Read();
  36.     }
  37. }
  38.  
  39. public class Member
  40. {
  41.     public int ID { get; set; }
  42.     public string FirstName { get; set; }
  43.     public string LastName { get; set; }
  44.     public DateTime? Birthday { get; set; }
  45. }
  46.  
  47. public class MemberDTO
  48. {
  49.     public int ID { get; set; }
  50.     [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
  51.     public string FirstName { get; set; }
  52.     [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
  53.     public string LastName { get; set; }
  54.     [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
  55.     public DateTime? Birthday { get; set; }
  56.  
  57.     #region
  58.     public bool ShouldSerializeFirstName()
  59.     {
  60.         return !string.IsNullOrWhiteSpace(FirstName);
  61.     }
  62.     public bool ShouldSerializeLastName()
  63.     {
  64.         return !string.IsNullOrWhiteSpace(LastName);
  65.     }
  66.     public bool ShouldSerializeBirthday()
  67.     {
  68.         return Birthday.HasValue;
  69.     }
  70.     #endregion
  71. }
Result:
  1. Serialize object to xml
  2. <?xml version="1.0" encoding="utf-16"?>
  3. <Member xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  4.   <ID>3</ID>
  5.   <FirstName>Bruce</FirstName>
  6.   <Birthday xsi:nil="true" />
  7. </Member>
  8. Serialize dto-object to xml
  9. <?xml version="1.0" encoding="utf-16"?>
  10. <MemberDTO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  11.   <ID>3</ID>
  12.   <FirstName>Bruce</FirstName>
  13. </MemberDTO>
  14. Serialize object to json
  15. {"ID":3,"FirstName":"Bruce","LastName":null,"Birthday":null}
  16. Serialize dto-object to json
  17. {"ID":3,"FirstName":"Bruce"}