Ejemplo n.º 1
0
 private void ValidateMessagePartDescription(MessagePartDescription part)
 {
     if (part != null)
     {
         this.ValidateCustomSerializableType(part.Type);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Add the Ping method to the existing contract
        /// </summary>
        private void AddPingToContractDescription(ContractDescription contractDescription)
        {
            OperationDescription pingOperationDescription = new OperationDescription(PingOperationName, contractDescription);

            MessageDescription inputMessageDescription = new MessageDescription(
                GetAction(contractDescription, PingOperationName),
                MessageDirection.Input);

            MessageDescription outputMessageDescription = new MessageDescription(
                GetAction(contractDescription, PingResponse),
                MessageDirection.Output);

            MessagePartDescription returnValue = new MessagePartDescription("PingResult", contractDescription.Namespace);

            returnValue.Type = typeof(DateTime);
            outputMessageDescription.Body.ReturnValue = returnValue;

            inputMessageDescription.Body.WrapperName = PingOperationName;
            inputMessageDescription.Body.WrapperNamespace = contractDescription.Namespace;
            outputMessageDescription.Body.WrapperName = PingResponse;
            outputMessageDescription.Body.WrapperNamespace = contractDescription.Namespace;

            pingOperationDescription.Messages.Add(inputMessageDescription);
            pingOperationDescription.Messages.Add(outputMessageDescription);

            pingOperationDescription.Behaviors.Add(new DataContractSerializerOperationBehavior(pingOperationDescription));
            pingOperationDescription.Behaviors.Add(new PingOperationBehavior());

            contractDescription.Operations.Add(pingOperationDescription);
        }
Ejemplo n.º 3
0
		private XmlReflectionMember CreateReflectionMember (MessagePartDescription partDesc, bool isReturnValue)
		{
			XmlReflectionMember m = new XmlReflectionMember ();
			m.IsReturnValue = isReturnValue;
			m.MemberName = partDesc.Name;
			m.MemberType = partDesc.Type;
			return m;
		}
 internal void Add(MessagePartDescription part, XmlMemberMapping memberMapping, XmlMembersMapping membersMapping, bool isEncoded)
 {
     PartInfo partInfo = new PartInfo();
     partInfo.MemberMapping = memberMapping;
     partInfo.MembersMapping = membersMapping;
     partInfo.IsEncoded = isEncoded;
     partInfoTable[part] = partInfo;
 }
Ejemplo n.º 5
0
		private XmlReflectionMember CreateReflectionMember (MessagePartDescription partDesc, bool isReturnValue)
		{
			XmlReflectionMember m = new XmlReflectionMember ();
			m.IsReturnValue = isReturnValue;
			m.MemberName = partDesc.Name;
			m.MemberType = partDesc.Type;
			m.XmlAttributes = partDesc.MemberInfo == null ? new XmlAttributes () : new XmlAttributes (partDesc.MemberInfo);
			return m;
		}
 public RequestMessagePartDescription(MessagePartDescription messagePart, MessagePartType partType, string alias)
     : base(messagePart.Name, messagePart.Namespace)
 {
     Index = messagePart.Index;
     MemberInfo = messagePart.MemberInfo;
     Multiple = messagePart.Multiple;
     ProtectionLevel = messagePart.ProtectionLevel;
     Type = messagePart.Type;
     Alias = alias;
     PartType = partType;
 }
 internal static XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isEncoded, bool isWrapped)
 {
     string ns = isRpc ? null : part.Namespace;
     ICustomAttributeProvider additionalAttributesProvider = null;
     if (isEncoded || (part.AdditionalAttributesProvider is MemberInfo))
     {
         additionalAttributesProvider = part.AdditionalAttributesProvider;
     }
     System.ServiceModel.Description.XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new System.ServiceModel.Description.XmlName(part.UniquePartName, true);
     System.ServiceModel.Description.XmlName xmlName = part.XmlName;
     return GetXmlReflectionMember(memberName, xmlName, ns, part.Type, additionalAttributesProvider, part.Multiple, isEncoded, isWrapped);
 }
Ejemplo n.º 8
0
 private StreamFormatter(MessageDescription messageDescription, MessagePartDescription streamPart, string operationName, bool isRequest)
 {
     if ((object)streamPart == (object)messageDescription.Body.ReturnValue)
         _streamIndex = returnValueIndex;
     else
         _streamIndex = streamPart.Index;
     _wrapperName = messageDescription.Body.WrapperName;
     _wrapperNS = messageDescription.Body.WrapperNamespace;
     _partName = streamPart.Name;
     _partNS = streamPart.Namespace;
     _isRequest = isRequest;
     _operationName = operationName;
 }
 internal MessagePartDescription(MessagePartDescription other)
 {
     this.name = other.name;
     this.ns = other.ns;
     this.index = other.index;
     this.type = other.type;
     this.serializationPosition = other.serializationPosition;
     this.hasProtectionLevel = other.hasProtectionLevel;
     this.protectionLevel = other.protectionLevel;
     this.memberInfo = other.memberInfo;
     this.multiple = other.multiple;
     this.additionalAttributesProvider = other.additionalAttributesProvider;
     this.baseType = other.baseType;
     this.uniquePartName = other.uniquePartName;
 }
 internal MessagePartDescription(MessagePartDescription other)
 {
     _name = other._name;
     _ns = other._ns;
     _index = other._index;
     _type = other._type;
     _serializationPosition = other._serializationPosition;
     _hasProtectionLevel = other._hasProtectionLevel;
     _protectionLevel = other._protectionLevel;
     _memberInfo = other._memberInfo;
     _multiple = other._multiple;
     _additionalAttributesProvider = other._additionalAttributesProvider;
     _baseType = other._baseType;
     _uniquePartName = other._uniquePartName;
 }
 private StreamFormatter(MessageDescription messageDescription, MessagePartDescription streamPart, string operationName, bool isRequest)
 {
     if (streamPart == messageDescription.Body.ReturnValue)
     {
         this.streamIndex = -1;
     }
     else
     {
         this.streamIndex = streamPart.Index;
     }
     this.wrapperName = messageDescription.Body.WrapperName;
     this.wrapperNS = messageDescription.Body.WrapperNamespace;
     this.partName = streamPart.Name;
     this.partNS = streamPart.Namespace;
     this.isRequest = isRequest;
     this.operationName = operationName;
 }
 public static void AddMessagePartDescription(OperationDescription operation, bool isResponse, MessageDescription message, string[] argumentNames, Type[] argumentTypes)
 {
     string ns = operation.DeclaringContract.Namespace;
     for (int i = 0; i < argumentNames.Length; i++)
     {
         string name = argumentNames[i];
         MessagePartDescription item = new MessagePartDescription(NamingHelper.XmlName(name), ns) {
             Index = i,
             Type = argumentTypes[i]
         };
         message.Body.Parts.Add(item);
     }
     if (isResponse)
     {
         SetReturnValue(message, operation);
     }
 }
        /// <summary>
        /// Adds an item to the collection.
        /// </summary>
        /// <param name="item">The object to add to the collection.</param>
        public void Add(HttpParameterDescription item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (this.IsSynchronized)
            {
                MessagePartDescription           mpd     = this.EnsureSynchronizedMessagePartDescription(item);
                MessagePartDescriptionCollection mpdColl = this.GetOrCreateMessagePartDescriptionCollection();
                mpdColl.Add(mpd);
            }
            else
            {
                this.innerCollection.Add(item);
            }
        }
            public void AddMemberAttributes(XmlName messageName, MessagePartDescription part, CodeAttributeDeclarationCollection attributesImported, CodeAttributeDeclarationCollection typeAttributes, CodeAttributeDeclarationCollection fieldAttributes)
            {
                CodeAttributeDeclaration dataContractAttributeDecl = null;

                foreach (CodeAttributeDeclaration attr in typeAttributes)
                {
                    if (attr.AttributeType.BaseType == dataContractAttributeTypeRef.BaseType)
                    {
                        dataContractAttributeDecl = attr;
                        break;
                    }
                }

                if (dataContractAttributeDecl == null)
                {
                    Fx.Assert(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for  {0}", messageName));

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for  {0}", messageName)));
                }
                bool nsAttrFound = false;

                foreach (CodeAttributeArgument attrArg in dataContractAttributeDecl.Arguments)
                {
                    if (attrArg.Name == "Namespace")
                    {
                        nsAttrFound = true;
                        string nsValue = ((CodePrimitiveExpression)attrArg.Value).Value.ToString();
                        if (nsValue != part.Namespace)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxWrapperTypeHasMultipleNamespaces, messageName)));
                        }
                    }
                }
                if (!nsAttrFound)
                {
                    dataContractAttributeDecl.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(part.Namespace)));
                }

                DataMemberAttribute dataMemberAttribute = new DataMemberAttribute();

                dataMemberAttribute.Order            = memberCount++;
                dataMemberAttribute.EmitDefaultValue = !IsNonNillableReferenceType(part);
                fieldAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(context.Contract.ServiceContractGenerator, dataMemberAttribute));
            }
        void AddKnownTypesForPart(OperationContractGenerationContext context, MessagePartDescription part, Dictionary <CodeTypeReference, object> operationKnownTypes)
        {
            ICollection <CodeTypeReference> knownTypesForPart;

            if (knownTypes.TryGetValue(part, out knownTypesForPart))
            {
                foreach (CodeTypeReference knownTypeReference in knownTypesForPart)
                {
                    object value;
                    if (!operationKnownTypes.TryGetValue(knownTypeReference, out value))
                    {
                        operationKnownTypes.Add(knownTypeReference, null);
                        CodeAttributeDeclaration knownTypeAttribute = new CodeAttributeDeclaration(typeof(ServiceKnownTypeAttribute).FullName);
                        knownTypeAttribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(knownTypeReference)));
                        context.SyncMethod.CustomAttributes.Add(knownTypeAttribute);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        XmlSchemaElement GetSchemaElementForPart(MessagePartDescription part, XmlSchema schema)
        {
            XmlSchemaElement element = new XmlSchemaElement();

            element.Name = part.Name;
            XsdExporter.Export(part.Type);
            element.SchemaTypeName = XsdExporter.GetSchemaTypeName(part.Type);
            AddImport(schema, element.SchemaTypeName.Namespace);

            //FIXME: nillable, minOccurs
            if (XsdExporter.GetSchemaType(part.Type) is XmlSchemaComplexType ||
                part.Type == typeof(string))
            {
                element.IsNillable = true;
            }
            element.MinOccurs = 0;

            return(element);
        }
Ejemplo n.º 17
0
 private void ExportDataContract(MessagePartDescription md)
 {
     if (data_contract_importer == null)
     {
         data_contract_importer = md.DataContractImporter;
     }
     else if (md.DataContractImporter != null && data_contract_importer != md.DataContractImporter)
     {
         throw new Exception("INTERNAL ERROR: should not happen");
     }
     if (xml_serialization_importer == null)
     {
         xml_serialization_importer = md.XmlSerializationImporter;
     }
     else if (md.XmlSerializationImporter != null && xml_serialization_importer != md.XmlSerializationImporter)
     {
         throw new Exception("INTERNAL ERROR: should not happen");
     }
 }
Ejemplo n.º 18
0
        /* Sets the @name if the param or return type is SMMessage */
        string IsTypeMessage(MessageBodyDescription msgbody)
        {
            MessagePartDescription part = null;

            if (msgbody.Parts.Count == 0)
            {
                part = msgbody.ReturnValue;
            }
            else if (msgbody.Parts.Count == 1)
            {
                part = msgbody.Parts [0];
            }

            if (part != null && (part.Type.FullName == typeof(SMMessage).FullName))
            {
                return(part.Name);
            }

            return(null);
        }
 public static void AddMessagePartDescription(OperationDescription operation, bool isResponse, MessageDescription message, Type type, SerializerOption serializerOption)
 {
     if (type != null)
     {
         string name;
         string str2;
         if (serializerOption == SerializerOption.DataContractSerializer)
         {
             XmlQualifiedName rootElementName = XsdDataContractExporter.GetRootElementName(type);
             if (rootElementName == null)
             {
                 rootElementName = XsdDataContractExporter.GetSchemaTypeName(type);
             }
             if (!rootElementName.IsEmpty)
             {
                 name = rootElementName.Name;
                 str2 = rootElementName.Namespace;
             }
             else
             {
                 name = type.Name;
                 str2 = operation.DeclaringContract.Namespace;
             }
         }
         else
         {
             XmlTypeMapping mapping = XmlReflectionImporter.ImportTypeMapping(type);
             name = mapping.ElementName;
             str2 = mapping.Namespace;
         }
         MessagePartDescription item = new MessagePartDescription(NamingHelper.XmlName(name), str2) {
             Index = 0,
             Type = type
         };
         message.Body.Parts.Add(item);
     }
     if (isResponse)
     {
         SetReturnValue(message, operation);
     }
 }
        /// <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(HttpParameterDescription item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

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

                MessagePartDescription mpd = this.EnsureSynchronizedMessagePartDescription(item);
                return(mpdColl.IndexOf(mpd));
            }

            return(this.innerCollection.IndexOf(item));
        }
        /// <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(HttpParameterDescription item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (this.IsSynchronized)
            {
                MessagePartDescriptionCollection mdpColl = this.MessagePartDescriptionCollection;
                if (mdpColl == null)
                {
                    return(false);
                }

                MessagePartDescription mpd = this.EnsureSynchronizedMessagePartDescription(item);
                return(mdpColl.Remove(mpd));
            }

            return(this.innerCollection.Remove(item));
        }
            public void AddMemberAttributes(XmlName messageName, MessagePartDescription part, CodeAttributeDeclarationCollection attributesImported, CodeAttributeDeclarationCollection typeAttributes, CodeAttributeDeclarationCollection fieldAttributes)
            {
                CodeAttributeDeclaration declaration = null;

                foreach (CodeAttributeDeclaration declaration2 in typeAttributes)
                {
                    if (declaration2.AttributeType.BaseType == dataContractAttributeTypeRef.BaseType)
                    {
                        declaration = declaration2;
                        break;
                    }
                }
                if (declaration == null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for  {0}", new object[] { messageName })));
                }
                bool flag = false;

                foreach (CodeAttributeArgument argument in declaration.Arguments)
                {
                    if (argument.Name == "Namespace")
                    {
                        flag = true;
                        if (((CodePrimitiveExpression)argument.Value).Value.ToString() != part.Namespace)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxWrapperTypeHasMultipleNamespaces", new object[] { messageName })));
                        }
                    }
                }
                if (!flag)
                {
                    declaration.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(part.Namespace)));
                }
                DataMemberAttribute attribute = new DataMemberAttribute {
                    Order            = this.memberCount++,
                    EmitDefaultValue = !this.IsNonNillableReferenceType(part)
                };

                fieldAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(this.context.Contract.ServiceContractGenerator, attribute));
            }
Ejemplo n.º 23
0
 protected void ExportMessagePart(Message message, MessagePartDescription part, XmlQualifiedName typeName, XmlSchemaType xsdType, bool isOptional, bool isNillable, bool skipSchemaExport, bool generateElement, string wrapperNs, XmlSchemaSequence wrapperSequence, XmlSchemaSet schemaSet)
 {
     if (!IsNullOrEmpty(typeName) || (xsdType != null))
     {
         string      name        = part.Name;
         string      elementName = string.IsNullOrEmpty(part.UniquePartName) ? name : part.UniquePartName;
         MessagePart part2       = null;
         if (generateElement)
         {
             if (wrapperSequence != null)
             {
                 if (!skipSchemaExport)
                 {
                     this.ExportLocalElement(wrapperNs, elementName, part.Namespace, typeName, xsdType, part.Multiple, isOptional, isNillable, wrapperSequence, schemaSet);
                 }
             }
             else
             {
                 if (!skipSchemaExport)
                 {
                     this.ExportGlobalElement(name, part.Namespace, isNillable, typeName, xsdType, schemaSet);
                 }
                 part2 = AddMessagePart(message, elementName, new XmlQualifiedName(name, part.Namespace), XmlQualifiedName.Empty);
             }
         }
         else
         {
             if (string.IsNullOrEmpty(typeName.Name))
             {
                 throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxAnonymousTypeNotSupported", new object[] { message.Name, elementName })));
             }
             part2 = AddMessagePart(message, elementName, XmlQualifiedName.Empty, typeName);
         }
         if (part2 != null)
         {
             part.UniquePartName = part2.Name;
         }
     }
 }
                private MessagePartDescription GetWrapperPart(MessageDescription message)
                {
                    if (message.Body.Parts.Count != 1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxRpcMessageMustHaveASingleBody", new object[] { this.Operation.Name, message.MessageName })));
                    }
                    MessagePartDescription description = message.Body.Parts[0];

                    System.Type c = description.Type;
                    if ((c.BaseType != null) && (c.BaseType != typeof(object)))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxBodyObjectTypeCannotBeInherited", new object[] { c.FullName })));
                    }
                    if (typeof(IEnumerable).IsAssignableFrom(c))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxBodyObjectTypeCannotBeInterface", new object[] { c.FullName, typeof(IEnumerable).FullName })));
                    }
                    if (typeof(IXmlSerializable).IsAssignableFrom(c))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxBodyObjectTypeCannotBeInterface", new object[] { c.FullName, typeof(IXmlSerializable).FullName })));
                    }
                    return(description);
                }
        /// <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(HttpParameterDescription item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (this.IsSynchronized)
            {
                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 HttpParameterDescription.
                MessagePartDescription mpd = this.EnsureSynchronizedMessagePartDescription(item);
                return(mdpColl.Contains(mpd));
            }

            return(this.innerCollection.Contains(item));
        }
        /// <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, HttpParameterDescription item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

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

            if (this.IsSynchronized)
            {
                MessagePartDescription           mpd     = this.EnsureSynchronizedMessagePartDescription(item);
                MessagePartDescriptionCollection mpdColl = this.GetOrCreateMessagePartDescriptionCollection();
                Debug.Assert(mpdColl != null, "MessagePartDescriptionCollection cannot be null");
                mpdColl.Insert(index, mpd);
            }
            else
            {
                this.innerCollection.Insert(index, item);
            }
        }
        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);
        }
 static internal XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isWrapped)
 {
     string ns = isRpc ? null : part.Namespace;
     MemberInfo additionalAttributesProvider = null;
     if (part.AdditionalAttributesProvider.MemberInfo != null)
         additionalAttributesProvider = part.AdditionalAttributesProvider.MemberInfo;
     XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new XmlName(part.UniquePartName, true /*isEncoded*/);
     XmlName elementName = part.XmlName;
     return GetXmlReflectionMember(memberName, elementName, ns, part.Type, additionalAttributesProvider, part.Multiple, isWrapped);
 }
        private void AddKnownTypesForPart(OperationContractGenerationContext context, MessagePartDescription part, Dictionary <CodeTypeReference, object> operationKnownTypes)
        {
            ICollection <CodeTypeReference> is2;

            if (this.knownTypes.TryGetValue(part, out is2))
            {
                foreach (CodeTypeReference reference in is2)
                {
                    object obj2;
                    if (!operationKnownTypes.TryGetValue(reference, out obj2))
                    {
                        operationKnownTypes.Add(reference, null);
                        CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(typeof(ServiceKnownTypeAttribute).FullName);
                        declaration.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(reference)));
                        context.SyncMethod.CustomAttributes.Add(declaration);
                    }
                }
            }
        }
        protected void ExportMessagePart(WsdlNS.Message message, MessagePartDescription part, XmlQualifiedName typeName, XmlSchemaType xsdType, bool isOptional, bool isNillable, bool skipSchemaExport, bool generateElement, string wrapperNs, XmlSchemaSequence wrapperSequence, XmlSchemaSet schemaSet)
        {
            if (IsNullOrEmpty(typeName) && xsdType == null)
                return;
#if DEBUG
            if (xsdType == null)
                Fx.Assert(NamingHelper.IsValidNCName(typeName.Name), "Name value has to be a valid NCName.");
#endif
            string elementName = part.Name;
            string partName = string.IsNullOrEmpty(part.UniquePartName) ? elementName : part.UniquePartName;

            WsdlNS.MessagePart wsdlPart = null;
            if (generateElement)
            {
                if (wrapperSequence != null)
                {
                    if (!skipSchemaExport)
                        ExportLocalElement(wrapperNs, partName, part.Namespace, typeName, xsdType, part.Multiple, isOptional, isNillable, wrapperSequence, schemaSet);
                }
                else
                {
                    if (!skipSchemaExport)
                        ExportGlobalElement(elementName, part.Namespace, isNillable, typeName, xsdType, schemaSet);
                    wsdlPart = AddMessagePart(message, partName, new XmlQualifiedName(elementName, part.Namespace), XmlQualifiedName.Empty);
                }
            }
            else
            {
                if (String.IsNullOrEmpty(typeName.Name))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxAnonymousTypeNotSupported, message.Name, partName)));

                wsdlPart = AddMessagePart(message, partName, XmlQualifiedName.Empty, typeName);
            }
            if (wsdlPart != null)
            {
                part.UniquePartName = wsdlPart.Name;
            }
        }
 /// <summary>
 /// Validates the message part description.
 /// </summary>
 /// <param name="messagePartDescription">The message part description.</param>
 private static void ValidateMessagePartDescription(MessagePartDescription messagePartDescription)
 {
     if (messagePartDescription != null)
     {
         ValidateJsonSerializableType(messagePartDescription.Type);
     }
 }
Ejemplo n.º 32
0
		protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
		{
			if (part.Type == typeof (void))
				return null; // no serialization should be done.

			switch (msgfmt) {
			case WebContentFormat.Xml:
				if (xml_serializer == null)
					xml_serializer = isWrapped ? new DataContractSerializer (part.Type, part.Name, part.Namespace) : new DataContractSerializer (part.Type);
				return xml_serializer;
			case WebContentFormat.Json:
				// FIXME: after name argument they are hack
				if (json_serializer == null)
					json_serializer = isWrapped ? new DataContractJsonSerializer (part.Type, BodyName ?? part.Name, null, 0x100000, false, null, true) : new DataContractJsonSerializer (part.Type);
				return json_serializer;
			default:
				throw new NotImplementedException (msgfmt.ToString ());
			}
		}
Ejemplo n.º 33
0
        void resolveParticle(XmlSchemaImporter schema_importer,
                             XmlSchemaParticle particle,
                             List <MessagePartDescription> parts,
                             string ns,
                             int depth)
        {
            if (particle is XmlSchemaGroupBase)
            {
                //sequence,
                //FIXME: others?
                if (depth <= 0)
                {
                    return;
                }

                XmlSchemaGroupBase groupBase = particle as XmlSchemaGroupBase;
                foreach (XmlSchemaParticle item in groupBase.Items)
                {
                    resolveParticle(schema_importer, item, parts, ns, depth - 1);
                }

                return;
            }

            XmlSchemaElement elem = particle as XmlSchemaElement;

            if (elem == null)
            {
                return;
            }

            MessagePartDescription msg_part = null;

            XmlSchemaComplexType ct = elem.ElementSchemaType as XmlSchemaComplexType;

            if (ct == null)
            {
                //Not a complex type
                XmlSchemaSimpleType simple = elem.ElementSchemaType as XmlSchemaSimpleType;
                msg_part = new MessagePartDescription(
                    elem.Name, ns);
                if (elem.SchemaType != null)
                {
                    msg_part.XmlTypeMapping = schema_importer.ImportTypeMapping(elem.QualifiedName);
                }
                else
                {
                    msg_part.XmlTypeMapping = schema_importer.ImportSchemaType(elem.SchemaTypeName);
                }
                msg_part.TypeName = new QName(GetCLRTypeName(elem.SchemaTypeName), "");
                parts.Add(msg_part);

                return;
            }

            if (depth > 0)
            {
                resolveParticle(schema_importer, ct.ContentTypeParticle, parts, ns, depth - 1);
                return;
            }

            //depth <= 0
            msg_part = new MessagePartDescription(elem.Name, ns);
            if (elem.SchemaType != null)
            {
                msg_part.XmlTypeMapping = schema_importer.ImportTypeMapping(elem.QualifiedName);
            }
            else
            {
                msg_part.XmlTypeMapping = schema_importer.ImportSchemaType(elem.SchemaTypeName);
            }
            msg_part.TypeName = elem.SchemaTypeName;

            parts.Add(msg_part);
        }
Ejemplo n.º 34
0
        private static bool IsTypeSupported(MessagePartDescription bodyDescription)
        {
            Fx.Assert(bodyDescription != null, "");
            Type type = bodyDescription.Type;
            if (type == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxMessagePartDescriptionMissingType, bodyDescription.Name, bodyDescription.Namespace)));

            if (bodyDescription.Multiple)
                return false;

            if (type == typeof(void))
                return true;
            if (type.IsEnum())
                return false;
            switch (type.GetTypeCode())
            {
                case TypeCode.Boolean:
                case TypeCode.DateTime:
                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Single:
                case TypeCode.String:
                    return true;
                case TypeCode.Object:
                    if (type.IsArray && type.GetArrayRank() == 1 && IsArrayTypeSupported(type.GetElementType()))
                        return true;
                    break;
                default:
                    break;
            }
            return false;
        }
Ejemplo n.º 35
0
 private static PartInfo AddToDictionary(XmlDictionary dictionary, MessagePartDescription part, bool isRpc)
 {
     Type type = part.Type;
     XmlDictionaryString itemName = null;
     XmlDictionaryString itemNamespace = null;
     if (type.IsArray && type != typeof(byte[]))
     {
         const string ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
         string name = GetArrayItemName(type.GetElementType());
         itemName = AddToDictionary(dictionary, name);
         itemNamespace = AddToDictionary(dictionary, ns);
     }
     return new PartInfo(part,
         AddToDictionary(dictionary, part.Name),
         AddToDictionary(dictionary, isRpc ? string.Empty : part.Namespace),
         itemName, itemNamespace);
 }
        /// <summary>
        /// Create operation corresponding to given DomainService operation.
        /// </summary>
        /// <param name="declaringContract">Contract to which operation will belong.</param>
        /// <param name="operation">DomainService operation.</param>
        /// <returns>Created operation.</returns>
        private static OperationDescription CreateOperationDescription(ContractDescription declaringContract, DomainOperationEntry operation)
        {
            OperationDescription operationDesc = new OperationDescription(operation.Name, declaringContract);

            // Propagate behaviors.
            foreach (IOperationBehavior behavior in operation.Attributes.OfType<IOperationBehavior>())
            {
                operationDesc.Behaviors.Add(behavior);
            }

            // Add standard web behaviors behaviors.
            if ((operation.Operation == DomainOperation.Query && ((QueryAttribute)operation.OperationAttribute).HasSideEffects) ||
                (operation.Operation == DomainOperation.Invoke && ((InvokeAttribute)operation.OperationAttribute).HasSideEffects))
            {
                // For operations with side-effects i.e. with WebInvoke attribute, we need to build a default GET like
                // URI template so that, the parameter processing is taken care of by the WebHttpBehavior selector.
                WebInvokeAttribute attrib = ServiceUtils.EnsureBehavior<WebInvokeAttribute>(operationDesc);
                if (attrib.UriTemplate == null)
                {
                    attrib.UriTemplate = ODataEndpointFactory.BuildDefaultUriTemplate(operation);
                }
            }
            else
            {
                ServiceUtils.EnsureBehavior<WebGetAttribute>(operationDesc);
            }

            string action = ServiceUtils.GetRequestMessageAction(declaringContract, operationDesc.Name, null);

            // Define operation input.
            MessageDescription inputMessageDesc = new MessageDescription(action, MessageDirection.Input);
            inputMessageDesc.Body.WrapperName = operationDesc.Name;
            inputMessageDesc.Body.WrapperNamespace = ServiceUtils.DefaultNamespace;

            for (int i = 0; i < operation.Parameters.Count; i++)
            {
                DomainOperationParameter parameter = operation.Parameters[i];

                MessagePartDescription parameterPartDesc = new MessagePartDescription(parameter.Name, ServiceUtils.DefaultNamespace)
                {
                    Index = i,
                    Type = TypeUtils.GetClientType(parameter.ParameterType)
                };
                inputMessageDesc.Body.Parts.Add(parameterPartDesc);
            }

            operationDesc.Messages.Add(inputMessageDesc);

            // Define operation output.
            string responseAction = ServiceUtils.GetResponseMessageAction(declaringContract, operationDesc.Name, null);

            MessageDescription outputMessageDesc = new MessageDescription(responseAction, MessageDirection.Output);
            outputMessageDesc.Body.WrapperName = operationDesc.Name + "Response";
            outputMessageDesc.Body.WrapperNamespace = ServiceUtils.DefaultNamespace;

            if (operation.ReturnType != typeof(void))
            {
                outputMessageDesc.Body.ReturnValue = new MessagePartDescription(operationDesc.Name + "Result", ServiceUtils.DefaultNamespace)
                {
                    Type = TypeUtils.GetClientType(operation.ReturnType)
                };
            }
            operationDesc.Messages.Add(outputMessageDesc);

            return operationDesc;
        }
Ejemplo n.º 37
0
		public bool IsValidReturnValue (MessagePartDescription part)
		{
			return part != null && part.Type != typeof (void);
		}
Ejemplo n.º 38
0
			void WriteMessagePart (
				XmlDictionaryWriter writer, MessageBodyDescription desc, MessagePartDescription partDesc, object obj)
			{
				parent.GetSerializer (partDesc).WriteObject (writer, obj);
			}
Ejemplo n.º 39
0
		XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
		{
			if (!serializers.ContainsKey (partDesc))
				serializers [partDesc] = new DataContractSerializer (
					partDesc.Type, partDesc.Name, partDesc.Namespace, OperationKnownTypes);
			return serializers [partDesc];
		}
Ejemplo n.º 40
0
        static MessageDescription GetMessage(
            OperationDescription od, MethodInfo mi,
            OperationContractAttribute oca, bool isRequest,
            bool isCallback, Type asyncReturnType)
        {
            ContractDescription cd = od.DeclaringContract;

            ParameterInfo []         plist       = mi.GetParameters();
            Type                     messageType = null;
            string                   action      = isRequest ? oca.Action : oca.ReplyAction;
            MessageContractAttribute mca;

            Type retType = asyncReturnType;

            if (!isRequest && retType == null)
            {
                retType = mi.ReturnType;
            }

            // If the argument is only one and has [MessageContract]
            // then infer it as a typed messsage
            if (isRequest)
            {
                int len = mi.Name.StartsWith("Begin", StringComparison.Ordinal) ? 3 : 1;
                mca = plist.Length != len ? null :
                      GetMessageContractAttribute(plist [0].ParameterType);
                if (mca != null)
                {
                    messageType = plist [0].ParameterType;
                }
            }
            else
            {
                mca = GetMessageContractAttribute(retType);
                if (mca != null)
                {
                    messageType = retType;
                }
            }

            if (action == null)
            {
                action = String.Concat(cd.Namespace,
                                       cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith("/") ? "" : "/", cd.Name, "/",
                                       od.Name, isRequest ? String.Empty : "Response");
            }

            MessageDescription md;

            if (mca != null)
            {
                md = CreateMessageDescription(messageType, cd.Namespace, action, isRequest, isCallback, mca);
            }
            else
            {
                md = CreateMessageDescription(oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
            }

            // ReturnValue
            if (!isRequest)
            {
                MessagePartDescription mp = CreatePartCore(GetMessageParameterAttribute(mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
                mp.Index            = 0;
                mp.Type             = mca != null ? typeof(void) : retType;
                md.Body.ReturnValue = mp;
            }

            return(md);
        }
        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));
            }
        }
Ejemplo n.º 42
0
		private void ExportDataContract (MessagePartDescription md)
		{
			if (data_contract_importer == null)
				data_contract_importer = md.DataContractImporter;
			else if (md.DataContractImporter != null && data_contract_importer != md.DataContractImporter)
				throw new Exception ("INTERNAL ERROR: should not happen");
			if (xml_serialization_importer == null)
				xml_serialization_importer = md.XmlSerializationImporter;
			else if (md.XmlSerializationImporter != null && xml_serialization_importer != md.XmlSerializationImporter)
				throw new Exception ("INTERNAL ERROR: should not happen");
		}
Ejemplo n.º 43
0
 public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
 {
     _dictionaryName = dictionaryName;
     _dictionaryNamespace = dictionaryNamespace;
     _itemName = itemName;
     _itemNamespace = itemNamespace;
     _description = description;
     if (description.Type.IsArray)
     {
         _isArray = true;
         _typeCode = description.Type.GetElementType().GetTypeCode();
     }
     else
     {
         _isArray = false;
         _typeCode = description.Type.GetTypeCode();
     }
 }
        void ValidateExistingOrSetNewProtectionLevel(MessagePartDescription part, MessageDescription message, OperationDescription operation, ContractDescription contract, ProtectionLevel newProtectionLevel)
        {
            ProtectionLevel existingProtectionLevel;

            if (part != null && part.HasProtectionLevel)
            {
                existingProtectionLevel = part.ProtectionLevel;
            }
            else if (message.HasProtectionLevel)
            {
                existingProtectionLevel = message.ProtectionLevel;
            }
            else if (operation.HasProtectionLevel)
            {
                existingProtectionLevel = operation.ProtectionLevel;
            }
            else
            {
                if (part != null)
                {
                    part.ProtectionLevel = newProtectionLevel;
                }
                else
                {
                    message.ProtectionLevel = newProtectionLevel;
                }
                existingProtectionLevel = newProtectionLevel;
            }

            if (existingProtectionLevel != newProtectionLevel)
            {
                if (part != null && !part.HasProtectionLevel)
                {
                    part.ProtectionLevel = newProtectionLevel;
                }
                else if (part == null && !message.HasProtectionLevel)
                {
                    message.ProtectionLevel = newProtectionLevel;
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.CannotImportProtectionLevelForContract, contract.Name, contract.Namespace)));
                }
            }
        }
Ejemplo n.º 45
0
 private void GeneratePartType(Dictionary <XmlMembersMapping, XmlMembersMapping> alreadyExported, MessagePartDescription part)
 {
     if (this.partInfoTable.ContainsKey(part))
     {
         PartInfo          info           = this.partInfoTable[part];
         XmlMembersMapping membersMapping = info.MembersMapping;
         XmlMemberMapping  memberMapping  = info.MemberMapping;
         if (!alreadyExported.ContainsKey(membersMapping))
         {
             if (info.IsEncoded)
             {
                 this.SoapExporter.ExportMembersMapping(membersMapping);
             }
             else
             {
                 this.XmlExporter.ExportMembersMapping(membersMapping);
             }
             alreadyExported.Add(membersMapping, membersMapping);
         }
         CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();
         if (info.IsEncoded)
         {
             this.SoapExporter.AddMappingMetadata(metadata, memberMapping, false);
         }
         else
         {
             this.XmlExporter.AddMappingMetadata(metadata, memberMapping, part.Namespace, false);
         }
         part.BaseType = this.GetTypeName(memberMapping);
         this.operationGenerator.ParameterTypes.Add(part, new CodeTypeReference(part.BaseType));
         this.operationGenerator.ParameterAttributes.Add(part, metadata);
     }
 }
 /// <summary>
 /// Validate message part description
 /// </summary>
 /// <param name="pd"></param>
 private void ValidateMessagePartDescription(MessagePartDescription pd)
 {
     if (pd != null)
         this.ValidateIsIGraphable(pd.Type);
 }
Ejemplo n.º 47
0
        public static MessageDescription CreateMessageDescription(
            OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType, ICustomAttributeProvider retTypeAttributes)
        {
            var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
            MessageDescription md = new MessageDescription(action, dir)
            {
                IsRequest = isRequest
            };

            MessageBodyDescription mb = md.Body;

            mb.WrapperName      = name + (isRequest ? String.Empty : "Response");
            mb.WrapperNamespace = defaultNamespace;

            if (oca.HasProtectionLevel)
            {
                md.ProtectionLevel = oca.ProtectionLevel;
            }

            // Parts
            int index = 0;

            foreach (ParameterInfo pi in plist)
            {
                // AsyncCallback and state are extraneous.
                if (oca.AsyncPattern && pi.Position == plist.Length - 2)
                {
                    break;
                }

                // They are ignored:
                // - out parameter in request
                // - neither out nor ref parameter in reply
                if (isRequest && pi.IsOut)
                {
                    continue;
                }
                if (!isRequest && !pi.IsOut && !pi.ParameterType.IsByRef)
                {
                    continue;
                }

                MessagePartDescription pd = CreatePartCore(GetMessageParameterAttribute(pi), pi.Name, defaultNamespace);
                pd.Index = index++;
                pd.Type  = MessageFilterOutByRef(pi.ParameterType);
                mb.Parts.Add(pd);
            }

            // ReturnValue
            if (!isRequest)
            {
                MessagePartDescription mp = CreatePartCore(GetMessageParameterAttribute(retTypeAttributes), name + "Result", mb.WrapperNamespace);
                mp.Index       = 0;
                mp.Type        = retType;
                mb.ReturnValue = mp;
            }

            // FIXME: fill properties.

            return(md);
        }
Ejemplo n.º 48
0
		XmlSchemaElement GetSchemaElementForPart (MessagePartDescription part, XmlSchema schema)
		{
			XmlSchemaElement element = new XmlSchemaElement ();

			element.Name = part.Name;
			XsdExporter.Export (part.Type);
			element.SchemaTypeName = XsdExporter.GetSchemaTypeName (part.Type);
			AddImport (schema, element.SchemaTypeName.Namespace);

			//FIXME: nillable, minOccurs
			if (XsdExporter.GetSchemaType (part.Type) is XmlSchemaComplexType ||
				part.Type == typeof (string))
				element.IsNillable = true;
			element.MinOccurs = 0;

			return element;
		}
Ejemplo n.º 49
0
        private void GeneratePartType(Dictionary <XmlMembersMapping, XmlMembersMapping> alreadyExported, MessagePartDescription part, string partNamespace)
        {
            if (!partInfoTable.ContainsKey(part))
            {
                return;
            }
            PartInfo          partInfo       = partInfoTable[part];
            XmlMembersMapping membersMapping = partInfo.MembersMapping;
            XmlMemberMapping  memberMapping  = partInfo.MemberMapping;

            if (!alreadyExported.ContainsKey(membersMapping))
            {
                if (partInfo.IsEncoded)
                {
                    SoapExporter.ExportMembersMapping(membersMapping);
                }
                else
                {
                    XmlExporter.ExportMembersMapping(membersMapping);
                }
                alreadyExported.Add(membersMapping, membersMapping);
            }
            CodeAttributeDeclarationCollection additionalAttributes = new CodeAttributeDeclarationCollection();

            if (partInfo.IsEncoded)
            {
                SoapExporter.AddMappingMetadata(additionalAttributes, memberMapping, false /*forceUseMemberName*/);
            }
            else
            {
                XmlExporter.AddMappingMetadata(additionalAttributes, memberMapping, partNamespace, false /*forceUseMemberName*/);
            }
            part.BaseType = GetTypeName(memberMapping);
            operationGenerator.ParameterTypes.Add(part, new CodeTypeReference(part.BaseType));
            operationGenerator.ParameterAttributes.Add(part, additionalAttributes);
        }