using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; namespace YLPublishTool { static class Helper { static readonly Dictionary _actionMap; static Helper() { _actionMap = new Dictionary(); var bast = typeof(IPublishAction); var types = typeof(Helper).Assembly.GetTypes().Where(t => bast.IsAssignableFrom(t)).ToArray(); foreach (var t in types) { var attr = t.GetCustomAttributes(typeof(DescriptionAttribute), false)?.FirstOrDefault(); if (attr is DescriptionAttribute desc && desc.Description != null) { _actionMap[desc.Description] = t; } } } public static IPublishAction GetAction(string actionName) { return actionName != null && _actionMap.TryGetValue(actionName, out var t) ? (IPublishAction)Activator.CreateInstance(t) : null; } public static bool ExistsAction(string actionName) { return _actionMap.ContainsKey(actionName); } public static string ConvertWildCardToRegex(string str) { if (string.IsNullOrWhiteSpace(str)) { return null; } str = Regex.Replace(str, "\\*+", "*").Replace(" ", "").Replace("||", "|"); return "^" + Regex.Escape(str).Replace("\\|", "|").Replace("\\*", ".*") + "$"; } /// /// 解析url查询字符串,支持&&转义为&,所以和标准规范有出入 /// public static NameValueCollection ParseQueryString(string query, bool urlencoded = false) { if (string.IsNullOrWhiteSpace(query)) { return null; } var len = query.Length; var buf = new char[len + 2]; query.CopyTo(0, buf, 0, len); len += 2; //在下面的循环中正好排除最后一个处理 buf[len - 2] = '&'; buf[len - 1] = 'm'; var start = 0; var hasEscape = false; var nv = new NameValueCollection(10); for (var index = 0; index < len; index++) { if (buf[index] != '&') { continue; } if (buf[index + 1] == '&') { index++; hasEscape = true; continue; } //处理遇到单个&的情况 var substr = new string(buf, start, index - start).Trim(); start = index + 1; if (substr.Length == 0) { continue; } if (hasEscape) { hasEscape = false; substr = substr.Replace("&&", "&"); } var index2 = substr.IndexOf('='); if (index2 > 0) { var key = substr.Substring(0, index2); var value = substr.Substring(index2 + 1); if (urlencoded) { key = Uri.UnescapeDataString(key); value = Uri.UnescapeDataString(value); } nv.Add(key.Trim(), value.Trim()); } else { var key = substr; if (urlencoded) { key = Uri.UnescapeDataString(key); } nv.Add(key.Trim(), string.Empty); } } return nv; } } }