/* PowerOfTwoIntProperty.cs Copyright © 2008 Diversified Technical Systems, Inc. All Rights Reserved */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using DTS.Common.Utilities; namespace DTS.Common.Utilities.DotNetProgrammingConstructs { /// /// A class to implement self-checking, on-error-auto-syntax-building /// power of 2 int properties. /// public class PowerOfTwoIntProperty : Property { /// /// Determine whether or not the specified value is valid for this property. /// /// /// /// The value to be validity checked. /// /// /// /// true if the value is valid; false otherwise. /// /// public override bool IsValidValue(int value) { try { return IsPowerOf2(value); } catch (System.Exception ex) { throw new Exception( string.Format(Properties.Resources.PowerOfTwoProperty_IsValidValue_UnableToDetermineValidityString, value.ToString()), ex); } } /// /// Determine whether or not the specified value is a power of two. /// /// /// /// The value to be power of 2-checked. /// /// /// /// true if the value is a power of 2, false otherwise. /// /// private bool IsPowerOf2(int value) { try { for (var r = value; r > 0; r >>= 1) if (2 == r) return true; return false; } catch (System.Exception ex) { throw new Exception( string.Format(Properties.Resources.PowerOfTwoProperty_IsPowerOf2_UnableToDeterminePowerOf2nessString, value.ToString()), ex); } } /// /// Generate a user-readable explanation as to why the specified value is /// not valid for this property. /// /// /// /// The value to be described. /// /// /// /// A description explaining why the specified value /// is not valid for this property. /// /// public override string GetInvalidValueDescription(int value) { try { return string.Format(Properties.Resources.PowerOfTwoProperty_GetInvalidValueDescription_ProposedValueIsNotPowerOf2String, value.ToString()); } catch (System.Exception ex) { throw new Exception(Properties.Resources.PowerOfTwoProperty_GetInvalidValueDescription_UnableToGetDescriptionString, ex); } } /// /// Initialize an instance of a power of two int property. /// /// /// /// The initialize value of the int property. /// /// public PowerOfTwoIntProperty(int initialValue) : base(initialValue, true) { try { if (!IsValidValue(initialValue)) throw new InvalidValueException(GetInvalidValueDescription(initialValue)); else return; } catch (System.Exception ex) { throw new ConstructionException( string.Format(Properties.Resources.Generic_EncounteredProblemConstructingClassString, GetType().FullName) , ex); } } /// /// Initialize an instance of a power of two int property. /// public PowerOfTwoIntProperty() : base(0, false) { } } }