/// <summary> /// System.Security.SecurityElement.Escape(); /// </summary> /// <param name="xml"></param> /// <returns></returns> public static string GetSafeXml(string xml) { //s = <You're angle & evil>, ['&<>] return Regex.Replace(xml, "'|&|<|>", m => { switch (m.Value) { case "'": return "&apos"; case "&": return "&"; case "<": return "<"; case ">": return ">"; default: return string.Empty; } }); }
#define PerfMonitor //#undef PerfMonitor using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; namespace Rocky.Caching { public sealed class MethodPerformanceMonitor : MarshalByRefObject { #region StaticMembers public const string CompilerSymbal = "PerfMonitor"; #endregion #region Fields private Stopwatch _watch; private string _signature; private long _execTimes; private long _totalRunTicks; private long _hitTimes; private long _totalHitRunTicks; #endregion #region Properties public bool IsEnabled { get { return _watch != null; } } /// <summary> /// 方法签名 /// </summary> public string Signature { get { return _signature; } } public long ExecuteTimes { get { return _execTimes; } } public TimeSpan TotalRunTime { get { return TimeSpan.FromTicks(_totalRunTicks); } } public TimeSpan AverageRunTime { get { return TimeSpan.FromTicks(_totalRunTicks / _execTimes); } } /// <summary> /// 命中率 /// </summary> public double HitRate { get { return (double)_hitTimes / (double)_execTimes; } } /// <summary> /// 命中时的总执行时间 /// </summary> public TimeSpan TotalHitRunTime { get { return TimeSpan.FromTicks(_totalHitRunTicks); } } /// <summary> /// 命中时的平均执行时间 /// </summary> public TimeSpan AverageHitRunTime { get { return TimeSpan.FromTicks((long)((double)_totalHitRunTicks / (double)_hitTimes)); } } #endregion #region Methods public MethodPerformanceMonitor(string signature) { _signature = signature; #if PerfMonitor _watch = new Stopwatch(); #endif } /// <summary> /// 方法try{}语块开始前调用 /// </summary> [Conditional(CompilerSymbal)] public void EnterMethod() { _watch.Start(); } /// <summary> /// 方法finally{}语块结束前调用 /// </summary> [Conditional(CompilerSymbal)] public void ExitMethod(bool isHitCache = false) { long elapsedTicks = _watch.ElapsedTicks; _watch.Reset(); Interlocked.Add(ref _totalRunTicks, elapsedTicks); Interlocked.Increment(ref _execTimes); if (isHitCache) { Interlocked.Add(ref _totalHitRunTicks, elapsedTicks); Interlocked.Increment(ref _hitTimes); } } #endregion } }