Pastie now auto-senses if line-wrap is a bad or good idea. Feedback?
## mark a section (Learn more)
static void Main(string[] args) { SetupClaimsPrincipal(); Console.WriteLine(Thread.CurrentPrincipal.AsClaims().EmailAddress); Console.WriteLine(Thread.CurrentPrincipal.AsClaims().Name); Console.ReadLine(); } private static void SetupClaimsPrincipal() { var claims = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "matias"), new Claim(ClaimTypes.Email, "matias@southworks.net") }); var principal = new ClaimsPrincipal(new ClaimsIdentity[] { claims }); Thread.CurrentPrincipal = principal; } } static class ClaimsExtensions { public static dynamic AsClaims(this IPrincipal principal) { var claimsPrincipal = principal as IClaimsPrincipal; if (claimsPrincipal != null) { var identity = claimsPrincipal.Identity as IClaimsIdentity; return new DynamicClaims(identity.Claims); } return null; } } class DynamicClaims : DynamicObject { private readonly ClaimCollection claims; public DynamicClaims(ClaimCollection claims) { this.claims = claims; } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = GetClaim(binder.Name, this.claims); return result != null; } private string GetClaim(string hint, ClaimCollection claims) { var found = claims.Where( c => c.ClaimType.Substring(c.ClaimType.LastIndexOf('/') + 1).Equals(hint, StringComparison.OrdinalIgnoreCase)); if (found.Count() > 1) throw new InvalidOperationException(string.Format("More than one claim ({0}) matched the name: {1}", string.Join(",", claims.Select(c => c.Value)), hint)); if (found.SingleOrDefault() == null) throw new InvalidOperationException(string.Format("No claim was found that ends with after the trailing slash: {0}", hint)); return found.SingleOrDefault().Value; } }
This paste will be private.
From the Design Piracy series on my blog: