コード例 #1
0
        public void HttpOperationDescription_Insert_OutputParameters_From_HttpOperationDescription()
        {
            OperationDescription             od      = GetOperationDescription(typeof(MockService2), "OneInOneOutReturnsString");
            MessagePartDescriptionCollection mpdColl = od.Messages[1].Body.Parts;

            Assert.AreEqual(1, mpdColl.Count, "Test assumes we start with 1 output param");

            // Get a synchronized HOD and HODCollection
            HttpOperationDescription           hod     = od.ToHttpOperationDescription();
            HttpParameterDescriptionCollection hpdColl = hod.OutputParameters;

            // Get an HPD for the newly created MPD
            MessagePartDescription mpdNew = new MessagePartDescription("NewMPD", "NewMPDNS")
            {
                Type = typeof(byte)
            };
            HttpParameterDescription hpd = mpdNew.ToHttpParameterDescription();

            // Add it to the output parameters
            hpdColl.Add(hpd);

            // Verify it appears in the MPD coll
            Assert.AreEqual(2, mpdColl.Count, "Adding new MPD to HPD collection should have updated MPD collection");
            Assert.AreEqual(2, od.Messages[1].Body.Parts.Count, "Adding new MPD should have updated Parts");
            Assert.AreEqual(typeof(byte), od.Messages[1].Body.Parts[1].Type, "Adding new MPD failed due to type");
        }
コード例 #2
0
        /// <summary>
        /// Inserts an item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which item should be inserted.</param>
        /// <param name="item">The object to insert at the specified index.</param>
        public void Insert(int index, HttpParameter item)
        {
            if (item == null)
            {
                throw Fx.Exception.ArgumentNull("item");
            }

            if (index < 0 || (index > this.Count))
            {
                throw Fx.Exception.AsError(new ArgumentOutOfRangeException("index"));
            }

            item.SynchronizeToMessagePartDescription(this.MessageDescription);

            if (this.IsSynchronized)
            {
                MessagePartDescriptionCollection mpdColl = this.GetOrCreateMessagePartDescriptionCollection();
                Fx.Assert(mpdColl != null, "MessagePartDescriptionCollection cannot be null");
                mpdColl.Insert(index, item.MessagePartDescription);
            }
            else
            {
                this.innerCollection.Insert(index, item);
            }
        }
コード例 #3
0
        /// <summary>
        /// Copies the elements of the collection to an <see cref="Array"/>, starting at a particular array index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from collection. The array must have zero-based indexing.</param>
        /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
        public void CopyTo(HttpParameter[] array, int arrayIndex)
        {
            if (array == null)
            {
                throw Fx.Exception.ArgumentNull("array");
            }

            if (arrayIndex < 0 || ((arrayIndex + this.Count) > array.Length))
            {
                throw Fx.Exception.AsError(new ArgumentOutOfRangeException("arrayIndex"));
            }

            if (this.IsSynchronized)
            {
                MessagePartDescriptionCollection mdpColl = this.MessagePartDescriptionCollection;
                if (mdpColl != null)
                {
                    HttpParameter[] newArray = ToArray(mdpColl);
                    Array.Copy(newArray, 0, array, arrayIndex, newArray.Length);
                }
                else if (array.Length > 0)
                {
                    // clear out the contents from the arrayIndex till the end of the array
                    Array.Clear(array, arrayIndex, array.Length - arrayIndex);
                }
            }
            else
            {
                this.innerCollection.CopyTo(array, arrayIndex);
            }
        }
コード例 #4
0
 private static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
 {
     PartInfo[] partInfos = new PartInfo[parts.Count];
     for (int i = 0; i < parts.Count; i++)
     {
         partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
     }
     return(partInfos);
 }
コード例 #5
0
        protected RequestBodyDispatchFormatter(OperationDescription operation, UriTemplate uriTemplate, QueryStringConverter converter, IDispatchMessageFormatter innerFormatter)
        {
            // The inner formatter is the default formatter that WCF normally uses.  When the request can't be deserialized
            //  by our custom formatter, we'll use the default formatter.
            this.innerFormatter = innerFormatter;

            // We'll use the query string converter for both Uri query string parameters and the values of the
            //  form post data
            this.QueryStringConverter = converter;

            // Messages[0] is the request message
            MessagePartDescriptionCollection parts = operation.Messages[0].Body.Parts;

            // This partsCount includes the Uri parts (both path segment variables and query string variables)
            //  1 body content part
            partsCount = parts.Count;

            ReadOnlyCollection <string> uriPathVariables  = uriTemplate.PathSegmentVariableNames;
            ReadOnlyCollection <string> uriQueryVariables = uriTemplate.QueryValueVariableNames;

            // For each part of the message, we need to capture it's name, type, and whether it is
            //  a Uri path segment variable, a Uri query string variable or the body content
            operationParameterInfo = new OperationParameterInfo[partsCount];
            for (int x = 0; x < partsCount; x++)
            {
                string name = parts[x].Name;
                Type   type = parts[x].Type;

                // We'll assume this part is the message body, but then check if there are
                //  uri variables that match the name
                OperationParameterKind kind = OperationParameterKind.MessageBody;
                bool canConvert             = false;
                CaseInsensitiveEqualityComparer <string> comparer = new CaseInsensitiveEqualityComparer <string>();

                if (uriPathVariables.Contains(name, comparer))
                {
                    kind = OperationParameterKind.UriPathVariable;
                }
                else if (uriQueryVariables.Contains(name, comparer))
                {
                    canConvert = converter.CanConvert(type);
                    kind       = OperationParameterKind.UriQueryVariable;
                }
                else
                {
                    // If we reached here, then this part really is the message body part.
                    //  We'll store the name and type in the class properties so that derived
                    //  types have access to this information
                    this.BodyParameterName = name;
                    this.BodyParameterType = type;
                }

                operationParameterInfo[x] = new OperationParameterInfo(kind, type, name, canConvert);
            }
        }
コード例 #6
0
 private static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
 {
     for (int i = 0; i < bodyDescriptions.Count; i++)
     {
         if (!IsTypeSupported(bodyDescriptions[i]))
         {
             return(false);
         }
     }
     return(true);
 }
コード例 #7
0
 internal MessageBodyDescription(MessageBodyDescription other)
 {
     this.WrapperName = other.WrapperName;
     this.WrapperNamespace = other.WrapperNamespace;
     this.parts = new MessagePartDescriptionCollection();
     foreach (MessagePartDescription mpd in other.Parts)
     {
         this.Parts.Add(mpd.Clone());
     }
     if (other.ReturnValue != null)
     {
         this.ReturnValue = other.ReturnValue.Clone();
     }
 }
コード例 #8
0
        /// <summary>
        /// Gets or sets the element at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the element to get or set.</param>
        /// <returns>The item at the specified index.</returns>
        public HttpParameter this[int index]
        {
            get
            {
                if (index < 0 || (index >= this.Count))
                {
                    throw Fx.Exception.AsError(new ArgumentOutOfRangeException("index"));
                }

                if (this.IsSynchronized)
                {
                    // The Count check above will have thrown if there is no MessagePartDescriptionCollection,
                    // because Count would have been zero.
                    MessagePartDescriptionCollection messagePartDescriptions = this.MessagePartDescriptionCollection;
                    Fx.Assert(messagePartDescriptions != null, "MessagePartDescriptionCollection cannot be null");
                    return(new HttpParameter(messagePartDescriptions[index]));
                }

                return(this.innerCollection[index]);
            }

            set
            {
                if (index < 0 || (index >= this.Count))
                {
                    throw Fx.Exception.AsError(new ArgumentOutOfRangeException("index"));
                }

                if (value == null)
                {
                    throw Fx.Exception.ArgumentNull("value");
                }

                value.SynchronizeToMessagePartDescription(this.MessageDescription);

                if (this.innerCollection != null)
                {
                    this.innerCollection[index] = value;
                }
                else
                {
                    // The Count check above will have thrown if there is no MessagePartDescriptionCollection,
                    // because Count would have been zero.
                    MessagePartDescriptionCollection mpdColl = this.MessagePartDescriptionCollection;
                    Fx.Assert(mpdColl != null, "MessagePartDescriptionCollection cannot be null");
                    mpdColl[index] = value.MessagePartDescription;
                }
            }
        }
コード例 #9
0
        private MessageInfo CreateMessageInfo(DataContractFormatAttribute dataContractFormatAttribute,
                                              MessageDescription messageDescription, DataContractSerializerOperationBehavior serializerFactory)
        {
            if (messageDescription.IsUntypedMessage)
            {
                return(null);
            }

            MessageInfo messageInfo = new MessageInfo();

            MessageBodyDescription body = messageDescription.Body;

            if (body.WrapperName != null)
            {
                messageInfo.WrapperName      = AddToDictionary(body.WrapperName);
                messageInfo.WrapperNamespace = AddToDictionary(body.WrapperNamespace);
            }
            MessagePartDescriptionCollection parts = body.Parts;

            messageInfo.BodyParts = new PartInfo[parts.Count];
            for (int i = 0; i < parts.Count; i++)
            {
                messageInfo.BodyParts[i] = CreatePartInfo(parts[i], dataContractFormatAttribute.Style, serializerFactory);
            }

            if (IsValidReturnValue(messageDescription.Body.ReturnValue))
            {
                messageInfo.ReturnPart = CreatePartInfo(messageDescription.Body.ReturnValue, dataContractFormatAttribute.Style, serializerFactory);
            }

            messageInfo.HeaderDescriptionTable = new MessageHeaderDescriptionTable();
            messageInfo.HeaderParts            = new PartInfo[messageDescription.Headers.Count];
            for (int i = 0; i < messageDescription.Headers.Count; i++)
            {
                MessageHeaderDescription headerDescription = messageDescription.Headers[i];
                if (headerDescription.IsUnknownHeaderCollection)
                {
                    messageInfo.UnknownHeaderDescription = headerDescription;
                }
                else
                {
                    ValidateDataContractType(headerDescription.Type);
                    messageInfo.HeaderDescriptionTable.Add(headerDescription.Name, headerDescription.Namespace, headerDescription);
                }
                messageInfo.HeaderParts[i] = CreatePartInfo(headerDescription, OperationFormatStyle.Document, serializerFactory);
            }
            messageInfo.AnyHeaders = messageInfo.UnknownHeaderDescription != null || messageInfo.HeaderDescriptionTable.Count > 0;
            return(messageInfo);
        }
コード例 #10
0
 /// <summary>
 /// Removes all items from the collection.
 /// </summary>
 public void Clear()
 {
     if (this.IsSynchronized)
     {
         MessagePartDescriptionCollection mpdColl = this.MessagePartDescriptionCollection;
         if (mpdColl != null)
         {
             mpdColl.Clear();
         }
     }
     else
     {
         this.innerCollection.Clear();
     }
 }
コード例 #11
0
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>An enumerator that can be used to iterate through the collection.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            if (this.IsSynchronized)
            {
                MessagePartDescriptionCollection messagePartDescriptions = this.MessagePartDescriptionCollection;
                if (messagePartDescriptions == null)
                {
                    return(Enumerable.Empty <HttpParameter>().GetEnumerator());
                }

                HttpParameter[] newArray = ToArray(messagePartDescriptions);
                return(newArray.GetEnumerator());
            }

            return(this.innerCollection.GetEnumerator());
        }
コード例 #12
0
        public void PartsNamespace()
        {
            ContractDescription cd =
                ContractDescription.GetContract(typeof(IFoo4));

            MessagePartDescriptionCollection parts =
                cd.Operations [0].Messages [0].Body.Parts;

            Assert.AreEqual(1, parts.Count, "#1");
            MessagePartDescription part = parts [0];

            Assert.AreEqual("intValue", part.Name, "#2");
            Assert.AreEqual("http://MonoTests.System.ServiceModel.Description", part.Namespace, "#3");
            Assert.AreEqual(typeof(int), part.Type, "#4");
            Assert.AreEqual(0, part.Index, "#5");
            Assert.AreEqual(false, part.Multiple, "#5");
        }
コード例 #13
0
        public void Parts()
        {
            ContractDescription cd =
                ContractDescription.GetContract(typeof(IFoo3));

            MessagePartDescriptionCollection parts =
                cd.Operations [0].Messages [0].Body.Parts;

            Assert.AreEqual(1, parts.Count, "#1");
            MessagePartDescription part = parts [0];

            Assert.AreEqual("intValue", part.Name, "#2");
            Assert.AreEqual("http://tempuri.org/", part.Namespace, "#3");
            Assert.AreEqual(typeof(int), part.Type, "#4");
            Assert.AreEqual(0, part.Index, "#5");
            Assert.AreEqual(false, part.Multiple, "#5");
        }
コード例 #14
0
ファイル: WebHttpBehavior3.cs プロジェクト: nuxleus/WCFWeb
        protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            MessagePartDescriptionCollection parts = operationDescription.Messages[0].Body.Parts;
            int    jsonValuePosition = 0;
            string requestMethod     = GetHttpRequestMethod(operationDescription);

            if (requestMethod != "GET" && requestMethod != "HEAD" &&
                parts.Count > 0 &&
                HasExactlyOneJsonValue(parts, out jsonValuePosition))
            {
                this.CheckBodyStyle(operationDescription, true);
                this.CheckNoUnmappedParameters(operationDescription, jsonValuePosition);
                return(new JsonValueFormatter(operationDescription, endpoint, this.GetQueryStringConverter(operationDescription), jsonValuePosition));
            }

            return(base.GetRequestDispatchFormatter(operationDescription, endpoint));
        }
コード例 #15
0
        protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            //Messages[0] is the request message
            MessagePartDescriptionCollection parts = operationDescription.Messages[0].Body.Parts;

            //This formatter looks for [WebInvoke] operations with that have their last
            //parameter typed as NameValueCollection
            if (operationDescription.Behaviors.Find <WebInvokeAttribute>() != null &&
                parts.Count > 0)
            {
                return(new FormDataRequestFormatter(operationDescription));
            }
            else
            {
                return(base.GetRequestDispatchFormatter(operationDescription, endpoint));
            }
        }
コード例 #16
0
        private MessageInfo CreateMessageInfo(DataContractFormatAttribute dataContractFormatAttribute, MessageDescription messageDescription, DataContractSerializerOperationBehavior serializerFactory)
        {
            if (messageDescription.IsUntypedMessage)
            {
                return(null);
            }
            MessageInfo            info = new MessageInfo();
            MessageBodyDescription body = messageDescription.Body;

            if (body.WrapperName != null)
            {
                info.WrapperName      = base.AddToDictionary(body.WrapperName);
                info.WrapperNamespace = base.AddToDictionary(body.WrapperNamespace);
            }
            MessagePartDescriptionCollection parts = body.Parts;

            info.BodyParts = new PartInfo[parts.Count];
            for (int i = 0; i < parts.Count; i++)
            {
                info.BodyParts[i] = this.CreatePartInfo(parts[i], dataContractFormatAttribute.Style, serializerFactory);
            }
            if (OperationFormatter.IsValidReturnValue(messageDescription.Body.ReturnValue))
            {
                info.ReturnPart = this.CreatePartInfo(messageDescription.Body.ReturnValue, dataContractFormatAttribute.Style, serializerFactory);
            }
            info.HeaderDescriptionTable = new OperationFormatter.MessageHeaderDescriptionTable();
            info.HeaderParts            = new PartInfo[messageDescription.Headers.Count];
            for (int j = 0; j < messageDescription.Headers.Count; j++)
            {
                MessageHeaderDescription message = messageDescription.Headers[j];
                if (message.IsUnknownHeaderCollection)
                {
                    info.UnknownHeaderDescription = message;
                }
                else
                {
                    this.ValidateDataContractType(message.Type);
                    info.HeaderDescriptionTable.Add(message.Name, message.Namespace, message);
                }
                info.HeaderParts[j] = this.CreatePartInfo(message, OperationFormatStyle.Document, serializerFactory);
            }
            info.AnyHeaders = (info.UnknownHeaderDescription != null) || (info.HeaderDescriptionTable.Count > 0);
            return(info);
        }
コード例 #17
0
        /// <summary>
        /// Adds an item to the collection.
        /// </summary>
        /// <param name="item">The object to add to the collection.</param>
        public void Add(HttpParameter item)
        {
            if (item == null)
            {
                throw Fx.Exception.ArgumentNull("item");
            }

            item.SynchronizeToMessagePartDescription(this.MessageDescription);

            if (this.IsSynchronized)
            {
                MessagePartDescriptionCollection mpdColl = this.GetOrCreateMessagePartDescriptionCollection();
                mpdColl.Add(item.MessagePartDescription);
            }
            else
            {
                this.innerCollection.Add(item);
            }
        }
コード例 #18
0
        /// <summary>
        /// Removes the first occurrence of a specific object from the collection.
        /// </summary>
        /// <param name="item">The object to remove from the collection.</param>
        /// <returns><c>true</c> if <paramref name="item"/> was successfully removed from the collection; otherwise, <c>false</c>.
        /// This method also returns <c>false</c> if <paramref name="item"/> is not found in the original collection.</returns>
        public bool Remove(HttpParameter item)
        {
            if (item == null)
            {
                throw Fx.Exception.ArgumentNull("item");
            }

            if (this.IsSynchronized && item.MessagePartDescription != null)
            {
                MessagePartDescriptionCollection mdpColl = this.MessagePartDescriptionCollection;
                if (mdpColl == null)
                {
                    return(false);
                }

                return(mdpColl.Remove(item.MessagePartDescription));
            }

            return(this.innerCollection.Remove(item));
        }
コード例 #19
0
        /// <summary>
        /// Determines the index of a specific item in the collection.
        /// </summary>
        /// <param name="item">The object to locate in the collection.</param>
        /// <returns>The index of item if found in the list; otherwise, -1.</returns>
        public int IndexOf(HttpParameter item)
        {
            if (item == null)
            {
                throw Fx.Exception.ArgumentNull("item");
            }

            if (this.IsSynchronized && item.MessagePartDescription != null)
            {
                MessagePartDescriptionCollection mpdColl = this.MessagePartDescriptionCollection;
                if (mpdColl == null)
                {
                    return(-1);
                }

                return(mpdColl.IndexOf(item.MessagePartDescription));
            }

            return(this.innerCollection.IndexOf(item));
        }
コード例 #20
0
        /// <summary>
        /// Removes the item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove,</param>
        public void RemoveAt(int index)
        {
            if (index < 0 || (index >= this.Count))
            {
                throw Fx.Exception.AsError(new ArgumentOutOfRangeException("index"));
            }

            if (this.IsSynchronized)
            {
                // The Count check above will have thrown if there is no MessagePartDescriptionCollection,
                // because Count would have been zero.
                MessagePartDescriptionCollection mpdColl = this.MessagePartDescriptionCollection;
                Fx.Assert(mpdColl != null, "MessagePartDescriptionCollection cannot be null");
                mpdColl.RemoveAt(index);
            }
            else
            {
                this.innerCollection.RemoveAt(index);
            }
        }
コード例 #21
0
        /// <summary>
        /// Retrieves the appropriate <see cref="MessagePartDescriptionCollection"/> for the current instance.
        /// If the synchronized <see cref="OperationDescription"/> does not have the corresponding collection,
        /// this method will create a default <see cref="MessageDescription"/> element so that the collection exists.
        /// </summary>
        /// <returns>The <see cref="MessagePartDescriptionCollection"/>.</returns>
        private MessagePartDescriptionCollection GetOrCreateMessagePartDescriptionCollection()
        {
            Fx.Assert(this.IsSynchronized, "This method cannot be called for unsynchronized collections");
            MessagePartDescriptionCollection messagePartDescriptions = this.MessagePartDescriptionCollection;

            if (messagePartDescriptions == null)
            {
                OperationDescription operationDescription = this.operationDescription;
                int messageIndex = this.isOutputCollection ? 1 : 0;
                if (operationDescription.Messages.Count <= messageIndex)
                {
                    HttpOperationDescription.CreateMessageDescriptionIfNecessary(operationDescription, messageIndex);
                }

                Fx.Assert(operationDescription.Messages.Count > messageIndex, "CreateMessageDescription should have created Message element");
                messagePartDescriptions = operationDescription.Messages[messageIndex].Body.Parts;
            }

            Fx.Assert(messagePartDescriptions != null, "return value can never be null");
            return(messagePartDescriptions);
        }
コード例 #22
0
ファイル: WebHttpBehavior3.cs プロジェクト: nuxleus/WCFWeb
        private static bool HasExactlyOneJsonValue(MessagePartDescriptionCollection parts, out int jsonValuePosition)
        {
            int count = 0;

            jsonValuePosition = -1;
            for (int i = 0; i < parts.Count; i++)
            {
                if (parts[i].Type == typeof(JsonValue) || parts[i].Type == typeof(JsonObject))
                {
                    count++;
                    jsonValuePosition = i;
                }

                if (count > 1)
                {
                    break;
                }
            }

            return(count == 1);
        }
コード例 #23
0
        /// <summary>
        /// Determines whether the collection contains a specific value.
        /// </summary>
        /// <param name="item">The object to locate in the collection.</param>
        /// <returns><c>true</c> if item is found in the collection; otherwise, <c>false</c>.</returns>
        public bool Contains(HttpParameter item)
        {
            if (item == null)
            {
                throw Fx.Exception.ArgumentNull("item");
            }

            if (this.IsSynchronized && item.MessagePartDescription != null)
            {
                MessagePartDescriptionCollection mdpColl = this.MessagePartDescriptionCollection;
                if (mdpColl == null)
                {
                    return(false);
                }

                // Strategy: use the knowledge we would have wrapped the MessagePartDescription in the
                // past when we released this HttpParameter.
                return(mdpColl.Contains(item.MessagePartDescription));
            }

            return(this.innerCollection.Contains(item));
        }
コード例 #24
0
 internal void SetBody(SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
 {
     _body = body;
     _rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts;
 }
コード例 #25
0
 private static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
 {
     for (int i = 0; i < bodyDescriptions.Count; i++)
         if (!IsTypeSupported(bodyDescriptions[i]))
             return false;
     return true;
 }
コード例 #26
0
                private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
                {
                    MessagePartDescription returnPart;
                    string wrapperName, wrapperNs;
                    MessagePartDescriptionCollection bodyParts;
                    rpcEncodedTypedMessageBodyParts = null;
                    returnPart = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null;
                    bodyParts = message.Body.Parts;
                    wrapperName = message.Body.WrapperName;
                    wrapperNs = message.Body.WrapperNamespace;
                    bool isWrapped = (wrapperName != null);
                    bool hasReturnValue = returnPart != null;
                    int paramCount = bodyParts.Count + (hasReturnValue ? 1 : 0);
                    if (paramCount == 0 && !isWrapped) // no need to create serializer
                    {
                        return null;
                    }

                    XmlReflectionMember[] members = new XmlReflectionMember[paramCount];
                    int paramIndex = 0;
                    if (hasReturnValue)
                        members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(returnPart, IsRpc, isWrapped);

                    for (int i = 0; i < bodyParts.Count; i++)
                        members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(bodyParts[i], IsRpc, isWrapped);

                    if (!isWrapped)
                        wrapperNs = ContractNamespace;
                    return ImportMembersMapping(wrapperName, wrapperNs, members, isWrapped, IsRpc, mappingKey);
                }
 private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
 {
     MessagePartDescription description;
     string name;
     string wrapperNamespace;
     MessagePartDescriptionCollection parts;
     if ((this.IsEncoded && message.IsTypedMessage) && (message.Body.WrapperName == null))
     {
         MessagePartDescription wrapperPart = this.GetWrapperPart(message);
         description = null;
         rpcEncodedTypedMessageBodyParts = parts = this.GetWrappedParts(wrapperPart);
         name = wrapperPart.Name;
         wrapperNamespace = wrapperPart.Namespace;
     }
     else
     {
         rpcEncodedTypedMessageBodyParts = null;
         description = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null;
         parts = message.Body.Parts;
         name = message.Body.WrapperName;
         wrapperNamespace = message.Body.WrapperNamespace;
     }
     bool isWrapped = name != null;
     bool flag2 = description != null;
     int num = parts.Count + (flag2 ? 1 : 0);
     if ((num == 0) && !isWrapped)
     {
         return null;
     }
     XmlReflectionMember[] members = new XmlReflectionMember[num];
     int num2 = 0;
     if (flag2)
     {
         members[num2++] = XmlSerializerHelper.GetXmlReflectionMember(description, this.IsRpc, this.IsEncoded, isWrapped);
     }
     for (int i = 0; i < parts.Count; i++)
     {
         members[num2++] = XmlSerializerHelper.GetXmlReflectionMember(parts[i], this.IsRpc, this.IsEncoded, isWrapped);
     }
     if (!isWrapped)
     {
         wrapperNamespace = this.ContractNamespace;
     }
     return this.ImportMembersMapping(name, wrapperNamespace, members, isWrapped, this.IsRpc, mappingKey);
 }
コード例 #28
0
 private static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
 {
     PartInfo[] partInfos = new PartInfo[parts.Count];
     for (int i = 0; i < parts.Count; i++)
     {
         partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
     }
     return partInfos;
 }
コード例 #29
0
ファイル: JsonValueFormatter.cs プロジェクト: nuxleus/WCFWeb
        public void DeserializeRequest(Message message, object[] parameters)
        {
            JsonValue jsonValue   = null;
            bool      isJsonInput = false;

            if (message != null)
            {
                if (message.IsEmpty)
                {
                    Encoding contentEncoding;
                    if (IsContentTypeSupported(WebOperationContext.Current.IncomingRequest.ContentType, ApplicationJsonContentType, out contentEncoding))
                    {
                        isJsonInput = true;
                        jsonValue   = null;
                    }
                }
                else if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
                {
                    WebBodyFormatMessageProperty bodyFormatProperty =
                        (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name];
                    if (bodyFormatProperty.Format == WebContentFormat.Json)
                    {
                        isJsonInput = true;
                        jsonValue   = DeserializeFromJXML(message);
                    }
                }
            }

            if (!isJsonInput)
            {
                Encoding contentEncoding;
                if (!IsContentTypeSupported(WebOperationContext.Current.IncomingRequest.ContentType, FormUrlEncodedContentType, out contentEncoding))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ExpectUrlEncodedOrJson));
                }

                string formData = string.Empty;
                if (message != null && !message.IsEmpty)
                {
                    XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
                    bodyReader.ReadStartElement(BinaryElementName);

                    using (Stream s = new MemoryStream(bodyReader.ReadContentAsBase64()))
                    {
                        if (contentEncoding == null)
                        {
                            formData = new StreamReader(s).ReadToEnd();
                        }
                        else
                        {
                            formData = new StreamReader(s, contentEncoding).ReadToEnd();
                        }
                    }
                }

                jsonValue = FormUrlEncodedExtensions.ParseFormUrlEncoded(formData, this.readerQuotas.MaxDepth);
            }

            UriTemplateMatch match = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

            MessagePartDescriptionCollection messageParts = this.operationDescription.Messages[0].Body.Parts;

            Func <MessagePartDescription, object> binder = this.CreateParameterBinder(match);

            object[] values = messageParts.Select(p => binder(p)).ToArray();

            values[this.jsonValuePosition] = jsonValue;
            values.CopyTo(parameters, 0);
        }
 private MessagePartDescriptionCollection GetWrappedParts(MessagePartDescription bodyPart)
 {
     System.Type type = bodyPart.Type;
     MessagePartDescriptionCollection descriptions = new MessagePartDescriptionCollection();
     foreach (MemberInfo info in type.GetMembers(BindingFlags.Public | BindingFlags.Instance))
     {
         if (((info.MemberType & (MemberTypes.Property | MemberTypes.Field)) != 0) && !info.IsDefined(typeof(SoapIgnoreAttribute), false))
         {
             MessagePartDescription description;
             System.ServiceModel.Description.XmlName name = new System.ServiceModel.Description.XmlName(info.Name);
             description = new MessagePartDescription(name.EncodedName, string.Empty) {
                 AdditionalAttributesProvider = description.MemberInfo = info,
                 Index = description.SerializationPosition = descriptions.Count,
                 Type = (info.MemberType == MemberTypes.Property) ? ((PropertyInfo) info).PropertyType : ((FieldInfo) info).FieldType
             };
             if (bodyPart.HasProtectionLevel)
             {
                 description.ProtectionLevel = bodyPart.ProtectionLevel;
             }
             descriptions.Add(description);
         }
     }
     return descriptions;
 }
コード例 #31
0
 /// <summary>
 /// Creates an array of <see cref="HttpParameter"/> elements that are synchronized with their
 /// corresponding <see cref="MessagePartDescription"/> elements.
 /// </summary>
 /// <param name="messagePartDescriptionCollection">The existing collection from which to create the array.</param>
 /// <returns>The new array.</returns>
 private static HttpParameter[] ToArray(MessagePartDescriptionCollection messagePartDescriptionCollection)
 {
     return(messagePartDescriptionCollection
            .Select <MessagePartDescription, HttpParameter>(m => new HttpParameter(m))
            .ToArray());
 }
コード例 #32
0
 private MessagePartDescriptionCollection GetWrappedParts(MessagePartDescription bodyPart)
 {
     Type bodyObjectType = bodyPart.Type;
     MessagePartDescriptionCollection partList = new MessagePartDescriptionCollection();
     foreach (MemberInfo member in bodyObjectType.GetMembers(BindingFlags.Instance | BindingFlags.Public))
     {
         if ((member.MemberType & (MemberTypes.Field | MemberTypes.Property)) == 0)
             continue;
         if (member.IsDefined(typeof(SoapIgnoreAttribute), false/*inherit*/))
             continue;
         XmlName xmlName = new XmlName(member.Name);
         MessagePartDescription part = new MessagePartDescription(xmlName.EncodedName, string.Empty);
         part.AdditionalAttributesProvider = part.MemberInfo = member;
         part.Index = part.SerializationPosition = partList.Count;
         part.Type = (member.MemberType == MemberTypes.Property) ? ((PropertyInfo)member).PropertyType : ((FieldInfo)member).FieldType;
         if (bodyPart.HasProtectionLevel)
             part.ProtectionLevel = bodyPart.ProtectionLevel;
         partList.Add(part);
     }
     return partList;
 }
コード例 #33
0
 private void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object returnValue, object[] parameters)
 {
     if (serializer != null)
     {
         bool     flag = OperationFormatter.IsValidReturnValue(returnPart);
         object[] o    = new object[bodyParts.Count + (flag ? 1 : 0)];
         int      num  = 0;
         if (flag)
         {
             o[num++] = returnValue;
         }
         for (int i = 0; i < bodyParts.Count; i++)
         {
             o[num++] = parameters[bodyParts[i].Index];
         }
         string encodingStyle = this.isEncoded ? GetEncoding(version.Envelope) : null;
         serializer.Serialize(writer, o, null, encodingStyle);
     }
 }
コード例 #34
0
 public MessageBodyDescription()
 {
     parts = new MessagePartDescriptionCollection();
 }
コード例 #35
0
        private object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object[] parameters, bool isRequest)
        {
            object obj3;

            try
            {
                if (reader == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
                }
                if (parameters == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters"));
                }
                object obj2 = null;
                if (serializer == null)
                {
                    return(null);
                }
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    return(null);
                }
                object[] objArray = (object[])serializer.Deserialize(reader, this.isEncoded ? GetEncoding(version.Envelope) : null);
                int      num      = 0;
                if (OperationFormatter.IsValidReturnValue(returnPart))
                {
                    obj2 = objArray[num++];
                }
                for (int i = 0; i < bodyParts.Count; i++)
                {
                    parameters[bodyParts[i].Index] = objArray[num++];
                }
                obj3 = obj2;
            }
            catch (InvalidOperationException exception)
            {
                string name = isRequest ? "SFxErrorDeserializingRequestBody" : "SFxErrorDeserializingReplyBody";
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString(name, new object[] { base.OperationName }), exception));
            }
            return(obj3);
        }
 private object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object[] parameters, bool isRequest)
 {
     object obj3;
     try
     {
         if (reader == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
         }
         if (parameters == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters"));
         }
         object obj2 = null;
         if (serializer == null)
         {
             return null;
         }
         if (reader.NodeType == XmlNodeType.EndElement)
         {
             return null;
         }
         object[] objArray = (object[]) serializer.Deserialize(reader, this.isEncoded ? GetEncoding(version.Envelope) : null);
         int num = 0;
         if (OperationFormatter.IsValidReturnValue(returnPart))
         {
             obj2 = objArray[num++];
         }
         for (int i = 0; i < bodyParts.Count; i++)
         {
             parameters[bodyParts[i].Index] = objArray[num++];
         }
         obj3 = obj2;
     }
     catch (InvalidOperationException exception)
     {
         string name = isRequest ? "SFxErrorDeserializingRequestBody" : "SFxErrorDeserializingReplyBody";
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString(name, new object[] { base.OperationName }), exception));
     }
     return obj3;
 }
 private void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object returnValue, object[] parameters)
 {
     if (serializer != null)
     {
         bool flag = OperationFormatter.IsValidReturnValue(returnPart);
         object[] o = new object[bodyParts.Count + (flag ? 1 : 0)];
         int num = 0;
         if (flag)
         {
             o[num++] = returnValue;
         }
         for (int i = 0; i < bodyParts.Count; i++)
         {
             o[num++] = parameters[bodyParts[i].Index];
         }
         string encodingStyle = this.isEncoded ? GetEncoding(version.Envelope) : null;
         serializer.Serialize(writer, o, null, encodingStyle);
     }
 }
コード例 #38
0
        private void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object returnValue, object[] parameters)
        {
            if (serializer == null)
            {
                return;
            }

            bool hasReturnValue = IsValidReturnValue(returnPart);
            object[] bodyParameters = new object[bodyParts.Count + (hasReturnValue ? 1 : 0)];
            int paramIndex = 0;

            if (hasReturnValue)
                bodyParameters[paramIndex++] = returnValue;

            for (int i = 0; i < bodyParts.Count; i++)
                bodyParameters[paramIndex++] = parameters[bodyParts[i].Index];

            serializer.Serialize(writer, bodyParameters, null);
        }
 internal void SetBody(XmlSerializerOperationBehavior.Reflector.SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts)
 {
     this.body = body;
     this.rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts;
 }
コード例 #40
0
        private object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object[] parameters, bool isRequest)
        {
            try
            {
                if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
                if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters"));
                object returnValue = null;
                if (serializer == null)
                {
                    return null;
                }
                if (reader.NodeType == XmlNodeType.EndElement)
                    return null;

                object[] bodyParameters = (object[])serializer.Deserialize(reader);
                int paramIndex = 0;
                if (IsValidReturnValue(returnPart))
                    returnValue = bodyParameters[paramIndex++];

                for (int i = 0; i < bodyParts.Count; i++)
                    parameters[bodyParts[i].Index] = bodyParameters[paramIndex++];
                return returnValue;
            }
            catch (InvalidOperationException e)
            {
                // all exceptions from XmlSerializer get wrapped in InvalidOperationException,
                // so we must be conservative and never turn this into a fault
                string resourceKey = isRequest ? SR.SFxErrorDeserializingRequestBody : SR.SFxErrorDeserializingReplyBody;

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                    SR.Format(resourceKey, OperationName), e));
            }
        }
コード例 #41
0
        private object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object[] parameters, bool isRequest)
        {
            try
            {
                if (reader == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(reader)));
                }

                if (parameters == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(parameters)));
                }

                object returnValue = null;
                if (serializer == null)
                {
                    return(null);
                }
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    return(null);
                }

                object[] bodyParameters = (object[])serializer.Deserialize(reader, _isEncoded ? GetEncoding(version.Envelope) : null);
                int      paramIndex     = 0;
                if (IsValidReturnValue(returnPart))
                {
                    returnValue = bodyParameters[paramIndex++];
                }

                for (int i = 0; i < bodyParts.Count; i++)
                {
                    parameters[bodyParts[i].Index] = bodyParameters[paramIndex++];
                }

                return(returnValue);
            }
            catch (InvalidOperationException e)
            {
                // all exceptions from XmlSerializer get wrapped in InvalidOperationException,
                // so we must be conservative and never turn this into a fault
                string resourceKey = isRequest ? SR.SFxErrorDeserializingRequestBody : SR.SFxErrorDeserializingReplyBody;

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                              SR.Format(resourceKey, OperationName), e));
            }
        }
コード例 #42
0
        public static bool IsSendParameterContent(OperationDescription operation)
        {
            Fx.Assert(operation != null, "OperationDescription should not be null");
            if (operation.IsOneWay)
            {
                return(false);
            }

            bool contentIsParameter = false;
            bool isSendContentEmpty = false;
            MessageDescription message;

            if (operation.Messages.Count > 1)
            {
                message            = operation.Messages[1];
                contentIsParameter = false;

                if (message.MessageType == null)
                {
                    if (message.Body.ReturnValue != null && message.Body.ReturnValue.Type != typeof(void))
                    {
                        if (!message.Body.ReturnValue.Type.IsAssignableFrom(typeof(System.ServiceModel.Channels.Message)))
                        {
                            contentIsParameter = true;
                        }

                        isSendContentEmpty = true;
                    }
                }

                if (message.MessageType == null)
                {
                    if (message.Body.Parts != null)
                    {
                        if (message.Body.Parts.Count > 0)
                        {
                            MessagePartDescriptionCollection parts = message.Body.Parts;
                            foreach (MessagePartDescription messagePart in parts)
                            {
                                if (messagePart.Index >= 0)
                                {
                                    contentIsParameter = true;
                                    break;
                                }
                                if (!messagePart.Type.IsAssignableFrom(typeof(System.ServiceModel.Channels.Message)))
                                {
                                    contentIsParameter = true;
                                }
                            }
                            isSendContentEmpty = true;
                        }
                    }
                }

                if (!isSendContentEmpty)
                {
                    if (message.MessageType != null && message.MessageType.IsDefined(typeof(MessageContractAttribute), false))
                    {
                        contentIsParameter = false;
                    }
                    else if (operation.Messages[0].MessageType != null)
                    {
                        contentIsParameter = false;
                    }
                    else if (operation.Messages[0].Body.Parts != null &&
                             operation.Messages[0].Body.Parts.Count == 1 &&
                             operation.Messages[0].Body.Parts[0].Type.IsAssignableFrom(typeof(System.ServiceModel.Channels.Message)))
                    {
                        contentIsParameter = false;
                    }
                    else
                    {
                        contentIsParameter = true;
                    }
                }
            }

            return(contentIsParameter);
        }
コード例 #43
0
ファイル: WebHttpBehavior3.cs プロジェクト: nuxleus/WCFWeb
        private void CheckNoUnmappedParameters(OperationDescription operationDescription, int jsonValuePosition)
        {
            string             uriTemplate = null;
            WebInvokeAttribute wia         = operationDescription.Behaviors.Find <WebInvokeAttribute>();
            MessagePartDescriptionCollection inputBodyParts = operationDescription.Messages[0].Body.Parts;

            if (wia != null)
            {
                uriTemplate = wia.UriTemplate;
            }

            // if uriTemplate == null, no parameters are bound to the template; JsonValue must be the only parameter in the operation
            if (uriTemplate != null)
            {
                UriTemplate template = new UriTemplate(uriTemplate);
                Dictionary <string, Type> operationParameters       = new Dictionary <string, Type>(StringComparer.OrdinalIgnoreCase);
                Dictionary <string, bool> mappedOperationParameters = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                for (int i = 0; i < inputBodyParts.Count; i++)
                {
                    if (i != jsonValuePosition)
                    {
                        operationParameters.Add(inputBodyParts[i].Name, inputBodyParts[i].Type);
                        mappedOperationParameters[inputBodyParts[i].Name] = false;
                    }
                }

                foreach (string pathVar in template.PathSegmentVariableNames)
                {
                    if (operationParameters.ContainsKey(pathVar))
                    {
                        mappedOperationParameters[pathVar] = true;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.UriTemplateParameterNotInOperation,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name,
                                          pathVar)));
                    }
                }

                QueryStringConverter qsc = this.GetQueryStringConverter(operationDescription);
                foreach (string queryVar in template.QueryValueVariableNames)
                {
                    if (operationParameters.ContainsKey(queryVar))
                    {
                        mappedOperationParameters[queryVar] = true;
                        if (!qsc.CanConvert(operationParameters[queryVar]))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                      new InvalidOperationException(
                                          DiagnosticUtility.GetString(
                                              SR.QueryVariableCannotBeConverted,
                                              operationDescription.Name,
                                              operationDescription.DeclaringContract.Name,
                                              queryVar,
                                              operationParameters[queryVar].FullName,
                                              qsc.GetType().Name)));
                        }
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.UriTemplateParameterNotInOperation,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name,
                                          queryVar)));
                    }
                }

                foreach (string paramName in mappedOperationParameters.Keys)
                {
                    if (!mappedOperationParameters[paramName])
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.ParameterUnmappedInUriTemplate,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name)));
                    }
                }
            }
        }
コード例 #44
0
        private void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, object returnValue, object[] parameters)
        {
            if (serializer == null)
            {
                return;
            }

            bool hasReturnValue = IsValidReturnValue(returnPart);

            object[] bodyParameters = new object[bodyParts.Count + (hasReturnValue ? 1 : 0)];
            int      paramIndex     = 0;

            if (hasReturnValue)
            {
                bodyParameters[paramIndex++] = returnValue;
            }

            for (int i = 0; i < bodyParts.Count; i++)
            {
                bodyParameters[paramIndex++] = parameters[bodyParts[i].Index];
            }

            string encoding = _isEncoded ? GetEncoding(version.Envelope) : null;

            serializer.Serialize(writer, bodyParameters, null);
        }
コード例 #45
0
ファイル: WebHttpBehavior3.cs プロジェクト: nuxleus/WCFWeb
        private static bool HasExactlyOneJsonValue(MessagePartDescriptionCollection parts, out int jsonValuePosition)
        {
            int count = 0;
            jsonValuePosition = -1;
            for (int i = 0; i < parts.Count; i++)
            {
                if (parts[i].Type == typeof(JsonValue) || parts[i].Type == typeof(JsonObject))
                {
                    count++;
                    jsonValuePosition = i;
                }

                if (count > 1)
                {
                    break;
                }
            }

            return count == 1;
        }