Пример #1
0
        /// <summary>
        /// Attempts to parse the supplied string into a MonthYear value.
        /// </summary>
        /// <param name="value">String representation of MonthYear value to parse.</param>
        /// <returns>The MonthYear value that corresponds to the supplied string.</returns>
        /// <exception cref="ArgumentException">Thrown if the supplied string did not represent a valid MonthYear value.</exception>
        public static MonthYear Parse(string value)
        {
            MonthYear result = new MonthYear();

            bool suffixValid = false;

            // Note: This is probably better done with a regex at some point.
            if (value.Length == 8)
            {
                string suffix = value.Substring(6, 2);

                if (suffix[0] == 'w')
                {
                    result.Week = ValidateRange(suffix[1].ToString(), 1, 5);
                }
                else
                {
                    result.Day = ValidateRange(suffix, 1, 31);
                }

                suffixValid = true;
            }

            if (value.Length == 6 || (value.Length == 8 && suffixValid))
            {
                result.Year  = ValidateRange(value.Substring(0, 4), 0, 9999);
                result.Month = ValidateRange(value.Substring(4, 2), 1, 12);

                return(result);
            }

            throw ThrowHelper.New <ArgumentException>(ExceptionContext, ErrorMessages.InvalidMonthYearValue, value);
        }
Пример #2
0
        /// <summary>
        /// Gets/sets the boolean state of the enumerated element specified by the supplied EnumID value.
        /// </summary>
        /// <param name="enumId">EnumID to get/set the boolean state for.</param>
        /// <returns>Boolean state for the specified EnumID.</returns>
        public bool this[string enumId]
        {
            get
            {
                for (int n = 0; n < _enumIds.Length; n++)
                {
                    if (_enumIds[n] == enumId)
                    {
                        return(_enumStates[n]);
                    }
                }

                throw ThrowHelper.New <ArgumentException>(this, ErrorMessages.UnrecognisedEnumIdValue, enumId);
            }

            set
            {
                for (int n = 0; n < _enumIds.Length; n++)
                {
                    if (_enumIds[n] == enumId)
                    {
                        _enumStates[n] = value;

                        _log.Debug(m => m("EnumState state now {0}", this.ToString()));

                        return;
                    }
                }

                throw ThrowHelper.New <ArgumentException>(this, ErrorMessages.UnrecognisedEnumIdValue, enumId);
            }
        }
Пример #3
0
        /// <summary>
        /// Sets the wire value for this parameter.  This method is typically used to initialise the parameter through the
        /// InitValue mechanism, but may also be used to initialise the parameter when doing order amendments.
        /// </summary>
        /// <param name="hostParameter"><see cref="Atdl4net.Model.Elements.Parameter_t{T}"/> that is hosting this type.
        /// Parameters in Atdl4net are represented by means of the generic Parameter_t type with the appropriate type parameter,
        /// for example, Parameter_t&lt;Amt_t&gt;.</param>
        /// <param name="value">New wire value (all wire values in Atdl4net are strings).</param>
        public void SetWireValue(IParameter hostParameter, string value)
        {
            // When ConstValue is set, the only assignment we allow is if the supplied value is the same value as ConstValue.
            if (ConstValue != null)
            {
                if (ConvertToWireValueFormat(ConstValue) == value)
                {
                    return;
                }

                throw ThrowHelper.New <InvalidOperationException>(this, ErrorMessages.AttemptToSetConstValueParameter, ConstValue);
            }

            T?convertedValue = ConvertFromWireValueFormat(value);

            ValidationResult result = ValidateValue(convertedValue, true, hostParameter.EnumPairs);

            if (result.IsValid)
            {
                _value = convertedValue;
            }
            else
            {
                throw ThrowHelper.New <InvalidFieldValueException>(this,
                                                                   ErrorMessages.InvalidParameterSetValue, hostParameter.Name, value, result.ErrorText);
            }
        }
        /// <summary>
        /// Updates the values of each control from its respective parameter.
        /// </summary>
        /// <param name="parameters">Parameter collection.</param>
        public void UpdateValuesFromParameters(ParameterCollection parameters)
        {
            foreach (Control_t control in this)
            {
                bool       hasParameterRef  = control.ParameterRef != null;
                bool       isValidParameter = hasParameterRef && parameters.Contains(control.ParameterRef);
                IParameter parameter        = isValidParameter ? parameters[control.ParameterRef] : null;
                object     parameterValue   = isValidParameter ? parameter.GetCurrentValue() : null;

                if (hasParameterRef && !isValidParameter)
                {
                    throw ThrowHelper.New <ReferencedObjectNotFoundException>(this, ErrorMessages.UnresolvedParameterRefError, control.ParameterRef);
                }

                // We only want to update the control value if the parameter has a value
                if (parameterValue != null)
                {
                    _log.Debug(m => m("Updating control {0} value from parameter {1}", control.Id, parameter.Name));

                    control.SetValueFromParameter(parameter);

                    UpdateRelatedHelperControls(control);
                }
            }
        }
Пример #5
0
        public static object ConvertTo(string value, System.Type targetType)
        {
            switch (targetType.FullName)
            {
            case "System.String":
                return(value);

            case "System.Char":
                if (value.Length == 1)
                {
                    return(Convert.ToChar(value));
                }
                throw ThrowHelper.New <InvalidFieldValueException>(ExceptionContext, ErrorMessages.InvalidCharValue, value);

            case "System.Boolean":
                if (TrueWireValueString.Equals(value) || Boolean.TrueString.Equals(value, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(true);
                }
                if (FalseWireValueString.Equals(value) || Boolean.FalseString.Equals(value, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(false);
                }
                throw ThrowHelper.New <InvalidFieldValueException>(ExceptionContext, ErrorMessages.InvalidBooleanValue, value, TrueWireValueString, FalseWireValueString);

            case "System.Int32":
                return(Convert.ToInt32(value, CultureInfo.InvariantCulture));

            case "System.Decimal":
                return(Convert.ToDecimal(value, CultureInfo.InvariantCulture));

            case "System.DateTime":
            {
                DateTime result;

                if (!FixDateTime.TryParse(value, CultureInfo.InvariantCulture, out result))
                {
                    throw ThrowHelper.New <InvalidFieldValueException>(ExceptionContext, ErrorMessages.InvalidDateOrTimeValue, value);
                }

                return(result);
            }

            case "Atdl4net.Fix.FixTag":
                return(new FixTag(Convert.ToInt32(value, CultureInfo.InvariantCulture)));

            default:
                if (targetType.FullName.StartsWith("Atdl4net.Model.Controls.InitValue"))
                {
                    return(value);
                }
                else
                {
                    throw ThrowHelper.New <InternalErrorException>(ExceptionContext, InternalErrors.UnrecognisedAttributeType, targetType.FullName);
                }
            }
        }
Пример #6
0
        public static bool operator >=(Tenor lhs, Tenor rhs)
        {
            if (lhs.TenorType != rhs.TenorType)
            {
                throw ThrowHelper.New <NotSupportedException>(ExceptionContext, ErrorMessages.UnsupportedComparisonOperation, lhs, rhs);
            }

            return(lhs.Offset >= rhs.Offset);
        }
Пример #7
0
        /// <summary>
        /// Initializes a new instance of <see cref="EnumState"/> and copies the data from the supplied EnumState.
        /// </summary>
        /// <param name="sourceState">EnumState to copy the initial state from.</param>
        public EnumState(EnumState sourceState)
        {
            if (sourceState == null)
            {
                throw ThrowHelper.New <ArgumentException>(typeof(EnumState), "A valid EnumState value must be supplied to use this constuctor");
            }

            _enumIds      = sourceState._enumIds;
            _enumStates   = new BitArray(sourceState._enumStates);
            _nonEnumValue = sourceState._nonEnumValue;
        }
Пример #8
0
        /// <summary>
        /// Gets the wire value from enum id.
        /// </summary>
        /// <param name="enumId">The enum id.</param>
        /// <returns></returns>
        public string GetWireValueFromEnumId(string enumId)
        {
            EnumPair_t enumPair = this[enumId];

            if (enumPair == null)
            {
                throw ThrowHelper.New <InvalidOperationException>(this, ErrorMessages.EnumerationNotFound, enumId);
            }

            return(enumPair.WireValue);
        }
Пример #9
0
 public new void Add(ListItem_t item)
 {
     try
     {
         base.Add(item);
     }
     catch (ArgumentException ex)
     {
         throw ThrowHelper.New <DuplicateKeyException>(this, ex, ErrorMessages.AttemptToAddDuplicateKey,
                                                       item.EnumId, "ListItems");
     }
 }
Пример #10
0
        /// <summary>
        /// Provides the state of this EnumState in a format ready to be sent over FIX, e.g., "A B C E".
        /// </summary>
        /// <param name="enumPairs">The EnumPairs for this parameter, to provide the mapping from EnumID values.</param>
        /// <returns>A space-separated string containing zero or more EnumPair WireValues.  If no EnumIDs are enabled,
        /// then null is returned.</returns>
        public string ToWireValue(EnumPairCollection enumPairs)
        {
            _log.Debug(m => m("Converting EnumState to WireValue; current state is {0}", ToString()));

            if (enumPairs.Count != _enumStates.Count)
            {
                throw ThrowHelper.New <InvalidOperationException>(ExceptionContext, ErrorMessages.InconsistentEnumPairsListItemsError);
            }

            // Override the values in the states collection if a non-enum value is supplied.  This is used to handle
            // the unique case of the EditableDropDownList_t control.
            if (NonEnumValue != null)
            {
                return(NonEnumValue.Length > 0 ? NonEnumValue : null);
            }

            bool          hasAtLeastOneValue = false;
            StringBuilder sb = new StringBuilder();

            for (int n = 0; n < _enumStates.Length; n++)
            {
                if (_enumStates[n])
                {
                    string value = enumPairs.GetWireValueFromEnumId(_enumIds[n]);

                    // Typically {NULL} will only be used in a mutually exclusive fashion, although nothing enforces this
                    if (value != Atdl.NullValue)
                    {
                        // Only prepend a space after the first entry
                        if (hasAtLeastOneValue)
                        {
                            sb.AppendFormat(" {0}", value);
                        }
                        else
                        {
                            sb.Append(value);

                            hasAtLeastOneValue = true;
                        }
                    }
                }
            }

            _log.Debug(m => m("EnumState as WireValue is {0}", sb.ToString()));

            return(hasAtLeastOneValue ? sb.ToString() : null);
        }
Пример #11
0
        public static void Render(Strategy_t strategy, XmlWriter writer, WpfComboBoxSizer sizer)
        {
            if (strategy.StrategyLayout == null)
            {
                throw ThrowHelper.New <RenderingException>(ExceptionContext, ErrorMessages.NoStrategyLayoutSupplied);
            }

            StrategyPanel_t rootPanel = strategy.StrategyLayout.StrategyPanel;

            if (rootPanel == null)
            {
                throw ThrowHelper.New <RenderingException>(ExceptionContext, ErrorMessages.NoStrategyPanelsInStrategy);
            }

            WpfXmlWriter wpfWriter = new WpfXmlWriter(writer);

            // TODO: Move this somewhere better
            WpfControlRenderer controlRenderer = new WpfControlRenderer(wpfWriter, sizer);

            // TODO: Move this elsewhere

            CompositionContainer defaultContainer = new CompositionContainer(new TypeCatalog(_defaultRenderers));

            if (!string.IsNullOrEmpty(CustomControlRenderer))
            {
                string applicationDirectory = (from assembly in System.AppDomain.CurrentDomain.GetAssemblies()
                                               where assembly.CodeBase.EndsWith(".exe")
                                               select System.IO.Path.GetDirectoryName(assembly.CodeBase.Replace("file:///", ""))).FirstOrDefault();

                string customControlRendererPath = Path.Combine(applicationDirectory, CustomControlRenderer);

                AssemblyCatalog overridesCatalog = new AssemblyCatalog(customControlRendererPath);

                CompositionContainer aggregateContainer = new CompositionContainer(overridesCatalog, defaultContainer);

                aggregateContainer.ComposeParts(controlRenderer);
            }
            else
            {
                defaultContainer.ComposeParts(controlRenderer);
            }

            int depth = 0;

            ProcessPanel(rootPanel, wpfWriter, controlRenderer, -1, ref depth);
        }
        /// <summary>
        /// Loads the initial values for each control based on the InitPolicy, InitFixField and InitValue attributes.
        /// </summary>
        /// <param name="controlInitValueProvider">Value provider for initializing control values from InitFixField.</param>
        /// <remarks>The spec states: 'If the value of the initPolicy attribute is undefined or equal to "UseValue" and the initValue attribute is
        /// defined then initialize with initValue.  If the value is equal to "UseFixField" then attempt to initialize with the value of
        /// the tag specified in the initFixField attribute. If the value is equal to "UseFixField" and it is not possible to access the
        /// value of the specified fix tag then revert to using initValue. If the value is equal to "UseFixField", the field is not accessible,
        /// and initValue is not defined, then do not initialize.</remarks>
        public void LoadDefaults(FixFieldValueProvider controlInitValueProvider)
        {
            Control_t control = null;

            try
            {
                foreach (Control_t thisControl in this)
                {
                    control = thisControl;

                    thisControl.LoadInitValue(controlInitValueProvider);
                }
            }
            catch (System.Exception ex)
            {
                throw ThrowHelper.Rethrow(this, ex, ErrorMessages.InitControlValueError, control != null ? control.Id : "(unknown)");
            }
        }
Пример #13
0
        private static ushort ValidateRange(string value, int lowerBound, int upperBound)
        {
            try
            {
                ushort numValue = Convert.ToUInt16(value);

                if (numValue >= lowerBound && numValue <= upperBound)
                {
                    return(numValue);
                }

                throw ThrowHelper.New <ArgumentException>(ExceptionContext, ErrorMessages.InvalidMonthYearValue, value);
            }
            catch (FormatException ex)
            {
                throw ThrowHelper.New <ArgumentException>(ExceptionContext, ex, ErrorMessages.InvalidMonthYearValue, value);
            }
        }
Пример #14
0
        public static Tenor Parse(string value)
        {
            Tenor result = new Tenor();

            if (value.Length >= 2)
            {
                switch (value[0])
                {
                case 'D':
                    result.TenorType = TenorTypeValue.Day;
                    break;

                case 'W':
                    result.TenorType = TenorTypeValue.Week;
                    break;

                case 'M':
                    result.TenorType = TenorTypeValue.Month;
                    break;

                case 'Y':
                    result.TenorType = TenorTypeValue.Year;
                    break;
                }

                string number = value.Substring(1);

                try
                {
                    result.Offset = Convert.ToInt32(number);

                    if (result.TenorType != TenorTypeValue.Invalid)
                    {
                        return(result);
                    }
                }
                catch (FormatException ex)
                {
                    throw ThrowHelper.New <ArgumentException>(ExceptionContext, ex, ErrorMessages.InvalidTenorValue, value);
                }
            }

            throw ThrowHelper.New <ArgumentException>(ExceptionContext, ErrorMessages.InvalidTenorValue, value);
        }
Пример #15
0
        /// <summary>
        /// Initializes a new instance of <see cref="FixMessage"/> using the supplied FIX message.
        /// </summary>
        /// <param name="rawMessage">The FIX message to parse.</param>
        /// <remarks>The current implementation of this class does NOT support repeating blocks.</remarks>
        public FixMessage(string rawMessage)
        {
            if (string.IsNullOrEmpty(rawMessage))
            {
                throw ThrowHelper.New <FixParseException>(this, ErrorMessages.UnableToParseFixMessageEmpty);
            }

            string[] nameValuePairs = rawMessage.Split(new char[] { SOH }, StringSplitOptions.RemoveEmptyEntries);

            if (nameValuePairs.Length == 0)
            {
                throw ThrowHelper.New <FixParseException>(this, ErrorMessages.UnableToParseFixMessageInvalidContent, rawMessage);
            }

            char[] separator = new char[] { Separator };

            string tagText   = string.Empty;
            string valueText = string.Empty;

            try
            {
                foreach (string nameValuePair in nameValuePairs)
                {
                    string[] parts = nameValuePair.Split(separator);

                    if (parts.Length != 2)
                    {
                        throw ThrowHelper.New <FixParseException>(this, ErrorMessages.UnableToParseFixMessageInvalidContent, nameValuePair);
                    }

                    tagText   = parts[0];
                    valueText = parts[1];

                    int tag = Convert.ToInt32(tagText);

                    Add((FixField)tag, parts[1]);
                }
            }
            catch (FormatException fe)
            {
                throw ThrowHelper.New <FixParseException>(this, fe, ErrorMessages.UnableToParseFixMessageInvalidFormat, tagText, valueText, fe.Message);
            }
        }
Пример #16
0
        /// <summary>
        /// Evaluates based on the current field values.  Used for evaluating Edits in the context of StateRules.
        /// </summary>
        public void Evaluate()
        {
            _log.Debug(m => m("EditEvaluator evaluating state of Edit_t/EditRef_t; current state is {0}", CurrentState.ToString().ToLower()));

            if (_edit != null)
            {
                _edit.Evaluate();
            }
            else if (_editRef != null)
            {
                _editRef.Evaluate();
            }
            else
            {
                throw ThrowHelper.New <InvalidOperationException>(this, ErrorMessages.NeitherEditNorEditRefSetOnObject, this.GetType().Name);
            }

            _log.Debug(m => m("EditEvaluator evaluated to state {0}", CurrentState.ToString().ToLower()));
        }
Пример #17
0
        /// <summary>
        /// Compares one MonthYear value to see whether it is greater than or equal to a second MonthYear value.
        /// </summary>
        /// <param name="lhs">Left hand side value.</param>
        /// <param name="rhs">Right hand side value.</param>
        /// <returns>True if the left hand operand occurs at the same time or after the right hand operand; false otherwise.</returns>
        public static bool operator >=(MonthYear lhs, MonthYear rhs)
        {
            if (lhs.Year < rhs.Year)
            {
                return(false);
            }

            if (lhs.Year > rhs.Year)
            {
                return(true);
            }

            // Years equal...
            if (lhs.Month < rhs.Month)
            {
                return(false);
            }

            if (lhs.Month > rhs.Month)
            {
                return(true);
            }

            // Years and months equal...
            if (lhs.Day == null && rhs.Day == null && lhs.Week == null && lhs.Week == null)
            {
                return(true);
            }

            if (lhs.Day != null && rhs.Day != null)
            {
                return(lhs.Day >= rhs.Day);
            }

            if (lhs.Week != null && lhs.Week != null)
            {
                return(lhs.Week >= rhs.Week);
            }

            throw ThrowHelper.New <NotSupportedException>(ExceptionContext, ErrorMessages.UnsupportedComparisonOperation, lhs, rhs);
        }
Пример #18
0
        /// <summary>
        /// Gets the wire value for this parameter.  This method is used to retrieve the value of the parameter that should
        /// be transmitted over FIX.
        /// </summary>
        /// <param name="hostParameter"><see cref="Parameter_t{T}"/> that is hosting this type.  Parameters in Atdl4net are
        /// represented by means of the generic Parameter_t type with the appropriate type parameter, for example,
        /// Parameter_t&lt;Amt_t&gt;.</param>
        /// <returns>The parameter's current wire value (all wire values in Atdl4net are strings).</returns>
        public string GetWireValue(IParameter hostParameter)
        {
            T?value = ConstValue ?? _value;

            ValidationResult validity = ValidateValue(value, hostParameter.Use == Use_t.Required, hostParameter.EnumPairs);

            if (!validity.IsValid)
            {
                if (validity.IsMissing)
                {
                    throw ThrowHelper.New <MissingMandatoryValueException>(this, ErrorMessages.NonOptionalParameterNotSupplied, hostParameter.Name);
                }

                throw ThrowHelper.New <InvalidFieldValueException>(ErrorMessages.InvalidGetParameterValue,
                                                                   hostParameter.Name, value, validity.ErrorText);
            }

            string wireValue = ConvertToWireValueFormat(value);

            return(wireValue);
        }
Пример #19
0
        /// <summary>
        /// Sets the value of this parameter using the Control_t that references it.  The resulting parameter value may be
        /// null if the control is not set to a value, or if it has explicitly been set via a state rule to {NULL}.
        /// </summary>
        /// <param name="control">Control to extract this parameter's new value from.</param>
        public ValidationResult SetValueFromControl(Control_t control)
        {
            IParameterConvertible value = control.GetValueForParameter();

            try
            {
                ValidationResult result = _value.SetValueFromControl(this, value);

                // Update the text in the ValidationResult to include this parameter's name
                if (result.IsMissing)
                {
                    return(new ValidationResult(ValidationResult.ResultType.Missing, ErrorMessages.NonOptionalParameterNotSupplied, Name));
                }

                return(result);
            }
            catch (Atdl4netException ex)
            {
                throw ThrowHelper.Rethrow(this, ex, ErrorMessages.UnsuccessfulSetParameterOperation, Name, control.Id, ex.Message);
            }
        }
        /// <summary>
        /// Updates the parameter values from the controls in this control collection.
        /// </summary>
        /// <param name="parameters">Collection of parameters to be updated.</param>
        /// <param name="shortCircuit">If true, this method returns as soon as any error is found; if false, an attempt is made to update all parameter
        /// values before the method returns.</param>
        /// <param name="validationResults">If one or more validations fail, this parameter contains a list of ValidationResults; null otherwise.</param>
        public bool TryUpdateParameterValues(ParameterCollection parameters, bool shortCircuit, out IList <ValidationResult> validationResults)
        {
            bool isValid = true;

            validationResults = null;

            foreach (Control_t control in this)
            {
                string parameter = control.ParameterRef;

                if (parameter != null)
                {
                    if (!parameters.Contains(parameter))
                    {
                        throw ThrowHelper.New <ReferencedObjectNotFoundException>(this, ErrorMessages.UnresolvedParameterRefError, parameter);
                    }

                    ValidationResult result = parameters[parameter].SetValueFromControl(control);

                    if (!result.IsValid)
                    {
                        if (validationResults == null)
                        {
                            validationResults = new List <ValidationResult>();
                        }

                        validationResults.Add(result);

                        if (shortCircuit)
                        {
                            return(false);
                        }

                        isValid = false;
                    }
                }
            }

            return(isValid);
        }
        internal void SourceCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
            case NotifyCollectionChangedAction.Add:
                foreach (Control_t item in e.NewItems)
                {
                    if (_controls.ContainsKey(item.Id))
                    {
                        throw ThrowHelper.New <DuplicateKeyException>(this, ErrorMessages.AttemptToAddDuplicateKey, item.Id, "Controls");
                    }

                    _controls.Add(item.Id, item);
                }
                break;

            // MSDN documentation says helpfully: "The content of the collection changed dramatically."
            case NotifyCollectionChangedAction.Reset:
                _controls.Clear();
                break;

            case NotifyCollectionChangedAction.Remove:
                foreach (Control_t item in e.OldItems)
                {
                    if (_controls.ContainsKey(item.Id))
                    {
                        _controls.Remove(item.Id);
                    }
                }
                break;

            case NotifyCollectionChangedAction.Replace:
                for (int n = 0; n < e.OldItems.Count; n++)
                {
                    _controls[((Control_t)e.OldItems[n]).Id] = (Control_t)e.NewItems[n];
                }
                break;
            }
        }
Пример #22
0
        /// <summary>
        /// Compares the current instance with another object of the same type and returns an integer that indicates
        /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the
        /// other object.
        /// </summary>
        /// <param name="obj">An object to compare with this instance.</param>
        /// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings:
        /// <list type="bullet">
        /// <item><description>Less than zero - this instance precedes obj in the sort order.</description></item></list>
        /// <item><description></description>Zero - this instance occurs in the same position in the sort order as obj.</item></list>
        /// <item><description>Greater than zero - this instance follows obj in the sort order.</description></item></list>
        /// </returns>
        public int CompareTo(object obj)
        {
            // Null references are by definition less than the current instance.
            if (obj == null)
            {
                return(1);
            }

            if (!(obj is MonthYear))
            {
                throw ThrowHelper.New <ArgumentException>(this, InternalErrors.UnexpectedArgumentType, obj.GetType().FullName, this.GetType().FullName);
            }

            MonthYear rhs = (MonthYear)obj;

            if (rhs == this)
            {
                return(0);
            }

            return(rhs <= this ? 1 : -1);
        }
Пример #23
0
        /// <summary>
        /// Converts the supplied value from string format (as might be used on the FIX wire) into the type of the type
        /// parameter for this type.
        /// </summary>
        /// <param name="value">Type to convert from string; cannot be null as empty fields are invalid in FIX.</param>
        /// <returns>Value converted from a string.</returns>
        protected override bool?ConvertFromWireValueFormat(string value)
        {
            string trueValue  = (TrueWireValue != null) ? TrueWireValue : DefaultTrueValue;
            string falseValue = (FalseWireValue != null) ? FalseWireValue : DefaultFalseValue;

            bool?result = null;

            if (value == trueValue)
            {
                result = true;
            }
            else if (value == falseValue)
            {
                result = false;
            }
            else
            {
                throw ThrowHelper.New <ArgumentException>(this, ErrorMessages.InvalidBooleanValue, value, trueValue, falseValue);
            }

            return(result);
        }
Пример #24
0
        /// <summary>
        /// Updates this EnumState with the state of the supplied EnumState.
        /// </summary>
        /// <param name="source">Source EnumState to update this instance from.</param>
        /// <remarks>Implementation note: there are probably more effective ways to copy data from one BitArray to another that the one taken, but
        /// the current implementation ensures that the two EnumStates reference a common set of EnumIDs.</remarks>
        public void UpdateFrom(EnumState source)
        {
            if (source == null)
            {
                throw ThrowHelper.New <ArgumentNullException>(this, "A valid EnumState must be supplied");
            }

            if (_enumIds.Length != source._enumIds.Length)
            {
                throw ThrowHelper.New <ArgumentException>(this, "Unable to update this EnumState from supplied EnumState as the number of EnumIDs was not consistent");
            }

            _log.Debug(m => m("Updating EnumState from {0} to {1}", this.ToString(), source.ToString()));

            int enumCount = _enumIds.Length;

            for (int n = 0; n < _enumIds.Length; n++)
            {
                for (int index = 0; index < source._enumIds.Length; index++)
                {
                    if (source._enumIds[index] == _enumIds[n])
                    {
                        _enumStates.Set(n, source._enumStates[index]);

                        enumCount--;

                        break;
                    }
                }
            }

            if (enumCount != 0)
            {
                throw ThrowHelper.New <ArgumentException>(this, "Mismatch between the EnumIDs of the source and target EnumState");
            }

            _nonEnumValue = source._nonEnumValue;
        }
Пример #25
0
        // TODO: Provide a means to unbind (probably through dispose)
        void IBindable <ViewModelControlCollection> .Bind(ViewModelControlCollection controls)
        {
            if (_edits != null && _edits.Count > 0)
            {
                (_edits as IBindable <ViewModelControlCollection>).Bind(controls);
            }
            else
            {
                if (!string.IsNullOrEmpty(_underlyingEdit.Field))
                {
                    if (controls.Contains(_underlyingEdit.Field))
                    {
                        ControlViewModel targetControl = controls[_underlyingEdit.Field];

                        (targetControl as INotifyValueChanged).ValueChanged += new EventHandler <ValueChangedEventArgs>(OnFieldValueChanged);
                    }
                    else
                    {
                        throw ThrowHelper.New <ReferencedObjectNotFoundException>(this, ErrorMessages.EditRefFieldControlNotFound, _underlyingEdit.Field, "Field");
                    }
                }

                if (!string.IsNullOrEmpty(_underlyingEdit.Field2))
                {
                    if (controls.Contains(_underlyingEdit.Field2))
                    {
                        ControlViewModel targetControl = controls[_underlyingEdit.Field2];

                        (targetControl as INotifyValueChanged).ValueChanged += new EventHandler <ValueChangedEventArgs>(OnField2ValueChanged);
                    }
                    else
                    {
                        throw ThrowHelper.New <ReferencedObjectNotFoundException>(this, ErrorMessages.EditRefFieldControlNotFound, _underlyingEdit.Field2, "Field2");
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Creates a new EnumState from the supplied set of EnumPairs and input FIX string.
        /// </summary>
        /// <param name="enumPairs">EnumPairs for this parameter.</param>
        /// <param name="multiValueString">String containing one or more FIX wire values (space-separated).</param>
        /// <returns></returns>
        public static EnumState FromWireValue(EnumPairCollection enumPairs, string multiValueString)
        {
            _log.DebugFormat("Converting WireValue '{0}' to EnumState", multiValueString);

            string[] inputValues = multiValueString.Split(new char[] { ';', ' ', ',' });

            EnumState result = new EnumState(enumPairs.EnumIds);

            foreach (string inputValue in inputValues)
            {
                string enumId;

                if (!enumPairs.TryParseWireValue(inputValue, out enumId))
                {
                    throw ThrowHelper.New <ArgumentException>(ExceptionContext, ErrorMessages.UnrecognisedEnumIdValue, inputValue);
                }

                result[enumId] = true;
            }

            _log.Debug(m => m("Converting EnumState from WireValue; state is {0}", result.ToString()));

            return(result);
        }
Пример #27
0
        /// <summary>
        /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance
        /// precedes, follows, or occurs in the same position in the sort order as the other object.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <remarks>IComparable is implemented by EnumState to allow its use within Edit_t processing.  Although this interface is
        /// designed to provide less than/greater than comparison, it is primarily used here for determining equality.</remarks>
        public int CompareTo(object obj)
        {
            if (obj is string)
            {
                string enumId = (string)obj;

                if (!IsValidEnumId(enumId))
                {
                    throw ThrowHelper.New <InvalidFieldValueException>(this, ErrorMessages.UnrecognisedEnumIdValue, enumId);
                }

                return(this[enumId] ? 0 : -1);
            }
            else if (obj is EnumState)
            {
                EnumState enumState = (EnumState)obj;

                return(this.Equals(enumState) ? 0 : -1);
            }
            else
            {
                throw ThrowHelper.New <ArgumentException>(this, ErrorMessages.CompareValueFailure, this.ToString(), obj.GetType().FullName);
            }
        }
Пример #28
0
 /// <summary>
 /// Converts the value of this instance to an equivalent nullable DateTime value using the specified culture-specific formatting information.
 /// </summary>
 /// <param name="provider">An <see cref="IFormatProvider"/> interface implementation that supplies culture-specific formatting information.</param>
 /// <returns>A nullable DateTime equivalent to the value of this instance.</returns>
 public DateTime?ToDateTime()
 {
     throw ThrowHelper.New <InvalidCastException>(this, ErrorMessages.UnsupportedParameterValueConversion, _value, "DateTime");
 }
Пример #29
0
 /// <summary>
 /// Converts the value of this instance to an equivalent nullable boolean value.
 /// </summary>
 /// <returns>One of true, false or null which is equivalent to the value of this instance.</returns>
 public bool?ToBoolean()
 {
     throw ThrowHelper.New <InvalidCastException>(this, ErrorMessages.UnsupportedParameterValueConversion, _value, "Boolean");
 }
Пример #30
0
 /// <summary>
 /// Converts the value of this instance to an equivalent nullable decimal value using the specified culture-specific formatting information.
 /// </summary>
 /// <param name="provider">An <see cref="IFormatProvider"/> interface implementation that supplies culture-specific formatting information.</param>
 /// <returns>A nullable decimal equivalent to the value of this instance.</returns>
 public decimal?ToDecimal()
 {
     throw ThrowHelper.New <InvalidCastException>(this, ErrorMessages.UnsupportedParameterValueConversion, _value, "Decimal");
 }