initial commit
[CPE_learningsite] / CPE / CPE.App / CPE.App.Web / Elucidat / StringExtensions.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Text.RegularExpressions;
6 using System.Threading.Tasks;
7 using Newtonsoft.Json.Serialization;
8
9 namespace CPE.App.Web.Elucidat
10 {
11     public static class StringExtensions {
12         private static readonly Dictionary<string, string> ToBeEncoded = new Dictionary<string, string>() { 
13             { "%", "%25" }, 
14             { "!", "%21" }, 
15             { "#", "%23" }, 
16             { " ", "%20" },
17             { "$", "%24" }, 
18             { "&", "%26" }, 
19             { "'", "%27" }, 
20             { "(", "%28" }, 
21             { ")", "%29" }, 
22             { "*", "%2A" }, 
23             { "+", "%2B" }, 
24             { ",", "%2C" }, 
25             { "/", "%2F" }, 
26             { ":", "%3A" }, 
27             { ";", "%3B" }, 
28             { "=", "%3D" }, 
29             { "?", "%3F" }, 
30             { "@", "%40" }, 
31             { "[", "%5B" }, 
32             { "]", "%5D" } 
33         };
34         private static readonly Regex ReplaceRegex = new Regex(@"[%!# $&'()*+,/:;=?@\[\]]");
35
36         /// <summary>
37         /// .NET URL encoding functions (e.g. WebUtility.UrlEncode) do not precisely match the action of php rawurlencode(), 
38         /// which is used by the Elucidat API for signature checking. Therefore we use this custom function instead when URL encoding 
39         /// any data to be sent to the API or used in signature generation.
40         /// </summary>
41         /// <param name="s">The string to be encoded</param>
42         /// <returns>The encoded string</returns>
43         public static string RawUrlEncode(this string s) {
44             return ReplaceRegex.Replace(s, match => ToBeEncoded[match.Value]);
45         }
46
47         /// <summary>
48         /// Transform a .NET style property name (e.g. ProjectCode) into a PHP-style property name (e.g. project_code)
49         /// </summary>
50         /// <param name="propertyName"></param>
51         /// <returns></returns>
52         public static string TransformPropertyName(this string propertyName)
53         {
54             return String.Join("_", Regex.Split(propertyName, "(?=[A-Z])").Where(x => !String.IsNullOrWhiteSpace(x))).ToLower();
55         }
56     }
57 }