protected override object DoDeserializeValue(XmlReader reader, bool isSimpleValue)
        {
            ICollection <MLQueryResultGroup> result = new List <MLQueryResultGroup>();

            if (SoapHelper.ReadEmptyStartElement(reader)) // Read start of enclosing element
            {
                return(result);
            }
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                result.Add(MLQueryResultGroup.Deserialize(reader));
            }
            reader.ReadEndElement(); // End of enclosing element
            return(result);
        }
Exemplo n.º 2
0
        public void TestSoapSerial()
        {
            TestClassSoap t = new TestClassSoap
            {
                Name   = "t",
                Remark = "test",
                Soap   = new TestClassSoap
                {
                    Name   = "i",
                    Remark = "inner"
                },
            };

            testxml = SoapHelper.Serialize(t);
        }
        private static void ImportMessageSoapAction(WsdlContractConversionContext contractContext, MessageDescription message, MessageBinding wsdlMessageBinding, bool isResponse)
        {
            string str = SoapHelper.ReadSoapAction(wsdlMessageBinding.OperationBinding);

            if (((contractContext != null) && (WsdlImporter.WSAddressingHelper.FindWsaActionAttribute(contractContext.GetOperationMessage(message)) == null)) && (str != null))
            {
                if (isResponse)
                {
                    message.Action = "*";
                }
                else
                {
                    message.Action = str;
                }
            }
        }
Exemplo n.º 4
0
        protected override object DoDeserializeValue(XmlReader reader, bool isSimpleValue)
        {
            IDictionary <string, MediaCategory_DTO> result_dtos = new Dictionary <string, MediaCategory_DTO>();

            if (SoapHelper.ReadEmptyStartElement(reader)) // Read start of enclosing element
            {
                return(new List <MediaCategory>());
            }
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                MediaCategory_DTO result_dto = MediaCategory_DTO.Deserialize(reader);
                result_dtos.Add(result_dto.CategoryName, result_dto);
            }
            reader.ReadEndElement(); // End of enclosing element
            return(new List <MediaCategory>(result_dtos.Select(mCatDtoKvp => mCatDtoKvp.Value.GetMediaCategory(result_dtos))));
        }
Exemplo n.º 5
0
        protected override object DoDeserializeValue(XmlReader reader, bool isSimpleValue)
        {
            if (SoapHelper.ReadEmptyStartElement(reader)) // Read start of enclosing element
            {
                return(null);
            }

            Schedule result = null;

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                result = Schedule.Deserialize(reader);
            }
            reader.ReadEndElement(); // End of enclosing element
            return(result);
        }
Exemplo n.º 6
0
        public List <ShippingRate> GetShipmentRates(Shipment shipment)
        {
            System.Threading.Thread.Sleep(1500);
            return(new List <ShippingRate>()
            {
                new ShippingRate {
                    PackageType = "Package", MailClass = "Endicia Ground", MailService = "Parcel", Zone = "5", Pricing = "Retail", TotalAmount = 23.44m, DeliveryDate = new System.DateTime().AddDays(3)
                },
                new ShippingRate {
                    PackageType = "Package", MailClass = "Endicia Express", MailService = "Letter", Zone = "5", Pricing = "Retail", TotalAmount = 11.32m, DeliveryDate = new System.DateTime().AddDays(2)
                },
                new ShippingRate {
                    PackageType = "Package", MailClass = "Endicia Mail", MailService = "Enveloope", Zone = "5", Pricing = "Retail", TotalAmount = 12.25m, DeliveryDate = new System.DateTime().AddDays(5)
                },
            });

            // create request object
            var requestObject = RequestHelper.CreatePostageRatesRequest(shipment);

            // send the request to change the passphrase
            var response = SoapHelper.ProcessRequest <PostageRatesResponse>(requestObject);

            if (response.Status != 0)
            {
                throw new Exception(response.ErrorMessage);
            }

            var results = new List <ShippingRate>();

            foreach (var rate in response.PostagePrice)
            {
                results.Add(new ShippingRate
                {
                    TotalAmount = rate.TotalAmount,
                    MailClass   = rate.MailClass,
                    MailService = rate.Postage.MailService,
                    Pricing     = rate.Postage.Pricing,
                    Zone        = rate.Postage.Zone
                });
            }

            return(results);
        }
        static void ImportFaultSoapAction(WsdlContractConversionContext contractContext, FaultDescription fault, FaultBinding wsdlFaultBinding)
        {
            string soapAction = SoapHelper.ReadSoapAction(wsdlFaultBinding.OperationBinding);

            if (contractContext != null)
            {
                OperationFault wsdlOperationFault = contractContext.GetOperationFault(fault);
                string         wsaAction          = WsdlImporter.WSAddressingHelper.FindWsaActionAttribute(wsdlOperationFault);
                if (wsaAction == null && soapAction != null)
                {
                    fault.Action = soapAction;
                }
                //
            }
            else
            {
                //
            }
        }
Exemplo n.º 8
0
        private void SubmitDiagnosticsResult(UserDetail userDetail, HttpPostedFileBase file, FormInformation info)
        {
            try
            {
                var dbxlTemplateName = ApplicationConstants.ScanDiagnosticsConstant.ScanDiagnosticsTemplateName;
                var dbxlUrl          = ApplicationConstants.ScanDiagnosticsConstant.ScanDiagnosticsDbxlUrl;
                var dbxlUserName     = ApplicationConstants.ScanDiagnosticsConstant.ScanDiagnosticsDbxlUserName;
                var dbxlPassword     = ApplicationConstants.ScanDiagnosticsConstant.ScanDiagnosticsDbxlPassword;

                if (!String.IsNullOrWhiteSpace(dbxlTemplateName) &&
                    !String.IsNullOrWhiteSpace(dbxlUrl) &&
                    !String.IsNullOrWhiteSpace(dbxlUserName) &&
                    !String.IsNullOrWhiteSpace(dbxlPassword))
                {
                    var scanTemplateXml = GetQdScanTemplateXml(info, userDetail);

                    var submitDocument = new SubmitDocument
                    {
                        docTypeName = dbxlTemplateName,
                        xml         = scanTemplateXml,
                        name        = file.FileName,
                        author      = userDetail.UserName
                    };
                    var submitDocumentXml = GetSerializedXml <SubmitDocument>(submitDocument);

                    dbxlUrl = String.Format("{0}{1}qdabrawebservice/DbxlDocumentService.asmx", dbxlUrl, dbxlUrl.EndsWith("/") ? string.Empty : "/");

                    SoapHelper.CallSoapService(new SoapServiceRequest
                    {
                        data              = submitDocumentXml,
                        overrideAction    = false,
                        soapServiceAction = "http://qdabra.com/webservices/SubmitDocument",
                        url       = dbxlUrl,
                        useCookie = false
                    },
                                               new NetworkCredential(dbxlUserName, dbxlPassword));
                }
            }
            catch
            {
            }
        }
        private static void ImportFaultSoapAction(WsdlContractConversionContext contractContext, FaultDescription fault, FaultBinding wsdlFaultBinding)
        {
            string soapAction = SoapHelper.ReadSoapAction(wsdlFaultBinding.OperationBinding);

            if (contractContext != null)
            {
                OperationFault wsdlOperationFault = contractContext.GetOperationFault(fault);
                string         wsaAction          = WsdlImporter.WSAddressingHelper.FindWsaActionAttribute(wsdlOperationFault);
                if (wsaAction == null && soapAction != null)
                {
                    fault.Action = soapAction;
                }
                //CONSIDER, hsomu: If WS-Addressing action was found, we should verify that it is the same as the SOAP action
                //      (for the request message).
            }
            else
            {
                //CONSIDER, hsomu: verify SOAP action matches referenced contract.operation.message
            }
        }
Exemplo n.º 10
0
        protected static string CreateResultDocument(DvAction action, IList <OutParameter> outParameters, bool forceSimpleValues)
        {
            StringBuilder result = new StringBuilder(2000);

            using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(result, UPnPConsts.UTF8_NO_BOM))
                using (XmlWriter writer = XmlWriter.Create(stringWriter, UPnPConfiguration.DEFAULT_XML_WRITER_SETTINGS))
                {
                    SoapHelper.WriteSoapEnvelopeStart(writer, true);
                    writer.WriteStartElement("u", action.Name + "Response", action.ParentService.ServiceTypeVersion_URN);
                    foreach (OutParameter parameter in outParameters)
                    {
                        writer.WriteStartElement(parameter.Argument.Name);
                        parameter.Argument.SoapSerializeArgument(parameter.Value, forceSimpleValues, writer);
                        writer.WriteEndElement(); // parameter.Argument.Name
                    }
                    writer.WriteEndElement();     // u:[action.Name]Response
                    SoapHelper.WriteSoapEnvelopeEndAndClose(writer);
                }
            return(result.ToString());
        }
Exemplo n.º 11
0
        void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext endpointContext)
        {
            bool createdNew;
            MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(endpointContext, out createdNew);
            bool useWebSocketTransport = WebSocketHelper.UseWebSocketTransport(this.WebSocketSettings.TransportUsage, endpointContext.ContractConversionContext.Contract.IsDuplex());

            EndpointAddress address = endpointContext.Endpoint.Address;

            if (useWebSocketTransport)
            {
                address = new EndpointAddress(WebSocketHelper.GetWebSocketUri(endpointContext.Endpoint.Address.Uri), endpointContext.Endpoint.Address);
                WsdlNS.SoapAddressBinding binding = SoapHelper.GetSoapAddressBinding(endpointContext.WsdlPort);
                if (binding != null)
                {
                    binding.Location = address.Uri.AbsoluteUri;
                }
            }

            TransportBindingElement.ExportWsdlEndpoint(exporter, endpointContext,
                                                       this.GetWsdlTransportUri(useWebSocketTransport), address, encodingBindingElement.MessageVersion.Addressing);
        }
Exemplo n.º 12
0
        public static string CreateFaultDocument(uint errorCode, string errorDescription)
        {
            StringBuilder result = new StringBuilder(2000);

            using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(result, UPnPConsts.UTF8_NO_BOM))
                using (XmlWriter writer = XmlWriter.Create(stringWriter, UPnPConfiguration.DEFAULT_XML_WRITER_SETTINGS))
                {
                    SoapHelper.WriteSoapEnvelopeStart(writer, false);
                    writer.WriteStartElement("Fault", UPnPConsts.NS_SOAP_ENVELOPE);
                    string soapNamespacePrefix = writer.LookupPrefix(UPnPConsts.NS_SOAP_ENVELOPE);
                    writer.WriteElementString("faultcode", soapNamespacePrefix + ":Client");
                    writer.WriteElementString("faultstring", "UPnPError");
                    writer.WriteStartElement("detail");
                    writer.WriteStartElement(string.Empty, "UPnPError", UPnPConsts.NS_UPNP_CONTROL);
                    writer.WriteElementString("errorCode", errorCode.ToString());
                    writer.WriteElementString("errorDescription", errorDescription);
                    writer.WriteEndElement(); // UPnPError
                    writer.WriteEndElement(); // detail
                    writer.WriteEndElement(); // s:Fault
                    SoapHelper.WriteSoapEnvelopeEndAndClose(writer);
                }
            return(result.ToString());
        }
Exemplo n.º 13
0
 internal static void ExportWsdlEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext endpointContext, string wsdlTransportUri, AddressingVersion addressingVersion)
 {
     if (exporter == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
     }
     if (endpointContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointContext");
     }
     endpointContext.Endpoint.Binding.CreateBindingElements();
     if (wsdlTransportUri != null)
     {
         SoapBinding orCreateSoapBinding = SoapHelper.GetOrCreateSoapBinding(endpointContext, exporter);
         if (orCreateSoapBinding != null)
         {
             orCreateSoapBinding.Transport = wsdlTransportUri;
         }
     }
     if (endpointContext.WsdlPort != null)
     {
         WsdlExporter.WSAddressingHelper.AddAddressToWsdlPort(endpointContext.WsdlPort, endpointContext.Endpoint.Address, addressingVersion);
     }
 }
Exemplo n.º 14
0
        public void BasicSoapAuthTest()
        {
            var authenticationHeader = OAuthHelper.GetAuthenticationHeader();
            var serviceUriString     = SoapHelper.GetSoapServiceUriString(UserSessionServiceName, ClientConfiguration.Default.UriString);

            var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString);
            var binding         = SoapHelper.GetBinding();

            var client = new UserSessionServiceClient(binding, endpointAddress);

            var             channel     = client.InnerChannel;
            UserSessionInfo sessionInfo = null;

            using (OperationContextScope operationContextScope = new OperationContextScope(channel))
            {
                HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
                requestMessage.Headers[OAuthHelper.OAuthHeader] = authenticationHeader;
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
                sessionInfo = ((UserSessionService)channel).GetUserSessionInfo(new GetUserSessionInfo()).result;
            }

            Assert.IsNotNull(sessionInfo);
            Assert.IsNotNull(sessionInfo.UserId);
        }
Exemplo n.º 15
0
        private ActionResult InternalCallSoapService(SoapServiceRequest request)
        {
            // TODO: Add SSO handling

            SoapResult result = new SoapResult();

            try
            {
                // 2017/03/02 -- Move the code to SoapHelper.
                var uploadResult = SoapHelper.CallSoapService(request, GetCredentials(request.url));

                result.resultBody = GetBodyFromSoapResult(uploadResult);
                result.success    = true;
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    result.message = String.Format("The request to the service failed with an error: {0}", ex.Message);
                }
                else
                {
                    var fault = GetSoapFault(ex);
                    result.fault = fault;

                    result.message = !String.IsNullOrWhiteSpace(fault.faultstring)
                        ? String.Format("The service failed with an error: {0}", fault.faultstring)
                        : String.Format("The request failed with status {0}", fault.faultcode);
                }
            }
            catch (Exception ex)
            {
                result.message = String.Format("The request to the service failed with an error: {0}", ex.Message);
            }
            return(new ObjectResult <SoapResult>(result));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds "wsse:security" element to a message, or replaces existing element.
        /// </summary>
        /// <param name="request">Request string.</param>
        /// <returns>Request string with added (updated) "wsse:security" element.</returns>
        public string ApplySecurity(string request)
        {
            DeviceEnvironment env = ContextController.GetDeviceEnvironment();

            string secureRequest;

            if (!string.IsNullOrEmpty(env.Credentials.UserName))
            {
                SoapHelper soapHelper = new SoapHelper();
                secureRequest =
                    soapHelper.ApplySecurity(
                        request,
                        env.Credentials.UserName,
                        env.Credentials.Password,
                        env.Credentials.UseUTCTimeStamp,
                        true);
            }
            else
            {
                secureRequest = request;
            }

            return(secureRequest);
        }
        public override async Task <ResponseInfo> GetRates(RequestInfo request, ServerCallContext context)
        {
            var response = new ResponseInfo();

            var res = await SoapHelper.CallWebService(
                CBR_DAILY_SERIVCE_URL,
                NAMESPACE,
                VERB,
                "GetCursOnDate",
                new Dictionary <string, string>
            {
                { "On_date", DateTime.Now.ToString("yyyy-MM-dd") },
            });

            var doc = new XmlDocument();

            doc.LoadXml(res);

            var datas = doc.SelectNodes("//ValuteCursOnDate");

            _context.Rates.RemoveRange(_context.Rates);
            _context.SaveChanges();

            foreach (XmlElement data in datas)
            {
                try
                {
                    _context.Rates.Add(new CbrRate
                    {
                        Code  = data.SelectSingleNode("VchCode").InnerText.Trim(),
                        Title = data.SelectSingleNode("Vname").InnerText.Trim(),
                        Count = short.Parse(data.SelectSingleNode("Vnom").InnerText),
                        Rate  = double.Parse(data.SelectSingleNode("Vcurs").InnerText, CultureInfo.InvariantCulture),
                    });
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            _context.SaveChanges();

            var rates = await GetDataFromContextByODataFilterAsync <DataContext, IEnumerable <DtoRate> >(request.Query);

            foreach (var rate in rates)
            {
                var eRate = new ExchangeRate
                {
                    Code  = new StringValue(),
                    Title = new StringValue(),
                    Count = new Int32Value(),
                    Rate  = new DoubleValue()
                };

                if (!string.IsNullOrEmpty(rate.Code))
                {
                    eRate.Code.Value = rate.Code;
                }

                if (!string.IsNullOrEmpty(rate.Title))
                {
                    eRate.Title.Value = rate.Title;
                }

                if (rate.Count.HasValue)
                {
                    eRate.Count.Value = rate.Count.Value;
                }

                if (rate.Rate.HasValue)
                {
                    eRate.Rate.Value = rate.Rate.Value;
                }

                response.Rates.Add(eRate);
            }

            return(response);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Helper method to be used within the <see cref="SoapDeserializeValue"/> method to check if the serialization is
 /// a <c>null</c> value.
 /// The reader will read the end element tag after it encountered a <c>null</c> value.
 /// </summary>
 /// <param name="reader">XML reader which is positioned at the starting tag of the XML element enclosing the value.</param>
 protected bool SoapReadNull(XmlReader reader)
 {
     return(SoapHelper.ReadNull(reader));
 }
Exemplo n.º 19
0
 /// <summary>
 /// Helper method to be used within the <see cref="SoapSerializeValue"/> method to write a <c>null</c> value
 /// into a SOAP serialization.
 /// </summary>
 /// <param name="writer">XML writer which is positioned at the starting tag of the XML element enclosing the value.</param>
 protected void SoapWriteNull(XmlWriter writer)
 {
     SoapHelper.WriteNull(writer);
 }
Exemplo n.º 20
0
        public async Task <String> GetMethodRequest(string uri, string method)
        {
            var soapRequest = await SoapHelper.BuildSoapRequest(uri, method);

            return(XmlFormatParserHelper.GetFormattedXml(soapRequest));
        }
Exemplo n.º 21
0
        protected static IList <object> ParseResult(TextReader textReader, CpAction action, bool sourceSupportsUPnP11)
        {
            object[] outParameterValues = new object[action.OutArguments.Count];
            using (XmlReader reader = XmlReader.Create(textReader, UPnPConfiguration.DEFAULT_XML_READER_SETTINGS))
            {
                reader.MoveToContent();
                // Parse SOAP envelope
                reader.ReadStartElement("Envelope", UPnPConsts.NS_SOAP_ENVELOPE);
                reader.ReadStartElement("Body", UPnPConsts.NS_SOAP_ENVELOPE);
                // Reader is positioned at the action element
                string serviceTypeVersion_URN = reader.NamespaceURI;
                string type;
                int    version;
                // Parse service and action
                if (!ParserHelper.TryParseTypeVersion_URN(serviceTypeVersion_URN, out type, out version))
                {
                    throw new ArgumentException("Invalid service type or version");
                }
                string actionName = reader.LocalName;
                if (!actionName.EndsWith("Response") ||
                    actionName.Substring(0, actionName.Length - "Response".Length) != action.Name)
                {
                    throw new ArgumentException("Invalid action name in result message");
                }

                // UPnP spec says we have to be able to handle return values being out
                // of order to support UPnP 1.0 devices. See UPnP-arch-DeviceArchitecture-v1.1
                // section 2.5.4. We need a dictionary to make this easy.
                IDictionary <string, int> formalArgIdxDictionary = new Dictionary <string, int>();
                for (int i = 0; i < action.OutArguments.Count; i++)
                {
                    formalArgIdxDictionary.Add(action.OutArguments[i].Name, i);
                }

                int outArgCount = 0;
                if (!SoapHelper.ReadEmptyStartElement(reader))
                {
                    // Parse and check output parameters
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        string argumentName = reader.Name; // Arguments don't have a namespace, so take full name
                        int    formalArgumentIndex;
                        if (!formalArgIdxDictionary.TryGetValue(argumentName, out formalArgumentIndex))
                        {
                            throw new ArgumentException("Invalid argument name");
                        }
                        CpArgument formalArgument = action.OutArguments[formalArgumentIndex];

                        // Get the argument value and store it in the correct position in the return list.
                        object value = null;
                        if (!SoapHelper.ReadNull(reader))
                        {
                            formalArgument.SoapParseArgument(reader, !sourceSupportsUPnP11, out value);
                        }
                        outParameterValues[formalArgumentIndex] = value;
                        outArgCount++;

                        // Don't allow duplicates of the same argument.
                        formalArgIdxDictionary.Remove(formalArgument.Name);
                    }
                }
                if (outArgCount != action.OutArguments.Count) // Too few arguments
                {
                    throw new ArgumentException("Invalid out argument count");
                }
            }
            return(outParameterValues);
        }
        /// <summary>
        /// Serializes the given <paramref name="value"/> as contents of the current element in the
        /// given XML <paramref name="writer"/> in the formatting rules given by this data type.
        /// </summary>
        /// <param name="value">Value to serialize. The value must be of this data type.</param>
        /// <param name="writer">XML writer where the value will be serialized to. The value will be serialized as
        /// contents of the writer's current element.
        /// The writer's position is the start of the parent element, the result should go. The caller will write the end
        /// element tag.</param>
        public void SoapSerializeValue(object value, XmlWriter writer)
        {
            if (value == null)
            {
                SoapHelper.WriteNull(writer);
                return;
            }
            switch (_upnpTypeName)
            {
            case "ui1":
            case "ui2":
            case "ui4":
            case "ui8":
            case "i1":
            case "i2":
            case "i4":
            case "i8":
            case "int":
                writer.WriteString(value.ToString());
                break;

            case "r4":
            case "r8":
            case "number":
            case "float":
                writer.WriteString(((Double)value).ToString("E", CultureInfo.InvariantCulture));
                break;

            case "fixed.14.4":
                writer.WriteString(((Double)value).ToString("0.##############E+0", CultureInfo.InvariantCulture));
                break;

            case "char":
            case "string":
            case "uuid":
                writer.WriteString(value.ToString());
                break;

            case "date":
                writer.WriteString(((DateTime)value).ToString("yyyy-MM-dd"));
                break;

            case "dateTime":
                writer.WriteString(((DateTime)value).ToString("s"));
                break;

            case "dateTime.tz":
                writer.WriteString(((DateTime)value).ToUniversalTime().ToString("u"));
                break;

            case "time":
                writer.WriteString(((DateTime)value).ToString("T"));
                break;

            case "time.tz":
                writer.WriteString(((DateTime)value).ToUniversalTime().ToString("hh:mm:ss"));
                break;

            case "boolean":
                writer.WriteValue((bool)value);
                break;

            case "bin.base64":
                writer.WriteValue(value);
                break;

            case "bin.hex":
                writer.WriteString(EncodingUtils.ToHexString((byte[])value));
                break;

            case "uri":
                writer.WriteString(((Uri)value).AbsoluteUri);
                break;

            default:
                throw new NotImplementedException(string.Format("UPnP standard data type '{0}' is not implemented", _upnpTypeName));
            }
        }
Exemplo n.º 23
0
 public IntegrationContract()
 {
     _soapHelper = AutofacHostFactory.Container.Resolve <SoapHelper>();
     _mediator   = AutofacHostFactory.Container.Resolve <IMediator>();
 }
Exemplo n.º 24
0
            private void ProcessWSERequest(SoapEnvelope envelope, WSE.Security security)
            {
                // by default we consider that SOAP messages is not signed
                bool IsSigned = false;

                // if security element is null
                // the call is made not from WSE-enabled client
                if (security != null)
                {
                    foreach (ISecurityElement element in security.Elements)
                    {
                        if (element is MessageSignature)
                        {
                            // The given context contains a Signature element.
                            MessageSignature sign = element as MessageSignature;

                            if (CheckSignature(envelope, security, sign))
                            {
                                // The SOAP message is signed.
                                if (sign.SigningToken is UsernameToken)
                                {
                                    UsernameToken token = sign.SigningToken as UsernameToken;

                                    // The SOAP message is signed
                                    // with a UsernameToken.
                                    IsSigned = true;
                                }
                            }
                        }
                    }
                }

                // throw an exception if the message did not pass all the tests
                if (!IsSigned)
                {
                    throw new SecurityFault("SOAP response should be signed.");
                }

                // check encryption
                bool IsEncrypted = false;

                foreach (ISecurityElement element in security.Elements)
                {
                    if (element is EncryptedData)
                    {
                        EncryptedData         encryptedData = element as EncryptedData;
                        System.Xml.XmlElement targetElement = encryptedData.TargetElement;

                        if (SoapHelper.IsBodyElement(targetElement))
                        {
                            // The given SOAP message has the Body element Encrypted.
                            IsEncrypted = true;
                        }
                    }
                }

                if (!IsEncrypted)
                {
                    throw new SecurityFault("SOAP response should be encrypted.");
                }
            }
Exemplo n.º 25
0
 public WebServiceSituationCenter()
 {
     _soapHelper = AutofacHostFactory.Container.Resolve <SoapHelper>();
     _mediator   = AutofacHostFactory.Container.Resolve <IMediator>();
 }
Exemplo n.º 26
0
        /// <summary>
        /// Handler method for SOAP control requests.
        /// </summary>
        /// <param name="service">The service whose action was called.</param>
        /// <param name="messageStream">The stream which contains the HTTP message body with the SOAP envelope.</param>
        /// <param name="streamEncoding">Encoding of the <paramref name="messageStream"/>.</param>
        /// <param name="subscriberSupportsUPnP11">Should be set if the requester sent a user agent header which denotes a UPnP
        /// version of 1.1. If set to <c>false</c>, in- and out-parameters with extended data type will be deserialized/serialized
        /// using the string-equivalent of the values.</param>
        /// <param name="context">Context object holding data for the current action call.</param>
        /// <param name="result">SOAP result - may be an action result, a SOAP fault or <c>null</c> if no body should
        /// be sent in the HTTP response.</param>
        /// <returns>HTTP status code to be sent. Should be
        /// <list>
        /// <item><see cref="HttpStatusCode.OK"/> If the action could be evaluated correctly and produced a SOAP result.</item>
        /// <item><see cref="HttpStatusCode.InternalServerError"/> If the result is a SOAP fault.</item>
        /// <item><see cref="HttpStatusCode.BadRequest"/> If the message stream was malformed.</item>
        /// </list>
        /// </returns>
        public static HttpStatusCode HandleRequest(DvService service, Stream messageStream, Encoding streamEncoding,
                                                   bool subscriberSupportsUPnP11, CallContext context, out string result)
        {
            UPnPError res;

            try
            {
                IList <object> inParameterValues = null; // Default to null if there aren't parameters, will be lazily initialized later
                DvAction       action;
                using (StreamReader streamReader = new StreamReader(messageStream, streamEncoding))
                    using (XmlReader reader = XmlReader.Create(streamReader, UPnPConfiguration.DEFAULT_XML_READER_SETTINGS))
                    {
                        reader.MoveToContent();
                        // Parse SOAP envelope
                        reader.ReadStartElement("Envelope", UPnPConsts.NS_SOAP_ENVELOPE);
                        reader.ReadStartElement("Body", UPnPConsts.NS_SOAP_ENVELOPE);
                        // Reader is positioned at the action element
                        string serviceTypeVersion_URN = reader.NamespaceURI;
                        string type;
                        int    version;
                        // Parse service and action
                        if (!ParserHelper.TryParseTypeVersion_URN(serviceTypeVersion_URN, out type, out version))
                        {
                            throw new MediaPortal.Utilities.Exceptions.InvalidDataException("Unable to parse service type and version URN '{0}'", serviceTypeVersion_URN);
                        }
                        string actionName = reader.LocalName;
                        if (!service.Actions.TryGetValue(actionName, out action))
                        {
                            result = CreateFaultDocument(401, "Invalid Action");
                            return(HttpStatusCode.InternalServerError);
                        }
                        IEnumerator <DvArgument> formalArgumentEnumer = action.InArguments.GetEnumerator();
                        if (!SoapHelper.ReadEmptyStartElement(reader)) // Action name
                        {
                            while (reader.NodeType != XmlNodeType.EndElement)
                            {
                                string argumentName = reader.Name; // Arguments don't have a namespace, so take full name
                                if (!formalArgumentEnumer.MoveNext() || formalArgumentEnumer.Current.Name != argumentName)
                                {                                  // Too many arguments
                                    result = CreateFaultDocument(402, "Invalid Args");
                                    return(HttpStatusCode.InternalServerError);
                                }
                                object value;
                                if (SoapHelper.ReadNull(reader))
                                {
                                    value = null;
                                }
                                else
                                {
                                    res = formalArgumentEnumer.Current.SoapParseArgument(reader, !subscriberSupportsUPnP11, out value);
                                    if (res != null)
                                    {
                                        result = CreateFaultDocument(res.ErrorCode, res.ErrorDescription);
                                        return(HttpStatusCode.InternalServerError);
                                    }
                                }
                                if (inParameterValues == null)
                                {
                                    inParameterValues = new List <object>();
                                }
                                inParameterValues.Add(value);
                            }
                        }
                        if (formalArgumentEnumer.MoveNext())
                        { // Too few arguments
                            result = CreateFaultDocument(402, "Invalid Args");
                            return(HttpStatusCode.InternalServerError);
                        }
                    }
                IList <object> outParameterValues;
                // Invoke action
                try
                {
                    res = action.InvokeAction(inParameterValues, out outParameterValues, false, context);
                    // outParameterValues can be null if the action has no output parameters. Setting it to an empty list makes
                    // it easier to check parameter count later.
                    if (outParameterValues == null)
                    {
                        outParameterValues = EMPTY_OBJECT_LIST;
                    }
                }
                catch (Exception e)
                {
                    UPnPConfiguration.LOGGER.Warn("SOAPHandler: Error invoking UPnP action '{0}'", e, action.Name);
                    result = CreateFaultDocument(501, "Action Failed");
                    return(HttpStatusCode.InternalServerError);
                }
                if (res != null)
                {
                    result = CreateFaultDocument(res.ErrorCode, res.ErrorDescription);
                    return(HttpStatusCode.InternalServerError);
                }
                // Check output parameters
                IList <DvArgument> formalArguments = action.OutArguments;
                if (outParameterValues.Count != formalArguments.Count)
                {
                    result = CreateFaultDocument(501, "Action Failed");
                    return(HttpStatusCode.InternalServerError);
                }
                IList <OutParameter> outParams = formalArguments.Select((t, i) => new OutParameter(t, outParameterValues[i])).ToList();
                result = CreateResultDocument(action, outParams, !subscriberSupportsUPnP11);
                return(HttpStatusCode.OK);
            }
            catch (Exception e)
            {
                string message = "Error handling SOAP request: " + e.Message;
                UPnPConfiguration.LOGGER.Warn(message);     // Don't log the whole exception; it's only a communication error with a client

                result = CreateFaultDocument(500, message); // Also send message to client
                return(HttpStatusCode.InternalServerError);
            }
        }
Exemplo n.º 27
0
 public void TestSoapDeserial()
 {
     var s = SoapHelper.Deserialize(testxml);
 }
Exemplo n.º 28
0
        public static MediaItemAspect Deserialize(XmlReader reader)
        {
            if (!reader.MoveToAttribute("Id"))
            {
                throw new ArgumentException("Media item aspect cannot be deserialized: 'Id' attribute missing");
            }
            Guid aspectTypeId = new Guid(reader.ReadContentAsString());
            bool deleted      = false;

            if (reader.MoveToAttribute("Deleted"))
            {
                deleted = reader.ReadContentAsBoolean();
            }
            reader.MoveToElement();
            IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();
            MediaItemAspectMetadata          miaType;

            if (!miatr.LocallyKnownMediaItemAspectTypes.TryGetValue(aspectTypeId, out miaType))
            {
                throw new ArgumentException(string.Format("Media item aspect cannot be deserialized: Unknown media item aspect type '{0}' in [{1} / {2}]", aspectTypeId, string.Join(",", miatr.LocallyKnownMediaItemAspectTypes.Keys), string.Join(",", miatr.LocallyKnownMediaItemAspectTypes.Values.ToList().Select(x => x.Name))));
            }
            MediaItemAspect result = null;

            if (miaType is SingleMediaItemAspectMetadata)
            {
                result = new SingleMediaItemAspect((SingleMediaItemAspectMetadata)miaType);
            }
            else if (miaType is MultipleMediaItemAspectMetadata)
            {
                result = new MultipleMediaItemAspect((MultipleMediaItemAspectMetadata)miaType);
            }
            result.Deleted = deleted;
            if (SoapHelper.ReadEmptyStartElement(reader, "Aspect"))
            {
                return(result);
            }
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (!reader.MoveToAttribute("Name"))
                {
                    throw new ArgumentException("Media item aspect attribute cannot be deserialized: 'Name' attribute missing");
                }
                String attributeName = reader.ReadContentAsString();
                reader.MoveToElement();
                if (SoapHelper.ReadEmptyStartElement(reader, "Attr"))
                {
                    continue;
                }
                MediaItemAspectMetadata.AttributeSpecification attributeSpec;
                if (!miaType.AttributeSpecifications.TryGetValue(attributeName, out attributeSpec))
                {
                    throw new ArgumentException(string.Format(
                                                    "Media item aspect attribute cannot be deserialized: Unknown attribute specification '{0}'", attributeName));
                }
                if (attributeSpec.IsCollectionAttribute)
                {
                    IList valuesCollection = attributeSpec.CreateValuesCollection();
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        valuesCollection.Add(DeserializeValue(reader, attributeSpec.AttributeType));
                    }
                    result.SetCollectionAttribute(attributeSpec, valuesCollection);
                }
                else
                {
                    result.SetAttribute(attributeSpec, DeserializeValue(reader, attributeSpec.AttributeType));
                }
                reader.ReadEndElement(); // Attr
            }
            reader.ReadEndElement();     // Aspect
            return(result);
        }
Exemplo n.º 29
0
 public WebServiceIntelEGov()
 {
     _soapHelper = AutofacHostFactory.Container.Resolve <SoapHelper>();
     _mediator   = AutofacHostFactory.Container.Resolve <IMediator>();
 }
        /// <summary>
        /// Deserializes the contents of the given XML <paramref name="reader"/>'s current element in the formatting rules
        /// given by this data type.
        /// </summary>
        /// <param name="reader">XML reader whose current element's value will be deserialized.
        /// The reader's position is the start of the parent element, the result should go. After this method returns, the reader
        /// must have read the end element.</param>
        /// <returns>Deserialized object of this data type (may be <c>null</c>).</returns>
        public object SoapDeserializeValue(XmlReader reader)
        {
            object result;

            if (SoapHelper.ReadNull(reader))
            {
                result = null;
            }
            else
            {
                switch (_upnpTypeName)
                {
                case "ui1":
                case "ui2":
                case "ui4":
                case "ui8":
                case "i1":
                case "i2":
                case "i4":
                case "i8":
                case "int":
                case "r4":
                case "r8":
                case "number":
                case "fixed.14.4":
                case "float":
                case "char":
                    result = reader.ReadElementContentAs(_dotNetType, null);
                    break;

                case "string":
                case "uuid":
                    result = reader.ReadElementContentAsString();
                    break;

                case "date":
                    result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "yyyy-MM-dd", null);
                    break;

                case "dateTime":
                    result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "s", null);
                    break;

                case "dateTime.tz":
                    result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "u", null).ToLocalTime();
                    break;

                case "time":
                    result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "T", null);
                    break;

                case "time.tz":
                    result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "hh:mm:ss", null).ToLocalTime();
                    break;

                case "boolean":
                    result = reader.ReadElementContentAs(_dotNetType, null);
                    break;

                case "bin.base64":
                    result = reader.ReadElementContentAs(_dotNetType, null);
                    break;

                case "bin.hex":
                    result = EncodingUtils.FromHexString(reader.ReadElementContentAsString());
                    break;

                case "uri":
                    result = new Uri(reader.ReadElementContentAsString());
                    break;

                default:
                    throw new NotImplementedException(string.Format("UPnP standard data type '{0}' is not implemented", _upnpTypeName));
                }
                // Reader will already have read the end element in the methods ReadElementContentXXX
            }
            return(result);
        }