Example #1
0
        /// <summary>
        /// Get UriTemplate for operation
        /// </summary>
        /// <param name="operationDescription"></param>
        /// <returns></returns>
        public static string GetUriTemplate(OperationDescription operationDescription)
        {
            WebGetAttribute    webGet    = GetWebGet(operationDescription);
            WebInvokeAttribute webInvoke = GetWebInvoke(operationDescription);

            if (webGet != null)
            {
                if (webGet.UriTemplate != null)
                {
                    return(webGet.UriTemplate);
                }
                StringBuilder stringBuilder = new StringBuilder(operationDescription.Name);
                if (!IsUntypedMessage(operationDescription.Messages[0]))
                {
                    stringBuilder.Append("?");
                    foreach (MessagePartDescription mpd in operationDescription.Messages[0].Body.Parts)
                    {
                        string parameterName = mpd.Name;
                        stringBuilder.Append(parameterName);
                        stringBuilder.Append("={");
                        stringBuilder.Append(parameterName);
                        stringBuilder.Append("}&");
                    }
                    stringBuilder.Remove(stringBuilder.Length - 1, 1);
                }
                return(stringBuilder.ToString());
            }
            return(webInvoke.UriTemplate ?? operationDescription.Name);
        }
Example #2
0
        //[WebGet(UriTemplate = "help{operation}/request/example")]
        public Message GetRequestExample(string operation)
        {
            foreach (OperationDescription od in this.Description.Operations)
            {
                if (od.Name == operation)
                {
                    bool    isXmlSerializerType;
                    Type    body = GetRequestBodyType(od, out isXmlSerializerType);
                    Message result;
                    if (IsBodySpecial(body, "request", out result))
                    {
                        return(result);
                    }

                    WebInvokeAttribute invoke = od.Behaviors.Find <WebInvokeAttribute>();
                    bool generateJson         = false;
                    if (GetResponseFormat(null, invoke, od) == "Json")
                    {
                        generateJson = true;
                    }
                    try
                    {
                        return(CreateExample(body, od, generateJson));
                    }
                    catch (Exception e)
                    {
                        return(CreateTextMessage(String.Format("Could not generate example for request. Failed with error: {0}", e.Message)));
                    }
                }
            }
            return(null);
        }
Example #3
0
        public static string GetUriTemplateString(this HttpOperationDescription operation)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            WebGetAttribute    webGet    = operation.GetWebGetAttribute();
            WebInvokeAttribute webInvoke = operation.GetWebInvokeAttribute();

            if (webGet != null && webGet.UriTemplate != null)
            {
                return(webGet.UriTemplate);
            }

            if (webInvoke != null && webInvoke.UriTemplate != null)
            {
                return(webInvoke.UriTemplate);
            }

            if (operation.GetWebMethod() == "GET")
            {
                return(GetDefaultWebGetUriTemplate(operation));
            }

            return(operation.Name);
        }
Example #4
0
        /// <summary>
        /// Get request Body Type if any
        /// </summary>
        /// <param name="operationDescription"></param>
        /// <param name="isXmlSerializerType"></param>
        /// <returns></returns>
        public static Type GetRequestBodyType(OperationDescription operationDescription, out bool isXmlSerializerType)
        {
            isXmlSerializerType = (GetXmlSerializerBehavior(operationDescription) != null);

            //There is no request body if this WebGet
            if (GetWebGet(operationDescription) != null)
            {
                return(null);
            }

            WebInvokeAttribute invoke        = GetWebInvoke(operationDescription);
            List <string>      uriParameters = new List <string>();

            if (invoke.UriTemplate != null)
            {
                UriTemplate template = new UriTemplate(invoke.UriTemplate);

                foreach (string pathVariable in template.PathSegmentVariableNames)
                {
                    uriParameters.Add(pathVariable);
                }

                foreach (string queryVariable in template.QueryValueVariableNames)
                {
                    uriParameters.Add(queryVariable);
                }
            }

            if (operationDescription.Messages[0].MessageType != null)
            {
                return(null);
            }

            List <Type> bodyParts = new List <Type>();

            foreach (MessagePartDescription messagePart in operationDescription.Messages[0].Body.Parts)
            {
                bool isUriPart = false;
                foreach (string var in uriParameters)
                {
                    if (String.Equals(var, messagePart.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        isUriPart = true;
                        break;
                    }
                }
                if (isUriPart)
                {
                    continue;
                }

                bodyParts.Add(messagePart.Type);
            }
            if ((bodyParts.Count == 0) || (bodyParts.Count > 1))
            {
                return(null);
            }

            return(bodyParts[0]);
        }
        internal static void AddPreflightOperations(ServiceEndpoint endpoint, List <OperationDescription> corsOperations)
        {
            Dictionary <string, PreflightOperationBehavior> uriTemplates = new Dictionary <string, PreflightOperationBehavior>(StringComparer.OrdinalIgnoreCase);

            //
            foreach (OperationDescription operation in corsOperations)
            {
                if (operation.Behaviors.Find <WebGetAttribute>() != null || operation.IsOneWay == true)
                {
                    // no need to add preflight operation for GET requests, no support for 1-way messages
                    continue;
                }
                //
                WebInvokeAttribute originalWia         = operation.Behaviors.Find <WebInvokeAttribute>();
                string             originalUriTemplate = ((originalWia != null && originalWia.UriTemplate != null) ? NormalizeTemplate(originalWia.UriTemplate) : operation.Name);
                //
                string originalMethod = ((originalWia != null && originalWia.Method != null) ? originalWia.Method : "POST");
                if (uriTemplates.ContainsKey(originalUriTemplate) == true)
                {
                    // there is already an OPTIONS operation for this URI, we can reuse it
                    PreflightOperationBehavior operationBehavior = uriTemplates[originalUriTemplate];
                    operationBehavior.AddAllowedMethod(originalMethod);
                }
                else
                {
                    ContractDescription        contract = operation.DeclaringContract;
                    PreflightOperationBehavior preflightOperationBehavior = null;
                    OperationDescription       preflightOperation         = CreatePreflightOperation(operation, originalUriTemplate, originalMethod, out preflightOperationBehavior);
                    uriTemplates.Add(originalUriTemplate, preflightOperationBehavior);
                    //
                    contract.Operations.Add(preflightOperation);
                }
            }
        }
Example #6
0
        private void CheckBodyStyle(OperationDescription operationDescription, bool isRequest)
        {
            WebInvokeAttribute wia = operationDescription.Behaviors.Find <WebInvokeAttribute>();
            WebGetAttribute    wga = operationDescription.Behaviors.Find <WebGetAttribute>();

            CheckWebInvokeAndWebGet(wia, wga, operationDescription);

            WebMessageBodyStyle bodyStyle = this.DefaultBodyStyle;

            if (wia != null && wia.IsBodyStyleSetExplicitly)
            {
                bodyStyle = wia.BodyStyle;
            }
            else if (wga != null && wga.IsBodyStyleSetExplicitly)
            {
                bodyStyle = wga.BodyStyle;
            }

            if (isRequest)
            {
                if (wga == null && (bodyStyle == WebMessageBodyStyle.Wrapped || bodyStyle == WebMessageBodyStyle.WrappedRequest))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FormEncodedMustBeBare));
                }
            }
            else
            {
                if (bodyStyle == WebMessageBodyStyle.Wrapped || bodyStyle == WebMessageBodyStyle.WrappedResponse)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FormEncodedMustBeBare));
                }
            }
        }
Example #7
0
        protected override object CreateBehavior()
        {
            foreach (OperationElement op in Operations)
            {
                string method = op.Method.ToUpper();
                if (method == "GET")
                {
                    WebGetAttribute webOpBeh = new WebGetAttribute();
                    webOpBeh.UriTemplate    = op.UriTemplate;
                    webOpBeh.RequestFormat  = op.RequestFormat;
                    webOpBeh.ResponseFormat = op.ResponseFormat;
                    RESTOperationBehaviors.Add(op.Name, webOpBeh);
                }
                else if (method == "POST" || method == "DELETE" || method == "PUT")
                {
                    WebInvokeAttribute webInvBeh = new WebInvokeAttribute();
                    webInvBeh.UriTemplate    = op.UriTemplate;
                    webInvBeh.Method         = op.Method;
                    webInvBeh.RequestFormat  = op.RequestFormat;
                    webInvBeh.ResponseFormat = op.ResponseFormat;

                    RESTOperationBehaviors.Add(op.Name, webInvBeh);
                }
            }
            RestChangerBehavior beh = new RestChangerBehavior(RESTOperationBehaviors);

            return(beh);
        }
Example #8
0
 private static void TryGetSurrogateBehavior(OperationDescription operationDescription, ref IOperationBehavior original, ref IOperationBehavior surrogate)
 {
     if (!IsUntypedMessage(operationDescription.Messages[0]) &&
         operationDescription.Messages[0].Body.Parts.Count != 0)
     {
         var webGetAttribute = operationDescription.Behaviors.Find <WebGetAttribute>();
         if (webGetAttribute != null)
         {
             original  = webGetAttribute;
             surrogate = new WebInvokeAttribute {
                 BodyStyle      = webGetAttribute.BodyStyle,
                 Method         = "NONE",
                 RequestFormat  = webGetAttribute.RequestFormat,
                 ResponseFormat = webGetAttribute.ResponseFormat,
                 UriTemplate    = webGetAttribute.UriTemplate
             };
         }
         else
         {
             var webInvokeAttribute = operationDescription.Behaviors.Find <WebInvokeAttribute>();
             if (webInvokeAttribute != null && webInvokeAttribute.Method == "GET")
             {
                 original  = webInvokeAttribute;
                 surrogate = new WebInvokeAttribute {
                     BodyStyle      = webInvokeAttribute.BodyStyle,
                     Method         = "NONE",
                     RequestFormat  = webInvokeAttribute.RequestFormat,
                     ResponseFormat = webInvokeAttribute.ResponseFormat,
                     UriTemplate    = webInvokeAttribute.UriTemplate
                 };
             }
         }
     }
 }
Example #9
0
 private static void CheckWebInvokeAndWebGet(WebInvokeAttribute wia, WebGetAttribute wga, OperationDescription operationDescription)
 {
     if (wga != null && wia != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(DiagnosticUtility.GetString(SR.OperationContractConflictsWebGetOrWebInvoke, operationDescription.Name)));
     }
 }
        private static void CreatePreflightOperation(OperationDescription operation, string originalUriTemplate, string originalMethod, ContractDescription contract, out OperationDescription preflightOperation, out PreflightOperationBehavior preflightOperationBehavior)
        {
            preflightOperation = new OperationDescription(operation.Name + CorsConstants.PreflightSuffix, contract);
            MessageDescription inputMessage = new MessageDescription(operation.Messages[0].Action + CorsConstants.PreflightSuffix, MessageDirection.Input);

            inputMessage.Body.Parts.Add(new MessagePartDescription("input", contract.Namespace)
            {
                Index = 0, Type = typeof(Message)
            });
            preflightOperation.Messages.Add(inputMessage);
            MessageDescription outputMessage = new MessageDescription(operation.Messages[1].Action + CorsConstants.PreflightSuffix, MessageDirection.Output);

            outputMessage.Body.ReturnValue = new MessagePartDescription(preflightOperation.Name + "Return", contract.Namespace)
            {
                Type = typeof(Message)
            };
            preflightOperation.Messages.Add(outputMessage);

            WebInvokeAttribute wia = new WebInvokeAttribute();

            wia.UriTemplate = originalUriTemplate;
            wia.Method      = "OPTIONS";

            preflightOperation.Behaviors.Add(wia);
            preflightOperation.Behaviors.Add(new DataContractSerializerOperationBehavior(preflightOperation));
            preflightOperationBehavior = new PreflightOperationBehavior(preflightOperation);
            preflightOperationBehavior.AddAllowedMethod(originalMethod);
            preflightOperation.Behaviors.Add(preflightOperationBehavior);
        }
Example #11
0
 protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
     foreach (OperationDescription od in endpoint.Contract.Operations)
     {
         WebMessageFormat outgoingFormat = WebMessageFormat.Xml;
         WebGetAttribute  getAttr        = od.Behaviors.Find <WebGetAttribute>();
         if (getAttr != null)
         {
             outgoingFormat = (getAttr.IsResponseFormatSetExplicitly) ? getAttr.ResponseFormat : base.DefaultOutgoingResponseFormat;
         }
         else
         {
             WebInvokeAttribute invokeAttr = od.Behaviors.Find <WebInvokeAttribute>();
             if (invokeAttr != null)
             {
                 outgoingFormat = (invokeAttr.IsResponseFormatSetExplicitly) ? invokeAttr.ResponseFormat : base.DefaultOutgoingResponseFormat;
             }
         }
         endpointDispatcher.DispatchRuntime.Operations[od.Name].ParameterInspectors.Add(new ResponseWebFormatPropertyAttacher()
         {
             Format = outgoingFormat
         });
     }
     endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new WebErrorHandler()
     {
         EnableAspNetCustomErrors = this.EnableAspNetCustomErrors
     });
 }
        protected override IClientMessageFormatter GetRequestClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            if (operationDescription.Behaviors.Find <WebGetAttribute>() != null)
            {
                // no change for GET operations
                return(base.GetRequestClientFormatter(operationDescription, endpoint));
            }
            else
            {
                WebInvokeAttribute wia = operationDescription.Behaviors.Find <WebInvokeAttribute>();
                if (wia != null)
                {
                    if (wia.Method == "HEAD")
                    {
                        // essentially a GET operation
                        return(base.GetRequestClientFormatter(operationDescription, endpoint));
                    }
                }
            }

            if (operationDescription.Messages[0].Body.Parts.Count == 0)
            {
                // nothing in the body, still use the default
                return(base.GetRequestClientFormatter(operationDescription, endpoint));
            }

            return(new NewtonsoftJsonClientFormatter(operationDescription, endpoint));
        }
 private static void EnsureOk(WebGetAttribute wga, WebInvokeAttribute wia, OperationDescription od)
 {
     if (wga != null && wia != null)
     {
         throw new InvalidOperationException();
     }
 }
Example #14
0
 private static bool IsResponseWrapped(WebGetAttribute wg, WebInvokeAttribute wi)
 {
     return((wg != null) &&
            (wg.BodyStyle == WebMessageBodyStyle.Wrapped || wg.BodyStyle == WebMessageBodyStyle.WrappedResponse)
            ||
            (wi != null) &&
            (wi.BodyStyle == WebMessageBodyStyle.Wrapped || wi.BodyStyle == WebMessageBodyStyle.WrappedResponse));
 }
Example #15
0
 WebMessageBodyStyle GetBodyStyle(WebGetAttribute get, WebInvokeAttribute invoke)
 {
     if (get != null)
     {
         return(get.BodyStyle);
     }
     return(invoke.BodyStyle);
 }
Example #16
0
 private string GetRequestFormat(WebInvokeAttribute invoke, OperationDescription od)
 {
     if (IsRequestStream(od))
     {
         return("binary");
     }
     return("xml or json");
 }
Example #17
0
 void GetWebGetAndInvoke(OperationDescription od, out WebGetAttribute get, out WebInvokeAttribute invoke)
 {
     get    = od.Behaviors.Find <WebGetAttribute>();
     invoke = od.Behaviors.Find <WebInvokeAttribute>();
     if (get == null && invoke == null)
     {
         // default is POST
         invoke = new WebInvokeAttribute();
     }
 }
        private static void CreatePreflightOperation(OperationDescription operation, string originalUriTemplateStr, string originalMethod, ContractDescription contract, out OperationDescription preflightOperation, out PreflightOperationBehavior preflightOperationBehavior)
        {
            var originalUriTemplate = new UriTemplate(originalUriTemplateStr);

            preflightOperation = new OperationDescription(operation.Name + "_preflight", contract);

            //First the input message
            MessageDescription inputMessage = new MessageDescription(operation.Messages[0].Action + "_preflight", MessageDirection.Input);

            preflightOperation.Messages.Add(inputMessage);

            //We need to mirror the input parameters in the URI template
            //First any variables in the path
            if (originalUriTemplate.PathSegmentVariableNames != null && originalUriTemplate.PathSegmentVariableNames.Count > 0)
            {
                foreach (string uriParameter in originalUriTemplate.PathSegmentVariableNames)
                {
                    inputMessage.Body.Parts.Add(new MessagePartDescription(uriParameter, "")
                    {
                        Type = typeof(string)
                    });
                }
            }
            //Next any in the querystring
            if (originalUriTemplate.QueryValueVariableNames != null && originalUriTemplate.QueryValueVariableNames.Count > 0)
            {
                foreach (string uriParameter in originalUriTemplate.QueryValueVariableNames)
                {
                    inputMessage.Body.Parts.Add(new MessagePartDescription(uriParameter, "")
                    {
                        Type = typeof(string)
                    });
                }
            }

            //Now the output message, we only need the CORS headers in reality
            MessageDescription outputMessage = new MessageDescription(operation.Messages[1].Action + "_preflight", MessageDirection.Output);

            //outputMessage.Body.ReturnValue = new MessagePartDescription(preflightOperation.Name + "Return", contract.Namespace) { Type = typeof(Message) };
            preflightOperation.Messages.Add(outputMessage);

            WebInvokeAttribute wia = new WebInvokeAttribute();

            wia.UriTemplate = originalUriTemplate.ToString();
            wia.Method      = "OPTIONS";

            //TODO:TEST
            //wia.BodyStyle = WebMessageBodyStyle.WrappedRequest;

            preflightOperation.Behaviors.Add(wia);
            preflightOperation.Behaviors.Add(new DataContractSerializerOperationBehavior(preflightOperation));
            preflightOperationBehavior = new PreflightOperationBehavior(preflightOperation);
            preflightOperationBehavior.AddAllowedMethod(originalMethod);
            preflightOperation.Behaviors.Add(preflightOperationBehavior);
        }
Example #19
0
        /// <summary>
        /// Get the Request format if this is WebInvoke
        /// </summary>
        /// <param name="operationDescription"></param>
        /// <returns></returns>
        public static string GetRequestFormat(OperationDescription operationDescription)
        {
            if (GetWebGet(operationDescription) != null)
            {
                return(null);
            }

            WebInvokeAttribute invokeAttribute = GetWebInvoke(operationDescription);

            return(invokeAttribute != null && IsRequestStream(operationDescription) ? "Binary" : "Xml or Json");
        }
Example #20
0
        /// <summary>
        /// Get the REST METHOD specified by the operation description
        /// </summary>
        /// <param name="operationDescription"></param>
        /// <returns></returns>
        public static string GetMethod(OperationDescription operationDescription)
        {
            if (GetWebGet(operationDescription) != null)
            {
                return("GET");
            }

            WebInvokeAttribute invokeAttribute = GetWebInvoke(operationDescription);

            return(!String.IsNullOrEmpty(invokeAttribute.Method) ? invokeAttribute.Method : "POST");
        }
Example #21
0
        protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            // This is the default formatter for the operation, which we may wrap with our custom formatter
            IDispatchMessageFormatter formatter = base.GetRequestDispatchFormatter(operationDescription, endpoint);

            // Messages[0] is the request message
            int partsCount = operationDescription.Messages[0].Body.Parts.Count;

            // If the message doesn't have any parts, then it can't have any body content so a form post isn't applicable
            if (partsCount == 0)
            {
                return(formatter);
            }

            //For [WebInvoke] operations with body content, we want to wrap the base formatter with our HtmlFormRequestDispatchFormatter
            WebInvokeAttribute webInvoke = operationDescription.Behaviors.Find <WebInvokeAttribute>();

            if (webInvoke != null)
            {
                if (webInvoke.BodyStyle == WebMessageBodyStyle.Wrapped)
                {
                    throw new InvalidOperationException("The FormProcessingBehavior does not support wrapped requests or responses.");
                }

                // We need to determine the parts of the message that are associated with the Uri and those that are associated
                //  with the body content of the request.  To do this, we need to get the Uri template for the operation and determine
                //  how many parameters it has
                UriTemplate uriTemplate    = null;
                int         bodyPartsCount = partsCount;

                if (!string.IsNullOrEmpty(webInvoke.UriTemplate))
                {
                    uriTemplate = new UriTemplate(webInvoke.UriTemplate);
                    // The number of message parts for the request body will be the equal to the total parts for the message minus
                    //  the total number of UriTemplate variables
                    bodyPartsCount = partsCount - (uriTemplate.PathSegmentVariableNames.Count + uriTemplate.QueryValueVariableNames.Count);
                }
                else
                {
                    uriTemplate = new UriTemplate(string.Empty);
                }

                // Since we've disallowed wrapped message bodies, we can be sure that the message will only have
                //  0 or 1 message parts that are associated with the body of the request.
                if (bodyPartsCount == 1)
                {
                    QueryStringConverter converter = this.GetQueryStringConverter(operationDescription);
                    formatter = new HtmlFormRequestDispatchFormatter(operationDescription, uriTemplate, converter, formatter);
                }
            }

            return(formatter);
        }
Example #22
0
 private string GetMethod(WebGetAttribute get, WebInvokeAttribute invoke)
 {
     if (get != null)
     {
         return("GET");
     }
     if (!string.IsNullOrEmpty(invoke.Method))
     {
         return(invoke.Method);
     }
     return("POST");
 }
Example #23
0
        public override void Validate(ServiceEndpoint endpoint)
        {
            base.Validate(endpoint);

#pragma warning disable 56506 // Microsoft, endpoint.Contract is never null
            foreach (OperationDescription operation in endpoint.Contract.Operations)
#pragma warning restore 56506
            {
                if (operation.Behaviors.Find <XmlSerializerOperationBehavior>() != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                                      SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(XmlSerializerFormatAttribute).Name, this.GetType().ToString())));
                }
                string method = WebHttpBehavior.GetWebMethod(operation);
                if (method != WebHttpBehavior.GET &&
                    method != WebHttpBehavior.POST)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                                      SR2.GetString(SR2.WebScriptInvalidHttpRequestMethod, operation.Name,
                                                                                                                    endpoint.Contract.Name, method, this.GetType().ToString())));
                }
                WebGetAttribute webGetAttribute = operation.Behaviors.Find <WebGetAttribute>();
                if (webGetAttribute != null && webGetAttribute.UriTemplate != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                                      SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(UriTemplate).Name, this.GetType().ToString())));
                }
                WebInvokeAttribute webInvokeAttribute = operation.Behaviors.Find <WebInvokeAttribute>();
                if (webInvokeAttribute != null && webInvokeAttribute.UriTemplate != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                                      SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(UriTemplate).Name, this.GetType().ToString())));
                }
                WebMessageBodyStyle bodyStyle = GetBodyStyle(operation);
                if (bodyStyle != webScriptBodyStyle)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.BodyStyleNotSupportedByWebScript, bodyStyle, this.GetType().Name, webScriptBodyStyle)));
                }

                foreach (MessageDescription messageDescription in operation.Messages)
                {
                    if (!messageDescription.IsTypedMessage &&
                        (messageDescription.Direction == MessageDirection.Output) &&
                        (messageDescription.Body.Parts.Count > 0))
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                                          SR2.GetString(SR2.WebScriptOutRefOperationsNotSupported, operation.Name,
                                                                                                                        endpoint.Contract.Name)));
                    }
                }
            }
        }
Example #24
0
 private static void EnsureOneOneWebAttribute(WebGetAttribute webGet, WebInvokeAttribute webInvoke, HttpOperationDescription operation)
 {
     if (webGet != null && webInvoke != null)
     {
         throw Fx.Exception.AsError(
                   new InvalidOperationException(
                       SR.MultipleWebAttributes(
                           operation.Name,
                           operation.DeclaringContract.Name,
                           webGetAttributeType.Name,
                           webInvokeAttributeType.Name)));
     }
 }
    private bool IsRequestWrapped(WebInvokeAttribute wia)
    {
        WebMessageBodyStyle bodyStyle;

        if (wia.IsBodyStyleSetExplicitly)
        {
            bodyStyle = wia.BodyStyle;
        }
        else
        {
            bodyStyle = this.DefaultBodyStyle;
        }
        return(bodyStyle == WebMessageBodyStyle.Wrapped || bodyStyle == WebMessageBodyStyle.WrappedRequest);
    }
Example #26
0
        public RestInvoker()
        {
            Type type = typeof(T);

            if (!type.IsInterface)
            {
                throw new Exception("T must be interface");
            }

            var methods = type.GetMethods();

            foreach (var method in methods)
            {
                object[] attrs = method.GetCustomAttributes(false);
                if (null == attrs)
                {
                    continue;
                }

                foreach (var attr in attrs)
                {
                    WebInvokeAttribute invokeAttr = attr as WebInvokeAttribute;
                    if (null != invokeAttr)
                    {
                        MethodData data = new MethodData();
                        data.Url              = invokeAttr.UriTemplate;
                        data.Method           = invokeAttr.Method;
                        data.ReturnType       = method.ReturnType;
                        data.ReturnKnownTypes = GetKnownTypes(method.ReturnType);

                        var paras = method.GetParameters();
                        if ((null == paras) || (paras.Length == 0))
                        {
                            data.ParaNames      = null;
                            data.ParaTypes      = null;
                            data.ParaKnownTypes = null;
                        }
                        else
                        {
                            data.ParaNames      = paras.Select(para => "\"" + para.Name + "\"").ToArray();
                            data.ParaTypes      = paras.Select(para => para.ParameterType).ToArray();
                            data.ParaKnownTypes = paras.Select(para => GetKnownTypes(para.ParameterType)).ToArray();
                        }

                        this._methodDic[method.Name] = data;
                        break;
                    }
                }
            }
        }
Example #27
0
        /// <summary>
        /// 构造Api接口
        /// </summary>
        public void GeneratorApi()
        {
            List <MethodInfo> methodList = GetApiMethods();

            //构造Api接口
            foreach (var method in methodList)
            {
                CustomApi api = new CustomApi();
                api.Name = GetMethodAnnoatation(method);
                //Post Put
                WebInvokeAttribute webAttr = method.GetCustomAttribute <WebInvokeAttribute>();
                if (webAttr != null)
                {
                    api.RequestType = webAttr.Method;
                    api.Address     = webAttr.UriTemplate;
                    //Post Put 输入参数都是第一个
                    if (api.RequestType.Equals("POST"))
                    {
                        ParameterInfo[] paraInfos = method.GetParameters();
                        //Post参数
                        api.PostParameterList = GetParameterList(paraInfos[0]);
                        //输入参数
                        api.InParameterList = GetParameterList(1, method);
                    }
                    if (api.RequestType.Equals("PUT"))
                    {
                        ParameterInfo[] paraInfos = method.GetParameters();
                        //Put参数
                        api.PutParameterList = GetParameterList(paraInfos[0]);
                        //输入参数
                        api.InParameterList = GetParameterList(1, method);
                    }
                }
                //Get
                WebGetAttribute webGetAttr = method.GetCustomAttribute <WebGetAttribute>();
                if (webGetAttr != null)
                {
                    api.RequestType = "GET";
                    api.Address     = webGetAttr.UriTemplate;
                    ParameterInfo[] paraInfos = method.GetParameters();
                    //输入参数
                    api.InParameterList = GetParameterList(0, method);
                }
                //输出参数
                api.OutParameterList = GetCmfChinaOutParameter(method);
                _apiList.Add(api);
            }
        }
        public void IOperationBehaviorMethods()
        {
            IOperationBehavior oper = new WebInvokeAttribute();
            var pl = new BindingParameterCollection();
            var od = ContractDescription.GetContract(typeof(TestService)).Operations [0];

            oper.AddBindingParameters(od, pl);
            Assert.AreEqual(0, pl.Count, "#1");

            // yeah it really does nothing.
            oper.AddBindingParameters(null, null);

            oper.ApplyClientBehavior(od, null);
            oper.ApplyDispatchBehavior(od, null);
            oper.Validate(od);
        }
Example #29
0
        private string GetUriTemplate(WebInvokeAttribute wi, WebGetAttribute wg, MethodInfo declaration)
        {
            var uriTemplate = ((wi == null) ? wg.UriTemplate : wi.UriTemplate);

            if (string.IsNullOrWhiteSpace(uriTemplate))
            {
                uriTemplate = declaration.Name;
            }

            if (uriTemplate.StartsWith("{"))
            {
                uriTemplate = declaration.Name + uriTemplate;
            }

            return(uriTemplate);
        }
Example #30
0
 private string GetResponseFormat(WebGetAttribute get, WebInvokeAttribute invoke, OperationDescription od)
 {
     if (IsResponseStream(od))
     {
         return("binary");
     }
     if (get != null && get.IsResponseFormatSetExplicitly)
     {
         return(get.ResponseFormat.ToString());
     }
     if (invoke != null && invoke.IsResponseFormatSetExplicitly)
     {
         return(invoke.ResponseFormat.ToString());
     }
     return(this.Behavior.DefaultOutgoingResponseFormat.ToString());
 }