Exemplo n.º 1
0
        public void StarbaseListPersist()
        {
            ResponseCache.Clear();
            StarbaseList starbaseList = EveApi.GetStarbaseList(432435, 234523, "apiKey");

            ResponseCache.Save("ResponseCache.xml");
            ResponseCache.Clear();
            ResponseCache.Load("ResponseCache.xml");

            StarbaseList cachedStarbaseList = EveApi.GetStarbaseList(432435, 234523, "apiKey");

            Assert.AreEqual(starbaseList.CachedUntilLocal, cachedStarbaseList.CachedUntilLocal);

            for (int i = 0; i < starbaseList.StarbaseListItems.Length; i++)
            {
                Assert.AreEqual(starbaseList.StarbaseListItems[i].ItemId, cachedStarbaseList.StarbaseListItems[i].ItemId);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].TypeId, cachedStarbaseList.StarbaseListItems[i].TypeId);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].LocationId, cachedStarbaseList.StarbaseListItems[i].LocationId);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].MoonId, cachedStarbaseList.StarbaseListItems[i].MoonId);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].State, cachedStarbaseList.StarbaseListItems[i].State);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].StateTimestamp, cachedStarbaseList.StarbaseListItems[i].StateTimestamp);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].OnlineTimestamp, cachedStarbaseList.StarbaseListItems[i].OnlineTimestamp);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].StateTimestampLocal, cachedStarbaseList.StarbaseListItems[i].StateTimestampLocal);
                Assert.AreEqual(starbaseList.StarbaseListItems[i].OnlineTimestampLocal, cachedStarbaseList.StarbaseListItems[i].OnlineTimestampLocal);
            }
        }
Exemplo n.º 2
0
        public void StarbaseDetailPersist()
        {
            ResponseCache.Clear();
            StarbaseDetail starbaseDetail = EveApi.GetStarbaseDetail(432435, 234523, "fullApiKey", 25245);

            ResponseCache.Save("ResponseCache.xml");
            ResponseCache.Clear();
            ResponseCache.Load("ResponseCache.xml");

            StarbaseDetail cachedStarbaseDetail = EveApi.GetStarbaseDetail(432435, 234523, "fullApiKey", 25245);

            Assert.AreEqual(starbaseDetail.CachedUntilLocal, cachedStarbaseDetail.CachedUntilLocal);

            Assert.AreEqual(starbaseDetail.UsageFlags, cachedStarbaseDetail.UsageFlags);
            Assert.AreEqual(starbaseDetail.DeployFlags, cachedStarbaseDetail.DeployFlags);
            Assert.AreEqual(starbaseDetail.AllowCorporationMembers, cachedStarbaseDetail.AllowCorporationMembers);
            Assert.AreEqual(starbaseDetail.AllowAllianceMembers, cachedStarbaseDetail.AllowAllianceMembers);
            Assert.AreEqual(starbaseDetail.ClaimSovereignty, cachedStarbaseDetail.ClaimSovereignty);

            Assert.AreEqual(starbaseDetail.OnStandingDropEnabled, cachedStarbaseDetail.OnStandingDropEnabled);
            Assert.AreEqual(starbaseDetail.OnStandingDropStanding, cachedStarbaseDetail.OnStandingDropStanding);
            Assert.AreEqual(starbaseDetail.OnStatusDropEnabled, cachedStarbaseDetail.OnStatusDropEnabled);
            Assert.AreEqual(starbaseDetail.OnStatusDropStanding, cachedStarbaseDetail.OnStatusDropStanding);
            Assert.AreEqual(starbaseDetail.OnAgressionEnabled, cachedStarbaseDetail.OnAgressionEnabled);
            Assert.AreEqual(starbaseDetail.OnCorporationWarEnabled, cachedStarbaseDetail.OnCorporationWarEnabled);

            for (int i = 0; i < starbaseDetail.FuelList.Length; i++)
            {
                Assert.AreEqual(starbaseDetail.FuelList[i].TypeId, cachedStarbaseDetail.FuelList[i].TypeId);
                Assert.AreEqual(starbaseDetail.FuelList[i].Quantity, cachedStarbaseDetail.FuelList[i].Quantity);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Performs an HTTP GET request on the <see cref="IEndpoint.Uri"/> and caches the response if the server sends an <see cref="HttpResponseHeaders.ETag"/>.
        /// </summary>
        /// <remarks>Sends If-None-Match header if there is already a cached ETag.</remarks>
        /// <param name="cancellationToken">Used to cancel the request.</param>
        /// <returns>The response of the request or the cached response if the server responded with <see cref="HttpStatusCode.NotModified"/>.</returns>
        /// <exception cref="AuthenticationException"><see cref="HttpStatusCode.Unauthorized"/></exception>
        /// <exception cref="UnauthorizedAccessException"><see cref="HttpStatusCode.Forbidden"/></exception>
        /// <exception cref="KeyNotFoundException"><see cref="HttpStatusCode.NotFound"/> or <see cref="HttpStatusCode.Gone"/></exception>
        /// <exception cref="HttpRequestException">Other non-success status code.</exception>
        protected async Task <HttpContent> GetContentAsync(CancellationToken cancellationToken)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, Uri);
            var cache   = ResponseCache; // Copy reference for thread-safety

            if (cache?.ETag != null)
            {
                request.Headers.IfNoneMatch.Add(cache.ETag);
            }

            var response = await HttpClient.SendAsync(request, cancellationToken).NoContext();

            if (response.StatusCode == HttpStatusCode.NotModified && cache != null)
            {
                return(cache.GetContent());
            }
            else
            {
                await HandleResponseAsync(Task.FromResult(response)).NoContext();

                if (response.Content != null)
                {
                    ResponseCache = new ResponseCache(response);
                }
                return(response.Content);
            }
        }
Exemplo n.º 4
0
        public async Task Cache_EntriesLowestTT_Expires()
        {
            var cache    = new ResponseCache(true);
            var record   = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 1000, 100));
            var recordB  = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 100, 100));
            var recordC  = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 1, 100));
            var response = new DnsResponseMessage(new DnsResponseHeader(1, 256, 1, 1, 0, 0), 0);

            response.AddAnswer(record);
            response.AddAdditional(recordB);
            response.AddAuthority(recordC);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any), null));

            await Task.Delay(200);

            var item = cache.Get("key", out double?effectiveTtl);

            Assert.NotNull(item);
            Assert.Equal(1 * 1000, effectiveTtl);

            await Task.Delay(1100);

            var item3 = cache.Get("key", out double?effectiveTtl2);

            Assert.Null(item3);
        }
Exemplo n.º 5
0
        public void GetSkillTree()
        {
            ResponseCache.Clear();
            SkillTree skillTree = EveApi.GetSkillTree();

            SkillTree.Skill skill = findSkill(3368, skillTree);

            Assert.AreEqual("Ethnic Relations", skill.TypeName);
            Assert.AreEqual(266, skill.GroupId);
            Assert.AreEqual(3368, skill.TypeId);
            Assert.AreEqual("Skill at operating multiracial", skill.Description.Substring(0, 30));
            Assert.AreEqual(2, skill.Rank);

            Assert.AreEqual(2, skill.RequiredSkills.Length);
            Assert.AreEqual(3363, skill.RequiredSkills[0].TypeId);
            Assert.AreEqual(2, skill.RequiredSkills[0].SkillLevel);
            Assert.AreEqual(3355, skill.RequiredSkills[1].TypeId);
            Assert.AreEqual(3, skill.RequiredSkills[1].SkillLevel);

            Assert.AreEqual(SkillTree.AttributeType.Memory, skill.PrimaryAttribute);
            Assert.AreEqual(SkillTree.AttributeType.Charisma, skill.SecondaryAttribute);

            Assert.AreEqual(1, skill.SkillBonuses.Length);
            Assert.AreEqual("nonRaceCorporationMembersBonus", skill.SkillBonuses[0].BonusType);
            Assert.AreEqual(20, skill.SkillBonuses[0].BonusValue);

            Assert.AreEqual("Corporation Management", skillTree.SkillGroups[0].GroupName);
            Assert.AreEqual(266, skillTree.SkillGroups[0].GroupId);
        }
Exemplo n.º 6
0
        public void GetSkillInTraining()
        {
            ResponseCache.Clear();
            SkillQueue skillqueue = EveApi.GetSkillQueue(456456, 456436, "asdf");

            SkillQueue.Skill skill0 = skillqueue.SkillList[0];
            SkillQueue.Skill skill1 = skillqueue.SkillList[1];

            //Attributes of the first skill in the queue
            Assert.AreEqual(1, skill0.QueuePosition);
            Assert.AreEqual(11441, skill0.TrainingTypeId);
            Assert.AreEqual(3, skill0.TrainingToLevel);
            Assert.AreEqual(7072, skill0.TrainingStartSP);
            Assert.AreEqual(40000, skill0.TrainingEndSP);
            Assert.AreEqual(new DateTime(2009, 03, 18, 02, 01, 06), skill0.TrainingStartTime);
            Assert.AreEqual(new DateTime(2009, 03, 18, 15, 19, 21), skill0.TrainingEndTime);
            Assert.AreEqual(new DateTime(2009, 03, 17, 21, 01, 06), skill0.TrainingStartTimeLocal);
            Assert.AreEqual(new DateTime(2009, 03, 18, 10, 19, 21), skill0.TrainingEndTimeLocal);

            //Attributes of the second skill in the queue
            Assert.AreEqual(2, skill1.QueuePosition);
            Assert.AreEqual(20533, skill1.TrainingTypeId);
            Assert.AreEqual(4, skill1.TrainingToLevel);
            Assert.AreEqual(112000, skill1.TrainingStartSP);
            Assert.AreEqual(633542, skill1.TrainingEndSP);
            Assert.AreEqual(new DateTime(2009, 03, 18, 15, 19, 21), skill1.TrainingStartTime);
            Assert.AreEqual(new DateTime(2009, 03, 30, 03, 16, 14), skill1.TrainingEndTime);
            Assert.AreEqual(new DateTime(2009, 03, 18, 10, 19, 21), skill1.TrainingStartTimeLocal);
            Assert.AreEqual(new DateTime(2009, 03, 29, 22, 16, 14), skill1.TrainingEndTimeLocal);
        }
Exemplo n.º 7
0
 public void Init()
 {
     _mockCommand   = new Mock <ICommand>();
     _mockResponse  = new Mock <Response>();
     _mockResponse2 = new Mock <Response>();
     _sut           = new ResponseCache();
 }
Exemplo n.º 8
0
        public async Task Cache_EntriesLowestTT_Expires()
        {
            var cache    = new ResponseCache();
            var record   = new EmptyRecord(new ResourceRecord(DnsString.Parse("a"), ARecord.ResourceRecordType, QueryClass.In, 1000, 100));
            var recordB  = new EmptyRecord(new ResourceRecord(DnsString.Parse("a"), ARecord.ResourceRecordType, QueryClass.In, 100, 100));
            var recordC  = new EmptyRecord(new ResourceRecord(DnsString.Parse("a"), ARecord.ResourceRecordType, QueryClass.In, 1, 100));
            var response = new DnsResponseMessage(new DnsResponseHeader(1, 256, 1, 1, 0, 0), 0)
            {
                Audit = new LookupClientAudit()
            };

            response.AddAnswer(record);
            response.AddAdditional(recordB);
            response.AddAuthority(recordC);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any)));

            await Task.Delay(200);

            var item = cache.Get("key", out var effectiveTtl);

            Assert.NotNull(item);
            Assert.Equal(1 * 1000, effectiveTtl);

            await Task.Delay(1100);

            var item3 = cache.Get("key", out _);

            Assert.Null(item3);
        }
Exemplo n.º 9
0
        public void PersistSkillInTraining()
        {
            ResponseCache.Clear();
            SkillQueue skillqueue = EveApi.GetSkillQueue(56456, 4564356, "asdf");

            ResponseCache.Save("ResponseCache.xml");
            ResponseCache.Clear();
            ResponseCache.Load("ResponseCache.xml");
            SkillQueue cached = EveApi.GetSkillQueue(4563456, 36456, "asdf");

            //Test the Cache Time
            Assert.AreEqual(skillqueue.CachedUntilLocal, cached.CachedUntilLocal);

            //Attributes of the first skill in the queue
            Assert.AreEqual(cached.SkillList[0].QueuePosition, skillqueue.SkillList[0].QueuePosition);
            Assert.AreEqual(cached.SkillList[0].TrainingTypeId, skillqueue.SkillList[0].TrainingTypeId);
            Assert.AreEqual(cached.SkillList[0].TrainingToLevel, skillqueue.SkillList[0].TrainingToLevel);
            Assert.AreEqual(cached.SkillList[0].TrainingStartSP, skillqueue.SkillList[0].TrainingStartSP);
            Assert.AreEqual(cached.SkillList[0].TrainingEndSP, skillqueue.SkillList[0].TrainingEndSP);
            Assert.AreEqual(cached.SkillList[0].TrainingStartTime, skillqueue.SkillList[0].TrainingStartTime);
            Assert.AreEqual(cached.SkillList[0].TrainingEndTime, skillqueue.SkillList[0].TrainingEndTime);
            Assert.AreEqual(cached.SkillList[0].TrainingStartTimeLocal, skillqueue.SkillList[0].TrainingStartTimeLocal);
            Assert.AreEqual(cached.SkillList[0].TrainingEndTimeLocal, skillqueue.SkillList[0].TrainingEndTimeLocal);

            //Attributes of the second skill in the queue
            Assert.AreEqual(cached.SkillList[1].QueuePosition, skillqueue.SkillList[1].QueuePosition);
            Assert.AreEqual(cached.SkillList[1].TrainingTypeId, skillqueue.SkillList[1].TrainingTypeId);
            Assert.AreEqual(cached.SkillList[1].TrainingToLevel, skillqueue.SkillList[1].TrainingToLevel);
            Assert.AreEqual(cached.SkillList[1].TrainingStartSP, skillqueue.SkillList[1].TrainingStartSP);
            Assert.AreEqual(cached.SkillList[1].TrainingEndSP, skillqueue.SkillList[1].TrainingEndSP);
            Assert.AreEqual(cached.SkillList[1].TrainingStartTime, skillqueue.SkillList[1].TrainingStartTime);
            Assert.AreEqual(cached.SkillList[1].TrainingEndTime, skillqueue.SkillList[1].TrainingEndTime);
            Assert.AreEqual(cached.SkillList[1].TrainingStartTimeLocal, skillqueue.SkillList[1].TrainingStartTimeLocal);
            Assert.AreEqual(cached.SkillList[1].TrainingEndTimeLocal, skillqueue.SkillList[1].TrainingEndTimeLocal);
        }
Exemplo n.º 10
0
        public void UsingStreams()
        {
            ResponseCache.Clear();
            string errorListLocation = Constants.ErrorList;

            Constants.ErrorList = "/ErrorListNotExpired.xml.aspx";

            ErrorList errorList = EveApi.GetErrorList();

            using (Stream s = new FileStream("ResponseCache.xml", FileMode.Create))
            {
                ResponseCache.Save(s);
            }

            ResponseCache.Clear();

            using (Stream s = new FileStream("ResponseCache.xml", FileMode.Open))
            {
                ResponseCache.Load(s);
            }

            ErrorList cached = EveApi.GetErrorList();

            Assert.AreEqual(errorList.CachedUntilLocal, cached.CachedUntilLocal);
            Assert.AreEqual(false, errorList.FromCache);
            Assert.AreEqual(true, cached.FromCache);

            Constants.ErrorList = errorListLocation;
        }
Exemplo n.º 11
0
        public void FactionSystemsPersist()
        {
            ResponseCache.Clear();
            MapFacWarSystems systems = EveApi.GetFactionWarSystems();

            ResponseCache.Save("ResponseCache.xml");
            ResponseCache.Clear();
            ResponseCache.Load("ResponseCache.xml");
            MapFacWarSystems cache = EveApi.GetFactionWarSystems();

            Assert.AreEqual(cache.CachedUntilLocal, systems.CachedUntilLocal);
            Assert.AreEqual(cache.FactionWarSystems.Length, systems.FactionWarSystems.Length);

            for (int i = 0; i < systems.FactionWarSystems.Length; i++)
            {
                MapFacWarSystems.FactionWarSystem system = systems.FactionWarSystems[i];
                MapFacWarSystems.FactionWarSystem cached = cache.FactionWarSystems[i];

                Assert.AreEqual(cached.SolarSystemId, system.SolarSystemId);
                Assert.AreEqual(cached.SolarSystemName, system.SolarSystemName);
                Assert.AreEqual(cached.OccupyingFactionId, system.OccupyingFactionId);
                Assert.AreEqual(cached.OccupyingFactionName, system.OccupyingFactionName);
                Assert.AreEqual(cached.Contested, system.Contested);
            }
        }
Exemplo n.º 12
0
 public async Task<ActionResult> Patients(int? id, CancellationToken ct)
 {
     _credentials.OnBehalfOf = User.Identity.GetUserId();
     if (id == null)
     {
         return await ViewPatients(ct);
     }
     var cache = new ResponseCache<PatientViewModel>(false, DefaultCacheTime.Long, _settings.ResponseCacheEnabled,
         _settings.ResponseCacheDefaultShortTimeInMinutes, _settings.ResponseCacheDefaultLongTimeInMinutes);
     var patientModel = cache.GetValue(Request);
     if (patientModel == null)
     {
         var muscles = await _glanceDa.GetMusclesAsync(_credentials, ct);
         var yearBounds = await _glanceDa.GetYearBoundsAsync(_credentials, id.Value, ct);
         var patient = await _glanceDa.GetPatientAsync(_credentials, id.Value, ct);
         patientModel = new PatientViewModel
         {
             Name = patient.Name,
             Keycol = id.Value,
             YearMax = yearBounds.Max,
             YearMin = yearBounds.Min,
             Muscles = muscles.ToArray(),
         };
         cache.SetValue(Request, patientModel);
     }
     patientModel.VersionedSettings = new Tuple<string, string>(string.Empty, "{}");
     return View("Patient", patientModel);
 }
Exemplo n.º 13
0
        public IQueryable <Fact> Get(ODataQueryOptions <Fact> options)
        {
            var parameters = _binder.BindFilter(options.Filter, ex =>
            {
                throw new HttpResponseException(Request.CreateBadRequestResponse(ex.Message));
            });

            var patientId = parameters.SingleOrDefault("Patient/Id", () =>
            {
                throw new HttpResponseException(Request.CreateNotImplementedResponse());
            });

            if (!string.IsNullOrEmpty(patientId))
            {
                var cache = new ResponseCache <IEnumerable <Fact> >(false, DefaultCacheTime.Long, _settings.ResponseCacheEnabled, _settings.ResponseCacheDefaultShortTimeInMinutes, _settings.ResponseCacheDefaultLongTimeInMinutes);
                var facts = cache.GetValue(Request);
                if (facts == null)
                {
                    var id = Convert.ToInt64(patientId);
                    facts = _uow.Facts.GetAll().Where(e => e.PatientId == id).ToArray();
                    cache.SetValue(Request, facts);
                }
                return(facts.AsQueryable());
            }
            return(_uow.Facts.GetAll());
        }
Exemplo n.º 14
0
        public async Task <ActionResult> Patients(int?id, CancellationToken ct)
        {
            _credentials.OnBehalfOf = User.Identity.GetUserId();
            if (id == null)
            {
                return(await ViewPatients(ct));
            }
            var cache = new ResponseCache <PatientViewModel>(false, DefaultCacheTime.Long, _settings.ResponseCacheEnabled,
                                                             _settings.ResponseCacheDefaultShortTimeInMinutes, _settings.ResponseCacheDefaultLongTimeInMinutes);
            var patientModel = cache.GetValue(Request);

            if (patientModel == null)
            {
                var muscles = await _glanceDa.GetMusclesAsync(_credentials, ct);

                var yearBounds = await _glanceDa.GetYearBoundsAsync(_credentials, id.Value, ct);

                var patient = await _glanceDa.GetPatientAsync(_credentials, id.Value, ct);

                patientModel = new PatientViewModel
                {
                    Name    = patient.Name,
                    Keycol  = id.Value,
                    YearMax = yearBounds.Max,
                    YearMin = yearBounds.Min,
                    Muscles = muscles.ToArray(),
                };
                cache.SetValue(Request, patientModel);
            }
            patientModel.VersionedSettings = new Tuple <string, string>(string.Empty, "{}");
            return(View("Patient", patientModel));
        }
Exemplo n.º 15
0
 /// <summary>
 /// Creates an ApiCalls object and instantiates the available API objects.
 /// </summary>
 /// <param name="configuration">An <see cref="IConfiguration"/> object to access application settings.</param>
 /// <param name="logger">The log4net logger.</param>
 public ApiCalls(IConfiguration configuration, ILog logger)
 {
     Logger   = logger;
     Cache    = new ResponseCache(configuration);
     DolarBot = new DolarBotApiService(configuration, Cache, LogError);
     Cuttly   = new CuttlyApiService(configuration);
     Topgg    = new TopggApiService(configuration, logger);
 }
Exemplo n.º 16
0
        public void Add_KeyIsNotNullValueIsNull_AddsNullValue()
        {
            ResponseCache.Clear();
            ResponseCache.Add("test", null);
            var item = ResponseCache.Get("test");

            Assert.That(string.IsNullOrEmpty(item), Is.True);
        }
Exemplo n.º 17
0
        public void Add_KeyIsNotNullValueIsNotNull_AddsNonNullValue()
        {
            ResponseCache.Clear();
            ResponseCache.Add("test", "value");
            var item = ResponseCache.Get("test");

            Assert.That(item, Is.EqualTo("value"));
        }
Exemplo n.º 18
0
 public Swapi(ResponseCache cache)
 {
     _cache  = cache;
     _client = new HttpClient();
     _client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json")
         );
 }
Exemplo n.º 19
0
        public GoodreadsClient(string cache_filename, string api_secret_filename)
        {
            var encoded_api_key = GetType().GetResource(api_secret_filename);
            var encoded_bytes = Convert.FromBase64String(encoded_api_key);
            api_key = Encoding.UTF8.GetString(encoded_bytes);

            cache = new ResponseCache(cache_filename);
            cache.IsDirty = false;
        }
Exemplo n.º 20
0
        public void GetErrorList()
        {
            ResponseCache.Clear();
            ErrorList errorList = EveApi.GetErrorList();

            Assert.AreEqual("Expected before ref/trans ID = 0: wallet not previously loaded.", errorList.GetMessageForErrorCode("100"));
            Assert.AreEqual("Current security level not high enough.", errorList.GetMessageForErrorCode("200"));
            Assert.AreEqual("User forced test error condition.", errorList.GetMessageForErrorCode("999"));
        }
Exemplo n.º 21
0
            /// <summary>
            /// Creats a <see cref="DolarArgentinaApi"/> object using the provided configuration, cache and error action.
            /// </summary>
            /// <param name="configuration">An <see cref="IConfiguration"/> object to access application settings.</param>
            /// <param name="cache">A cache of in-memory objects.</param>
            /// <param name="onError">An action to execute in case of error.</param>
            internal DolarArgentinaApi(IConfiguration configuration, ResponseCache cache, Action <IRestResponse> onError)
            {
                this.configuration = configuration;
                this.cache         = cache;
                OnError            = onError;

                client = new RestClient(this.configuration["apiUrl"]);
                client.UseNewtonsoftJson();
            }
Exemplo n.º 22
0
        public void GetServerStatusTest()
        {
            ResponseCache.Clear();

            ServerStatus serverStatus = EveApi.GetServerStatus();

            Assert.AreEqual(true, serverStatus.ServerOpen);
            Assert.AreEqual(28968, serverStatus.OnlinePlayers);
        }
Exemplo n.º 23
0
        public void Cache_DoesCacheFailureIfEnabled()
        {
            var cache         = new ResponseCache(true);
            var failureStatus = DnsResponseCode.NotExistentDomain;
            var response      = new DnsResponseMessage(new DnsResponseHeader(1, (ushort)failureStatus, 0, 0, 0, 0), 0);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any), null), true);
            var item = cache.Get("key", out _);

            Assert.NotNull(item);
        }
Exemplo n.º 24
0
        public IQueryable <DMuscle> Get()
        {
            var cache   = new ResponseCache <IEnumerable <DMuscle> >(false, DefaultCacheTime.Long, _settings.ResponseCacheEnabled, _settings.ResponseCacheDefaultShortTimeInMinutes, _settings.ResponseCacheDefaultLongTimeInMinutes);
            var muscles = cache.GetValue(Request);

            if (muscles == null)
            {
                muscles = _uow.Muscles.GetAll().ToArray();
                cache.SetValue(Request, muscles);
            }
            return(muscles.AsQueryable());
        }
Exemplo n.º 25
0
        public void Cache_DoesNotCacheFailureIfDisabled()
        {
            var cache         = new ResponseCache(true);
            var failureStatus = DnsResponseCode.NotExistentDomain;
            var response      = new DnsResponseMessage(new DnsResponseHeader(1, (ushort)failureStatus, 0, 0, 0, 0), 0);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any), null));
            var item = cache.Get("key", out _);

            // Should be null because cache does not accept failure responses by default.
            Assert.Null(item);
        }
Exemplo n.º 26
0
        public void GetCorporationSheet()
        {
            ResponseCache.Clear();
            CorporationSheet cs = EveApi.GetCorporationSheet(432435, 234523, "apiKey");

            testCorporationSheet(cs);

            ResponseCache.Clear();
            CorporationSheet cs2 = EveApi.GetCorporationSheet(432435, 234523, "apiKey", 2345);

            testCorporationSheet(cs2);
        }
Exemplo n.º 27
0
        public void RefTypePersist()
        {
            ResponseCache.Clear();

            RefTypes referenceType = EveApi.GetRefTypesList();

            ResponseCache.Save("ResponseCache.xml");
            ResponseCache.Clear();
            ResponseCache.Load("ResponseCache.xml");
            RefTypes cachedReferenceType = EveApi.GetRefTypesList();

            Assert.AreEqual(referenceType.CachedUntilLocal, cachedReferenceType.CachedUntilLocal);
        }
Exemplo n.º 28
0
        public void Cache_GetOrAdd()
        {
            var cache    = new ResponseCache(true);
            var record   = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 100, 100));
            var response = new DnsResponseMessage(new DnsResponseHeader(1, 256, 1, 1, 0, 0), 0);

            response.AddAnswer(record);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any)));
            var item = cache.Get("key");

            Assert.Equal(item, response.AsQueryResponse(new NameServer(IPAddress.Any)));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Performs an HTTP DELETE request on the <see cref="IEndpoint.Uri"/>. Sets <see cref="HttpRequestHeaders.IfMatch"/> if there is a cached ETag to detect lost updates.
        /// </summary>
        /// <param name="cancellationToken">Used to cancel the request.</param>
        /// <returns>The response message.</returns>
        /// <exception cref="InvalidDataException"><see cref="HttpStatusCode.BadRequest"/></exception>
        /// <exception cref="AuthenticationException"><see cref="HttpStatusCode.Unauthorized"/></exception>
        /// <exception cref="UnauthorizedAccessException"><see cref="HttpStatusCode.Forbidden"/></exception>
        /// <exception cref="KeyNotFoundException"><see cref="HttpStatusCode.NotFound"/> or <see cref="HttpStatusCode.Gone"/></exception>
        /// <exception cref="InvalidOperationException">The content has changed since it was last retrieved with <see cref="GetContentAsync"/>. Your changes were rejected to prevent a lost update.</exception>
        /// <exception cref="HttpRequestException">Other non-success status code.</exception>
        protected Task <HttpResponseMessage> DeleteContentAsync(CancellationToken cancellationToken)
        {
            var request = new HttpRequestMessage(HttpMethod.Delete, Uri);
            var cache   = ResponseCache; // Copy reference for thread-safety

            if (cache?.ETag != null)
            {
                request.Headers.IfMatch.Add(cache.ETag);
            }

            ResponseCache = null;
            return(HandleResponseAsync(HttpClient.SendAsync(request, cancellationToken)));
        }
Exemplo n.º 30
0
        public void Cache_DoesNotCacheIfZeroTTL()
        {
            var cache    = new ResponseCache(true);
            var record   = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 0, 100));
            var response = new DnsResponseMessage(new DnsResponseHeader(1, 256, 1, 1, 0, 0), 0);

            response.AddAnswer(record);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any)));
            var item = cache.Get("key");

            // should be null because ttl of the record is 0 which disables caching for this record
            Assert.Null(item);
        }
Exemplo n.º 31
0
        public void Cache_DoesNotCacheIfDisabled()
        {
            var cache    = new ResponseCache(false);
            var record   = new EmptyRecord(new ResourceRecordInfo("a", ResourceRecordType.A, QueryClass.IN, 100, 100));
            var response = new DnsResponseMessage(new DnsResponseHeader(1, 256, 1, 1, 0, 0), 0);

            response.AddAnswer(record);

            cache.Add("key", response.AsQueryResponse(new NameServer(IPAddress.Any)));
            var item = cache.Get("key");

            // should be null because cache is disabled and we create null in the second call of GetOrAdd
            Assert.Null(item);
        }
Exemplo n.º 32
0
        private async Task<ActionResult> ViewPatients(CancellationToken ct)
        {
            var cache = new ResponseCache<AgeBounds>(false, DefaultCacheTime.Long, _settings.ResponseCacheEnabled,
                _settings.ResponseCacheDefaultShortTimeInMinutes, _settings.ResponseCacheDefaultLongTimeInMinutes);
            var ageBounds = cache.GetValue(Request);
            if (ageBounds == null)
            {
                ageBounds = await _glanceDa.GetAgeBoundsAsync(_credentials, ct);
                cache.SetValue(Request, ageBounds);
            }

            var model = new PatientsViewModel
            {
                AgeMax = Math.Ceiling(ageBounds.Max).ToString(System.Globalization.CultureInfo.InvariantCulture),
                AgeMin = Math.Floor(ageBounds.Min).ToString(System.Globalization.CultureInfo.InvariantCulture),
            };
            return View(model);
        }