Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="urls"></param>
        /// <param name="lookupURL"></param>
        /// <param name="token"></param>
        /// <param name="apiKey"></param>
        /// <param name="backendId"></param>
        /// <returns>todo: insert docstring</returns>
        /// <exception cref="HfException" >if Could not perform lookup and silentFailure is false</exception>
        public async Task <GenericLookupResult> RetrieveURLsWithUserToken(IList <Bo4eUri> urls, Uri lookupURL, string token, string apiKey, BOBackendId backendId)
        {
            GenericLookupQuery urlObject = new GenericLookupQuery()
            {
                Uris = urls
            };
            string requestBody = JsonConvert.SerializeObject(urlObject);
            var    request     = new HttpRequestMessage()
            {
                Content    = new StringContent(requestBody, System.Text.UTF8Encoding.UTF8, MIME_TYPE_JSON),
                Method     = HttpMethod.Post,
                RequestUri = lookupURL
            };
            var responseMessage = await httpClient.SendAsync(request);

            string responseContent = await responseMessage.Content.ReadAsStringAsync();

            if (!responseMessage.IsSuccessStatusCode)
            {
                _logger.LogCritical($"Could not perform lookup: {responseMessage.ReasonPhrase} / {responseContent}; The original request was: {requestBody} POSTed to {lookupURL}");
                _logger.LogDebug($"Returning null from lookup helper because of negative response code '{responseMessage.StatusCode}'");
                if (_silentFailure)
                {
                    return(null);
                }
                else
                {
                    throw new HfException(responseMessage);
                }
            }
            GenericLookupResult resultObject = DeserializeObjectAndLog <GenericLookupResult>(responseContent);

            return(resultObject);
        }
Пример #2
0
        public GenericDictionaryLookup ComputeGenericLookup(MethodDesc contextMethod, ReadyToRunHelperId lookupKind, object targetOfLookup)
        {
            GenericContextSource contextSource;

            if (contextMethod.RequiresInstMethodDescArg())
            {
                contextSource = GenericContextSource.MethodParameter;
            }
            else if (contextMethod.RequiresInstMethodTableArg())
            {
                contextSource = GenericContextSource.TypeParameter;
            }
            else
            {
                Debug.Assert(contextMethod.AcquiresInstMethodTableFromThis());
                contextSource = GenericContextSource.ThisObject;
            }

            // Can we do a fixed lookup? Start by checking if we can get to the dictionary.
            // Context source having a vtable with fixed slots is a prerequisite.
            if (contextSource == GenericContextSource.MethodParameter ||
                HasFixedSlotVTable(contextMethod.OwningType))
            {
                DictionaryLayoutNode dictionaryLayout;
                if (contextSource == GenericContextSource.MethodParameter)
                {
                    dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod);
                }
                else
                {
                    dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod.OwningType);
                }

                // If the dictionary layout has fixed slots, we can compute the lookup now. Otherwise defer to helper.
                if (dictionaryLayout.HasFixedSlots)
                {
                    int pointerSize = _nodeFactory.Target.PointerSize;

                    GenericLookupResult lookup = ReadyToRunGenericHelperNode.GetLookupSignature(_nodeFactory, lookupKind, targetOfLookup);
                    int dictionarySlot         = dictionaryLayout.GetSlotForEntry(lookup);
                    int dictionaryOffset       = dictionarySlot * pointerSize;

                    if (contextSource == GenericContextSource.MethodParameter)
                    {
                        return(GenericDictionaryLookup.CreateFixedLookup(contextSource, dictionaryOffset));
                    }
                    else
                    {
                        int vtableSlot   = VirtualMethodSlotHelper.GetGenericDictionarySlot(_nodeFactory, contextMethod.OwningType);
                        int vtableOffset = EETypeNode.GetVTableOffset(pointerSize) + vtableSlot * pointerSize;
                        return(GenericDictionaryLookup.CreateFixedLookup(contextSource, vtableOffset, dictionaryOffset));
                    }
                }
            }

            // Fixed lookup not possible - use helper.
            return(GenericDictionaryLookup.CreateHelperLookup(contextSource));
        }
Пример #3
0
        public async Task GetTypeByIdIsSuccessfulAndLogsInformation()
        {
            GenericLookupResult type = await _pokedexAPILogic.GetTypeById(0);

            Assert.AreEqual(0, type.Id);
            Assert.AreEqual("Name0", type.Name);

            _pokedexRepositoryMock.Verify(prm => prm.GetTypeById(0), Times.Once);

            _loggerAPIMock.Verify(lm => lm.LogInformation("Mapping Type Results."), Times.Once);
        }
Пример #4
0
        public async Task <IActionResult> GetCategoryById(int id)
        {
            GenericLookupResult category = await _pokedexAPILogic.GetCategoryById(id);

            if (category == null)
            {
                _logger.LogInformation(Constants.InvalidRequest + " for " + Constants.Category + Constants.WithId + id);

                return(BadRequest());
            }

            return(Ok(category));
        }
Пример #5
0
        public async Task <IActionResult> GetPokeballById(int id)
        {
            GenericLookupResult pokeball = await _pokedexAPILogic.GetPokeballById(id);

            if (pokeball == null)
            {
                _logger.LogInformation(Constants.InvalidRequest + " for " + Constants.Pokeball + Constants.WithId + id);

                return(BadRequest());
            }

            return(Ok(pokeball));
        }
Пример #6
0
        public GenericDictionaryLookup ComputeGenericLookup(MethodDesc contextMethod, ReadyToRunHelperId lookupKind, object targetOfLookup)
        {
            if (targetOfLookup is TypeSystemEntity typeSystemEntity)
            {
                _nodeFactory.TypeSystemContext.DetectGenericCycles(contextMethod, typeSystemEntity);
            }

            GenericContextSource contextSource;

            if (contextMethod.RequiresInstMethodDescArg())
            {
                contextSource = GenericContextSource.MethodParameter;
            }
            else if (contextMethod.RequiresInstMethodTableArg())
            {
                contextSource = GenericContextSource.TypeParameter;
            }
            else
            {
                Debug.Assert(contextMethod.AcquiresInstMethodTableFromThis());
                contextSource = GenericContextSource.ThisObject;
            }

            //
            // Some helpers represent logical concepts that might not be something that can be looked up in a dictionary
            //

            // Downgrade type handle for casting to a normal type handle if possible
            if (lookupKind == ReadyToRunHelperId.TypeHandleForCasting)
            {
                var type = (TypeDesc)targetOfLookup;
                if (!type.IsRuntimeDeterminedType ||
                    (!((RuntimeDeterminedType)type).CanonicalType.IsCanonicalDefinitionType(CanonicalFormKind.Universal) &&
                     !((RuntimeDeterminedType)type).CanonicalType.IsNullable))
                {
                    if (type.IsNullable)
                    {
                        targetOfLookup = type.Instantiation[0];
                    }
                    lookupKind = ReadyToRunHelperId.NecessaryTypeHandle;
                }
            }

            // We don't have separate entries for necessary type handles to avoid possible duplication
            if (lookupKind == ReadyToRunHelperId.NecessaryTypeHandle)
            {
                lookupKind = ReadyToRunHelperId.TypeHandle;
            }

            // Can we do a fixed lookup? Start by checking if we can get to the dictionary.
            // Context source having a vtable with fixed slots is a prerequisite.
            if (contextSource == GenericContextSource.MethodParameter ||
                HasFixedSlotVTable(contextMethod.OwningType))
            {
                DictionaryLayoutNode dictionaryLayout;
                if (contextSource == GenericContextSource.MethodParameter)
                {
                    dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod);
                }
                else
                {
                    dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod.OwningType);
                }

                // If the dictionary layout has fixed slots, we can compute the lookup now. Otherwise defer to helper.
                if (dictionaryLayout.HasFixedSlots)
                {
                    int pointerSize = _nodeFactory.Target.PointerSize;

                    GenericLookupResult lookup = ReadyToRunGenericHelperNode.GetLookupSignature(_nodeFactory, lookupKind, targetOfLookup);
                    int dictionarySlot         = dictionaryLayout.GetSlotForFixedEntry(lookup);
                    if (dictionarySlot != -1)
                    {
                        int dictionaryOffset = dictionarySlot * pointerSize;

                        bool indirectLastOffset = lookup.LookupResultReferenceType(_nodeFactory) == GenericLookupResultReferenceType.Indirect;

                        if (contextSource == GenericContextSource.MethodParameter)
                        {
                            return(GenericDictionaryLookup.CreateFixedLookup(contextSource, dictionaryOffset, indirectLastOffset: indirectLastOffset));
                        }
                        else
                        {
                            int vtableSlot   = VirtualMethodSlotHelper.GetGenericDictionarySlot(_nodeFactory, contextMethod.OwningType);
                            int vtableOffset = EETypeNode.GetVTableOffset(pointerSize) + vtableSlot * pointerSize;
                            return(GenericDictionaryLookup.CreateFixedLookup(contextSource, vtableOffset, dictionaryOffset, indirectLastOffset: indirectLastOffset));
                        }
                    }
                }
            }

            // Fixed lookup not possible - use helper.
            return(GenericDictionaryLookup.CreateHelperLookup(contextSource, lookupKind, targetOfLookup));
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="urls"></param>
        /// <param name="lookupURL"></param>
        /// <param name="clientCertString"></param>
        /// <param name="apiKey"></param>
        /// <param name="backendId"></param>
        /// <returns></returns>
        /// <exception cref="HfException" >if Could not perform lookup and silentFailure is false</exception>

        public async Task <GenericLookupResult> RetrieveURLs(IList <Bo4eUri> urls, Uri lookupURL, string clientCertString, string apiKey, BOBackendId backendId, string correlationId = null)
        {
            if (string.IsNullOrWhiteSpace(clientCertString))
            {
                _logger.LogWarning($"{nameof(clientCertString)} is initial: '{clientCertString}'");
            }
            if (lookupURL == null)
            {
                _logger.LogCritical($"{nameof(lookupURL)} is null!");
            }

            GenericLookupQuery urlObject = new GenericLookupQuery()
            {
                Uris = urls
            };
            string requestBody = JsonConvert.SerializeObject(urlObject, new StringEnumConverter());
            var    request     = new HttpRequestMessage()
            {
                Content    = new StringContent(requestBody, System.Text.UTF8Encoding.UTF8, MIME_TYPE_JSON),
                RequestUri = lookupURL,
                Method     = HttpMethod.Post
            };

            if (request.Headers.Contains(HeaderNames.Auth.XArrClientCert))
            {
                _logger.LogDebug($"Removing header '{HeaderNames.Auth.XArrClientCert}'");
                request.Headers.Remove(HeaderNames.Auth.XArrClientCert);
            }

            request.Headers.Add(HeaderNames.Auth.XArrClientCert, clientCertString);
            if (request.Headers.Contains(HeaderNames.Azure.SUBSCRIPTION_KEY))
            {
                _logger.LogDebug($"Removing header '{HeaderNames.Azure.SUBSCRIPTION_KEY}'");
                request.Headers.Remove(HeaderNames.Azure.SUBSCRIPTION_KEY);
            }
            if (!string.IsNullOrEmpty(apiKey))
            {
                _logger.LogDebug($"Adding {HeaderNames.Azure.SUBSCRIPTION_KEY} header");
                request.Headers.Add(HeaderNames.Azure.SUBSCRIPTION_KEY, apiKey);
            }
            else
            {
                _logger.LogWarning($"{nameof(apiKey)} is initial: '{apiKey}'");
            }
            if (request.Headers.Contains(HeaderNames.BACKEND_ID))
            {
                _logger.LogDebug($"Removing {HeaderNames.BACKEND_ID} header");
                request.Headers.Remove(HeaderNames.BACKEND_ID);
            }
            request.Headers.Add(HeaderNames.BACKEND_ID, backendId.ToString());

            if (request.Headers.Contains("x-correlation-id"))
            {
                _logger.LogDebug($"Removing header 'x-correlation-id'");
                request.Headers.Remove("x-correlation-id");
            }
            if (!string.IsNullOrEmpty(correlationId))
            {
                _logger.LogDebug($"Adding x-correlation-id header");
                request.Headers.Add("x-correlation-id", correlationId);
            }

            var responseMessage = await httpClient.SendAsync(request);

            if (!responseMessage.IsSuccessStatusCode)
            {
                string responseContentPost = await responseMessage.Content.ReadAsStringAsync();

                _logger.LogCritical($"Could not perform lookup: {responseMessage.ReasonPhrase} / {responseContentPost}; The original request was: {requestBody} POSTed to {lookupURL}");
                if (_silentFailure)
                {
                    return(null);
                }
                else
                {
                    throw new HfException(responseMessage);
                }
            }

            string responseContent = await responseMessage.Content.ReadAsStringAsync();

            GenericLookupResult resultObject = DeserializeObjectAndLog <GenericLookupResult>(responseContent);

            return(resultObject);
        }