Exemplo n.º 1
0
        public void HoldAnErrorAWhenBuiltFromError()
        {
            IFallible <int> actual = Fallible.FromError <int>(new ArgumentException());

            Assert.That(actual.Error, Is.InstanceOf <ArgumentException>());
            Assert.That(actual.Value, Is.EqualTo(default(int)));
        }
Exemplo n.º 2
0
        public void ReturnAnErrorResultWhenBuiltFromError()
        {
            IFallible <int> actual = Fallible.FromError <int>(new ArgumentException());

            Assert.That(actual.IsError, Is.True);
            Assert.That(actual.IsValue, Is.False);
        }
Exemplo n.º 3
0
        public void ReturnASuccessfulResultWhenBuiltFromValue()
        {
            IFallible <int> actual = Fallible.FromValue(314);

            Assert.That(actual.IsValue, Is.True);
            Assert.That(actual.IsError, Is.False);
        }
Exemplo n.º 4
0
 private void OnComplete(Fallible <T> value)
 {
     valueChecker.Dispose();
     Status = FetchStatus.Complete;
     result = value;
     Complete?.Invoke(this, new EventArgs <Fallible <T> >(value));
 }
Exemplo n.º 5
0
        internal static Fallible <TSource> ReduceImpl <TSource>(
            this IEnumerable <TSource> source,
            Func <TSource, TSource, Fallible <TSource> > accumulator,
            Func <Fallible <TSource>, bool> predicate)
        {
            Debug.Assert(source != null);
            Debug.Assert(accumulator != null);
            Debug.Assert(predicate != null);

            using (var iter = source.GetEnumerator())
            {
                if (!iter.MoveNext())
                {
                    throw new InvalidOperationException("Source sequence was empty.");
                }

                Fallible <TSource> retval = Fallible <TSource> .η(iter.Current);

                while (predicate(retval) && iter.MoveNext())
                {
                    retval = retval.Bind(val => accumulator(val, iter.Current));
                }

                return(retval);
            }
        }
Exemplo n.º 6
0
        private IObservable <ITransition> PublishUntilErrorTransition()
        {
            return(Observable.Create <ITransition>(
                       observer =>
            {
                var inverter = Observable
                               .Interval(TimeSpan.FromSeconds(_config.Value.PollingIntervalSeconds), _scheduler)
                               .SelectMany(_ => Fallible.AsyncOperation(ReadExtractors))
                               .Publish();

                var successSubscription = inverter
                                          .Where(fallible => fallible.IsSuccessful)
                                          .Subscribe(fallible => PublishExtracts(fallible.Value));

                var failedSubscription = inverter
                                         .Where(fallible => fallible.IsError)
                                         .Do(fallible => _logger.Log(LogLevel.Error, fallible.Exception, "Encountered exception while querying inverter"))
                                         .Select(fallible => _transitionFactory.ToDisconnecting(_inverter))
                                         .Subscribe(observer);

                return new CompositeDisposable(
                    failedSubscription,
                    successSubscription,
                    inverter.Connect()
                    );
            }));
        }
Exemplo n.º 7
0
        public void HoldTheCorrectValueAWhenBuiltFromValue()
        {
            IFallible <int> actual = Fallible.FromValue(314);

            Assert.That(actual.Value, Is.EqualTo(314));
            Assert.That(actual.Error, Is.Null);
        }
Exemplo n.º 8
0
        public static IHost ValidateConfiguration <T1>(this IHost host)
            where T1 : class, new()
        {
            var value1 = Fallible.Operation(() => host.Services.GetService <IOptions <T1> >().Value);

            ThrowOnError(value1);

            return(host);
        }
Exemplo n.º 9
0
        internal static Fallible <IEnumerable <TSource> > CollectImpl <TSource>(
            this IEnumerable <Fallible <TSource> > source)
        {
            Debug.Assert(source != null);

            var seed = Fallible <IEnumerable <TSource> > .η(Enumerable.Empty <TSource>());

            Func <IEnumerable <TSource>, TSource, IEnumerable <TSource> > append
                = (seq, item) => seq.Append(item);

            var accumulator = Fallible.Lift <IEnumerable <TSource>, TSource, IEnumerable <TSource> >(append);

            return(source.Aggregate(seed, accumulator));
        }
Exemplo n.º 10
0
        public static IHost ValidateConfiguration <T1, T2, T3, T4>(this IHost host)
            where T1 : class, new()
            where T2 : class, new()
            where T3 : class, new()
            where T4 : class, new()
        {
            var value1 = Fallible.Operation(() => host.Services.GetService <IOptions <T1> >().Value);
            var value2 = Fallible.Operation(() => host.Services.GetService <IOptions <T2> >().Value);
            var value3 = Fallible.Operation(() => host.Services.GetService <IOptions <T3> >().Value);
            var value4 = Fallible.Operation(() => host.Services.GetService <IOptions <T4> >().Value);

            ThrowOnError(value1, value2, value3, value4);

            return(host);
        }
Exemplo n.º 11
0
 private static RenderingResult ProcessGalleryItem(GalleryItem item, string outputDirPath, Maybe <string> regressionDirPath) =>
 (
     from svgElement in
     Svg.Renderer.RenderSvgElement(item.Diagram.Compile().Invoke())
     .IfSuccessDo(svgElement => WriteOutToGallery(svgElement, item, outputDirPath))
     from _regressionTest in
     regressionDirPath.To <Fallible <string, Unit> >(
         dir =>
         CheckForRegressions(
             svgElement,
             Path.Combine(dir, $"{item.Title}.svg")),
         () => Fallible.Success <string, Unit>(Unit.Instance))
     select _regressionTest
 )
 .GetFailure()
 .Pipe(maybeFailure => new RenderingResult(item, maybeFailure));
Exemplo n.º 12
0
        internal static Fallible <IEnumerable <TSource> > WhereImpl <TSource>(
            this IEnumerable <TSource> source,
            Func <TSource, Fallible <bool> > predicate)
        {
            Debug.Assert(source != null);
            Debug.Assert(predicate != null);

            var seed = Fallible <IEnumerable <TSource> > .η(Enumerable.Empty <TSource>());

            Func <TSource, Func <bool, IEnumerable <TSource>, IEnumerable <TSource> > > func
                = item => (b, seq) => b?seq.Append(item) : seq;

            Func <Fallible <IEnumerable <TSource> >, TSource, Fallible <IEnumerable <TSource> > > accumulator
                = (mseq, item) => predicate(item).ZipWith(mseq, func(item));

            return(source.Aggregate(seed, accumulator));
        }
Exemplo n.º 13
0
        internal static Fallible <TAccumulate> FoldImpl <TSource, TAccumulate>(
            this IEnumerable <TSource> source,
            TAccumulate seed,
            Func <TAccumulate, TSource, Fallible <TAccumulate> > accumulator)
        {
            Debug.Assert(source != null);
            Debug.Assert(accumulator != null);

            Fallible <TAccumulate> retval = Fallible <TAccumulate> .η(seed);

            using (var iter = source.GetEnumerator())
            {
                while (iter.MoveNext())
                {
                    retval = retval.Bind(val => accumulator(val, iter.Current));
                }
            }

            return(retval);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Generates an SVG element containing the diagram
 /// </summary>
 /// <param name="diagram">the diagram to render</param>
 /// <param name="internalToSvgScaling">the "internal" to SVG scaling ratio.</param>
 /// <returns></returns>
 public static Fallible <string, XElement> RenderSvgElement(
     IDiagram diagram,
     int internalToSvgScaling = 1000)
 {
     return
         (from inputDiagram in Fallible.Success <string, IDiagram>(diagram)
          let boundingBox = EnsureNonZeroDimensions(inputDiagram.Bounds)
                            let converter = new CoordinatesConverter(boundingBox, internalToSvgScaling)
                                            let drawState = new SvgDrawState(converter)
                                                            let renderingResult = RenderSvg(diagram).Run(drawState)
                                                                                  let mainElement = renderingResult.Value
                                                                                                    let finalDrawState = renderingResult.State
                                                                                                                         let svgElements = finalDrawState.BuildDeclarations()
                                                                                                                                           .Concat(new[] { mainElement.Build() })
                                                                                                                                           select new XElement("svg",
                                                                                                                                                               new XAttribute("stroke", "black"),   // provide a reasonable default stroke
                                                                                                                                                               new XAttribute("stroke-width", "0"), // no stroke width.  Those that need it will set it explicitly.
                                                                                                                                                               new XAttribute("viewbox", $"0 0 {converter.SvgWidth} {converter.SvgHeight}"),
                                                                                                                                                               svgElements));
 }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            using (CustomerServiceClient customerService = new CustomerServiceClient()) {
                // Method #1 - get the Fallible object, then deal with it
                // Note that we use named arguments to make the intention clearer
                Log("Requesting customer #1 (who has died)");
                Fallible <Customer> cf = customerService.GetCustomerFallible(1);
                cf.Match(
                    onSuccess: c => Log("Success: (" + c.ID + ") " + c.Name),
                    onFailure: msg => Log("Exception: " + msg),
                    onBadIdea: msg => Log("Bad idea: " + msg)
                    );
                Log("=============================");

                // Method #2 - Don't bother assigning the Fallible object to a local variable as we can't do anything
                // with it other than call match, so might as well call it directly. This is neater
                Log("Requesting customer #2 (who is rude)");
                customerService.GetCustomerFallible(2)
                .Match(
                    onSuccess: c => Log("Success: (" + c.ID + ") " + c.Name),
                    onFailure: msg => Log("Exception: " + msg),
                    onBadIdea: msg => Log("Bad idea: " + msg)
                    );
                Log("=============================");

                // Method #3 - Use separate methods. This allows us to use method groups which is even neater
                // Given the obvious names, we don't need named arguments here
                Log("Requesting customer #3 (who returns without problem)");
                customerService.GetCustomerFallible(3)
                .Match(
                    OnGetCustomerSuccess,
                    OnGetCustomerFailure,
                    OnGetCustomerBadIdea
                    );
                Log("=============================");

                Console.ReadKey();
            }
        }
Exemplo n.º 16
0
 private void OnNext(Fallible <T> value) => Next?.Invoke(this, new EventArgs <Fallible <T> >(value));
Exemplo n.º 17
0
 public Fallible <Customer> GetCustomerFallible(int id)
 {
     return(Fallible <Customer> .Do(() => _customerServiceLogic.GetCustomer(id)));
 }
Exemplo n.º 18
0
 public Fallible UpdateCustomer(Customer c)
 {
     return(Fallible.Do(() => _customerServiceLogic.UpdateCustomer(c)));
 }