public void Errors_ErrorsExist_ShouldReturnErrors()
        {
            var result = new ParseResult();

            var optionMissingError = new OptionMissingError("optionA");

            result.AddError(optionMissingError);

            var unknownOptionError = new UnknownOptionError("optionB");

            result.AddError(unknownOptionError);

            result.Errors.Should().BeEquivalentTo(optionMissingError, unknownOptionError);
        }
Пример #2
0
        private void HandleChild(ParseResult result, XElement child)
        {
            if (child.IsType("visual"))
            {
                if (Visual != null)
                {
                    result.AddWarning("A visual element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                Visual visual = new Visual(NotificationType.Cortana, SupportedFeatures);
                visual.Parse(result, child);

                Visual = visual;
            }

            else if (child.IsType("actionDefinitions"))
            {
                if (ActionDefinitions != null)
                {
                    result.AddWarning("An actionDefinitions element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                ActionDefinitions actions = new ActionDefinitions(NotificationType.Cortana, SupportedFeatures);
                actions.Parse(result, child);

                ActionDefinitions = actions;
            }

            else
            {
                result.AddError($"Invalid child {child.Name.LocalName} under toast element.", GetErrorPositionInfo(child));
            }
        }
Пример #3
0
        internal virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result, string baseUri, bool addImageQuery)
        {
            // src is required
            XAttribute attrSrc = attributes.PopAttribute(ATTR_IMAGE_SRC);

            if (attrSrc == null)
            {
                result.AddError("src attribute on image element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Src = XmlTemplateParser.ConstructUri(attrSrc.Value, baseUri, addImageQuery);



            // alt is optional, I don't use it right now either
            attributes.PopAttribute(ATTR_IMAGE_ALT);


            // hint-crop is optional
            HintCrop hintCrop;

            if (TryParseEnum(result, attributes, ATTR_IMAGE_HINT_CROP, out hintCrop))
            {
                this.HintCrop = hintCrop;
            }
        }
Пример #4
0
        protected void HandleChild(ParseResult result, XElement child)
        {
            if (Type != InputType.Selection)
            {
                result.AddWarning($"Invalid child '{child.Name.LocalName}' found in an input. Only inputs of type 'selection' can contain children.", GetErrorPositionInfo(child));
                return;
            }

            if (child.IsType("selection"))
            {
                Selection selection = new Selection(Context, SupportedFeatures);
                selection.Parse(result, child);

                if (!result.IsOkForRender())
                {
                    throw new IncompleteElementException();
                }

                Children.Add(selection);
                selection.Parent = this;
            }

            else
            {
                result.AddError($@"Invalid child ""{child.Name.LocalName}"" found in an input. Selection inputs can only contain selection elements.", GetErrorPositionInfo(child));
            }
        }
        internal virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // id is required
            XAttribute attrId = attributes.PopAttribute(ATTR_ID);

            if (attrId == null)
            {
                result.AddError("id attribute on action element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Id = attrId.Value;


            // arguments is required
            XAttribute attrArguments = attributes.PopAttribute(ATTR_ARGUMENTS);

            if (attrArguments == null)
            {
                result.AddErrorButRenderAllowed("arguments attribute on action element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Arguments = attrArguments.Value;


            // activationType is optional
            ActivationType type;

            if (TryParseEnum(result, attributes, ATTR_ACTIVATIONTYPE, out type))
            {
                this.ActivationType = type;
            }
        }
        public void Handle_HasErrorsAndNoErrorHandler_ShouldReturn0()
        {
            var result = new ParseResult();

            result.AddError(new OptionMissingError("optionA"));

            result.Handle().Should().Be(0);
        }
        /// <summary>
        /// Parses the given value to the desired option value type of the option parser.
        /// </summary>
        /// <param name="optionValue">The option value to parse.</param>
        /// <param name="parseResult">The object where to put parse errors in if a parse error occurred.</param>
        /// <param name="resultValue">The parsed value.</param>
        /// <returns>True if the given option value could be parsed; otherwise false.</returns>
        protected override Boolean TryParseValue(String optionValue, ParseResult parseResult, out Guid resultValue)
        {
            if (!this.ValueParser.TryParseGuid(optionValue, this.GuidFormat, out resultValue))
            {
                parseResult.AddError(new OptionValueInvalidFormatError(this.OptionName, optionValue, "A valid Guid"));
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Parses the given value to the desired option value type of the option parser.
        /// </summary>
        /// <param name="optionValue">The option value to parse.</param>
        /// <param name="parseResult">The object where to put parse errors in if a parse error occurred.</param>
        /// <param name="resultValue">The parsed value.</param>
        /// <returns>True if the given option value could be parsed; otherwise false.</returns>
        protected override Boolean TryParseValue(String optionValue, ParseResult parseResult, out Int64 resultValue)
        {
            if (!this.ValueParser.TryParseInt64(optionValue, this.NumberStyles, this.FormatProvider, out resultValue))
            {
                parseResult.AddError(new OptionValueInvalidFormatError(this.OptionName, optionValue, $"An integer in the range from {Int64.MinValue} to {Int64.MaxValue}"));
                return(false);
            }

            return(true);
        }
        public void HasErrors_ErrorsExist_ShouldBeTrue()
        {
            var result = new ParseResult();

            var optionMissingError = new OptionMissingError("optionA");

            result.AddError(optionMissingError);

            result.HasErrors.Should().BeTrue();
        }
        public void AddError_ShouldAddError()
        {
            var result = new ParseResult();

            var optionMissingError = new OptionMissingError("optionA");

            result.AddError(optionMissingError);

            result.Errors.Should().BeEquivalentTo(optionMissingError);
        }
Пример #11
0
        /// <summary>
        /// Parses the given value to the desired option value type of the option parser.
        /// </summary>
        /// <param name="optionValue">The option value to parse.</param>
        /// <param name="parseResult">The object where to put parse errors in if a parse error occurred.</param>
        /// <param name="resultValue">The parsed value.</param>
        /// <returns>True if the given option value could be parsed; otherwise false.</returns>
        protected override Boolean TryParseValue(String optionValue, ParseResult parseResult, out TEnum resultValue)
        {
            if (!this.ValueParser.TryParseEnum(optionValue, out resultValue))
            {
                parseResult.AddError(new OptionValueInvalidFormatError(this.OptionName, optionValue, "One of the valid values (see help)"));
                resultValue = default;
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Parses the given value to the desired option value type of the option parser.
        /// </summary>
        /// <param name="optionValue">The option value to parse.</param>
        /// <param name="parseResult">The object where to put parse errors in if a parse error occurred.</param>
        /// <param name="resultValue">The parsed value.</param>
        /// <returns>True if the given option value could be parsed; otherwise false.</returns>
        protected override Boolean TryParseValue(String optionValue, ParseResult parseResult, out TimeSpan resultValue)
        {
            if (!this.ValueParser.TryParseTimeSpan(optionValue, this.TimeSpanFormat, this.FormatProvider, this.TimeSpanStyles, out resultValue))
            {
                var errorMessage = !String.IsNullOrEmpty(this.TimeSpanFormat) ? $"A valid time interval in the format '{this.TimeSpanFormat}'" : "A valid time interval";
                parseResult.AddError(new OptionValueInvalidFormatError(this.OptionName, optionValue, errorMessage));
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Parses the given value to the desired option value type of the option parser.
        /// </summary>
        /// <param name="optionValue">The option value to parse.</param>
        /// <param name="parseResult">The object where to put parse errors in if a parse error occurred.</param>
        /// <param name="resultValue">The parsed value.</param>
        /// <returns>True if the given option value could be parsed; otherwise false.</returns>
        protected override Boolean TryParseValue(String optionValue, ParseResult parseResult, out DateTime resultValue)
        {
            if (!this.ValueParser.TryParseDateTime(optionValue, this.DateTimeFormat, this.FormatProvider, this.DateTimeStyles, out resultValue))
            {
                var errorMessage = !String.IsNullOrEmpty(this.DateTimeFormat) ? $"A valid date (and optionally time of day) in the format '{this.DateTimeFormat}'" : "A valid date (and optionally time of day)";
                parseResult.AddError(new OptionValueInvalidFormatError(this.OptionName, optionValue, errorMessage));
                return(false);
            }

            return(true);
        }
        public void Handle_HasErrors_ShouldReturnValueOfErrorHandler()
        {
            var result   = new ParseResult();
            var handlers = A.Fake <ICommandHandlers>();

            A.CallTo(() => handlers.HandleError(result)).Returns(1);
            result.ErrorHandler(handlers.HandleError);

            result.AddError(new OptionMissingError("optionA"));

            result.Handle().Should().Be(1);
        }
        public void Handle_HasErrors_ShouldNotCallAnyCommandHandler()
        {
            var result   = new ParseResult();
            var handlers = A.Fake <ICommandHandlers>();

            result.CommandHandler <Command1Options>(handlers.HandleCommand1);

            result.AddError(new OptionMissingError("optionA"));

            result.Handle();
            A.CallTo(() => handlers.HandleCommand1(A <Command1Options> .Ignored)).MustNotHaveHappened();
        }
Пример #16
0
        internal void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // id is required
            XAttribute attrId = attributes.PopAttribute(ATTR_ID);

            if (attrId == null)
            {
                result.AddError("id attribute on input element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Id = attrId.Value;
        }
        public void Handle_HasErrors_ShouldCallCallErrorHandler()
        {
            var result   = new ParseResult();
            var handlers = A.Fake <ICommandHandlers>();

            result.ErrorHandler(handlers.HandleError);

            result.AddError(new OptionMissingError("optionA"));

            result.Handle();

            A.CallTo(() => handlers.HandleError(result)).MustHaveHappenedOnceExactly();
        }
        public void Handle_ErrorHandlerThrows_ShouldForwardErrorHandlerException()
        {
            var result   = new ParseResult();
            var handlers = A.Fake <ICommandHandlers>();

            A.CallTo(() => handlers.HandleError(result)).Throws(new Exception("Error Handler Exception"));
            result.ErrorHandler(handlers.HandleError);

            result.AddError(new OptionMissingError("optionA"));

            result.Invoking(a => a.Handle())
            .Should()
            .Throw <Exception>()
            .WithMessage("Error Handler Exception");
        }
Пример #19
0
        protected virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // id is required
            XAttribute attrId = attributes.PopAttribute(ATTR_ID);

            if (attrId == null)
            {
                result.AddError("id attribute on input element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            // type is required
            InputType type;

            if (!TryParseEnum(result, attributes, ATTR_TYPE, out type))
            {
                result.AddErrorButRenderAllowed("type attribute on input element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Id   = attrId.Value;
            this.Type = type;


            // title is optional
            var attrTitle = attributes.PopAttribute(ATTR_TITLE);

            if (attrTitle != null)
            {
                this.Title = attrTitle.Value;
            }

            // placeHolderContent is optional
            var attrPlaceHolderContent = attributes.PopAttribute(ATTR_PLACEHOLDERCONTENT);

            if (attrPlaceHolderContent != null)
            {
                this.PlaceHolderContent = attrPlaceHolderContent.Value;
            }

            // defaultInput is optional
            var attrDefaultInput = attributes.PopAttribute(ATTR_DEFAULTINPUT);

            if (attrDefaultInput != null)
            {
                this.DefaultInput = attrDefaultInput.Value;
            }
        }
Пример #20
0
        /// <summary>
        /// Parses the given tokens and puts the result of the parsing into the given parse result object.
        /// </summary>
        /// <param name="tokens">The tokens to parse.</param>
        /// <param name="parseResult">The object where to put result of the parsing into.</param>
        public override void Parse(List <Token> tokens, ParseResult parseResult)
        {
            var optionToken = tokens.OfType <OptionToken>().FirstOrDefault(a => this.OptionName == a.OptionName);

            if (optionToken != null)
            {
                optionToken.IsParsed = true;

                if (optionToken.OptionValues.Count == 0)
                {
                    this.TargetProperty.SetValue(parseResult.CommandOptions, true);
                }
                else
                {
                    parseResult.AddError(new InvalidOptionError(this.OptionName, "This option does not support any values."));
                }
            }
        }
Пример #21
0
        private void HandleChild(ParseResult result, XElement child)
        {
            if (child.IsType("visual"))
            {
                if (Visual != null)
                {
                    result.AddWarning("A visual element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                Visual visual = new Visual(NotificationType.NewsFeed, SupportedFeatures);
                visual.Parse(result, child);

                Visual = visual;
            }

            else
            {
                result.AddError($"Invalid child {child.Name.LocalName} under newsFeed element.", GetErrorPositionInfo(child));
            }
        }
Пример #22
0
        internal virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // content is required
            XAttribute attrContent = attributes.PopAttribute(ATTR_CONTENT);

            if (attrContent == null)
            {
                result.AddError("content attribute on action element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Content = attrContent.Value;

            // parse activationType, arguments, state
            base.ParseActivatableElementAttributes(node, attributes, result);


            // imageUri is optional
            var attrImageUri = attributes.PopAttribute(ATTR_IMAGEURI);

            if (attrImageUri != null)
            {
                this.ImageUri = attrImageUri.Value;
            }

            // inputId is optional
            var attrInputId = attributes.PopAttribute(ATTR_HINT_INPUTID);

            if (attrInputId != null)
            {
                this.InputId = attrInputId.Value;
            }

            ActionPlacement placement;

            if (TryParseEnum(result, attributes, ATTR_PLACEMENT, out placement))
            {
                this.Placement = placement;
            }
        }
Пример #23
0
        internal virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // target is required
            XAttribute attrTarget = attributes.PopAttribute(ATTR_TARGET);

            if (attrTarget == null)
            {
                result.AddError($"{ATTR_TARGET} attribute on {ELEMENT_NAME} element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Target = attrTarget.Value;


            // property is required
            SetterProperties property;

            if (TryParseEnum(result, attributes, ATTR_PROPERTY, out property))
            {
                this.Property = property;
            }
            else
            {
                result.AddErrorButRenderAllowed($"{ATTR_PROPERTY} attribute on {ELEMENT_NAME} element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }


            // value is required
            XAttribute attrValue = attributes.PopAttribute(ATTR_VALUE);

            if (attrValue == null)
            {
                result.AddErrorButRenderAllowed($"{ATTR_VALUE} attribute on {ELEMENT_NAME} element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Value = attrValue.Value;
        }
Пример #24
0
        protected virtual void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result)
        {
            // id is required
            XAttribute attrId = attributes.PopAttribute(ATTR_ID);

            if (attrId == null)
            {
                result.AddError("id attribute on input element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            // type is required
            XAttribute attrContent = attributes.PopAttribute(ATTR_CONTENT);

            if (attrContent == null)
            {
                result.AddErrorButRenderAllowed("content attribute on input element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Id      = attrId.Value;
            this.Content = attrContent.Value;
        }
Пример #25
0
        protected override void HandleChild(ParseResult result, XElement child, string baseUri, bool addImageQuery)
        {
            if (child.IsType("subgroup"))
            {
                TileSubgroup subgroup = new TileSubgroup();
                subgroup.Parse(result, child, baseUri, addImageQuery);

                if (!result.IsOkForRender())
                {
                    throw new IncompleteElementException();
                }

                if (subgroup != null)
                {
                    this.Add(subgroup);
                }
            }

            else
            {
                result.AddError($@"Invalid child ""{child.Name.LocalName}"" found in a group. Groups can only contain subgroups.", GetErrorPositionInfo(child));
            }
        }
Пример #26
0
        internal void ParseKnownAttributes(XElement node, AttributesHelper attributes, ParseResult result, string baseUri, bool addImageQuery)
        {
            // AddImageQuery is optional
            {
                bool val;
                if (TryParse(result, attributes, ATTR_IMAGE_ADDIMAGEQUERY, out val))
                {
                    addImageQuery = val; // Overwrite cascaded value if it was specified
                    AddImageQuery = val;
                }
            }

            // src is required
            XAttribute attrSrc = attributes.PopAttribute(ATTR_IMAGE_SRC);

            if (attrSrc == null)
            {
                result.AddError("src attribute on image element is required.", XmlTemplateParser.GetErrorPositionInfo(node));
                throw new IncompleteElementException();
            }

            this.Src = XmlTemplateParser.ConstructUri(attrSrc.Value, baseUri, addImageQuery);



            // alt is optional, I don't use it right now
            var altAttr = attributes.PopAttribute(ATTR_IMAGE_ALT);

            if (altAttr != null)
            {
                AlternateText = altAttr.Value;
            }

            // placement defaults to inline
            Placement placement;

            if (TryParseEnum(result, attributes, ATTR_IMAGE_PLACEMENT, out placement))
            {
                this.Placement = placement;
            }

            switch (placement)
            {
            case Placement.Background:

                if (SupportedFeatures.CropCircleOnBackgroundImage)
                {
                    HandleHintCrop(result, attributes);
                }

                if (SupportedFeatures.OverlayForBothBackgroundAndPeek)
                {
                    HandleHintOverlay(result, attributes);
                }

                break;

            case Placement.Peek:

                if (SupportedFeatures.CropCircleOnPeekImage)
                {
                    HandleHintCrop(result, attributes);
                }

                if (SupportedFeatures.OverlayForBothBackgroundAndPeek)
                {
                    HandleHintOverlay(result, attributes);
                }

                break;

            case Placement.Hero:
#if EXPERIMENTAL
                if (Context == NotificationType.NewsFeed)
                {
                    HintHeroHeight heroHeight;
                    if (TryParseEnum(result, attributes, "hint-heroHeight", out heroHeight))
                    {
                        this.HintHeroHeight = heroHeight;
                    }
                }
#endif
                break;

#if EXPERIMENTAL
            case Placement.HeroLogo:
                // No additional properties supported on hero logo
                break;
#endif

            default:
                HandleHintCrop(result, attributes);

                // These only apply to tiles, and only to inline images
                if (Context != NotificationType.Toast ||
                    SupportedFeatures.AdaptiveToasts
                    )
                {
                    // hint-removeMargin is optional
                    bool hintRemoveMargin;
                    if (TryParse(result, attributes, ATTR_IMAGE_HINT_REMOVE_MARGIN, out hintRemoveMargin))
                    {
                        this.HintRemoveMargin = hintRemoveMargin;
                    }

                    // hint-align is optional
                    HintImageAlign hintAlign;
                    if (TryParseEnum(result, attributes, ATTR_IMAGE_HINT_ALIGN, out hintAlign))
                    {
                        this.HintAlign = hintAlign;
                    }
                }

                break;
            }
        }
Пример #27
0
        private void HandleChild(ParseResult result, XElement child)
        {
            if (child.IsType("visual"))
            {
                if (Visual != null)
                {
                    result.AddWarning("A visual element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                Visual visual = new Visual(NotificationType.Toast, SupportedFeatures);
                visual.Parse(result, child);

                Visual = visual;
            }

            else if (child.IsType("actions"))
            {
                if (Actions != null)
                {
                    result.AddWarning("An actions element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                Actions actions = new Actions(NotificationType.Toast, SupportedFeatures);
                actions.Parse(result, child);

                Actions = actions;
            }

            else if (child.IsType("audio"))
            {
                if (Audio != null)
                {
                    result.AddWarning("An audio element was already provided. Only the first one will be used.", GetErrorPositionInfo(child));
                    return;
                }

                Audio audio = new Audio(NotificationType.Toast, SupportedFeatures);
                audio.Parse(result, child);

                Audio = audio;
            }

            else if (SupportedFeatures.ToastHeaders && child.IsType("header"))
            {
                if (Header != null)
                {
                    result.AddErrorButRenderAllowed("A header element was already provided. Only one header is allowed.", GetErrorPositionInfo(child));
                    return;
                }

                Header header = new Header(NotificationType.Toast, SupportedFeatures);
                header.Parse(result, child);

                Header = header;
            }

            else
            {
                result.AddError($"Invalid child {child.Name.LocalName} under toast element.", GetErrorPositionInfo(child));
            }
        }
Пример #28
0
        /// <summary>
        /// Parses the command line arguments
        /// </summary>
        /// <returns>Parse result</returns>
        internal ParseResult ParseCommandLine()
        {
            ParseResult Result           = new ParseResult();
            int         iParameterNumber = 1;

            try
            {
                // check plausibility: Options must follow parameters
                bool bOptionsAvailable = false;

                foreach (CommandArgsItem oItem in this.Tokenizer.Items)
                {
                    if (oItem.ItemType == CommandArgsItemType.Parameter)
                    {
                        if (bOptionsAvailable)
                        {
                            Result.AddError(new ParseError(ParseErrorType.InvalidCommandArgsFormat, oItem.Name, oItem.Value, Resources.ParametersMustPrecedeAnyOptionsErrorMessage));
                        }
                    }
                    else
                    {
                        bOptionsAvailable = true;
                    }
                }

                // process parameters
                foreach (CommandArgsItem oItem in this.Tokenizer.Items)
                {
                    try
                    {
                        foreach (System.Reflection.PropertyInfo oInfo in this.PropertyService.GetProperties())
                        {
                            if (oInfo.GetCustomAttributes(typeof(Parameter), true).FirstOrDefault() is Parameter oParameter && oParameter.OrdinalNumber == iParameterNumber)
                            {
                                if (oItem.ItemType == CommandArgsItemType.Parameter)
                                {
                                    this.PropertyService.SetPropertyValue(oInfo, oItem.Name);
                                    iParameterNumber++;
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Result.AddError(new ParseError(ParseErrorType.UnknownError, oItem.Name, oItem.Value, ex.Message));
                    }
                }

                // process options
                foreach (System.Reflection.PropertyInfo oInfo in this.PropertyService.GetProperties())
                {
                    try
                    {
                        bool bOptionProcessed = false;

                        if (oInfo.GetCustomAttributes(typeof(Option), true).FirstOrDefault() is Option oOption)
                        {
                            foreach (CommandArgsItem oItem in this.Tokenizer.Items)
                            {
                                switch (oItem.ItemType)
                                {
                                case CommandArgsItemType.Option:

                                    if (oOption.Name == oItem.Name ||
                                        oOption.LongName == oItem.Name ||
                                        oOption.AlternativeName == oItem.Name)
                                    {
                                        if (this.PropertyService.IsValidOptionValue(oItem.Name, oItem.Value))
                                        {
                                            this.PropertyService.SetPropertyValue(oInfo, oItem.Value);
                                            bOptionProcessed = true;
                                        }
                                        else
                                        {
                                            Result.AddError(new ParseError(ParseErrorType.InvalidOptionValue, oItem.Name, oItem.Value, String.Format(CultureInfo.InvariantCulture, Resources.ValueIsInvalidForOptionFormatErrorMessage, oItem.Value, oItem.Name)));
                                        }
                                    }

                                    break;

                                case CommandArgsItemType.OptionLongName:

                                    if (oOption.LongName == oItem.Name)
                                    {
                                        if (this.PropertyService.IsValidOptionValue(oItem.Name, oItem.Value))
                                        {
                                            this.PropertyService.SetPropertyValue(oInfo, oItem.Value);
                                            bOptionProcessed = true;
                                        }
                                        else
                                        {
                                            Result.AddError(new ParseError(ParseErrorType.InvalidOptionValue, oItem.Name, oItem.Value, String.Format(CultureInfo.InvariantCulture, Resources.ValueIsInvalidForOptionFormatErrorMessage, oItem.Value, oItem.Name)));
                                        }
                                    }

                                    break;
                                }

                                if (bOptionProcessed)
                                {
                                    break;
                                }
                            }
                        }

                        if (!bOptionProcessed && this.PropertyService.IsRequired(oInfo))
                        {
                            string sOptionName = this.PropertyService.GetOptionName(oInfo);

                            Result.AddError(new ParseError(ParseErrorType.RequiredOptionValue, sOptionName, null, String.Format(CultureInfo.InvariantCulture, Resources.OptionIsMissingRequiredValueFormatErrorMessage, sOptionName)));
                        }
                    }
                    catch (Exception ex)
                    {
                        Result.AddError(new ParseError(ParseErrorType.UnknownError, Resources.NotAvailableShortName, null, ex.Message));
                    }
                }
            }
            catch (InvalidCommandArgsFormatException ex)
            {
                Result.AddError(new ParseError(ParseErrorType.InvalidCommandArgsFormat, ex.ItemName, null, ex.Message));
            }
            catch (Exception ex)
            {
                Result.AddError(new ParseError(ParseErrorType.UnknownError, Resources.NotAvailableShortName, null, ex.Message));
            }

            return(Result);
        }
Пример #29
0
        public ParseResult <TDataRecord> ParseData(Stream fileStream, string separator)
        {
            if (fileStream == null || fileStream.Length <= 0)
            {
                throw new CsvParseException("File is empty");
            }
            var result = new ParseResult <TDataRecord>();

            try
            {
                var file = new StreamReader(fileStream);
                //
                //Stream stream = file;
                //DataTable csvTable = new DataTable();
                //using (CsvReader csvReader =
                //    new CsvReader(new StreamReader(stream), true))
                //{
                //    csvTable.Load(csvReader);
                //}

                var reader = new CsvReader(file);

                reader.Configuration.Delimiter = separator;
                reader.Configuration.IgnoreReadingExceptions = true;

                reader.Configuration.ReadingExceptionCallback = (ex, row) =>
                {
                    if (ex.GetType() == typeof(CsvTypeConverterException))
                    {
                        var error = ex.Data["CsvHelper"];

                        result.AddError("", string.Format("Could not read value {0}", error));
                    }
                    else
                    {
                        result.AddError("", "Could not read Csv file.");
                    }
                };

                while (reader.Read())
                {
                    var rowResult = ParseRow(reader);

                    if (!rowResult.IsValid)
                    {
                        result.AddErrors(rowResult.Errors);
                        return(result);
                    }
                    result.Records.Add(rowResult.Record);
                }
            }
            catch (CsvParseException ex)
            {
                result.AddError("", ex.Message);
            }
            catch (CsvMissingFieldException ex)
            {
                result.AddError("", ex.Message);
            }
            catch (Exception ex)
            {
                throw new CsvParseException("Coud not read csv file");
            }

            return(result);
        }