示例#1
0
 public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
 {
     // Caller should have already checked IsError before executing, so we shoulnd't be here.
     return(TaskHelpers.FromError(new InvalidOperationException()));
 }
示例#2
0
        public void ExecuteAuthorizationFilterAsync_IfContinuationTaskWasCanceled_ReturnsCanceledTask()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();
            Mock <AuthorizationFilterAttribute> filterMock = new Mock <AuthorizationFilterAttribute>();
            var filter = (IAuthorizationFilter)filterMock.Object;

            // Act
            var result = filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => TaskHelpers.Canceled <HttpResponseMessage>());

            // Assert
            result.WaitUntilCompleted();
            Assert.True(result.IsCanceled);
        }
示例#3
0
        public void ExecuteAuthorizationFilterAsync_IfContinuationFaulted_ReturnsFaultedTask()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();
            Mock <AuthorizationFilterAttribute> filterMock = new Mock <AuthorizationFilterAttribute>();
            var       filter    = (IAuthorizationFilter)filterMock.Object;
            Exception exception = new Exception();

            // Act
            var result = filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromError <HttpResponseMessage>(exception));

            // Assert
            result.WaitUntilCompleted();
            Assert.Same(exception, result.Exception.InnerException);
        }
 public async Task UnTriggered()
 {
     var e = new AutoResetEventAsync(false);
     await TaskHelpers.AssertNotTriggered(e.WaitAsync());
 }
        public void ExecuteAsync_IsCancelled_And_Traces_When_Inner_IsCancelled()
        {
            // Arrange
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(TaskHelpers.Canceled <HttpResponseMessage>());

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Warn)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            Task      task   = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);
            Exception thrown = Assert.Throws <TaskCanceledException>(() => task.Wait());

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
示例#6
0
        // TODO add cancelation token
        static private async Task NewConnection(CancellationToken stop)
        {
            NHLog.Info("NHWebSocket", "STARTING nhmws SESSION");
            try
            {
                // TODO think if we might want to dump prev data????
                // on each new connection clear the ConcurrentQueues,
                _recieveQueue   = new ConcurrentQueue <MessageEventArgs>();
                _sendQueue      = new ConcurrentQueue <IEnumerable <NHSendMessage> >();
                _isNhmwsRestart = false;
                _notifyMinerStatusAfter.Value = null;

                NHLog.Info("NHWebSocket", "Creating socket");
                using (_webSocket = new WebSocket(_address))
                {
                    _webSocket.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                    //stop.Register(() => _webSocket.Close(CloseStatusCode.Normal, "Closing CancellationToken"));
                    _webSocket.OnOpen           += Login;
                    _webSocket.OnMessage        += (s, eMsg) => _recieveQueue.Enqueue(eMsg);
                    _webSocket.OnError          += (s, e) => NHLog.Info("NHWebSocket", $"Error occured: {e.Message}");
                    _webSocket.OnClose          += (s, e) => NHLog.Info("NHWebSocket", $"Connection closed code {e.Code}: {e.Reason}");;
                    _webSocket.Log.Level         = LogLevel.Debug;
                    _webSocket.Log.Output        = (data, s) => NHLog.Info("NHWebSocket", data.ToString());
                    _webSocket.EnableRedirection = true;

                    NHLog.Info("NHWebSocket", "Connecting");
                    _webSocket.Connect();

                    const int minerStatusTickSeconds = 45;
                    var       checkWaitTime          = TimeSpan.FromMilliseconds(50);

                    var skipMinerStatus = !CredentialValidators.ValidateBitcoinAddress(_login.btc);

                    NHLog.Info("NHWebSocket", "Starting Loop");
                    while (IsWsAlive && !stop.IsCancellationRequested)
                    {
                        if (IsWsAlive)
                        {
                            HandleSendMessage();
                        }
                        if (IsWsAlive)
                        {
                            await HandleReceiveMessage();
                        }
                        // TODO add here the last miner status send check
                        if (IsWsAlive)
                        {
                            await TaskHelpers.TryDelay(checkWaitTime, stop);
                        }

                        if (skipMinerStatus)
                        {
                            continue;
                        }
                        var elapsedTime = DateTime.UtcNow - _lastSendMinerStatusTimestamp.Value;
                        if (elapsedTime.TotalSeconds > minerStatusTickSeconds)
                        {
                            var minerStatusJsonStr = CreateMinerStatusMessage();
                            var minerStatus        = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr);
                            _sendQueue.Enqueue(new NHSendMessage[1] {
                                minerStatus
                            });
                        }
                        if (_notifyMinerStatusAfter.Value.HasValue && DateTime.UtcNow >= _notifyMinerStatusAfter.Value.Value)
                        {
                            _notifyMinerStatusAfter.Value = null;
                            var minerStatusJsonStr = CreateMinerStatusMessage();
                            var minerStatus        = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr);
                            _sendQueue.Enqueue(new NHSendMessage[1] {
                                minerStatus
                            });
                        }
                    }
                    // Ws closed
                    NHLog.Info("NHWebSocket", "Exited Loop");
                }
            }
            catch (TaskCanceledException e)
            {
                NHLog.Debug("NHWebSocket", $"TaskCanceledException {e.Message}");
            }
            finally
            {
                NHLog.Info("NHWebSocket", "ENDING nhmws SESSION");
                ApplicationStateManager.SetNhmwsConnectionChanged(false);
            }
        }
 public async Task Triggered()
 {
     var e = new AutoResetEventAsync(true);
     await TaskHelpers.AssertTriggered(e.WaitAsync());
 }
示例#8
0
 private void SetupUpRoundTripSerialization(Func <Type, object> factory = null)
 {
     factory = factory ?? Activator.CreateInstance;
     _formatterMock.Setup(f => f.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>()))
     .Returns(TaskHelpers.Completed());
     _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny <Type>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <IFormatterLogger>()))
     .Returns <Type, Stream, HttpContent, IFormatterLogger>((type, stream, content, logger) => TaskHelpers.FromResult <object>(factory(type)));
 }
示例#9
0
 public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled()
 {
     // WriteToStreamAsync is not overridable on BufferedMediaTypeFormatter.
     // So, let this test be a NOOP
     return(TaskHelpers.Completed());
 }
示例#10
0
 public Task WrappedTaskReturningMethod()
 {
     return(TaskHelpers.FromResult(TaskHelpers.Completed()));
 }
示例#11
0
 public object TaskAsObjectReturningMethod()
 {
     return(TaskHelpers.Completed());
 }
示例#12
0
 public Task DeleteAllUsersAsync()
 {
     return(TaskHelpers.Completed());
 }
示例#13
0
        public When_a_consumer_has_multiple_handlers()
        {
            mockBuilder = new MockBuilder();

            var queue = new Queue("test_queue", false, false, false, false);

            var countdownEvent = new CountdownEvent(3);

            mockBuilder.Bus.Advanced.Consume(queue, x => x
                                             .Add <MyMessage>((message, info) => TaskHelpers.ExecuteSynchronously(() =>
            {
                myMessageResult = message.Body;
                countdownEvent.Signal();
            }))
                                             .Add <MyOtherMessage>((message, info) => TaskHelpers.ExecuteSynchronously(() =>
            {
                myOtherMessageResult = message.Body;
                countdownEvent.Signal();
            }))
                                             .Add <IAnimal>((message, info) => TaskHelpers.ExecuteSynchronously(() =>
            {
                animalResult = message.Body;
                countdownEvent.Signal();
            })));

            Deliver(new MyMessage {
                Text = "Hello Polymorphs!"
            });
            Deliver(new MyOtherMessage {
                Text = "Hello Isomorphs!"
            });
            Deliver(new Dog());

            countdownEvent.Wait(1000);
        }
示例#14
0
        /// <summary>
        /// Called during deserialization to read an object of the specified <paramref name="type"/>
        /// from the specified <paramref name="readStream"/>.
        /// </summary>
        /// <param name="type">The type of object to read.</param>
        /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
        /// <param name="content">The <see cref="HttpContent"/> for the content being written.</param>
        /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
        /// <returns>A <see cref="Task"/> whose result will be the object instance that has been read.</returns>
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            return(TaskHelpers.RunSynchronously <object>(() =>
            {
                HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

                // If content length is 0 then return default value for this type
                if (contentHeaders != null && contentHeaders.ContentLength == 0)
                {
                    return GetDefaultValueForType(type);
                }

                // Get the character encoding for the content
                Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);

                try
                {
#if !NETFX_CORE // No DataContractJsonSerializer in portable library version
                    if (UseDataContractJsonSerializer)
                    {
                        DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);
                        using (XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(new NonClosingDelegatingStream(readStream), effectiveEncoding, _readerQuotas, null))
                        {
                            return dataContractSerializer.ReadObject(reader);
                        }
                    }
                    else
#endif
                    {
                        using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(readStream, effectiveEncoding))
                        {
                            CloseInput = false, MaxDepth = _maxDepth
                        })
                        {
                            JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                            if (formatterLogger != null)
                            {
                                // Error must always be marked as handled
                                // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
                                jsonSerializer.Error += (sender, e) =>
                                {
                                    Exception exception = e.ErrorContext.Error;
                                    formatterLogger.LogError(e.ErrorContext.Path, exception);
                                    e.ErrorContext.Handled = true;
                                };
                            }
                            return jsonSerializer.Deserialize(jsonTextReader, type);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }
                    formatterLogger.LogError(String.Empty, e);
                    return GetDefaultValueForType(type);
                }
            }));
        }
示例#15
0
        public static AppFunc Middleware(AppFunc app)
        {
            return(env =>
            {
                Action <Exception, Action <byte[], int, int> > showErrorMessage =
                    (ex, write) =>
                    ErrorPage(env, ex, text =>
                {
                    var data = Encoding.ASCII.GetBytes(text);
                    write(data, 0, data.Length);
                });

                var response = new Response(env);
                Func <Exception, Task> showErrorPage = ex =>
                {
                    response.Status = "500 Internal Server Error";
                    response.ContentType = "text/html";
                    showErrorMessage(ex, response.Write);
                    return TaskHelpers.Completed();
                };

                // Don't try to modify the headers after the first write has occurred.
                TriggerStream triggerStream = new TriggerStream(response.Body);
                response.Body = triggerStream;

                bool bodyHasStarted = false;
                triggerStream.OnFirstWrite = () =>
                {
                    bodyHasStarted = true;
                };

                try
                {
                    return app(env)
                    .Catch(errorInfo =>
                    {
                        if (!bodyHasStarted)
                        {
                            showErrorPage(errorInfo.Exception).Wait();
                        }
                        else
                        {
                            showErrorMessage(errorInfo.Exception, triggerStream.Write);
                        }
                        return errorInfo.Handled();
                    });
                }
                catch (Exception exception)
                {
                    if (!bodyHasStarted)
                    {
                        return showErrorPage(exception);
                    }
                    else
                    {
                        showErrorMessage(exception, triggerStream.Write);
                        return TaskHelpers.Completed();
                    }
                }
            });
        }
示例#16
0
 public virtual Task WriteMessageAsync(Message message, Stream stream)
 {
     WriteMessage(message, stream);
     return(TaskHelpers.CompletedTask());
 }
示例#17
0
        private async Task RunMinerWatchDogLoop(TaskCompletionSource <object> tsc, CancellationToken stop, string miningLocation, string username)
        {
            // if we fail 3 times in a row under certain conditions mark on of them
            const int maxRestartCount         = 3;
            int       restartCount            = 0;
            const int minRestartTimeInSeconds = 15;

            try
            {
                var firstStart = true;
                using (_endMiner = new CancellationTokenSource())
                    using (var linkedEndMiner = CancellationTokenSource.CreateLinkedTokenSource(stop, _endMiner.Token))
                    {
                        Logger.Info(MinerTag(), $"Starting miner watchdog task");
                        while (!linkedEndMiner.IsCancellationRequested && (restartCount < maxRestartCount))
                        {
                            var startTime = DateTime.UtcNow;
                            try
                            {
                                if (!firstStart)
                                {
                                    Logger.Info(MinerTag(), $"Restart Mining in {MiningSettings.Instance.MinerRestartDelayMS}ms");
                                }
                                await TaskHelpers.TryDelay(MiningSettings.Instance.MinerRestartDelayMS, linkedEndMiner.Token);

                                var result = await StartAsync(linkedEndMiner.Token, miningLocation, username);

                                if (firstStart)
                                {
                                    firstStart = false;
                                    tsc.SetResult(result);
                                }
                                if (result is bool ok && ok)
                                {
                                    var runningMinerTask = _miner.MinerProcessTask;
                                    _ = MinerStatsLoop(runningMinerTask, linkedEndMiner.Token);
                                    await runningMinerTask;
                                    // TODO log something here
                                    Logger.Info(MinerTag(), $"Running Miner Task Completed");
                                }
                                else
                                {
                                    // TODO check if the miner file is missing or locked and blacklist the algorithm for a certain period of time
                                    Logger.Error(MinerTag(), $"StartAsync result: {result}");
                                }
                            }
                            catch (TaskCanceledException e)
                            {
                                Logger.Debug(MinerTag(), $"RunMinerWatchDogLoop TaskCanceledException: {e.Message}");
                                return;
                            }
                            catch (Exception e)
                            {
                                Logger.Error(MinerTag(), $"RunMinerWatchDogLoop Exception: {e.Message}");
                            }
                            finally
                            {
                                var endTime        = DateTime.UtcNow;
                                var elapsedSeconds = (endTime - startTime).TotalSeconds - (MiningSettings.Instance.MinerRestartDelayMS);
                                if (elapsedSeconds < minRestartTimeInSeconds)
                                {
                                    restartCount++;
                                }
                                else
                                {
                                    restartCount = 0;
                                }
                                if (restartCount >= maxRestartCount)
                                {
                                    var    firstAlgo = _algos.FirstOrDefault();
                                    Random randWait  = new Random();
                                    firstAlgo.IgnoreUntil = DateTime.UtcNow.AddMinutes(randWait.Next(20, 30));
                                    await MiningManager.MinerRestartLoopNotify();
                                }
                            }
                        }
示例#18
0
 public SharedAsyncConditionInverseValidator()
 {
     UnlessAsync(x => TaskHelpers.FromResult(x.Id == 0), () => { RuleFor(x => x.Forename).NotNull(); });
 }
 public async Task Cancellable()
 {
     var e   = new AutoResetEventAsync(false);
     var src = new CancellationTokenSource();
     await TaskHelpers.AssertNotTriggered(e.WaitAsync(src.Token));
 }
示例#20
0
        public void Executes_customasync_rule_when_async_condition_true()
        {
            var validator = new TestValidator();

            validator.WhenAsync(x => TaskHelpers.FromResult(true), () => validator.CustomAsync(x => TaskHelpers.FromResult(new ValidationFailure("foo", "bar"))));

            var result = validator.ValidateAsync(new Person()).Result;

            result.IsValid.ShouldBeFalse();
        }
 public async Task Uncancellable()
 {
     var e = new AutoResetEventAsync(false);
     await TaskHelpers.AssertNotTriggered(e.WaitAsync(CancellationToken.None));
 }
示例#22
0
        private async Task <Message> RequestAsyncInternal(Message message, TimeSpan timeout)
        {
            await TaskHelpers.EnsureDefaultTaskScheduler();

            return(await RequestAsync(message, timeout));
        }
        public void ExecuteAsync_Invokes_Inner_And_Traces()
        {
            // Arrange
            HttpResponseMessage  response       = new HttpResponseMessage();
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(TaskHelpers.FromResult <HttpResponseMessage>(response));

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            HttpResponseMessage actualResponse = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Result;

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(response, actualResponse);
        }
        public void Async_condition_should_work_with_child_collection()
        {
            var validator = new TestValidator()
            {
                v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).WhenAsync(x => TaskHelpers.FromResult(x.Orders.Count == 4 /*there are only 3*/))
            };

            var result = validator.ValidateAsync(person).Result;

            result.IsValid.ShouldBeTrue();
        }
示例#25
0
 protected internal override Task OnOpenAsync(TimeSpan timeout)
 {
     this.OnOpen(timeout);
     return(TaskHelpers.CompletedTask());
 }
 private Func <string, CancellationToken, Task <bool> > BeOneOfTheChildrensEmailAddress(Person person)
 {
     return((productName, cancel) => TaskHelpers.FromResult(person.Children.Any(child => child.Email == productName)));
 }
示例#27
0
        public void ExecuteAuthorizationFilterAsync_IfContinuationSucceeded_ReturnsSuccessTask()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();
            Mock <AuthorizationFilterAttribute> filterMock = new Mock <AuthorizationFilterAttribute>();
            var filter = (IAuthorizationFilter)filterMock.Object;
            HttpResponseMessage response = new HttpResponseMessage();

            // Act
            var result = filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromResult(response));

            // Assert
            result.WaitUntilCompleted();
            Assert.Same(response, result.Result);
        }
示例#28
0
        /// <summary>
        /// Performs asynchronous validation using a validation context and returns a collection of Validation Failures.
        /// </summary>
        /// <param name="context">Validation Context</param>
        /// <param name="cancellation"></param>
        /// <returns>A collection of validation failures</returns>
        public Task <IEnumerable <ValidationFailure> > ValidateAsync(ValidationContext context, CancellationToken cancellation)
        {
            try {
                var displayName = GetDisplayName();

                if (PropertyName == null && displayName == null)
                {
                    //No name has been specified. Assume this is a model-level rule, so we should use empty string instead.
                    displayName = string.Empty;
                }

                // Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
                var propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName);

                // Ensure that this rule is allowed to run.
                // The validatselector has the opportunity to veto this before any of the validators execute.
                if (!context.Selector.CanExecute(this, propertyName, context))
                {
                    return(TaskHelpers.FromResult(Enumerable.Empty <ValidationFailure>()));
                }

                var cascade  = cascadeModeThunk();
                var failures = new List <ValidationFailure>();

                var fastExit = false;

                // Firstly, invoke all syncronous validators and collect their results.
                foreach (var validator in validators.Where(v => !v.IsAsync))
                {
                    if (cancellation.IsCancellationRequested)
                    {
                        return(TaskHelpers.Canceled <IEnumerable <ValidationFailure> >());
                    }

                    var results = InvokePropertyValidator(context, validator, propertyName);

                    failures.AddRange(results);

                    // If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
                    // then don't continue to the next rule
                    if (fastExit = (cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0))
                    {
                        break;
                    }
                }

                //if StopOnFirstFailure triggered then we exit
                if (fastExit && failures.Count > 0)
                {
                    // Callback if there has been at least one property validator failed.
                    OnFailure(context.InstanceToValidate);

                    return(TaskHelpers.FromResult(failures.AsEnumerable()));
                }

                var asyncValidators = validators.Where(v => v.IsAsync).ToList();

                // if there's no async validators then we exit
                if (asyncValidators.Count == 0)
                {
                    if (failures.Count > 0)
                    {
                        // Callback if there has been at least one property validator failed.
                        OnFailure(context.InstanceToValidate);
                    }
                    else
                    {
                        RunDependentRulesAsync(failures, context, cancellation);
                    }

                    return(TaskHelpers.FromResult(failures.AsEnumerable()));
                }

                //Then call asyncronous validators in non-blocking way
                var validations =
                    asyncValidators
//						.Select(v => v.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation)
                    .Select(v => InvokePropertyValidatorAsync(context, v, propertyName, cancellation)
                            //this is thread safe because tasks are launched sequencially
                            .Then(fs => failures.AddRange(fs), runSynchronously: true)
                            );

                return
                    (TaskHelpers.Iterate(
                         validations,
                         breakCondition: _ => cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0,
                         cancellationToken: cancellation
                         ).Then(() => {
                    if (failures.Count > 0)
                    {
                        OnFailure(context.InstanceToValidate);
                    }
                    else
                    {
                        RunDependentRulesAsync(failures, context, cancellation);
                    }

                    return failures.AsEnumerable();
                },
                                runSynchronously: true
                                ));
            }
            catch (Exception ex) {
                return(TaskHelpers.FromError <IEnumerable <ValidationFailure> >(ex));
            }
        }
 Task IView.RenderAsync(ViewContext viewContext, TextWriter writer)
 {
     ((IView)this).Render(viewContext, writer);
     return(TaskHelpers.Completed());
 }
示例#30
0
        Task NewServerCallback(IDictionary <string, object> env)
        {
            var path = (string)env[OwinConstants.RequestPath];

            Tracing.Info(path);

            if (!content.IsAvailable(path))
            {
                var path404 = "/404.html";
                var use404  = content.IsAvailable(path404);

                var response = new Response(env)
                {
                    ContentType = use404 ? path404.MimeType() : path.MimeType()
                };
                using (var writer = new StreamWriter(response.OutputStream))
                {
                    if (use404)
                    {
                        writer.Write(content.GetContent(path404));
                    }
                    else
                    {
                        writer.Write("Page not found: " + path);
                    }
                }
                return(TaskHelpers.Completed());
            }

            if (path.MimeType().IsBinaryMime())
            {
                var fileContents = content.GetBinaryContent(path);
                var response     = new Response(env)
                {
                    ContentType = path.MimeType()
                };
                response.Headers["Content-Range"]  = new[] { string.Format("bytes 0-{0}", (fileContents.Length - 1)) };
                response.Headers["Content-Length"] = new[] { fileContents.Length.ToString(CultureInfo.InvariantCulture) };
                response.Write(new ArraySegment <byte>(fileContents));
            }
            else if (content.IsDirectory(path) && !path.EndsWith("/"))
            {
                //if path is a directory without trailing slash, redirects to the same url with a trailing slash
                var response = new Response(env)
                {
                    Status = "301 Moved Permanently"
                };
                response.Headers["Location"] = new[] { String.Format("http://localhost:{0}{1}/", Port, path) };
            }
            else
            {
                var response = new Response(env)
                {
                    ContentType = path.MimeType()
                };
                using (var writer = new StreamWriter(response.OutputStream))
                {
                    writer.Write(content.GetContent(path));
                }
            }

            return(TaskHelpers.Completed());
        }