public static string GetModifiers(MethodMetadata model)
        {
            string type = null;

            type += model.Modifiers.AccessLevel.ToString().ToLower() + " ";
            type += model.Modifiers.AbstractEnum == AbstractEnum.Abstract ? AbstractEnum.Abstract.ToString().ToLower() + " " : String.Empty;
            type += model.Modifiers.StaticEnum == StaticEnum.Static ? StaticEnum.Static.ToString().ToLower() + " " : String.Empty;
            type += model.Modifiers.VirtualEnum == VirtualEnum.Virtual ? VirtualEnum.Virtual.ToString().ToLower() + " " : String.Empty;
            return(type);
        }
Example #2
0
        public void Can_add_header_parameter()
        {
            MethodMetadata metadata = new MethodMetadata();

            metadata.AddHeaderParameter("Header-Name", "Header-Value");

            WebRequest request = CreateRequest(metadata);

            Assert.AreEqual("Header-Value", request.Headers["Header-Name"]);
        }
Example #3
0
        public void Accept_header_defaults_to_consumes_property()
        {
            MethodMetadata metadata = new MethodMetadata();

            metadata.Consumes = "application/json";

            HttpWebRequest request = (HttpWebRequest)CreateRequest(metadata);

            Assert.AreEqual("application/json", request.Accept);
        }
Example #4
0
        internal MethodMetadata GetMethodMetadata(ActionModel actionModel, JsonRpcMethodOptions methodOptions)
        {
            var serializer     = Utils.GetSerializer(serializers, methodOptions.RequestSerializer);
            var controllerName = serializer.GetJsonName(actionModel.Controller.ControllerName);
            var actionName     = serializer.GetJsonName(actionModel.ActionName);
            var result         = new MethodMetadata(methodOptions, controllerName, actionName);

            log.LogTrace($"{actionModel.DisplayName}: metadata [{result}]");
            return(result);
        }
Example #5
0
        public void Full_uri_uses_service_path()
        {
            MethodMetadata meta = new MethodMetadata {
                ServicePath = "/service/1.0"
            };

            WebRequest request = CreateRequest(meta);

            Assert.AreEqual("http://example.com/service/1.0/", request.RequestUri.AbsoluteUri);
        }
Example #6
0
        public void Request_method_is_set_to_verb_property()
        {
            MethodMetadata metadata = new MethodMetadata {
                Verb = HttpVerb.DELETE
            };

            HttpWebRequest request = (HttpWebRequest)CreateRequest(metadata);

            Assert.AreEqual("DELETE", request.Method);
        }
Example #7
0
        public void Can_add_content_type_header()
        {
            MethodMetadata metadata = new MethodMetadata();

            metadata.AddHeaderParameter("Content-Type", "application/json");

            WebRequest request = CreateRequest(metadata);

            Assert.AreEqual("application/json", request.ContentType);
        }
Example #8
0
        public void Can_add_accept_header()
        {
            MethodMetadata metadata = new MethodMetadata();

            metadata.AddHeaderParameter("Accept", "application/json");

            HttpWebRequest request = (HttpWebRequest)CreateRequest(metadata);

            Assert.AreEqual("application/json", request.Accept);
        }
Example #9
0
 private static MethodDTG MethodDtg(MethodMetadata methodModel)
 {
     return(new MethodDTG()
     {
         Name = methodModel.Name,
         MetadataName = methodModel.MetadataName,
         SerReturnType = LoadType(methodModel.ReturnType),
         SerParameters = methodModel.Parameters?.Select(ParameterDtg).ToList()
     });
 }
Example #10
0
        private static DTGTypeMetadata EmitReturnTypeDTG(MethodMetadata method)
        {
            MethodMetadata methodInfo = method as MethodMetadata;

            if (methodInfo == null)
            {
                return(null);
            }
            return(TypeMapper.EmitReferenceDTG(methodInfo.ReturnType));
        }
 internal OverrideActionMethodSelector(List <MethodInfo> namedMethods)
 {
     _metadataList = new MethodMetadata[namedMethods.Count];
     for (int i = 0; i < namedMethods.Count; i++)
     {
         var            namedMethod = namedMethods[i];
         MethodMetadata metadata    = GetMethodMetadata(namedMethod);
         _metadataList[i] = metadata;
     }
 }
            public DelegateMetadata Build()
            {
                var methodMetadata = new MethodMetadata(
                    Lambda.Method,
                    Name,
                    hasInstance: true,
                    parameters: BuildParameterMetadatas()
                    );

                return(new DelegateMetadata(Lambda, methodMetadata));
            }
Example #13
0
        public void Test_GetActionName_ThrowsOnUnknown()
        {
            var matcher  = testEnvironment.ServiceProvider.GetRequiredService <MethodMatcher>();
            var metadata = new MethodMetadata(new JsonRpcMethodOptions()
            {
                MethodStyle = (MethodStyle)(-1)
            }, new JsonName("", ""), new JsonName("", ""));
            Action action = () => matcher.GetActionName(metadata);

            action.Should().Throw <ArgumentOutOfRangeException>();
        }
Example #14
0
        public void Test_GetActionName_ReturnsName(MethodStyle style, string expected)
        {
            var matcher  = testEnvironment.ServiceProvider.GetRequiredService <MethodMatcher>();
            var metadata = new MethodMetadata(new JsonRpcMethodOptions()
            {
                MethodStyle = style
            }, new JsonName("", "controller"), new JsonName("", "action"));
            var result = matcher.GetActionName(metadata);

            result.Should().Be(expected);
        }
Example #15
0
        public static TypeViewModelAbstract CreateTypeViewClass(MethodMetadata metadata)
        {
            switch (metadata)
            {
            case ConstructorMetadata constructorMetadata:
                return(new ConstructorViewModel(constructorMetadata));

            default:
                return(new MethodViewModel(metadata));
            }
        }
            private MethodMetadata GetMethodMetadata(MethodKey key)
            {
                MethodMetadata metadata;

                if (!MethodAttributes.TryGetValue(key, out metadata))
                {
                    metadata = new MethodMetadata(key.Parameters.Count);
                }

                return(metadata);
            }
Example #17
0
        public void Can_add_query_parameters_to_request()
        {
            MethodMetadata meta = new MethodMetadata();

            meta.AddQueryParameter("q", "test");
            meta.AddQueryParameter("q2", "test2");

            WebRequest request = CreateRequest(meta);

            Assert.AreEqual("http://example.com/?q=test&q2=test2", request.RequestUri.AbsoluteUri);
        }
        private object GetResult(MethodMetadata methodMetadata, IResponse response)
        {
            var responseMetadata = methodMetadata.Response;
            var responseType     = response.GetType();

            if (responseMetadata.ResultType.IsAssignableFrom(responseType))
            {
                return(response);
            }

            return(_modelMapper.MapResponse(methodMetadata.Response, response));
        }
Example #19
0
        public static IEnumerable <ParameterBinder> GetParameterBinders(this MethodMetadata method)
        {
            var binders = method.Attributes.OfType <ParameterBinderCollection>().FirstOrDefault();

            if (binders == null)
            {
                binders = new ParameterBinderCollection(CreateParameterBinders(method).ToArray());
                method.Attributes.Add(binders);
            }

            return(binders.Binders);
        }
Example #20
0
        public static DTGMethodMetadata MapToDTGModel(MethodMetadata methodMetadata)
        {
            DTGMethodMetadata methodModel = new DTGMethodMetadata
            {
                Name             = methodMetadata.Name,
                GenericArguments = TypeMapper.EmitGenericArgumentsDTG(methodMetadata.GenericArguments),
                ReturnType       = EmitReturnTypeDTG(methodMetadata),
                Parameters       = EmitParametersDTG(methodMetadata.Parameters),
            };

            return(methodModel);
        }
Example #21
0
        public void Test_IsMatch_ComparesIgnoreCase(string method, bool expected)
        {
            var matcher  = testEnvironment.ServiceProvider.GetRequiredService <MethodMatcher>();
            var metadata = new MethodMetadata(new JsonRpcMethodOptions()
            {
                MethodStyle = MethodStyle.ActionOnly
            }, new JsonName("", ""), new JsonName("", "action"));

            var result = matcher.IsMatch(metadata, method);

            result.Should().Be(expected);
        }
Example #22
0
        public void Method_path_is_appended_to_uri()
        {
            MethodMetadata meta = new MethodMetadata
            {
                ServicePath = "api/v1",
                MethodPath  = "/action"
            };

            WebRequest request = CreateRequest(meta);

            Assert.AreEqual("http://example.com/api/v1/action", request.RequestUri.AbsoluteUri);
        }
Example #23
0
        public static MethodMetadata MapToModel(DTGMethodMetadata methodMetadata)
        {
            MethodMetadata methodModel = new MethodMetadata
            {
                Name             = methodMetadata.Name,
                GenericArguments = TypeMapper.EmitGenericArgumentsModel(methodMetadata.GenericArguments),
                ReturnType       = EmitReturnTypeModel(methodMetadata),
                Parameters       = EmitParametersModel(methodMetadata.Parameters),
            };

            return(methodModel);
        }
Example #24
0
        public void Test_GetRpcBindingContext_ThrowsOnNoParameterMetadata()
        {
            var methodMetadata     = new MethodMetadata(new JsonRpcMethodOptions(), new JsonName("test", "test"), new JsonName("test", "test"));
            var bindingContextMock = MockContext(methodMetadata: methodMetadata);
            var binder             = testEnvironment.ServiceProvider.GetRequiredService <JsonRpcModelBinder>();

            Action action = () => binder.GetRpcBindingContext(bindingContextMock.Object, "test");

            action.Should().Throw <ArgumentNullException>();
            bindingContextMock.VerifyGet(x => x.HttpContext);
            bindingContextMock.VerifyGet(x => x.ActionContext);
        }
Example #25
0
        private TreeItem MapItem(MethodMetadata objectToMap)
        {
            bool hasChildren =
                objectToMap.GenericArguments.Any() ||
                objectToMap.Parameters.Any();

            return(new TreeItem(
                       $"{objectToMap.Modifiers.Item1} " +
                       $"{objectToMap.ReturnType?.Name ?? "void"} " +
                       $"{objectToMap.Name}",
                       hasChildren));
        }
Example #26
0
        /// <summary>
        /// Returns the test file that is associated with the
        /// given type
        /// </summary>
        /// <param name="methodMetadata">The type to determine the test file for</param>
        /// <returns>The test file that should contain the tests for the specified type</returns>
        public TestFile MapMethodToTestFile(MethodMetadata methodMetadata)
        {
            List <string> paths = new List <string>();

            paths.Add(BaseDirectory);
            paths.AddRange(methodMetadata.ParentType.Namespace.Split('.'));
            paths.Add(methodMetadata.Name + "Tests.cs");

            string pathToTestFile = Path.Combine(paths.ToArray());

            return(new TestFile(pathToTestFile));
        }
Example #27
0
        public void Test_ParseObject_ThrowsOnUnknownIfNotAllowed()
        {
            jsonRpcOptions.AllowRawResponses = false;
            var converter      = GetConverterMock();
            var serializerMock = new Mock <IJsonRpcSerializer>();

            serializerMock.Setup(x => x.Serializer)
            .Returns(new JsonSerializer());
            var    metadata = new MethodMetadata(new JsonRpcMethodOptions(), new JsonName("", ""), new JsonName("", ""));
            Action action   = () => converter.Object.ConvertActionResult(new FileContentResult(new byte[] { }, "application/octet-stream"), metadata, serializerMock.Object);

            action.Should().Throw <JsonRpcInternalException>();
        }
        private IRestRequest GetRequest(MethodMetadata methodMetadata, object[] args)
        {
            var bindingSource = new ModelBindingSource();

            foreach (var parameter in methodMetadata.MethodInfo.GetParameters())
            {
                var parameterValue = new RestValue(args[parameter.Position], parameter.ParameterType);

                bindingSource.AddValue(parameter.Name, parameterValue);
            }

            return(_modelMapper.MapRequest(methodMetadata.Request, bindingSource));
        }
Example #29
0
 private static MethodMetadata InstantiateMethodWithType(
     MethodMetadata methodTemplate,
     TypeMetadata typeMetadata)
 {
     return(new MethodMetadata(
                methodTemplate.Name,
                methodTemplate.ProtectionLevel,
                methodTemplate.IsStatic)
     {
         ReturnType = methodTemplate.ReturnType == s_arrayProbeTypeMetadata ? typeMetadata : methodTemplate.ReturnType,
         GenericParameters = InstantiateGenericParameterListWithType(methodTemplate.GenericParameters, typeMetadata)
     });
 }
Example #30
0
        public void Uri_is_escaped()
        {
            MethodMetadata meta = new MethodMetadata
            {
                MethodPath = "/users/{user}"
            };

            meta.AddPathParameter("user", "bart simpson");

            WebRequest request = CreateRequest(meta);

            Assert.AreEqual("http://example.com/users/bart%20simpson", request.RequestUri.AbsoluteUri);
        }
        public virtual void DeserializeAllMetadataAndCacheIt(Stream byteStream)
        {
            long initialStreamPostion = byteStream.Position;
            uint metadataByteCount = byteStream.DeserializeUint32();
            long metadataLastBytePosition = metadataByteCount + sizeof (uint) + initialStreamPostion;
            while (byteStream.Position < metadataLastBytePosition)
            {
                MetadataTypes metadataType = byteStream.DeserializeMetadataType();
                MetadataBase result = null;
                switch (metadataType)
                {
                    case MetadataTypes.AssemblyMetadata:
                        var assemblyMetadata = new AssemblyMetadata(byteStream);
                        _assemblyCache.Add(assemblyMetadata);
                        result = assemblyMetadata;
                        break;
                    case MetadataTypes.ModuleMedatada:
                        var moduleMetadata = new ModuleMetadata(byteStream, _assemblyCache);
                        _moduleCache.Add(moduleMetadata);
                        result = moduleMetadata;
                        break;
                    case MetadataTypes.ClassMedatada:
                        var classMetadata = new ClassMetadata(byteStream, _moduleCache);
                        _classCache.Add(classMetadata);
                        result = classMetadata;
                        break;
                    case MetadataTypes.MethodMedatada:
                        var methodMetadata = new MethodMetadata(byteStream, _classCache, _sourceLocatorFactory);
                        _methodCache.Add(methodMetadata);
                        result = methodMetadata;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                Contract.Assume(result != null);
                Contract.Assume(result.Id != 0);
                Contract.Assume(result.MdToken != 0);
                Contract.Assume(metadataType == result.MetadataType);
            }
        }
 public SamplingMethodAggregator(MethodMetadata methodMd)
 {
     FunctionId = methodMd.Id;
     MethodMd = methodMd;
 }
		/// <summary>
		///   Transforms the <paramref name="method" />.
		/// </summary>
		private static Ssm.Method Transform(MethodMetadata method)
		{
			var transformation = new MethodBodyTransformation(method.DeclaringObject);
			var methodBody = method.MethodBody;
			var locals = methodBody == null ? Enumerable.Empty<Ssm.Var>() : methodBody.LocalVariables.Select(Transform);
			var body = methodBody == null ? Ssm.Stm.NopStm : transformation.TransformMethodBody(methodBody.Body);

			Ssm.MethodKind kind;
			if (method is RequiredPortMetadata)
				kind = Ssm.MethodKind.ReqPort;
			else if (method is ProvidedPortMetadata || method is GuardMetadata || method is ActionMetadata)
				kind = Ssm.MethodKind.ProvPort;
			else if (method is FaultEffectMetadata) // TODO: Fault effects for non-provided ports
				kind = Ssm.MethodKind.ProvPort;
            else
				kind = Ssm.MethodKind.Step;

			return Ssm.CreateMethod(method.Name, method.MethodInfo.GetParameters().Select(Transform), body,
				Transform(method.MethodInfo.ReturnType), locals, kind);
		}
Example #34
0
		/// <summary>
		///     Recursively inlines all methods invoked within <paramref name="method" />'s body.
		/// </summary>
		/// <param name="method">The method which should have all invoked methods inlined.</param>
		public static MethodBodyMetadata Inline(MethodMetadata method)
		{
			Requires.NotNull(method, () => method);
			return Inline(method.MethodBody, _ => true);
		}
 public ISourceLocator GetSourceLocator(MethodMetadata methodMd)
 {
     return GetSourceLocator(methodMd.Class.Module.FilePath);
 }
 public ISourceLocator GetSourceLocator(MethodMetadata methodMd)
 {
     ISourceLocator sourceLocator = GetSourceLocator(methodMd.Class.Module.FilePath);
     return sourceLocator;
 }
        public void SetUp()
        {
            var mockModuleCache = new Mock<MetadataCache<ModuleMetadata>>(MockBehavior.Strict);
            mockModuleCache.Setup(cache => cache[It.IsAny<uint>()]).Returns(() => null);
            _classMetadata = new ClassMetadata(_classBytes.ConvertToMemoryStream(), mockModuleCache.Object);

            var mockClassCache = new Mock<MetadataCache<ClassMetadata>>(MockBehavior.Strict);
            mockClassCache.Setup(cache => cache[It.IsAny<uint>()]).Returns(_classMetadata);

            _mockMethodLine = new Mock<IMethodLine>(MockBehavior.Strict);
            _mockMethodLine.SetupGet(meLin => meLin.StartLine).Returns(12);
            _mockMethodLine.SetupGet(meLin => meLin.EndLine).Returns(12);
            _mockMethodLine.SetupGet(meLin => meLin.StartIndex).Returns(160);
            _mockMethodLine.SetupGet(meLin => meLin.EndIndex).Returns(220);
            _mockMethodLine.SetupGet(meLin => meLin.StartColumn).Returns(10);
            _mockMethodLine.SetupGet(meLin => meLin.EndColumn).Returns(70);

            var mockSourceLocator = new Mock<ISourceLocator>(MockBehavior.Strict);
            mockSourceLocator.Setup(soLoc => soLoc.GetMethodLines(It.IsAny<uint>())).Returns(
                new[]
                    {
                        _mockMethodLine.Object,
                        _mockMethodLine.Object,
                        _mockMethodLine.Object
                    });

            mockSourceLocator.Setup(soLoc => soLoc.GetSourceFilePath(It.IsAny<uint>())).Returns(SourceFilePath);

            _mockSourceLocatorFactory = new Mock<ISourceLocatorFactory>(MockBehavior.Strict);
            _mockSourceLocatorFactory.Setup(soFac => soFac.GetSourceLocator(It.IsAny<MethodMetadata>())).Returns(
                mockSourceLocator.Object);

            _methodMetadata1 = new MethodMetadata(_method1Bytes.ConvertToMemoryStream(), mockClassCache.Object,
                                                  _mockSourceLocatorFactory.Object);
            _methodMetadata2 = new MethodMetadata(_method2Bytes.ConvertToMemoryStream(), mockClassCache.Object,
                                                  _mockSourceLocatorFactory.Object);
            _methodMetadata3 = new MethodMetadata(_method3Bytes.ConvertToMemoryStream(), mockClassCache.Object,
                                                  _mockSourceLocatorFactory.Object);

            mockClassCache.Verify(cache => cache[It.IsAny<uint>()], Times.Exactly(3));
        }
 /// <summary>
 /// Dumps the specified Method metadata instance
 /// </summary>
 /// <param name="meth">The Method metadata to dump</param>
 internal void Dump(MethodMetadata meth)
 {
     Begin("MethodMetadata", "Name", meth.Name, "IsStatic", meth.IsStatic);
     Dump(meth.DefiningType, "DeclaringType");
     Dump(meth.Parameters);
     Dump(meth.Type, "ReturnType");
     End("MethodMetadata");
 }