예제 #1
0
        public override byte[] StopFiltering(int itemId, bool deleteData)
        {
            if (HasErrored)
            {
                return(null);
            }

            if ((CaptureStream) != null)
            {
                CaptureStream.Close();

                if (File.Exists(CachedOutputFileName))
                {
                    FileSystemUtils.DeleteFileWithWait(CachedOutputFileName, 100, 200);
                }

                File.Move(CachedOutputTempFileName, CachedOutputFileName);

                StreamWriter oWrite = File.CreateText(CachedOutputAttribFileName);
                oWrite.WriteLine(_cacheExpiration.ToString());
                oWrite.Close();
            }
            if (deleteData)
            {
                FileSystemUtils.DeleteFileWithWait(CachedOutputFileName, 100, 200);
                FileSystemUtils.DeleteFileWithWait(CachedOutputAttribFileName, 100, 200);
            }

            return(null);
        }
예제 #2
0
        static void Main(string[] args)
        {
            bool capture = true;
            //bool mock = true;
            bool       mock = false;
            SerialPort port = null;
            Stream     ecuStream;

            if (mock)
            {
                ecuStream = MockEcuStream.GetInstance();
            }
            else
            {
                port = new SerialPort("COM3", 4800, Parity.None, 8, StopBits.One);
                port.Open();
                port.ReadTimeout = 1000;
                port.DiscardInBuffer();
                port.DiscardOutBuffer();
                ecuStream = port.BaseStream;
            }

            if (capture)
            {
                Stream captureStream = File.Open(captureFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                captureStream.SetLength(0);
                ecuStream = new CaptureStream(ecuStream, new StreamWriter(captureStream));
            }

            ManualLoggingTest(ecuStream, port);
            //ReadMultipleTest(ecuStream, port);
        }
예제 #3
0
 void context_PreSendRequestContent(object sender, EventArgs e)
 {
     if (_LogAlwaysResponse || _IsMatch)
     {
         CaptureStream filter = _context.Response.Filter as CaptureStream;
         if (filter != null)
         {
             string responseText = filter.StreamContent;
             //LOG responseText
         }
     }
 }
        public virtual byte[] StopFiltering(int itemId, bool deleteData)
        {
            if (HasErrored)
            {
                return(null);
            }

            if ((((CaptureStream) != null)))
            {
                CaptureStream.Position = 0;
                var    reader = new StreamReader(CaptureStream, Encoding.Default);
                string output = reader.ReadToEnd();
                AddItemToCache(itemId, output);
                CaptureStream.Close();
                CaptureStream = null;
            }
            if (deleteData)
            {
                RemoveItemFromCache(itemId);
            }
            return(null);
        }
예제 #5
0
        public void CaptureStreamRead()
        {
            Stream     memoryStream = new MemoryStream();
            TextWriter log          = new StreamWriter(memoryStream);
            Stream     dataStream   = new MemoryStream();

            dataStream.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
            dataStream.Position = 0;
            CaptureStream target = new CaptureStream(dataStream, log);

            byte[] buffer = new byte[5];
            int    offset = 0;
            int    count  = buffer.Length;

            target.Read(buffer, offset, count);

            memoryStream.Position = 0;
            TextReader reader   = new StreamReader(memoryStream);
            string     actual   = reader.ReadToEnd();
            string     expected = "Read  0x01, 0x02, 0x03, 0x04, 0x05, " + Environment.NewLine;

            Assert.AreEqual(expected, actual);
        }
예제 #6
0
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var captureHandlerIsAttached = false;

            try {
                // This filter is not reentrant (multiple executions within the same request are
                // not supported) so child actions are ignored completely.
                if (filterContext.IsChildAction || !_isCachingRequest)
                {
                    return;
                }

                Logger.Debug("Item '{0}' was rendered.", _cacheKey);


                if (!ResponseIsCacheable(filterContext))
                {
                    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                    filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));
                    return;
                }

                // Determine duration and grace time.
                var cacheDuration  = _cacheRouteConfig != null && _cacheRouteConfig.Duration.HasValue ? _cacheRouteConfig.Duration.Value : CacheSettings.DefaultCacheDuration;
                var cacheGraceTime = _cacheRouteConfig != null && _cacheRouteConfig.GraceTime.HasValue ? _cacheRouteConfig.GraceTime.Value : CacheSettings.DefaultCacheGraceTime;

                // Include each content item ID as tags for the cache entry.
                var contentItemIds = _displayedContentItemHandler.GetDisplayed().Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray();

                // Capture the response output using a custom filter stream.
                var response      = filterContext.HttpContext.Response;
                var captureStream = new CaptureStream(response.Filter);
                response.Filter = captureStream;

                // Add ETag header for the newly created item
                var etag = Guid.NewGuid().ToString("n");
                if (HttpRuntime.UsingIntegratedPipeline)
                {
                    if (response.Headers.Get("ETag") == null)
                    {
                        response.Headers["ETag"] = etag;
                    }
                }

                captureStream.Captured += (output) => {
                    try {
                        // Since this is a callback any call to injected dependencies can result in an Autofac exception: "Instances
                        // cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."
                        // To prevent access to the original lifetime scope a new work context scope should be created here and dependencies
                        // should be resolved from it.

                        using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                            var cacheItem = new CacheItem()
                            {
                                CachedOnUtc       = _now,
                                Duration          = cacheDuration,
                                GraceTime         = cacheGraceTime,
                                Output            = output,
                                ContentType       = response.ContentType,
                                QueryString       = filterContext.HttpContext.Request.Url.Query,
                                CacheKey          = _cacheKey,
                                InvariantCacheKey = _invariantCacheKey,
                                Url        = filterContext.HttpContext.Request.Url.AbsolutePath,
                                Tenant     = scope.Resolve <ShellSettings>().Name,
                                StatusCode = response.StatusCode,
                                Tags       = new[] { _invariantCacheKey }.Union(contentItemIds).ToArray(),
                                ETag       = etag
                            };

                            // Write the rendered item to the cache.
                            var cacheStorageProvider = scope.Resolve <IOutputCacheStorageProvider>();
                            cacheStorageProvider.Set(_cacheKey, cacheItem);

                            Logger.Debug("Item '{0}' was written to cache.", _cacheKey);

                            // Also add the item tags to the tag cache.
                            var tagCache = scope.Resolve <ITagCache>();
                            foreach (var tag in cacheItem.Tags)
                            {
                                tagCache.Tag(tag, _cacheKey);
                            }
                        }
                    }
                    finally {
                        // Always release the cache key lock when the request ends.
                        ReleaseCacheKeyLock();
                    }
                };

                captureHandlerIsAttached = true;
            }
            finally {
                // If the response filter stream capture handler was attached then we'll trust
                // it to release the cache key lock at some point in the future when the stream
                // is flushed; otherwise we'll make sure we'll release it here.
                if (!captureHandlerIsAttached)
                {
                    ReleaseCacheKeyLock();
                }
            }
        }
예제 #7
0
 protected virtual void OnCaptureStream(MemoryStream ms)
 {
     CaptureStream?.Invoke(ms);
 }
예제 #8
0
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var captureHandlerIsAttached = false;

            try {
                // This filter is not reentrant (multiple executions within the same request are
                // not supported) so child actions are ignored completely.
                if (filterContext.IsChildAction || !_isCachingRequest)
                {
                    return;
                }

                Logger.Debug("Item '{0}' was rendered.", _cacheKey);

                // Obtain individual route configuration, if any.
                CacheRouteConfig configuration = null;
                var configurations             = _cacheService.GetRouteConfigs();
                if (configurations.Any())
                {
                    var route = filterContext.Controller.ControllerContext.RouteData.Route;
                    var key   = _cacheService.GetRouteDescriptorKey(filterContext.HttpContext, route);
                    configuration = configurations.FirstOrDefault(c => c.RouteKey == key);
                }

                if (!ResponseIsCacheable(filterContext, configuration))
                {
                    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                    filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));
                    return;
                }

                // Determine duration and grace time.
                var cacheDuration  = configuration != null && configuration.Duration.HasValue ? configuration.Duration.Value : CacheSettings.DefaultCacheDuration;
                var cacheGraceTime = configuration != null && configuration.GraceTime.HasValue ? configuration.GraceTime.Value : CacheSettings.DefaultCacheGraceTime;

                // Include each content item ID as tags for the cache entry.
                var contentItemIds = _displayedContentItemHandler.GetDisplayed().Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray();

                // Capture the response output using a custom filter stream.
                var response      = filterContext.HttpContext.Response;
                var captureStream = new CaptureStream(response.Filter);
                response.Filter         = captureStream;
                captureStream.Captured += (output) => {
                    try {
                        var cacheItem = new CacheItem()
                        {
                            CachedOnUtc       = _now,
                            Duration          = cacheDuration,
                            GraceTime         = cacheGraceTime,
                            Output            = output,
                            ContentType       = response.ContentType,
                            QueryString       = filterContext.HttpContext.Request.Url.Query,
                            CacheKey          = _cacheKey,
                            InvariantCacheKey = _invariantCacheKey,
                            Url        = filterContext.HttpContext.Request.Url.AbsolutePath,
                            Tenant     = _shellSettings.Name,
                            StatusCode = response.StatusCode,
                            Tags       = new[] { _invariantCacheKey }.Union(contentItemIds).ToArray()
                        };

                        // Write the rendered item to the cache.
                        _cacheStorageProvider.Remove(_cacheKey);
                        _cacheStorageProvider.Set(_cacheKey, cacheItem);

                        Logger.Debug("Item '{0}' was written to cache.", _cacheKey);

                        // Also add the item tags to the tag cache.
                        foreach (var tag in cacheItem.Tags)
                        {
                            _tagCache.Tag(tag, _cacheKey);
                        }
                    }
                    finally {
                        // Always release the cache key lock when the request ends.
                        ReleaseCacheKeyLock();
                    }
                };

                captureHandlerIsAttached = true;
            }
            finally {
                // If the response filter stream capture handler was attached then we'll trust
                // it to release the cache key lock at some point in the future when the stream
                // is flushed; otherwise we'll make sure we'll release it here.
                if (!captureHandlerIsAttached)
                {
                    ReleaseCacheKeyLock();
                }
            }
        }