Exemplo n.º 1
0
        /// <summary>
        /// Validates the <paramref name="filter"/> then applies as a filter to the reference data <paramref name="coll"/>.
        /// </summary>
        /// <typeparam name="TColl">The collection <see cref="System.Type"/>.</typeparam>
        /// <typeparam name="TItem">The item <see cref="System.Type"/>.</typeparam>
        /// <param name="coll">The reference data collection.</param>
        /// <param name="filter">The <see cref="ReferenceDataFilter"/>.</param>
        /// <param name="includeInactive">Indicates whether to include inactive (<see cref="ReferenceDataBase.IsActive"/> equal <c>false</c>) entries.</param>
        /// <returns>The filtered collection and corresponding ETag.</returns>
        public static async Task <ReferenceDataFilterResult <TItem> > ApplyFilterAsync <TColl, TItem>(TColl coll, ReferenceDataFilter filter, bool includeInactive = false) where TColl : ReferenceDataCollectionBase <TItem>, new() where TItem : ReferenceDataBase, new()
        {
            Check.NotNull(coll, nameof(coll));
            Check.NotNull(filter, nameof(filter));
            if (!filter.Codes.Any() && string.IsNullOrEmpty(filter.Text) && !includeInactive)
            {
                return new ReferenceDataFilterResult <TItem>(coll.ActiveList)
                       {
                           ETag = coll.ETag
                       }
            }
            ;

            // Validate the arguments.
            (await Validator.ValidateAsync(filter).ConfigureAwait(false)).ThrowOnError();

            // Apply the filter.
            var items = includeInactive ? coll.AllList : coll.ActiveList;
            var list  = items
                        .WhereWhen(x => filter.Codes.Contains(x.Code, StringComparer.OrdinalIgnoreCase), filter.Codes != null && filter.Codes.FirstOrDefault() != null)
                        .WhereWildcard(x => x.Text, filter.Text);

            return(new ReferenceDataFilterResult <TItem>(list)
            {
                ETag = ETagGenerator.Generate(list)
            });
        }
    }
Exemplo n.º 2
0
        public IActionResult GetModConfig(string modDllName)
        {
            var modConfig = GetModAppConfig(modDllName);

            if (modConfig == null)
            {
                return(NotFound());
            }

            var modConfigFile = Path.Combine(EmpyrionConfiguration.SaveGameModPath, modConfig.Current.ModConfigFile);

            if (!System.IO.File.Exists(modConfigFile))
            {
                return(NotFound());
            }


            DateTimeOffset?LastModified = new DateTimeOffset(System.IO.File.GetLastWriteTime(modConfigFile));

            return(PhysicalFile(
                       modConfigFile,
                       "application/" + Path.GetExtension(modConfigFile).Substring(1).ToLower(),
                       Path.GetFileName(modConfigFile),
                       LastModified,
                       new Microsoft.Net.Http.Headers.EntityTagHeaderValue("\"" + ETagGenerator.GetETag(modConfigFile, System.IO.File.ReadAllBytes(modConfigFile)) + "\""),
                       true
                       ));
        }
Exemplo n.º 3
0
        public void Generate()
        {
            var p = new Person {
                First = "Jane", Last = "Doe"
            };

            Assert.AreEqual("\"2I0QhKAlJMdHjCAocBhQeuzmze73jSnnWqyOkofhRn4=\"", ETagGenerator.Generate(p));
            Assert.AreEqual("\"471H/SShWDDr5wOVpMnhcu00Fw3nhOHN1aE8VNpXCsY=\"", ETagGenerator.Generate(p, "XYZ"));
        }
Exemplo n.º 4
0
        public void Generate()
        {
            var p = new Person {
                First = "Jane", Last = "Doe"
            };

            Assert.AreEqual("XCmFjH2zioLOelNdmU8hEQ==", ETagGenerator.Generate(p));
            Assert.AreEqual("E9ik+Agqes6hzHMezoJigw==", ETagGenerator.Generate(p, "XYZ"));
        }
        public IActionResult GetPlayfieldMap(string aPlayfieldname)
        {
            if (!Directory.Exists(MapsPath))
            {
                return(NotFound());
            }
            if (PlayfieldManager.Playfields == null)
            {
                PlayfieldManager.ReadPlayfields();
            }

            var PlayfieldMap = Path.Combine(
                EmpyrionConfiguration.SaveGameModPath,
                "EWA",
                "Maps",
                aPlayfieldname,
                "map.png");

            if (!System.IO.File.Exists(PlayfieldMap) && PlayfieldManager.Playfields == null)
            {
                return(NotFound());
            }

            var CurrentPlayfield = PlayfieldManager.Playfields.FirstOrDefault(P => P.name == aPlayfieldname);

            if (!System.IO.File.Exists(PlayfieldMap) && (CurrentPlayfield == null || CurrentPlayfield.isPlanet))
            {
                return(NotFound());
            }

            if (!CurrentPlayfield.isPlanet &&
                (!System.IO.File.Exists(PlayfieldMap) || (DateTime.Now - System.IO.File.GetLastWriteTime(PlayfieldMap)).TotalDays > 1))
            {
                try { ReadFromHubbleImages(PlayfieldMap); }
                catch (Exception Error)
                {
                    Logger.LogError(Error, "LoadSpace: {0} to {1}", aPlayfieldname, PlayfieldMap);
                    PlayfieldMap = Path.Combine(EmpyrionConfiguration.ModPath, @"EWALoader\EWA\ClientApp\dist\ClientApp\empty.png");
                }
            }

            DateTimeOffset?LastModified = new DateTimeOffset(System.IO.File.GetLastWriteTime(PlayfieldMap));

            return(PhysicalFile(
                       PlayfieldMap,
                       "image/png",
                       aPlayfieldname + ".png",
                       LastModified,
                       new Microsoft.Net.Http.Headers.EntityTagHeaderValue("\"" + ETagGenerator.GetETag(PlayfieldMap, System.IO.File.ReadAllBytes(PlayfieldMap)) + "\""),
                       true
                       ));
        }
Exemplo n.º 6
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                                CancellationToken cancellationToken)
        {
            if (request.Method == HttpMethod.Get)
            {
                //if this resource has been updated, let the request proceed to the operation and set a new etag on the return
                return(base.SendAsync(request, cancellationToken).ContinueWith(task =>
                {
                    var resp = task.Result;
                    if (resp.IsSuccessStatusCode && resp.Content is ObjectContent)
                    {
                        IViewModelAuditable viewModelAuditable = resp.Content.ReadAsAsync <object>(cancellationToken).Result as IViewModelAuditable;
                        if (viewModelAuditable != null)
                        {
                            resp.Headers.CacheControl = new CacheControlHeaderValue {
                                Public = true
                            };
                            resp.Headers.ETag = new EntityTagHeaderValue(ETagGenerator.GeneratorETag(viewModelAuditable.LastUpdatedDateUtc));
                            resp.Content.Headers.LastModified = viewModelAuditable.LastUpdatedDateUtc;
                        }
                    }
                    return resp;
                }, cancellationToken));
            }

            //if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Post)
            //    //let the request processing continue; new etag value for resource; update response header
            //    if (IfMatchContainsStoredEtagValue(request))
            //        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
            //        {
            //            var resp = task.Result;
            //            resp.Headers.ETag = new EntityTagHeaderValue(_eTagStore.UpdateETagFor(request.RequestUri));
            //            return resp;
            //        }, cancellationToken);

            //    //stop processing and return a 412/precondition failed; update response header
            //    else
            //        return taskFactory.StartNew(() =>
            //        {
            //            var resp = new HttpResponseMessage(HttpStatusCode.PreconditionFailed);
            //            resp.Headers.ETag = new EntityTagHeaderValue(_eTagStore.Fetch(request.RequestUri));
            //            return resp;
            //        }, cancellationToken);

            //by default, let the request keep moving up the message handler stack
            return(base.SendAsync(request, cancellationToken));
        }
Exemplo n.º 7
0
        public void ConvertToString()
        {
            Assert.AreEqual(("X", false), ETagGenerator.ConvertToString("X"));
            Assert.AreEqual(("1", false), ETagGenerator.ConvertToString(1));
            Assert.AreEqual(("1.51", false), ETagGenerator.ConvertToString(1.51m));
            Assert.AreEqual(("1990-01-31T08:09:10.0000000", false), ETagGenerator.ConvertToString(new DateTime(1990, 01, 31, 08, 09, 10)));

            var g = Guid.NewGuid();

            Assert.AreEqual((g.ToString(), false), ETagGenerator.ConvertToString(g));

            var p = new Person {
                First = "Jane", Last = "Doe"
            };

            Assert.AreEqual(("{\"First\":\"Jane\",\"Last\":\"Doe\"}", true), ETagGenerator.ConvertToString(p));
        }
Exemplo n.º 8
0
    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.HttpContext.Request.Method == "GET")
        {
            if (_statusCodes.Contains(context.HttpContext.Response.StatusCode))
            {
                //I just serialize the result to JSON, could do something less costly
                var content = JsonConvert.SerializeObject(context.Result);

                var etag = ETagGenerator.GetETag(context.HttpContext.Request.Path.ToString(), Encoding.UTF8.GetBytes(content));

                if (context.HttpContext.Request.Headers.Keys.Contains("If-None-Match") && context.HttpContext.Request.Headers["If-None-Match"].ToString() == etag)
                {
                    context.Result = new StatusCodeResult(304);
                }
                context.HttpContext.Response.Headers.Add("ETag", new[] { etag });
            }
        }
    }
Exemplo n.º 9
0
        private IActionResult GetImage(ImageType type, Guid userId, string name, string v)
        {
            string baseUrl = Constants.DefaultCdnPath;

            name = name.Replace(Constants.DefaultImagePath, string.Empty);

            try
            {
                string storageBasePath = FormatBasePath(type, userId, baseUrl);

                string url = UrlFormatter.CdnCommon(userId, name);

                if (!string.IsNullOrWhiteSpace(v))
                {
                    url += "?v=" + v;
                }

                byte[] data;

                using (WebClient webClient = new WebClient())
                {
                    data = webClient.DownloadData(url);
                }

                string etag = ETagGenerator.GetETag(httpContextAccessor.HttpContext.Request.Path.ToString(), data);
                if (httpContextAccessor.HttpContext.Request.Headers.Keys.Contains(HeaderNames.IfNoneMatch) && httpContextAccessor.HttpContext.Request.Headers[HeaderNames.IfNoneMatch].ToString() == etag)
                {
                    return(new StatusCodeResult(StatusCodes.Status304NotModified));
                }
                httpContextAccessor.HttpContext.Response.Headers.Add(HeaderNames.ETag, new[] { etag });

                return(File(new MemoryStream(data), "image/jpeg"));
            }
            catch (Exception ex)
            {
                string msg = $"Unable to save get the Image.";
                logger.Log(LogLevel.Error, ex, msg);

                return(ReturnDefaultImage(type));
            }
        }
        private IActionResult GetResult(string resourceName, string contentType)
        {
            var assembly = typeof(FileManagerController).GetTypeInfo().Assembly;

            resourceName = _resourceHelper.ResolveResourceIdentifier(resourceName);
            var resourceStream = assembly.GetManifestResourceStream(resourceName);

            if (resourceStream == null)
            {
                _log.LogError("resource not found for " + resourceName);
                return(NotFound());
            }

            _log.LogDebug("resource found for " + resourceName);

            var status = ETagGenerator.AddEtagForStream(HttpContext, resourceStream);

            if (status != null)
            {
                return(status);
            }                                     //304

            return(new FileStreamResult(resourceStream, contentType));
        }
Exemplo n.º 11
0
 public string GetMovieTranslationsETag(int MovieID)
 {
     //return ProcessRequestETag(BuildGetMovieTranslationsRequest(MovieID));
     return(ProcessRequestETag(ETagGenerator.GetMovieTranslations(MovieID)));
 }
Exemplo n.º 12
0
 public string GetMovieChangesETag(int MovieID)
 {
     return(ProcessRequestETag(ETagGenerator.GetMovieChanges(MovieID)));
 }
Exemplo n.º 13
0
 public string GetMovieReleasesETag(int MovieID)
 {
     //return ProcessRequestETag(BuildGetMovieReleasesRequest(MovieID));
     return(ProcessRequestETag(ETagGenerator.GetMovieReleases(MovieID)));
 }
Exemplo n.º 14
0
 public string GetMovieTrailersETag(int MovieID, string language = "")
 {
     //return ProcessRequestETag(BuildGetMovieTrailersRequest(MovieID, language));
     return(ProcessRequestETag(ETagGenerator.GetMovieTrailers(MovieID, language)));
 }
Exemplo n.º 15
0
 public string GetMovieKeywordsETag(int MovieID)
 {
     //return ProcessRequestETag(BuildGetMovieKeywordsRequest(MovieID));
     return(ProcessRequestETag(ETagGenerator.GetMovieKeywords(MovieID)));
 }
Exemplo n.º 16
0
 public string GetMovieAlternateTitlesETag(int MovieID, string Country)
 {
     //return ProcessRequestETag(BuildGetMovieAlternateTitlesRequest(MovieID, Country));
     return(ProcessRequestETag(ETagGenerator.GetMovieAlternateTitles(MovieID, Country)));
 }
Exemplo n.º 17
0
 public string GetPersonCreditsETag(int PersonID, string language = null)
 {
     //return ProcessRequestETag(BuildGetPersonCreditsRequest(PersonID, language));
     return(ProcessRequestETag(ETagGenerator.GetPersonCredits(PersonID, language)));
 }
Exemplo n.º 18
0
 public string GetUpcomingMoviesETag(int page, string language = null)
 {
     //return ProcessRequestETag(BuildGetUpcomingMoviesRequest(page, language));
     return(ProcessRequestETag(ETagGenerator.GetUpcomingMovies(page, language)));
 }
Exemplo n.º 19
0
 public string GetPersonChangesETag(int PersonID)
 {
     return(ProcessRequestETag(ETagGenerator.GetPersonChanges(PersonID)));
 }
Exemplo n.º 20
0
 public string GetPersonImagesETag(int PersonID)
 {
     //return ProcessRequestETag(BuildGetPersonImagesRequest(PersonID));
     return(ProcessRequestETag(ETagGenerator.GetPersonImages(PersonID)));
 }
Exemplo n.º 21
0
 public string GetGenreListETag(string language = null)
 {
     //return ProcessRequestETag(BuildGetGenreListRequest(language));
     return(ProcessRequestETag(ETagGenerator.GetGenreList(language)));
 }
Exemplo n.º 22
0
 public string GetLatestMovieETag()
 {
     //return ProcessRequestETag(BuildGetLatestMovieRequest());
     return(ProcessRequestETag(ETagGenerator.GetLatestMovies()));
 }
Exemplo n.º 23
0
 public string GetGenreMoviesETag(int GenreID, int page, string language = null)
 {
     //return ProcessRequestETag(BuildGetGenreMoviesRequest(GenreID, page, language));
     return(ProcessRequestETag(ETagGenerator.GetGenreMovies(GenreID, page, language)));
 }
Exemplo n.º 24
0
 public string GetCompanyInfoETag(int CompanyID)
 {
     //return ProcessRequestETag(BuildGetCompanyInfoRequest(CompanyID));
     return(ProcessRequestETag(ETagGenerator.GetCompanyInfo(CompanyID)));
 }
Exemplo n.º 25
0
 public string GetCollectionImagesETag(int CollectionID, string language = "")
 {
     //return ProcessRequestETag(BuildGetCollectionImagesRequest(CollectionID, language));
     return(ProcessRequestETag(ETagGenerator.GetCollectionImages(CollectionID, language)));
 }