Пример #1
0
        public async Task <CacheResponse> IsCacheOutOfDate(DateTime cacheLastUpdatedTimeUtc, int appId, CancellationToken token)
        {
            var endpoint = configurationProvider.GetConnectionStringById(connectionStringKey);

            endpoint += $"?appId={appId}";

            var gatewayResponse = await webGateway.GetResponseFromEndpoint <ResponseDao>(endpoint, token);

            if (gatewayResponse.ResultCode != WebRequestResponseResultCode.Succeeded)
            {
                return(CacheResponse.CacheCheckFailed(gatewayResponse.ResultMessage));
            }

            var response = gatewayResponse.Value;

            if (!response.IsCached)
            {
                return(CacheResponse.OutOfDate());
            }

            if (response.CachedDateTimeUtc < cacheLastUpdatedTimeUtc)
            {
                return(CacheResponse.NotOutOfDate());
            }

            return(CacheResponse.OutOfDate());
        }
        public async Task <HttpResponseMessage> Get(int numberOfRecords)
        {
            var response = new CacheResponse {
                CacheInfo = new System.Collections.Generic.List <Cache>()
            };

            for (int i = 0; i < numberOfRecords; i++)
            {
                var res = await beanCacheController.Get(i.ToString());

                Cache cache = new Cache
                {
                    key   = i.ToString(),
                    value = res.Value
                };

                response.CacheInfo.Add(cache);
            }

            var jsonContent = JsonConvert.SerializeObject(response);

            return(new HttpResponseMessage()
            {
                Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
            });
        }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         if (response.StatusCode != HttpStatusCode.OK)
         {
             MessageBox.Show("aaa");
         }
         using (CryptoStream stream = new CryptoStream(response.Response, this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
         {
             MemoryStream stream2 = new MemoryStream();
             long num = 0L;
             int count = 0x1000;
             byte[] buffer = new byte[count];
             while (stream.CanRead)
             {
                 int num2 = stream.Read(buffer, 0, count);
                 num += num2;
                 if (num2 == 0)
                 {
                     break;
                 }
                 stream2.Write(buffer, 0, num2);
             }
             stream2.Position = 0L;
             //response.Response = stream2;
             response = new CacheResponse(stream2);
         }
     }
     return null;
 }
        public bool EndPersist(IAsyncResult asyncResult)
        {
            asyncResult.AsyncWaitHandle.WaitOne();

            CacheAsyncResult cacheAsyncResult = asyncResult as CacheAsyncResult;

            if (cacheAsyncResult != null && cacheAsyncResult.Result != null)
            {
                if (!this.cache.ContainsKey(cacheAsyncResult.FragmentUrl))
                {
                    Stream        memoryStream  = new MemoryStream();
                    CacheResponse cacheResponse = cacheAsyncResult.Result as CacheResponse;

                    if (cacheResponse != null && cacheResponse.StatusCode == HttpStatusCode.OK)
                    {
                        cacheResponse.WriteTo(memoryStream);
                        memoryStream.Position = 0;

                        CacheItem cacheItem = new CacheItem
                        {
                            CachedValue = memoryStream,
                            Date        = DateTime.Now
                        };

                        this.cache.Add(cacheAsyncResult.FragmentUrl, cacheItem);
                        this.OnCacheUpdated(cacheAsyncResult.FragmentUrl);

                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #5
0
 public void on_proxy_only()
 {
     CacheResponse.GetResponseDirective(new CacheProxyAttribute {
         MustRevalidateWhenStale = true
     })
     .CacheDirectives.ShouldContain("must-revalidate");
 }
        private void OnManifestResponse(IAsyncResult ar)
        {
            var wreq = ar.AsyncState as WebRequest;

            if (wreq != null)
            {
                var wresp = (HttpWebResponse)wreq.EndGetResponse(ar);

                if (wresp.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(wresp.StatusDescription);
                }

                Stream respStream = wresp.GetResponseStream();

                if (!Directory.Exists(RootFolderPath))
                {
                    Directory.CreateDirectory(RootFolderPath);
                }
                //open a filestream
                using (var fs = new FileStream(ManifestFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    //create a CacheResponse
                    var cacheResp = new CacheResponse(respStream.Length, wresp.ContentType, null,
                                                      respStream, wresp.StatusCode, wresp.StatusDescription,
                                                      DateTime.UtcNow);
                    //serialize to the file
                    cacheResp.WriteTo(fs);
                    fs.Flush();
                    fs.Close();
                }
            }
        }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         try
         {
             using (CryptoStream stream = new CryptoStream(response.Response, this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
             {
                 MemoryStream stream2 = new MemoryStream();
                 int count = 0x1000;
                 byte[] buffer = new byte[count];
                 while (stream.CanRead)
                 {
                     int num = stream.Read(buffer, 0, count);
                     if (num == 0)
                     {
                         break;
                     }
                     stream2.Write(buffer, 0, num);
                 }
                 stream2.Position = 0L;
                 response.Response = stream2;
             }
         }
         catch
         {
             response.Response = null;
         }
     }
     return null;
 }
Пример #8
0
            public void Must_throw_exception()
            {
                var cacheResponse = new CacheResponse(new Response().OK());

                Assert.That(() => new CacheItem(cacheResponse, new DateTime(2012, 01, 01, 0, 0, 0, DateTimeKind.Local), new DateTime(2012, 01, 01, 0, 0, 0, DateTimeKind.Utc)), Throws.InstanceOf <ArgumentException>());
                Assert.That(() => new CacheItem(cacheResponse, new DateTime(2012, 01, 01, 0, 0, 0, DateTimeKind.Utc), new DateTime(2012, 01, 01, 0, 0, 0, DateTimeKind.Local)), Throws.InstanceOf <ArgumentException>());
            }
Пример #9
0
        public async Task <CacheResponse> IsCacheOutOfDate(DateTime cacheLastUpdatedTimeUtc, CancellationToken token)
        {
            var endpoint = configurationProvider.GetConnectionStringById(connectionStringKey);

            var gatewayResponse = await webGateway.GetResponseFromEndpoint <ResponseDao>(endpoint, token);

            if (!gatewayResponse.Succeeded)
            {
                return(CacheResponse.OutOfDate());
            }

            var response = gatewayResponse.Value;

            if (!response.IsCached)
            {
                return(CacheResponse.OutOfDate());
            }

            if (response.CachedDateTimeUtc < cacheLastUpdatedTimeUtc)
            {
                return(CacheResponse.NotOutOfDate());
            }

            return(CacheResponse.OutOfDate());
        }
Пример #10
0
 public void SetUp()
 {
     _cacheResponse       = new CacheResponse(new Response().OK());
     _cachedUtcTimestamp  = new DateTime(2012, 01, 01, 0, 0, 0, DateTimeKind.Utc);
     _expiresUtcTimestamp = new DateTime(2013, 01, 01, 0, 0, 0, DateTimeKind.Utc);
     _cacheItem           = new CacheItem(_cacheResponse, _cachedUtcTimestamp, _expiresUtcTimestamp);
 }
Пример #11
0
        public override void ProcessMubbleRequest(System.Web.HttpContext context)
        {
            bool force = context.Request["Recache"] != null && context.Request["Recache"].Equals("true", StringComparison.CurrentCultureIgnoreCase);

            string key = this.BuildCacheKey(context);
            CacheResponse response = context.Cache[key] as CacheResponse;

            context.Response.Cache.SetValidUntilExpires(true);
            context.Response.Cache.SetCacheability(System.Web.HttpCacheability.ServerAndNoCache);

            if (response == null || force || !this.AllowCaching)
            {
                response = new CacheResponse();
                response.Output = this.ProcessUncachedRequest(context);
                response.LastModified = DateTime.Now;

                DateTime absExp = (this.UseSlidingExpiration) ? Cache.NoAbsoluteExpiration : DateTime.Now.AddMinutes(this.CacheTime);
                TimeSpan slidingExp = (this.UseSlidingExpiration) ? TimeSpan.FromMinutes(this.CacheTime) : Cache.NoSlidingExpiration;

                CacheDependency dep = this.fileDependencies.Count > 0 || this.cacheKeyDependencies.Count > 0
                    ?
                    new CacheDependency(this.fileDependencies.ToArray(), this.cacheKeyDependencies.ToArray()) :
                    null;

                if (this.CacheTime > 0)
                {
                    context.Cache.Insert(key, response, dep, absExp, slidingExp);
                }
            }

            context.Response.Cache.SetLastModified(response.LastModified);
            context.Response.Write(response.Output);
        }
Пример #12
0
        public ActionResult GetMovies(string tags)
        {
            tags = tags.Trim();
            CacheResponse <List <MovieModel> > movies = _moviesRepository.GetMovies(tags);

            ViewBag.MoviesSource = movies.IsLoadedFromCache ? "Loaded from cache" : "Loaded from Service";
            return(PartialView("_Movies", movies.Obj));
        }
Пример #13
0
        // To see the raw data, have a look at
        // http://api.flickr.com/services/feeds/photos_public.gne?tags=cats


        public CacheResponse<List<FlickrImage>> GetImagesByTagsWIthCacheResponse(string tags)
        {
            var images = GetImagesByTags(tags);
            var response = new CacheResponse<List<FlickrImage>>
            {
                Obj = images,
                IsLoadedFromCache = false
            };
            return response;
        }
        public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
        {
            CacheResponse response = null;

            CacheAsyncResult cacheAsyncResult = new CacheAsyncResult {
                FragmentUrl = request.CanonicalUri.ToString()
            };

            cacheAsyncResult.Complete(response, true);
            return(cacheAsyncResult);
        }
Пример #15
0
 public void on_proxy_not_on_client()
 {
     CacheResponse.GetResponseDirective(
         new CacheProxyAttribute {
         MustRevalidateWhenStale = true
     },
         new CacheClientAttribute {
         MustRevalidateWhenStale = false
     })
     .CacheDirectives.ShouldContain("proxy-revalidate");
 }
Пример #16
0
 protected void when_getting_response_caching()
 {
     try
     {
         cache = CacheResponse.GetResponseDirective(_proxy, client);
     }
     catch (Exception e)
     {
         exception = e;
     }
 }
Пример #17
0
        public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
        {
            CacheResponse response = null;
            var           ar       = new CacheAsyncResult {
                strUrl = request.CanonicalUri.ToString()
            };

            // ar.strUrl = "http://mediadl.microsoft.com/mediadl/iisnet/smoothmedia/Experience/BigBuckBunny_720p.ism/Manifest";

            ar.Complete(response, true);
            return(ar);
        }
Пример #18
0
        private async Task <CacheResponse <IEsiFragment> > RequestAndParse(
            Uri uri, EsiExecutionContext executionContext)
        {
            var response = await _httpLoader.Get(uri, executionContext);

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var fragment = _esiBodyParser.Parse(content);

            return(CacheResponse.Create(fragment, response.Headers.CacheControl, response.Headers.Vary.ToList()));
        }
Пример #19
0
        public async Task <ActionResult <HttpResponseMessage> > Downstream(string name = "")
        {
            try
            {
                CacheResponse downstreamResponse = await _downstream.GetAsyncDownstream(name);

                return(await Task.FromResult(Ok(downstreamResponse)));
            }
            catch (DownstreamConfigException e)
            {
                _logger.LogError("Configuration error with downstream", e);
                return(await Task.FromResult(StatusCode(503, "Downstream call failed")));
            }
        }
        public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
        {
            CacheAsyncResult cacheAsyncResult = new CacheAsyncResult();

            if (!this.cache.ContainsKey(request.CanonicalUri.ToString()) && !request.CanonicalUri.ToString().ToUpperInvariant().EndsWith(".ISML/MANIFEST") && !request.CanonicalUri.ToString().ToUpperInvariant().EndsWith(".ISM/MANIFEST"))
            {
                cacheAsyncResult.FragmentUrl = request.CanonicalUri.ToString();
                cacheAsyncResult.Complete(response, true);
                return(cacheAsyncResult);
            }

            cacheAsyncResult.Complete(null, true);
            return(cacheAsyncResult);
        }
        public Func <IOperationAsync, Task <IEnumerable <OutputMember> > > Compose(
            Func <IOperationAsync, Task <IEnumerable <OutputMember> > > next)
        {
            return(async operation =>
            {
                var outputMembers = await next(operation);

                _proxy = operation.FindAttribute <CacheProxyAttribute>();
                _client = operation.FindAttribute <CacheClientAttribute>();

                _data[CacheKeys.ResponseCache] = CacheResponse.GetResponseDirective(_proxy, _client);
                return outputMembers;
            });
        }
        public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
        {
            IAsyncResult result = null;

            if (this.primary != null)
            {
                result = this.primary.BeginPersist(request, response, callback, state);
            }
            else if (this.secondary != null)
            {
                result = this.secondary.BeginPersist(request, response, callback, state);
            }

            return(result);
        }
Пример #23
0
        public Task AddAsync(string key, CacheResponse response, DateTime expirationUtcTimestamp)
        {
            key.ThrowIfNull("key");
            response.ThrowIfNull("response");

            if (expirationUtcTimestamp.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Expiration must be UTC.", "expirationUtcTimestamp");
            }

            var cacheItem = new CacheItem(response, _systemClock.UtcDateTime);

            _httpRuntime.Cache.Insert(key, cacheItem, null, expirationUtcTimestamp, Cache.NoSlidingExpiration);

            return(Task.Factory.Empty());
        }
Пример #24
0
            public void SetUp()
            {
                Response response = new Response()
                                    .OK()
                                    .ApplicationJson()
                                    .Charset("utf-8")
                                    .Content("content")
                                    .ContentEncoding(Encoding.ASCII)
                                    .Cookie(new HttpCookie("name", "value"))
                                    .Header("field", "value")
                                    .HeaderEncoding(Encoding.UTF8);

                response.CachePolicy.ETag("etag");

                _cacheResponse = new CacheResponse(response);
            }
Пример #25
0
        private async Task StoreFragmentInCache(
            HttpContext context, Uri pageUri, EsiExecutionContext executionContext, IEsiFragment fragment)
        {
            CacheControlHeaderValue.TryParse(
                context.Response.Headers[HeaderNames.CacheControl], out var cacheControl);

            if (ShouldSetCache(context))
            {
                var headers      = context.Response.Headers.ToDictionary();
                var pageResponse = new FragmentPageResponse(fragment, headers);

                var vary          = context.Response.Headers[HeaderNames.Vary];
                var cacheResponse = CacheResponse.Create(pageResponse, cacheControl, vary);

                await _cache.Set(pageUri, executionContext, cacheResponse);
            }
        }
Пример #26
0
        /// <summary>
        /// Simple cache helper
        /// </summary>
        /// <param name="key">The cache key used to reference the item.</param>
        /// <param name="function">The underlying method that referes to the object to be stored in the cache.</param>
        /// <returns>The item</returns>
        public static CacheResponse <T> Get(string key, Func <T> function)
        {
            var response = new CacheResponse <T>();

            var obj = HttpContext.Current.Cache[key];

            response.IsLoadedFromCache = true;

            if (obj == null)
            {
                response.IsLoadedFromCache = false;
                obj = function.Invoke();
                HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddHours(ConfigurationHelper.CacheExpiresHours),
                                              TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            response.Obj = (T)obj;
            return(response);
        }
Пример #27
0
        public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
        {
            state = false;
            var ar = new CacheAsyncResult();

            //Manipulate the URI
            String tempUri = request.CanonicalUri.ToString();

            if (!_keyUrls.ContainsKey(tempUri))
            {
                //state = true;
                ar.strUrl = tempUri;
                ar.Complete(response, true);
                return(ar);
            }

            ar.Complete(null, true);
            return(ar);
        }
        public CacheResponse EndRetrieve(IAsyncResult ar)
        {
            CacheResponse primaryResponse = null;

            if (this.primary != null)
            {
                primaryResponse = this.primary.EndRetrieve(ar);
            }

            if (this.secondary != null)
            {
                CacheResponse secondaryResponse = this.secondary.EndRetrieve(ar);

                if ((secondaryResponse == null || secondaryResponse.ContentLength == 0) && (primaryResponse != null && primaryResponse.ContentLength > 0))
                {
                    CacheAsyncResult cacheAsyncResult = ar as CacheAsyncResult;

                    if (cacheAsyncResult != null)
                    {
                        cacheAsyncResult.Result = primaryResponse;

                        this.secondary.EndPersist(cacheAsyncResult);
                    }
                }

                if ((primaryResponse == null || primaryResponse.ContentLength == 0) && (secondaryResponse != null && secondaryResponse.ContentLength > 0))
                {
                    CacheAsyncResult cacheAsyncResult = ar as CacheAsyncResult;

                    if (cacheAsyncResult != null && this.primary != null)
                    {
                        cacheAsyncResult.Result = secondaryResponse;

                        this.primary.EndPersist(cacheAsyncResult);
                    }

                    primaryResponse = secondaryResponse;
                }
            }

            return(primaryResponse);
        }
Пример #29
0
        public bool EndPersist(IAsyncResult asyncResult)
        {
            asyncResult.AsyncWaitHandle.WaitOne();

            CacheAsyncResult cacheAsyncResult = asyncResult as CacheAsyncResult;

            if (cacheAsyncResult != null && cacheAsyncResult.Result != null)
            {
                CacheResponse cacheResponse = cacheAsyncResult.Result as CacheResponse;

                if (cacheResponse != null && cacheResponse.Response != null && !this.cache.ContainsKey(cacheAsyncResult.FragmentUrl) && cacheResponse.StatusCode == HttpStatusCode.OK)
                {
                    string fileGuid = Guid.NewGuid().ToString();

                    using (MemoryStream stream = new MemoryStream())
                    {
                        cacheResponse.WriteTo(stream);
                        stream.Position = 0;

                        bool result = this.persitenceService.Persist(fileGuid, stream);

                        if (result)
                        {
                            CacheItem cacheItem = new CacheItem
                            {
                                CachedValue = fileGuid,
                                Date        = DateTime.Now
                            };

                            this.cache.Add(cacheAsyncResult.FragmentUrl, cacheItem);
                            this.OnCacheUpdated(cacheAsyncResult.FragmentUrl);

                            this.persitenceService.AddApplicationSettings(cacheAsyncResult.FragmentUrl, cacheItem);

                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Пример #30
0
        public CacheResponse EndRetrieve(IAsyncResult ar)
        {
            ar.AsyncWaitHandle.WaitOne();

            CacheResponse response = null;

            if ((((CacheAsyncResult)ar).strUrl).ToLower().EndsWith("/manifest"))
            {
                //manifest file exists on file system hence retrive it!
                if (Directory.Exists(RootFolderPath) && (File.Exists(ManifestFilePath)))
                {
                    using (FileStream fs = new FileStream(ManifestFilePath, FileMode.Open, FileAccess.Read))
                    {
                        return(new CacheResponse(fs));
                    }
                }
            }
            else
            {
                if (_keyUrls.ContainsKey(((CacheAsyncResult)ar).strUrl))
                {
                    string filename = _keyUrls[((CacheAsyncResult)ar).strUrl];

                    var chunkFilename = RootFolderPath + Path.DirectorySeparatorChar + filename;

                    if (Directory.Exists(RootFolderPath) && (File.Exists(chunkFilename)))
                    {
                        var stream = File.OpenRead(chunkFilename);
                        response = new CacheResponse(stream);
                    }
                }
            }
            return(response);
            //if (response != null)
            //return response;
            //else
            //return
            //response = new CacheResponse(0, null, null, null, HttpStatusCode.NotFound, "Not Found", DateTime.Now);
        }
 public CacheResponse GetResponseMessageDetails(CacheRequest objRequest)
 {
     try
     {
         if (objRequest.WebConfig)
         {
             objcacheresp.CacheGrid = objclsDashboard.GetCacheresponseMessage();
         }
         else
         {
             objcacheresp.CacheGrid = objclsDashboard.GetCacheFailedData(objRequest.ResponseMessage, objRequest.DateTime);
         }
         return(objcacheresp);
     }
     catch (Exception)
     {
         return(objcacheresp);
     }
     finally
     {
         objcacheresp    = null;
         objclsDashboard = null;
     }
 }
Пример #32
0
            public void SetUp()
            {
                _httpCachePolicyBase = MockRepository.GenerateMock <HttpCachePolicyBase>();

                _httpResponseBase = MockRepository.GenerateMock <HttpResponseBase>();
                _httpResponseBase.Stub(arg => arg.Cache).Return(_httpCachePolicyBase);
                _httpResponseBase.Stub(arg => arg.Cookies).Return(new HttpCookieCollection());
                _httpResponseBase.Stub(arg => arg.Headers).Return(new NameValueCollection());

                Response response = new Response()
                                    .OK()
                                    .ApplicationJson()
                                    .Charset("utf-8")
                                    .Content("content")
                                    .ContentEncoding(Encoding.ASCII)
                                    .Cookie(new HttpCookie("name", "value"))
                                    .Header("field", "value")
                                    .HeaderEncoding(Encoding.UTF8);

                response.CachePolicy.NoClientCaching();

                _cacheResponse = new CacheResponse(response);
                _cacheResponse.WriteResponseAsync(_httpResponseBase).Wait();
            }
        async Task <IAccessToken> IAccessTokenProvider.ProvisionAccessTokenAsync(
            IEnumerable <Claim> claims,
            IEnumerable <Scope> scopes,
            ICache cache
            )
        {
            if (cache == null)
            {
                cache = new NullCache();
            }

            claims = claims.ToList();
            scopes = scopes.ToList();

            string cacheKey = TokenCacheKeyBuilder.BuildKey(claims, scopes);

            CacheResponse cacheResponse = await cache.GetAsync(cacheKey).SafeAsync();

            if (cacheResponse.Success)
            {
                SecurityToken securityToken = m_tokenHandler.ReadToken(cacheResponse.Value);
                if (securityToken.ValidTo > DateTime.UtcNow.Add(m_tokenRefreshGracePeriod))
                {
                    return(new AccessToken(cacheResponse.Value));
                }
            }

            IAccessToken token =
                await m_accessTokenProvider.ProvisionAccessTokenAsync(claims, scopes).SafeAsync();

            DateTime validTo = m_tokenHandler.ReadToken(token.Token).ValidTo;

            await cache.SetAsync(cacheKey, token.Token, validTo - DateTime.UtcNow).SafeAsync();

            return(token);
        }
Пример #34
0
        public CacheResponse EndRetrieve(IAsyncResult ar)
        {
            ar.AsyncWaitHandle.WaitOne();

            CacheResponse response = null;

            if ((((CacheAsyncResult) ar).strUrl).ToLower().EndsWith("/manifest"))
            {
                //manifest file exists on file system hence retrive it!
                if (Directory.Exists(RootFolderPath) && (File.Exists(ManifestFilePath)))
                {
                    using (FileStream fs = new FileStream(ManifestFilePath, FileMode.Open, FileAccess.Read))
                    {
                        return new CacheResponse(fs);
                    }
                }
            }
            else
            {
                if (_keyUrls.ContainsKey(((CacheAsyncResult) ar).strUrl))
                {
                    string filename = _keyUrls[((CacheAsyncResult) ar).strUrl];

                    var chunkFilename = RootFolderPath + Path.DirectorySeparatorChar + filename;

                    if (Directory.Exists(RootFolderPath) && (File.Exists(chunkFilename)))
                    {
                        var stream = File.OpenRead(chunkFilename);
                        response = new CacheResponse(stream);
                    }
                }
            }
            return response;
            //if (response != null)
                //return response;
            //else
                //return
                    //response = new CacheResponse(0, null, null, null, HttpStatusCode.NotFound, "Not Found", DateTime.Now);
        }
Пример #35
0
        public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
        {
            state = false;
            var ar = new CacheAsyncResult();

            //Manipulate the URI
            String tempUri = request.CanonicalUri.ToString();

            if (!_keyUrls.ContainsKey(tempUri))
            {
                //state = true;
                ar.strUrl = tempUri;
                ar.Complete(response, true);
                return ar;
            }

            ar.Complete(null, true);
            return ar;
        }
 public void ResponseData(CacheRequest pDownloaderRequest, CacheResponse pDownloaderResponse)
 {
     // do nothing
 }
Пример #37
0
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     throw new NotImplementedException();
 }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     return null;
 }
 public CacheResponse EndRetrieve(IAsyncResult ar)
 {
     CacheAsyncResult result = ar as CacheAsyncResult;
     if (result == null)
     {
         return null;
     }
     if (this.IsStopping || this.IsStopped)
     {
         return null;
     }
     WebRequestResult result2 = OVPClientHttpRequest.BrowserHttpRequest(result.strUrl, 0x1770);
     if (result2.HttpStatusCode != 200)
     {
         return null;
     }
     using (CryptoStream stream2 = new CryptoStream(result2.Response.GetResponseStream(), this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
     {
         MemoryStream stream = new MemoryStream();
         long contentLength = 0L;
         int count = 0x1000;
         byte[] buffer = new byte[count];
         while (stream2.CanRead)
         {
             int num2 = stream2.Read(buffer, 0, count);
             contentLength += num2;
             if (num2 == 0)
             {
                 break;
             }
             stream.Write(buffer, 0, num2);
         }
         stream.Position = 0L;
         if (result.strUrl.Contains("Manifest"))
         {
             StreamReader reader = new StreamReader(stream);
             string s = reader.ReadToEnd().Replace("{start time})", "{start time})?" + this._decryptionInfo.SessionID).Replace("300000000", "550000000");
             stream = new MemoryStream(Encoding.Unicode.GetBytes(s)) {
                 Position = 0L
             };
         }
         CacheResponse response = new CacheResponse(contentLength, result2.Response.ContentType, null, stream, result2.Response.StatusCode, result2.Response.StatusDescription, DateTime.Now, true);
         stream.Position = 0L;
         return response;
     }
 }
Пример #40
0
        private void OnManifestResponse(IAsyncResult ar)
        {
            var wreq = ar.AsyncState as WebRequest;
            if (wreq != null)
            {
                var wresp = (HttpWebResponse) wreq.EndGetResponse(ar);

                if (wresp.StatusCode != HttpStatusCode.OK)
                    throw new Exception(wresp.StatusDescription);

                Stream respStream = wresp.GetResponseStream();

                if (!Directory.Exists(RootFolderPath))
                    Directory.CreateDirectory(RootFolderPath);
                //open a filestream
                using (var fs = new FileStream(ManifestFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    //create a CacheResponse
                    var cacheResp = new CacheResponse(respStream.Length, wresp.ContentType, null,
                        respStream, wresp.StatusCode, wresp.StatusDescription,
                        DateTime.UtcNow);
                    //serialize to the file
                    cacheResp.WriteTo(fs);
                    fs.Flush();
                    fs.Close();
                }
            }
        }
 public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
 {
     if (this.IsStopped)
     {
         CacheAsyncResult result = new CacheAsyncResult();
         result.Complete(new CacheResponse(0L, null, null, null, HttpStatusCode.NotFound, "Not Found", DateTime.Now, false), true);
         return result;
     }
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         return null;
     }
     CacheAsyncResult ar = new CacheAsyncResult {
         strUrl = request.CanonicalUri.ToString()
     };
     HttpWebRequest webRequest = WebRequestCreator.BrowserHttp.Create(request.CanonicalUri) as HttpWebRequest;
     webRequest.BeginGetResponse(delegate (IAsyncResult result) {
         try
         {
             HttpWebResponse response = webRequest.EndGetResponse(result) as HttpWebResponse;
             if (response.StatusCode != HttpStatusCode.OK)
             {
                 ar.Complete(null, true);
             }
             else
             {
                 using (CryptoStream stream = new CryptoStream(response.GetResponseStream(), this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
                 {
                     MemoryStream stream2 = new MemoryStream();
                     long contentLength = 0L;
                     int count = 0x1000;
                     byte[] buffer = new byte[count];
                     while (stream.CanRead)
                     {
                         int num2 = stream.Read(buffer, 0, count);
                         contentLength += num2;
                         if (num2 == 0)
                         {
                             break;
                         }
                         stream2.Write(buffer, 0, num2);
                     }
                     stream2.Position = 0L;
                     if (request.CanonicalUri.ToString().Contains("Manifest"))
                     {
                         StreamReader reader = new StreamReader(stream2);
                         string s = reader.ReadToEnd().Replace("{start time})", "{start time})?" + this._decryptionInfo.SessionID).Replace("300000000", "550000000");
                         stream2 = new MemoryStream(Encoding.Unicode.GetBytes(s)) {
                             Position = 0L
                         };
                     }
                     CacheResponse response2 = new CacheResponse(contentLength, response.ContentType, null, stream2, response.StatusCode, response.StatusDescription, DateTime.Now, true);
                     stream2.Position = 0L;
                     ar.Complete(response2, true);
                 }
             }
         }
         catch (Exception)
         {
             ar.Complete(null, true);
         }
     }, null);
     return ar;
 }