SecurityAttributeGenerationHelper.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.CodeDom;
  7. using System.Xml;
  8. static class SecurityAttributeGenerationHelper
  9. {
  10. public static CodeAttributeDeclaration FindOrCreateAttributeDeclaration<T>(CodeAttributeDeclarationCollection attributes)
  11. where T : Attribute
  12. {
  13. if (attributes == null)
  14. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attributes");
  15. CodeTypeReference refT = new CodeTypeReference(typeof(T));
  16. foreach (CodeAttributeDeclaration attribute in attributes)
  17. if (attribute.AttributeType.BaseType == refT.BaseType)
  18. return attribute;
  19. CodeAttributeDeclaration result = new CodeAttributeDeclaration(refT);
  20. attributes.Add(result);
  21. return result;
  22. }
  23. public static void CreateOrOverridePropertyDeclaration<V>(CodeAttributeDeclaration attribute, string propertyName, V value)
  24. {
  25. if (attribute == null)
  26. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attribute");
  27. if (propertyName == null)
  28. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("propertyName");
  29. CodeExpression newValue;
  30. if (value is TimeSpan)
  31. newValue = new CodeObjectCreateExpression(
  32. typeof(TimeSpan),
  33. new CodePrimitiveExpression(((TimeSpan)(object)value).Ticks));
  34. else if (value is Enum)
  35. newValue = new CodeFieldReferenceExpression(
  36. new CodeTypeReferenceExpression(typeof(V)),
  37. ((object)value).ToString());
  38. else
  39. newValue = new CodePrimitiveExpression((object)value);
  40. CodeAttributeArgument attributeProperty = TryGetAttributeProperty(attribute, propertyName);
  41. if (attributeProperty == null)
  42. {
  43. attributeProperty = new CodeAttributeArgument(propertyName, newValue);
  44. attribute.Arguments.Add(attributeProperty);
  45. }
  46. else
  47. attributeProperty.Value = newValue;
  48. }
  49. public static CodeAttributeArgument TryGetAttributeProperty(CodeAttributeDeclaration attribute, string propertyName)
  50. {
  51. if (attribute == null)
  52. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attribute");
  53. if (propertyName == null)
  54. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("propertyName");
  55. foreach (CodeAttributeArgument argument in attribute.Arguments)
  56. if (argument.Name == propertyName)
  57. return argument;
  58. return null;
  59. }
  60. }
  61. }