commodore73

Attribute to identify JsonConverters to add automatically

Jul 23rd, 2020
42
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. namespace Deliverystack.Core.Attributes
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Diagnostics;
  6.     using System.Reflection;
  7.    
  8.     /// <summary>
  9.     /// Attribute to decorate JsonConverters, mainly to manage modular blocks,
  10.     /// so that SerializationConfigurator can add them to the JsonSerializerSettings
  11.     /// exposed by ContentstackClient and used to instantiate objects from Contentstack JSON.
  12.     /// [AutoLoadJsonConverter(true)]
  13.     /// </summary>
  14.     [AttributeUsage(AttributeTargets.Class)]
  15.     public class AutoLoadJsonConverter : AttributeBase
  16.     {
  17.        
  18. #region Fields
  19.  
  20.         private static List<Type> _types;
  21.  
  22. #endregion
  23.        
  24. #region Properties
  25.  
  26.         /// <summary>
  27.         /// Enabled by default.
  28.         /// </summary>
  29.         public bool Enabled { get; }
  30.  
  31.         /// <summary>
  32.         /// Constructor.
  33.         /// </summary>
  34.         /// <param name="enabled"></param>
  35.         public AutoLoadJsonConverter(bool enabled = true)
  36.         {
  37.             Enabled = enabled;
  38.         }
  39.        
  40. #endregion
  41.  
  42.         public static bool IsEnabledForType(Type t)
  43.         {
  44.             Trace.Assert(t != null, "t is null");
  45.  
  46.             foreach (var attr in t.GetCustomAttributes(typeof(AutoLoadJsonConverter)))
  47.             {
  48.                 AutoLoadJsonConverter ctdAttr = attr as AutoLoadJsonConverter;
  49.                 Trace.Assert(ctdAttr != null, "cast is null");
  50.  
  51.                 if (!ctdAttr.Enabled)
  52.                 {
  53.                     return ctdAttr.Enabled;
  54.                 }
  55.             }
  56.  
  57.             return true;
  58.         }
  59.     }
  60. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×