Exemplo n.º 1
0
        public void BuildsInCorrectOrder()
        {
            var pipeline = new Pipeline();

            pipeline.Use((env, next) => {
                OwinContext.Get(env)
                .TraceOutput.Write("Before.");
                return(next(env));
            })
            .Use((env, next) => {
                next(env)
                .Wait();
                OwinContext.Get(env)
                .TraceOutput.Write("After.");
                return(TaskHelper.Completed());
            })
            .Use(env => {
                OwinContext.Get(env)
                .TraceOutput.Write("App.");
                return(TaskHelper.Completed());
            });
            var host = new TestHostAndServer(pipeline);

            host.Process(TestRequest.Get("/"));
            host.TraceOutputValue.ShouldEqual("Before.App.After.");
        }
Exemplo n.º 2
0
        public void BuildsWithSetup()
        {
            var pipeline = new Pipeline();

            pipeline.Use((env, next) => {
                OwinContext.Get(env)
                .TraceOutput.Write("Do Before.");
                return(next(env));
            },
                         env => new OwinHostContext(env).TraceOutput.Write("Setup Before."))
            .Use((env, next) => {
                next(env)
                .Wait();
                OwinContext.Get(env)
                .TraceOutput.Write("Do After.");
                return(TaskHelper.Completed());
            },
                 env => new OwinHostContext(env).TraceOutput.Write("Setup After."))
            .Use(env => {
                OwinContext.Get(env)
                .TraceOutput.Write("Do App.");
                return(TaskHelper.Completed());
            },
                 env => new OwinHostContext(env).TraceOutput.Write("Setup App."));
            var host = new TestHostAndServer(pipeline);

            host.Process(TestRequest.Get("/"));
            host.TraceOutputValue.ShouldEqual("Setup Before.Setup After.Setup App.Do Before.Do App.Do After.");
        }
Exemplo n.º 3
0
        public Task RenewAsync(String name, TimeSpan?lockExtension = null)
        {
#if DEBUG
            Logger.Trace().Message("RenewAsync: {0}", name).Write();
#endif
            return(TaskHelper.Completed());
        }
        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                var enumerable = content.Model as IEnumerable <object>;
                if (enumerable != null)
                {
                    WriteList(outputStream, enumerable);
                }
                else
                {
                    var links = content.Links.ToList();
                    if (links.Count == 0)
                    {
                        new DataContractSerializer(content.Model.GetType()).WriteObject(outputStream, content.Model);
                    }
                    else
                    {
                        WriteWithLinks(content, outputStream, links);
                    }
                }
            }

            return(TaskHelper.Completed());
        }
Exemplo n.º 5
0
 protected virtual async Task OnLockRenewedAsync(IQueueEntry <T> entry)
 {
     await(LockRenewed?.InvokeAsync(this, new LockRenewedEventArgs <T> {
         Queue = this,
         Entry = entry
     }) ?? TaskHelper.Completed()).AnyContext();
 }
Exemplo n.º 6
0
        public override Task OnActionExecutedAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Response == null || context.Response.StatusCode != HttpStatusCode.Accepted)
            {
                return(TaskHelper.Completed());
            }

            var project = context.Request?.GetProject();

            if (project == null)
            {
                return(TaskHelper.Completed());
            }

            string headerName = ExceptionlessHeaders.ConfigurationVersion;

            if (context.Request.RequestUri.AbsolutePath.StartsWith("/api/v1"))
            {
                headerName = ExceptionlessHeaders.LegacyConfigurationVersion;
            }

            // add the current configuration version to the response headers so the client will know if it should update its config.
            context.Response.Headers.Add(headerName, project.Configuration.Version.ToString());

            return(TaskHelper.Completed());
        }
Exemplo n.º 7
0
 public void StartWorking(Action <QueueEntry <T> > handler, bool autoComplete = false)
 {
     StartWorking(entry => {
         handler(entry);
         return(TaskHelper.Completed());
     }, autoComplete);
 }
Exemplo n.º 8
0
        /// <summary>
        /// This method supports the framework directly and should not be used from your code
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public static void Impl(IOutputStream handler, IContext context)
        {
            context.Response.SetContentType(handler.ContentType);
            if (!string.IsNullOrWhiteSpace(handler.ContentDisposition))
            {
                context.Response.SetHeader("Content-Disposition", handler.ContentDisposition);
            }
            if (context.Request.HttpMethod.Equals("HEAD"))
            {
                return;
            }

            if (!handler.Output.CanSeek)
            {
                throw new InvalidOperationException("Output stream must support Seek operations.");
            }
            context.Response.WriteFunction = (stream) =>
            {
                using (var outputStream = handler.Output)
                {
                    outputStream.Position = 0;
                    outputStream.CopyTo(stream);
                }
                return(TaskHelper.Completed());
            };
        }
Exemplo n.º 9
0
        public virtual async Task CanAutoCompleteWorker()
        {
            var queue = GetQueue();

            if (queue == null)
            {
                return;
            }

            using (queue) {
                await queue.DeleteQueueAsync();

                var resetEvent = new AsyncManualResetEvent(false);
                queue.StartWorking(w => {
                    Assert.Equal("Hello", w.Value.Data);
                    resetEvent.Set();
                    return(TaskHelper.Completed());
                }, true);

                await queue.EnqueueAsync(new SimpleWorkItem {
                    Data = "Hello"
                });

                Assert.Equal(1, (await queue.GetQueueStatsAsync()).Enqueued);
                await resetEvent.WaitAsync(TimeSpan.FromSeconds(2));

                await Task.Delay(10);

                var stats = await queue.GetQueueStatsAsync();

                Assert.Equal(0, stats.Queued);
                Assert.Equal(1, stats.Completed);
                Assert.Equal(0, stats.Errors);
            }
        }
Exemplo n.º 10
0
        public void WhenAll()
        {
            var control = new ControlComponent(ControlComponent.Match.All);

            control.When(env => false, (env, next) => TaskHelper.Exception(new Exception()));
            control.When(env => true,
                         (env, next) => {
                env.SetValue("branch1", "pass");
                return(TaskHelper.Completed());
            });
            control.When(env => false, (env, next) => TaskHelper.Exception(new Exception()));
            control.When(env => true,
                         (env, next) => {
                env.SetValue("branch2", "pass");
                return(TaskHelper.Completed());
            });
            var environment       = OwinFactory.CreateEnvironment();
            var pipelineComponent = control as IPipelineComponent;

            pipelineComponent.Connect(Pipeline.ReturnDone);
            Task task = pipelineComponent.Execute(environment);

            task.Wait();
            task.IsCanceled.ShouldBeFalse();
            task.IsFaulted.ShouldBeFalse();
            task.IsCompleted.ShouldBeTrue();
            environment.GetValue <string>("branch1")
            .ShouldEqual("pass");
            environment.GetValue <string>("branch2")
            .ShouldEqual("pass");
        }
Exemplo n.º 11
0
        private Task WorkerLoop(CancellationToken token)
        {
            Log.Trace().Message("WorkerLoop Start {0}", _queueName).Write();
            while (!token.IsCancellationRequested && _workerAction != null)
            {
                Log.Trace().Message("WorkerLoop Pass {0}", _queueName).Write();
                QueueEntry <T> queueEntry = null;
                try {
                    queueEntry = Dequeue();
                } catch (TimeoutException) { }

                if (token.IsCancellationRequested || queueEntry == null)
                {
                    continue;
                }

                try {
                    _workerAction(queueEntry);
                    if (_workerAutoComplete)
                    {
                        queueEntry.Complete();
                    }
                } catch (Exception ex) {
                    Log.Error().Exception(ex).Message("Worker error: {0}", ex.Message).Write();
                    queueEntry.Abandon();
                    Interlocked.Increment(ref _workerErrorCount);
                }
            }

            Log.Trace().Message("Worker exiting: {0} Cancel Requested: {1}", _queueName, token.IsCancellationRequested).Write();

            return(TaskHelper.Completed());
        }
Exemplo n.º 12
0
        public Task ReleaseAsync(string name)
        {
#if DEBUG
            Logger.Trace().Message("ReleaseAsync: {0}", name).Write();
#endif
            return(TaskHelper.Completed());
        }
Exemplo n.º 13
0
        public override Task EventProcessingAsync(EventContext context)
        {
            if (context.Event.Type != Event.KnownTypes.NotFound)
            {
                return(TaskHelper.Completed());
            }

            context.Event.Data.Remove(Event.KnownDataKeys.EnvironmentInfo);
            context.Event.Data.Remove(Event.KnownDataKeys.TraceLog);

            var req = context.Event.GetRequestInfo();

            if (req == null)
            {
                return(TaskHelper.Completed());
            }

            if (String.IsNullOrWhiteSpace(context.Event.Source))
            {
                context.Event.Message = null;
                context.Event.Source  = req.GetFullPath(includeHttpMethod: true, includeHost: false, includeQueryString: false);
            }

            context.Event.Data.Remove(Event.KnownDataKeys.Error);
            context.Event.Data.Remove(Event.KnownDataKeys.SimpleError);

            return(TaskHelper.Completed());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Reads content from the specified input stream, which is assumed to be in x-www-form-urlencoded format.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <returns>
        /// A model constructed from the content in the input stream.
        /// </returns>
        public Task <T> Read <T>(Stream inputStream)
        {
            string text;

            using (var streamReader = new StreamReader(inputStream))
            {
                text = streamReader.ReadToEnd();
            }
            var pairs = text.Split(SplitTokens, StringSplitOptions.RemoveEmptyEntries);
            var obj   = Activator.CreateInstance <T>();
            // reflection is slow, get the property[] once.
            var properties = typeof(T).GetProperties();

            foreach (var pair in pairs)
            {
                var nameValue = pair.Split('=');
                var property  =
                    properties.FirstOrDefault(p => p.Name.Equals(nameValue[0], StringComparison.Ordinal)) ??
                    properties.FirstOrDefault(
                        p => p.Name.Equals(nameValue[0], StringComparison.OrdinalIgnoreCase));
                if (property != null)
                {
                    property.SetValue(obj,
                                      Convert.ChangeType(HttpUtility.UrlDecode(nameValue[1]),
                                                         property.PropertyType), null);
                }
            }
            return(TaskHelper.Completed(obj));
        }
Exemplo n.º 15
0
 public static void Subscribe <T>(this IMessageSubscriber subscriber, Action <T> handler, CancellationToken cancellationToken = default(CancellationToken)) where T : class
 {
     subscriber.Subscribe <T>((msg, token) => {
         handler(msg);
         return(TaskHelper.Completed());
     }, cancellationToken);
 }
Exemplo n.º 16
0
 public void Register <T>(Func <WorkItemContext> handler) where T : class
 {
     Register <T>(ctx => {
         handler();
         return(TaskHelper.Completed());
     });
 }
Exemplo n.º 17
0
        public override Task EventProcessingAsync(EventContext context)
        {
            if (!context.Event.IsError())
            {
                return(TaskHelper.Completed());
            }

            SimpleError error = context.Event.GetSimpleError();

            if (error == null)
            {
                return(TaskHelper.Completed());
            }

            if (String.IsNullOrWhiteSpace(context.Event.Message))
            {
                context.Event.Message = error.Message;
            }

            // TODO: Parse the stack trace and upgrade this to a full error.
            if (!String.IsNullOrEmpty(error.Type))
            {
                context.StackSignatureData.Add("ExceptionType", error.Type);
            }

            if (!String.IsNullOrEmpty(error.StackTrace))
            {
                context.StackSignatureData.Add("StackTrace", error.StackTrace.ToSHA1());
            }

            return(TaskHelper.Completed());
        }
Exemplo n.º 18
0
        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                object output;

                var enumerable = content.Model as IEnumerable <object>;
                if (enumerable != null)
                {
                    output = ProcessList(enumerable.ToList());
                }
                else
                {
                    output = ProcessContent(content);
                }
                byte[] buffer;
                using (var writer = new StringWriter())
                {
                    var dataWriterSettings = new DataWriterSettings(new MonoCompatResolverStrategy(),
                                                                    new Iso8601DateFilter());

                    new JsonWriter(dataWriterSettings).Write(output, writer);
                    buffer = Encoding.Default.GetBytes(writer.ToString());
                }
                return(outputStream.WriteAsync(buffer, 0, buffer.Length));
            }

            return(TaskHelper.Completed());
        }
        protected override Task <T> FromWireFormat <T>(JToken wireFormat)
        {
            JsonReader reader = new JTokenReader(wireFormat);
            var        result = Serializer.Deserialize <T>(reader);

            return(TaskHelper.Completed(result));
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (writeStream == null)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(TaskHelper.Canceled());
            }

            try
            {
                this.WriteToStream(type, value, writeStream, content);
                return(TaskHelper.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelper.FromError(ex));
            }
        }
        protected override Task <T> FromWireFormat <T>(XElement wireFormat)
        {
            var       dataContractSerializer = new DataContractSerializer(typeof(T));
            XmlReader xmlReader = wireFormat.CreateReader();
            object    obj       = dataContractSerializer.ReadObject(xmlReader);

            return(TaskHelper.Completed((T)obj));
        }
Exemplo n.º 22
0
        public override Task EventProcessingAsync(EventContext context)
        {
            var request = context.Event.GetRequestInfo();

            if (request == null)
            {
                return(TaskHelper.Completed());
            }

            var exclusions = context.Project.Configuration.Settings.ContainsKey(SettingsDictionary.KnownKeys.DataExclusions)
                    ? DefaultExclusions.Union(context.Project.Configuration.Settings.GetStringCollection(SettingsDictionary.KnownKeys.DataExclusions)).ToList()
                    : DefaultExclusions;

            if (!String.IsNullOrEmpty(request.UserAgent))
            {
                try {
                    var info = Parser.GetDefault().Parse(request.UserAgent);

                    if (!String.Equals(info.UserAgent.Family, "Other"))
                    {
                        request.Data[RequestInfo.KnownDataKeys.Browser] = info.UserAgent.Family;
                        if (!String.IsNullOrEmpty(info.UserAgent.Major))
                        {
                            request.Data[RequestInfo.KnownDataKeys.BrowserVersion]      = String.Join(".", new[] { info.UserAgent.Major, info.UserAgent.Minor, info.UserAgent.Patch }.Where(v => !String.IsNullOrEmpty(v)));
                            request.Data[RequestInfo.KnownDataKeys.BrowserMajorVersion] = info.UserAgent.Major;
                        }
                    }

                    if (!String.Equals(info.Device.Family, "Other"))
                    {
                        request.Data[RequestInfo.KnownDataKeys.Device] = info.Device.Family;
                    }


                    if (!String.Equals(info.OS.Family, "Other"))
                    {
                        request.Data[RequestInfo.KnownDataKeys.OS] = info.OS.Family;
                        if (!String.IsNullOrEmpty(info.OS.Major))
                        {
                            request.Data[RequestInfo.KnownDataKeys.OSVersion]      = String.Join(".", new[] { info.OS.Major, info.OS.Minor, info.OS.Patch }.Where(v => !String.IsNullOrEmpty(v)));
                            request.Data[RequestInfo.KnownDataKeys.OSMajorVersion] = info.OS.Major;
                        }
                    }

                    var botPatterns = context.Project.Configuration.Settings.ContainsKey(SettingsDictionary.KnownKeys.UserAgentBotPatterns)
                      ? context.Project.Configuration.Settings.GetStringCollection(SettingsDictionary.KnownKeys.UserAgentBotPatterns).ToList()
                      : new List <string>();

                    request.Data[RequestInfo.KnownDataKeys.IsBot] = info.Device.IsSpider || request.UserAgent.AnyWildcardMatches(botPatterns);
                } catch (Exception ex) {
                    Logger.Warn().Project(context.Event.ProjectId).Message("Unable to parse user agent {0}. Exception: {1}", request.UserAgent, ex.Message).Write();
                }
            }

            context.Event.AddRequestInfo(request.ApplyDataExclusions(exclusions, MAX_VALUE_LENGTH));

            return(TaskHelper.Completed());
        }
Exemplo n.º 23
0
 private static Func <string, long, long?, CancellationToken, Task> CreateSendFileFunc(HttpResponse response)
 {
     return((path, offset, byteCount, cancel) =>
     {
         var length = byteCount.HasValue ? byteCount.Value : -1;
         response.TransmitFile(path, offset, length);
         return TaskHelper.Completed();
     });
 }
Exemplo n.º 24
0
        protected virtual Task AfterResultMapAsync <TDestination>(ICollection <TDestination> models)
        {
            foreach (var model in models.OfType <IData>())
            {
                model.Data.RemoveSensitiveData();
            }

            return(TaskHelper.Completed());
        }
Exemplo n.º 25
0
        public override Task EventProcessedAsync(EventContext context)
        {
            if (String.IsNullOrEmpty(context.Event.ReferenceId))
            {
                return(TaskHelper.Completed());
            }

            return(_cacheClient.SetAsync(GetCacheKey(context), true, TimeSpan.FromDays(1)));
        }
Exemplo n.º 26
0
        private Task OnPlanOverageAsync(PlanOverage planOverage, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (planOverage != null)
            {
                return(Context.Groups.TypedSend(planOverage.OrganizationId, planOverage));
            }

            return(TaskHelper.Completed());
        }
Exemplo n.º 27
0
        private Task OnPlanChangedAsync(PlanChanged planChanged, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (planChanged != null)
            {
                return(Context.Groups.TypedSend(planChanged.OrganizationId, planChanged));
            }

            return(TaskHelper.Completed());
        }
Exemplo n.º 28
0
        public Task TimerAsync(string statName, long milliseconds)
        {
            _timings.AddOrUpdate(statName, key => new TimingStats(milliseconds), (key, stats) => {
                stats.Set(milliseconds);
                return(stats);
            });

            return(TaskHelper.Completed());
        }
Exemplo n.º 29
0
        public Task GaugeAsync(string statName, double value)
        {
            _gauges.AddOrUpdate(statName, key => new GaugeStats(value), (key, stats) => {
                stats.Set(value);
                return(stats);
            });

            return(TaskHelper.Completed());
        }
Exemplo n.º 30
0
        public override Task HandleItemAsync(WorkItemContext context)
        {
            if (_handler == null)
            {
                return(TaskHelper.Completed());
            }

            return(_handler(context));
        }