public void Test_ParseNull_ChecksBindingStyle(BindingStyle bindingStyle, Type expectedType)
        {
            var result = paramsParserMock.Object.ParseNull(bindingStyle);

            result.Should().BeOfType(expectedType);
            paramsParserMock.Verify(x => x.ParseNull(bindingStyle));
            paramsParserMock.VerifyNoOtherCalls();
        }
 public ParameterMetadata(JsonName name, Type type, int index, BindingStyle bindingStyle, bool isOptional)
 {
     Name         = name ?? throw new ArgumentNullException(nameof(name));
     Type         = type;
     Index        = index;
     BindingStyle = bindingStyle;
     IsOptional   = isOptional;
 }
Ejemplo n.º 3
0
        public IDiBinding AsSingleton(Type to)
        {
            // configure
            ToType = to;
            Style  = BindingStyle.BySingleton;

            // return
            return(this);
        }
        public void Test_ParseObject_ReturnsResult(JObject jObject, string property, BindingStyle style, IParseResult expected)
        {
            var result = paramsParserMock.Object.ParseObject(jObject, property, style);

            result.Should().BeOfType(expected.GetType());
            result.Should().BeEquivalentTo(expected, options =>
                                           options.Excluding(x => x.Type == typeof(ErrorParseResult) && x.Name == nameof(ErrorParseResult.Message))
                                           );
            paramsParserMock.Verify(x => x.ParseObject(jObject, property, style));
            paramsParserMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 5
0
        public IDiBinding AsConversion <TO>(Func <object, object> converter)
        {
            // Conversion is reversed, from becomes the type.
            ConversionFrom = typeof(TO);
            Style          = BindingStyle.ByConversion;
            Conversion     = converter;
            ConversionTo   = FromType;

            //return
            return(this);
        }
Ejemplo n.º 6
0
        public void Test_ParseArray_ReturnsResult(JArray jArray, int index, BindingStyle style, IParseResult expected)
        {
            var result = paramsParserMock.Object.ParseArray(jArray, index, style);

            result.Should().BeOfType(expected.GetType());
            result.Should().BeEquivalentTo(expected, options =>
                                           options.Excluding(x => x.RuntimeType == typeof(ErrorParseResult) && x.SelectedMemberInfo.Name == nameof(ErrorParseResult.Message))
                                           );
            paramsParserMock.Verify(x => x.ParseArray(jArray, index, style));
            paramsParserMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 7
0
        internal static MethodObjectParamStructure ToParamStructure(this BindingStyle bindingStyle)
        {
            switch (bindingStyle)
            {
            case BindingStyle.Default:
                return(MethodObjectParamStructure.Either);

            case BindingStyle.Object:
                return(MethodObjectParamStructure.ByName);

            case BindingStyle.Array:
                return(MethodObjectParamStructure.ByPosition);

            default:
                throw new ArgumentOutOfRangeException(nameof(bindingStyle), bindingStyle, null);
            }
        }
Ejemplo n.º 8
0
        public void Test_GetRpcParameterInfo_UsesAttributes(BindingStyle bindingStyle)
        {
            var attribute       = new FromParamsAttribute(bindingStyle);
            var serializerType  = typeof(SnakeCaseJsonRpcSerializer);
            var controllerModel = new Mock <ControllerModel>(typeof(JsonRpcTestController).GetTypeInfo(), new List <object>()).Object;
            var actionModel     = new Mock <ActionModel>(typeof(JsonRpcTestController).GetMethod(nameof(JsonRpcTestController.VoidAction)), new List <object>()).Object;
            var model           = new Mock <ParameterModel>(typeof(JsonRpcTestController).GetMethod(nameof(JsonRpcTestController.VoidAction)).GetParameters()[0], new List <object> {
                attribute
            }).Object;

            actionModel.Controller = controllerModel;
            model.Action           = actionModel;
            var parameterConvention = testEnvironment.ServiceProvider.GetRequiredService <ParameterConvention>();

            var result = parameterConvention.GetParameterMetadata(model, serializerType);

            result.BindingStyle.Should().Be(bindingStyle);
        }
Ejemplo n.º 9
0
        protected internal virtual IParseResult ParseNull(BindingStyle bindingStyle)
        {
            switch (bindingStyle)
            {
            case BindingStyle.Default:
                log.LogWarning($"Binding null to regular parameter failed");
                return(new ErrorParseResult("Can not bind method arguments from [null] json params", string.Empty));

            case BindingStyle.Object:
            case BindingStyle.Array:
                // this is fine
                log.LogTrace($"Binding null to object or array parameter");
                return(new NullParseResult(string.Empty));

            default:
                log.LogWarning($"Binding null failed");
                return(new ErrorParseResult($"Unknown {nameof(bindingStyle)} [{bindingStyle}]", string.Empty));
            }
        }
Ejemplo n.º 10
0
        protected internal virtual IParseResult ParseArray(JArray jArray, int index, BindingStyle bindingStyle)
        {
            var indexString = index.ToString();

            switch (bindingStyle)
            {
            case BindingStyle.Default:
                // map array items to args by indices
                if (index < jArray.Count)
                {
                    var value = jArray[index];
                    if (value.Type == JTokenType.Null)
                    {
                        log.LogTrace($"Json value for binding by index [{indexString}] is null");
                        return(new NullParseResult(indexString));
                    }

                    log.LogTrace($"Json value for binding by index [{indexString}] found");
                    return(new SuccessParseResult(value, indexString));
                }
                else
                {
                    log.LogTrace($"Json value for binding by index [{indexString}] not found");
                    return(new NoParseResult(indexString));
                }

            case BindingStyle.Object:
                log.LogWarning($"Can not bind json array to object for [{indexString}]");
                return(new ErrorParseResult("Can not bind array to object parameter", indexString));

            case BindingStyle.Array:
                // map 1:1 to collection
                log.LogTrace($"Binding whole json array to [{indexString}]");
                return(new SuccessParseResult(jArray, indexString));

            default:
                log.LogWarning($"Binding failed for index [{indexString}]");
                return(new ErrorParseResult($"Unknown {nameof(bindingStyle)} [{bindingStyle}]", indexString));
            }
        }
        internal void ValidateParameter(ParameterModel parameterModel, BindingStyle bindingStyle)
        {
            var isCollection = Common.Utils.IsCollection(parameterModel.ParameterType);

            switch (bindingStyle)
            {
            case BindingStyle.Default:
                return;

            case BindingStyle.Object:
                // meh, dont want to check if complex type
                return;

            case BindingStyle.Array:
                if (!isCollection)
                {
                    throw new ArgumentOutOfRangeException(parameterModel.Name, parameterModel.ParameterType.Name, $"[{nameof(BindingStyle)}.{nameof(BindingStyle.Array)}] only works with collections. Change signature of [{parameterModel.Action.Controller.ControllerName}.{parameterModel.Action.ActionName}]");
                }
                return;

            default:
                throw new ArgumentOutOfRangeException(nameof(bindingStyle), bindingStyle, null);
            }
        }
 public FromParamsAttribute(BindingStyle bindingStyle)
 {
     BindingStyle = bindingStyle;
 }
Ejemplo n.º 13
0
        /// <summary>
        /// For a given wsdl service operation, generate an Rpc or document style wrapped data contract
        /// and data contract serializer.
        /// </summary>
        /// <param name="BindingStyle">A flag indicating the binding style.</param>
        /// <param name="operationMessage">A OperationMessage type containing an OperationInput or OperationOutput type.</param>
        /// <param name="messageParts">A collection of message parts used by the operation.</param>
        /// <param name="messageTypes">An arraylist of message elements and or types used by the operation.</param>
        private void GenerateWrappedContracts(BindingStyle bindingStyle, OperationMessage operationMessage, MessagePartCollection messageParts, ArrayList messageTypes)
        {
            if (messageTypes.Count == 0)
                return;
            
            // Rules: Rpc/Literal support only. WS-I basic profile Rpc/Literal rules apply.
            
            // Create a temporary wrapper element type that will be used to wrap the message parts.
            // As per rpc/literal spec the name of the type is the name of the operation
            // If the message is a response the name = the operation name + "Response".
            // The temporary wrapper element is stored in a new schema that will be added to the existing
            // ServiceDescription schema set and recompiled to resolve all type references.
            XmlSchema schema = operationMessage.Operation.PortType.ServiceDescription.Types.Schemas[0];
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            XmlSchemaElement wrapperElement = new XmlSchemaElement();
            schema.Items.Add(wrapperElement);
            string elementName = operationMessage.Operation.Name;
            elementName = operationMessage is OperationOutput ? elementName + "Response" : elementName + "Request";
            wrapperElement.Name = elementName;

            // The element namespace is the target namespace by default else it is 
            // defined by the binding/operation/soap12Body/namespace attribute
            schema.TargetNamespace = CodeGenUtils.GetOperationNamespace(operationMessage);

            // Add a new complex type to the element
            XmlSchemaComplexType complexType = new XmlSchemaComplexType();
            wrapperElement.SchemaType = complexType;

            // Add a sequence particles to the complex type
            XmlSchemaSequence sequence = new XmlSchemaSequence();
            complexType.Particle = sequence;

            // Loop through the list of parts and add thier definitions to the sequence
            for (int i = 0; i < messageTypes.Count; ++i)
            {
                if (bindingStyle == BindingStyle.Rpc)
                {
                    XmlSchemaElement typeElement = new XmlSchemaElement();
                    typeElement.Name = messageParts[i].Name;
                    typeElement.SchemaTypeName = new XmlQualifiedName(messageParts[i].Type.Name, messageParts[i].Type.Namespace);
                    sequence.Items.Add(typeElement);
                    schema.Items.Add((XmlSchemaType)messageTypes[i]);
                }
                else
                    sequence.Items.Add((XmlSchemaElement)messageTypes[i]);
            }

            // Add the new schema containing the new element to a set and compile
            schemaSet.Add(schema);
            schemaSet.Compile();

            // Build the new element and serializer
            CodeTypeDeclaration codeType = new CodeTypeDeclaration();
            CodeNamespace codeNs = CodeGenUtils.GetDotNetNamespace(m_codeNamespaces, wrapperElement.QualifiedName.Namespace);
            BuildElementType(wrapperElement, codeType);
            if (!CodeGenUtils.TypeExists(codeNs, codeType.Name))
            {
                codeNs.Types.Add(codeType);
                m_dcsCodeGen.BuildDataContractSerializer(m_encodingType, codeType, codeNs);
            }

            // Swap the existing message parts with a new replacement part. All subsequent processing
            // will use the new single message part
            foreach (Message message in operationMessage.Operation.PortType.ServiceDescription.Messages)
            {
                if (message.Name == operationMessage.Message.Name)
                {
                    MessagePart replacementPart = new MessagePart();
                    replacementPart.Element = new XmlQualifiedName(elementName);
                    replacementPart.Type = wrapperElement.QualifiedName;
                    replacementPart.Name = operationMessage.Name;
                    replacementPart.Namespaces = operationMessage.Namespaces;
                    message.Parts.Clear();
                    message.Parts.Add(replacementPart);
                    break;
                }
            }
        }
Ejemplo n.º 14
0
        protected internal virtual IParseResult ParseObject(JObject jObject, string jsonProperty, BindingStyle bindingStyle)
        {
            switch (bindingStyle)
            {
            case BindingStyle.Default:
                // map keys to args by names
                if (jObject.ContainsKey(jsonProperty))
                {
                    var value = jObject[jsonProperty];
                    if (value.Type == JTokenType.Null)
                    {
                        log.LogTrace($"Json value for binding [{jsonProperty}] is null");
                        return(new NullParseResult(jsonProperty));
                    }
                    log.LogTrace($"Json value for binding [{jsonProperty}] found");
                    return(new SuccessParseResult(value, jsonProperty));
                }
                else
                {
                    log.LogTrace($"Json value for binding [{jsonProperty}] not found");
                    return(new NoParseResult(jsonProperty));
                }

            case BindingStyle.Object:
                // map 1:1 to object
                log.LogTrace($"Binding whole json object to [{jsonProperty}]");
                return(new SuccessParseResult(jObject, jsonProperty));

            case BindingStyle.Array:
                log.LogTrace($"Can not bind json object to array for [{jsonProperty}]");
                return(new ErrorParseResult("Can not bind object to collection parameter", jsonProperty));

            default:
                log.LogWarning($"Binding failed for [{jsonProperty}]");
                return(new ErrorParseResult($"Unknown {nameof(bindingStyle)} [{bindingStyle}]", jsonProperty));
            }
        }