Esempio n. 1
0
	public void WriteOutput(SoapMessage message)
	{
		FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
		StreamWriter w = new StreamWriter(fs);

		if (message is SoapServerMessage)
		{
			w.WriteLine("METHOD RESPONSE at " + DateTime.Now);
			int opc = message.MethodInfo.OutParameters.Length;
			if (opc > 0) w.WriteLine ("  Out parameters:");
			for (int n=0; n<opc; n++)
				w.WriteLine ("     " + message.GetOutParameterValue (n));
			w.WriteLine ("  Return value: " + message.GetReturnValue ());
		}

		w.Flush();
		w.Close();
	}
Esempio n. 2
0
	//  If the SoapMessageStage is such that the SoapRequest or
	//  SoapResponse is still in the SOAP format to be sent or received,
	//  save it out to a file.
	public override void ProcessMessage(SoapMessage message) 
	{
		switch (message.Stage) 
		{
			case SoapMessageStage.BeforeSerialize:
				WriteOutput(message);
				break;
			case SoapMessageStage.AfterSerialize:
				break;
			case SoapMessageStage.BeforeDeserialize:
				break;
			case SoapMessageStage.AfterDeserialize:
				WriteInput(message);
				break;
			default:
				throw new Exception("invalid stage");
		}
	}
Esempio n. 3
0
	public override void ProcessMessage(SoapMessage message) 
	{
		if (!dump) return;

		switch (message.Stage) 
		{
			case SoapMessageStage.BeforeSerialize:
				break;
			case SoapMessageStage.AfterSerialize:
				DumpOut ();
				break;
			case SoapMessageStage.BeforeDeserialize:
				DumpIn ();
				break;
			case SoapMessageStage.AfterDeserialize:
				break;
			default:
				throw new Exception("invalid stage");
		}
	}
Esempio n. 4
0
	public override void ProcessMessage(SoapMessage message) 
	{
		if (syma == null) return;

		switch (message.Stage) 
		{
			case SoapMessageStage.BeforeSerialize:
				break;
			case SoapMessageStage.AfterSerialize:
				Encrypt (message);
				break;
			case SoapMessageStage.BeforeDeserialize:
				Decrypt (message);
				break;
			case SoapMessageStage.AfterDeserialize:
				break;
			default:
				throw new Exception("invalid stage");
		}
	}
Esempio n. 5
0
 private void BeforeExecuteMethodCounter(SoapMessage message)
 {
     this._GlobalInstance.RequestCount.Increment();
     this._ActionInstance.RequestCount.Increment();
 }
Esempio n. 6
0
        // used by the server
        internal object BuildSoapMessageFromMethodResponse(IMethodReturnMessage mrm, out ITransportHeaders responseHeaders)
        {
            responseHeaders = new TransportHeaders();

            if (mrm.Exception == null)
            {
                // *normal* function return

                SoapMessage soapMessage = new SoapMessage();

                // fill the transport headers
                responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\"";

                // build the SoapMessage
                ArrayList paramNames  = new ArrayList();
                ArrayList paramValues = new ArrayList();
                ArrayList paramTypes  = new ArrayList();
                soapMessage.MethodName = mrm.MethodName + "Response";

                Type retType = ((MethodInfo)mrm.MethodBase).ReturnType;

                if (retType != typeof(void))
                {
                    paramNames.Add("return");
                    paramValues.Add(mrm.ReturnValue);
                    if (mrm.ReturnValue != null)
                    {
                        paramTypes.Add(mrm.ReturnValue.GetType());
                    }
                    else
                    {
                        paramTypes.Add(retType);
                    }
                }

                for (int i = 0; i < mrm.OutArgCount; i++)
                {
                    paramNames.Add(mrm.GetOutArgName(i));
                    paramValues.Add(mrm.GetOutArg(i));
                    if (mrm.GetOutArg(i) != null)
                    {
                        paramTypes.Add(mrm.GetOutArg(i).GetType());
                    }
                }
                soapMessage.ParamNames   = (string[])paramNames.ToArray(typeof(string));
                soapMessage.ParamValues  = (object[])paramValues.ToArray(typeof(object));
                soapMessage.ParamTypes   = (Type[])paramTypes.ToArray(typeof(Type));
                soapMessage.XmlNameSpace = _xmlNamespace;
                soapMessage.Headers      = BuildMessageHeaders(mrm);
                return(soapMessage);
            }
            else
            {
                // an Exception was thrown while executing the function
                responseHeaders["__HttpStatusCode"]   = "500";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                // fill the transport headers
                responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\"";
                ServerFault serverFault = CreateServerFault(mrm.Exception);
                return(new SoapFault("Server", String.Format(" **** {0} - {1}", mrm.Exception.GetType().ToString(), mrm.Exception.Message), null, serverFault));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Handle exceptions where the base exception is a <see cref="SoapException"/>.
        /// </summary>
        /// <param name="message">
        /// The Soap message
        /// </param>
        private void HandleException(SoapMessage message)
        {
            var soapException = message.Exception;

            if (soapException != null && soapException.Detail != null)
            {
                return;
            }

            soapException = message.Exception.GetBaseException() as SoapException;

            if (soapException == null)
            {
                return;
            }

            try
            {
                var document = new XmlDocument();

                this._newStream.Position = 0;
                document.Load(this._newStream);
                this._newStream.Dispose();
                this._newStream = null;

                var root = document.DocumentElement;
                if (root == null)
                {
                    return;
                }

                bool soap12 = message.SoapVersion == SoapProtocolVersion.Soap12;
                var  xmlNamespaceManager = new XmlNamespaceManager(document.NameTable);
                xmlNamespaceManager.AddNamespace(SoapPrefix, root.NamespaceURI);

                var code = document.SelectSingleNode(
                    soap12 ? Soap12CodePath : SoapConstants.SoapCodePath, xmlNamespaceManager);
                if (code != null)
                {
                    code.Value = string.Format(
                        CultureInfo.InvariantCulture, "{0}:{1}", root.Prefix, soapException.Code.Name);
                }

                var reason =
                    document.SelectSingleNode(
                        soap12 ? SoapConstants.Soap12ReasonPath : SoapConstants.SoapReasonPath, xmlNamespaceManager);
                if (reason != null)
                {
                    var text = soap12
                                   ? reason.SelectSingleNode(SoapConstants.Soap12ReasonTextPath, xmlNamespaceManager)
                                   : reason;
                    if (text != null)
                    {
                        text.InnerText = soapException.Message;
                    }

                    var node = soap12
                                   ? document.CreateElement(
                        root.Prefix, SoapConstants.Soap12ActorLocalName, root.NamespaceURI)
                                   : document.CreateElement(SoapConstants.SoapActorLocalName);
                    node.InnerText = message.MethodInfo.Name;
                    if (reason.ParentNode != null)
                    {
                        reason.ParentNode.InsertAfter(node, reason);
                    }
                }

                var details =
                    document.SelectSingleNode(
                        soap12 ? SoapConstants.Soap12DetailPath : SoapConstants.SoapDetailPath, xmlNamespaceManager);
                if (details != null)
                {
                    details.InnerXml = soapException.Detail.InnerXml;
                }

                this._newStream = new MemoryStream();
                document.Save(this._newStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
 public abstract void ProcessMessageAfterSerialize(SoapMessage message);
Esempio n. 9
0
    public void WriteInput(SoapMessage message)
    {
// method added so sample will compile
    }
Esempio n. 10
0
	private void LogMessage(SoapMessage message, Stream stream)
	{
		String eventMessage;
		TextReader reader;

		reader = new StreamReader(stream);
		eventMessage = reader.ReadToEnd();

		if (level > 2)
			eventMessage = message.Stage.ToString() +"\n" + eventMessage;

		if (eventMessage.IndexOf("<soap:Fault>") > 0)
		{
			//The SOAP body contains a fault
			if (level > 0) 
				WriteToLog(eventMessage, EventLogEntryType.Error);
		}
		else
		{
			// The SOAP body contains a message
			if (level > 1)
				WriteToLog(eventMessage, EventLogEntryType.Information);	
		}
	}
Esempio n. 11
0
    public override void ProcessMessage(SoapMessage message)
    {
        string SOAPMessage;
        StreamReader Reader;
        StreamWriter Writer;
        XmlDocument SOAPPayload;
        XmlNodeList Root, Fault, OriginalFaultString;
        XmlNode FaultCode, FaultString, FaultActor, Detail;
        string FaultCodeValue, FaultStringValue, FaultActorValue;
        bool HandleErrorFlag;

        HandleErrorFlag = false;
        FaultCodeValue = string.Empty;
        FaultStringValue = string.Empty;
        FaultActorValue = string.Empty;

        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize:
                this._inwardStream.Position = 0;

                Reader = new StreamReader(this._inwardStream);
                Writer = new StreamWriter(this._outwardStream);

                SOAPMessage = Reader.ReadToEnd();
                SOAPPayload = new XmlDocument();
                SOAPPayload.LoadXml(SOAPMessage);
                Fault = SOAPPayload.GetElementsByTagName(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SOAP + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.Fault);

                if (Fault != null && Fault.Count > 0)
                {
                    OriginalFaultString = SOAPPayload.GetElementsByTagName(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.faultstring);

                    if (OriginalFaultString != null && OriginalFaultString.Count > 0)
                    {
                        if (OriginalFaultString[0].InnerText.Contains(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NotImplemented.Message))
                        {
                            HandleErrorFlag = true;
                            FaultCodeValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NotImplemented.Code;
                            FaultStringValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NotImplemented.Message;
                        }
                        else if (OriginalFaultString[0].InnerText.Contains(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.ServerError.Message))
                        {
                            HandleErrorFlag = true;
                            FaultCodeValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.ServerError.Code;
                            FaultStringValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.ServerError.Message;
                        }
                        else if (OriginalFaultString[0].InnerText.Contains(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.InvalidSyntax.Message))
                        {
                            HandleErrorFlag = true;
                            FaultCodeValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.InvalidSyntax.Code;
                            FaultStringValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.InvalidSyntax.Message;
                        }
                        else if (OriginalFaultString[0].InnerText.Contains(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NoResults.Message))
                        {
                            HandleErrorFlag = true;
                            FaultCodeValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NoResults.Code;
                            FaultStringValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.NoResults.Message;
                        }
                        else
                        {
                            HandleErrorFlag = true;
                            FaultCodeValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.ServerError.Code;
                            FaultStringValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Exceptions.ServerError.Message;
                        }
                    }

                    if (HandleErrorFlag == true)
                    {
                        Fault[0].InnerXml = string.Empty;
                        FaultActorValue = DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXWebservice + ":" + message.Action.Replace(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.URIs.SDMXWebservice, string.Empty);

                        FaultCode = SOAPPayload.CreateNode(XmlNodeType.Element, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.faultcode, string.Empty);
                        FaultCode.InnerText = FaultCodeValue;
                        Fault[0].AppendChild(FaultCode);

                        FaultString = SOAPPayload.CreateNode(XmlNodeType.Element, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.faultstring, string.Empty);
                        FaultString.InnerText = FaultStringValue;
                        Fault[0].AppendChild(FaultString);

                        FaultActor = SOAPPayload.CreateNode(XmlNodeType.Element, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.faultactor, string.Empty);
                        FaultActor.InnerText = FaultActorValue;
                        Fault[0].AppendChild(FaultActor);

                        Root = SOAPPayload.GetElementsByTagName(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SOAP + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.Envelope);

                        if (Root != null && Root.Count > 0)
                        {
                            ((XmlElement)Root[0]).SetAttribute(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.xmlns + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXError, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.URIs.SDMXError);
                            ((XmlElement)Root[0]).SetAttribute(DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.xmlns + ":" + DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.Prefixes.SDMXWebservice, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.Namespaces.URIs.SDMXWebservice);
                        }

                        Detail = SOAPPayload.CreateNode(XmlNodeType.Element, DevInfo.Lib.DI_LibSDMX.Constants.SDMXWebServices.SOAPTags.detail, string.Empty);
                        Detail.InnerText = SOAPPayload.OuterXml;
                        Fault[0].AppendChild(Detail);
                    }
                }

                Writer.Write(SOAPPayload.OuterXml);
                Writer.Flush();
                break;
            case SoapMessageStage.BeforeDeserialize:
                Reader = new StreamReader(this._outwardStream);
                Writer = new StreamWriter(this._inwardStream);

                SOAPMessage = Reader.ReadToEnd();

                Writer.Write(SOAPMessage);
                Writer.Flush();

                this._inwardStream.Position = 0;
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
        }
    }
Esempio n. 12
0
        public void DeviceScopesConfigurationTest()
        {
            bool scopesAdded = false;

            string[] newScopes         = null;
            bool     scopesReplaced    = false;
            var      oldNonfixedScopes = new List <string>();

            RunTest(new Backup <string[]>(() => null),
                    () =>
            {
                //get and validate fixed scopes
                var scopes = GetScopes();

                //set configurable scopes
                var newNonfixedScopes = new List <string> {
                    "onvif://www.onvif.org/" + Guid.NewGuid()
                };
                foreach (Scope scope in scopes)
                {
                    if (scope.ScopeDef == ScopeDefinition.Configurable)
                    {
                        oldNonfixedScopes.Add(scope.ScopeItem);
                        foreach (string mandatoryScope in DiscoveryUtils.GetManadatoryScopes())
                        {
                            if (scope.ScopeItem.Contains(mandatoryScope))
                            {
                                if (!newNonfixedScopes.Contains(mandatoryScope))
                                {
                                    newNonfixedScopes.Add(mandatoryScope);
                                }
                            }
                        }
                    }
                }
                SetScopes(newNonfixedScopes.ToArray());

                // fix for 10767
                Sleep(2000);

                scopesReplaced = true;

                //add new scopes
                //begin wait before sending AddScopes, because Hello can be sent by NVT before response to AddScopes
                newScopes         = new string[] { "onvif://www.onvif.org/" + Guid.NewGuid().ToString(), "onvif://www.onvif.org/" + Guid.NewGuid().ToString() };
                bool canAddScopes = true;
                SoapMessage <WSD.HelloType> hello = null;
                try
                {
                    hello = ReceiveHelloMessage(
                        true,
                        true,
                        () =>
                    {
                        AddScopes(newScopes);
                        scopesAdded = true;
                    });
                }
                catch (FaultException fault)
                {
                    if (fault.IsValidOnvifFault("Receiver/Action/TooManyScopes"))
                    {
                        StepPassed();
                        canAddScopes = false;
                    }
                    else
                    {
                        throw;
                    }
                }
                //According to CR26, if device cannot add scopes, consider test as passed.
                if (canAddScopes)
                {
                    var currentScopes = new List <string>(ScopesToStringArray(scopes).Except(oldNonfixedScopes).Concat(newNonfixedScopes).Concat(newScopes));
                    string reason;
                    Assert(ValidateHelloMessage(hello, currentScopes.ToArray(), out reason), reason, "Hello message validation");

                    //probe new scopes
                    SoapMessage <WSD.ProbeMatchesType> probeMatch = ProbeDeviceStep(true, newScopes);

                    Assert(ValidateProbeMatchMessage(probeMatch, out reason), reason, Resources.StepValidateProbeMatch_Title);

                    //delete create scopes
                    hello = ReceiveHelloMessage(true,
                                                true,
                                                () =>
                    {
                        RemoveScopes(newScopes);
                        scopesAdded = false;
                    });

                    Assert(ValidateHelloMessage(hello, currentScopes.Except(newScopes).ToArray(), out reason),
                           reason, "Hello message validation");

                    //probe deleted scopes
                    InvalidProbeDeviceStep(true, newScopes);
                }
            },
                    (param) =>
            {
                if (scopesAdded && (newScopes != null))
                {
                    RemoveScopes(newScopes);
                }
                if (scopesReplaced && oldNonfixedScopes.Any())
                {
                    if (oldNonfixedScopes.Any())
                    {
                        SetScopes(oldNonfixedScopes.ToArray());
                    }
                }
            });
        }
Esempio n. 13
0
 public void BeforeSerialize(SoapMessage message)         //ObjectOut
 {
     //NOTE this only works if you handle StreamOut/In too
     //NOTE this only works on .NETfx
     return;
 }
Esempio n. 14
0
        /// <summary>
        /// Collects the the set of DimeAttachment objects to send in the message.
        /// For referenced attachments these are collected from the parameter list or return value.
        /// For unreferenced attachments these are collected from the IDimeAttachmentContainter
        /// collections. The SOAP envelope and attachments are written into the network stream
        /// in the AfterSerialize method.
        /// If an exception has been thrown, the soap message containing the exception is
        /// not encapsulated.
        /// </summary>
        private void BeforeSerialize(SoapMessage message)
        {
            if (dimeDir == DimeDir.Response)
            {
                return;                 //because not on request
            }
            if (message.Exception == null)
            {
                id = message.Action;
                message.ContentType = DimeContentType;
                outputAttachments   = new ArrayList();

                if (message.GetType() != typeof(SoapClientMessage))
                {
                    throw new Exception("DIME library not for server side processing");

                    /*
                     * // check for unreferenced attachments in the container
                     * IDimeAttachmentContainer container = ((SoapServerMessage)message).Server as IDimeAttachmentContainer;
                     * if (container != null)
                     *      outputAttachments.AddRange(container.ResponseAttachments);
                     * else
                     * {
                     *      // check for referenced attachments in out parameter list
                     *      ParameterInfo[] parameters = message.MethodInfo.OutParameters;
                     *      for (int i = 0; i < parameters.Length; i++)
                     *      {
                     *              // Note, using the as operator to test the type since out params have a unique type
                     *              object outValue = message.GetOutParameterValue(i);
                     *              if ((outValue as DimeAttachment) != null || (outValue as DimeAttachment[]) != null)
                     *                      AddAttachmentValue(outValue.GetType(), outValue);
                     *      }
                     *
                     *      // check for referenced attachment in return value
                     *      Type returnType = message.MethodInfo.ReturnType;
                     *      if (returnType == typeof(DimeAttachment) || returnType == typeof(DimeAttachment[]))
                     *              AddAttachmentValue(returnType, message.GetReturnValue());
                     * }
                     */
                }
                else                 //client side
                {
                    // check for unreferenced attachments in the container
                    IDimeAttachmentContainer container = ((SoapClientMessage)message).Client as IDimeAttachmentContainer;
                    if (container != null)
                    {
                        outputAttachments.AddRange(container.RequestAttachments);
                    }
                    else
                    {
                        // check for referenced attachments in the parameter list
                        ParameterInfo[] parameters = message.MethodInfo.InParameters;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            Type type = parameters[i].ParameterType;
                            if (type == typeof(DimeAttachment) || type == typeof(DimeAttachment[]))
                            {
                                AddAttachmentValue(type, message.GetInParameterValue(i));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Sets the method's DimeAttachment parameters and return value to the stored values.
        /// </summary>
        private void AfterDeSerialize(SoapMessage message)
        {
            if (contentType == DimeContentType)
            {
                if (message.GetType() != typeof(SoapClientMessage))
                {
                    throw new Exception("DIME library not for server side processing");

                    /*
                     * // check for unreferenced attachments in the container
                     * IDimeAttachmentContainer container = ((SoapServerMessage)message).Server as IDimeAttachmentContainer;
                     * if (container != null)
                     * {
                     *      if (container.RequestAttachments == null)
                     *              throw new InvalidOperationException("The IDimeAttachmentContainer.RequestAttachments property must not be null.");
                     *      container.RequestAttachments.AddRange(inputAttachments.Values);
                     * }
                     * else
                     * {
                     *      // check for referenced attachments in the parameter list
                     *      ParameterInfo[] parameters = message.MethodInfo.InParameters;
                     *      for (int i = 0; i < parameters.Length; i++)
                     *      {
                     *              Type type = parameters[i].ParameterType;
                     *              if (type == typeof(DimeAttachment))
                     *              {
                     *                      // only the id is in the SOAP body so copy over other attachment fields into
                     *                      // the DimeAttachment object created during deserialization
                     *                      CopyFieldsFromInputAttachment((DimeAttachment)message.GetInParameterValue(i));
                     *              }
                     *              else if (type == typeof(DimeAttachment[]))
                     *              {
                     *                      CopyFieldsFromInputAttachment((DimeAttachment[])message.GetInParameterValue(i));
                     *              }
                     *      }
                     * }
                     */
                }
                else                 //client side
                {
                    // check for unreferenced attachments in the container
                    IDimeAttachmentContainer container = ((SoapClientMessage)message).Client as IDimeAttachmentContainer;
                    if (container != null)
                    {
                        if (container.ResponseAttachments == null)
                        {
                            throw new InvalidOperationException("The IDimeAttachmentContainer.ResponseAttachments property must not be null.");
                        }
                        container.ResponseAttachments.AddRange(inputAttachments.Values);
                    }
                    else
                    {
                        // check for referenced attachments in the out parameter list
                        ParameterInfo[] parameters = message.MethodInfo.OutParameters;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            // Note, using the as operator to test the type since out params have a unique type
                            object         outValue = message.GetOutParameterValue(i);
                            DimeAttachment a        = outValue as DimeAttachment;
                            if (a != null)
                            {
                                CopyFieldsFromInputAttachment(a);
                            }
                            else
                            {
                                DimeAttachment[] aa = outValue as DimeAttachment[];
                                if (aa != null)
                                {
                                    CopyFieldsFromInputAttachment(aa);
                                }
                            }
                        }
                        Type returnType = message.MethodInfo.ReturnType;
                        if (returnType == typeof(DimeAttachment))
                        {
                            CopyFieldsFromInputAttachment((DimeAttachment)message.GetReturnValue());
                        }
                        else if (returnType == typeof(DimeAttachment[]))
                        {
                            CopyFieldsFromInputAttachment((DimeAttachment[])message.GetReturnValue());
                        }
                    }
                }
            }
        }
Esempio n. 16
0
    public void WriteOutput(SoapMessage message)
    {
        newStream.Position = 0;
        FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write ,FileShare.ReadWrite);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ? "SoapResponse" : "SoapRequest";
        logger.Debug(soapString);
        w.WriteLine("----- " + soapString + " at " + DateTime.Now);
        w.Flush();
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
        Copy(newStream, oldStream);
    }
 public abstract virtual void ProcessMessage(SoapMessage message)
 {
 }
Esempio n. 18
0
    public void WriteInput(SoapMessage message)
    {
        Copy(oldStream, newStream);
        FileStream fs = new FileStream(filename, FileMode.Append,
            FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ? "SoapRequest" : "SoapResponse";
        w.WriteLine("---------------------------------------------");
        w.WriteLine("----- " + soapString + " at " + DateTime.Now);
        w.Flush();
        newStream.Position = 0;
        newStream.ToString();
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
    }
Esempio n. 19
0
        /// <summary>
        ///     this will be called four times (before/after serialize/deserialize) for each [WebMethod]
        /// </summary>
        /// <param name="message">Message being processed</param>
        public override void ProcessMessage(SoapMessage message)
        {
            Argument.Assert.IsNotNull(message, "message");

            if (context.ClassContext)
            {
                return;
            }

            // this extension only cares about the BeforeSerialize stage where it
            Trace.WriteLine("process message");
            // performs schema/assertion validation
            SoapMessageStage checkStage = context.CurrentEndpoint == Endpoint.Server ? SoapMessageStage.BeforeDeserialize : SoapMessageStage.AfterSerialize;

            if (checkStage == message.Stage && context != null)
            {
                Trace.WriteLine("Stage check");
                Stream useStream = message.Stream;
                if (context.CurrentEndpoint == Endpoint.Client)
                {
                    useStream = Filter;
                }
                long streamPosition = useStream.Position;
                try
                {
                    useStream.Position = 0L;
                    // create an XPathNavigator on the request stream
                    XmlReader reader;
                    // check to see if the user wants schema validation
                    if (context.ValidationAttribute != null &&
                        context.ValidationAttribute.SchemaValidation)
                    {
                        // this message should be schema validated so
                        // configure XmlValidatingReader
                        // add specified schemas, including the ones from the WSDL file
                        XmlReaderSettings settings = new XmlReaderSettings();
                        // add the schemas specified by
                        settings.ValidationType   = ValidationType.Schema;
                        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
                        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
                        settings.Schemas.Add(context.SchemaCollection);
                        XmlReader xmlValidatingReader = XmlReader.Create(useStream, settings);
                        if (context.ValidationAttribute.CheckAssertions == false)
                        {
                            try
                            {
                                // read through the stream,
                                // if something in it does not
                                // comply with the schemas it
                                // will through an exception
                                //AssertNamespaceBindingAttribute
                                while (xmlValidatingReader.Read())
                                {
                                }                                      // read through stream
                            }
                            catch (Exception)
                            {
                                ThrowSchemaError();
                            }
                        }
                        reader = xmlValidatingReader;
                    }
                    else
                    {
                        // if we get to here then no schema validation
                        // was require, just make a reader that
                        // can be used to evaluate xpath expressions
                        reader = new XmlTextReader(useStream);
                    }
                    // evaluate the XPath assertions - if complete expression returns true
                    // let the System.Web.Services infrastructure finish processing
                    if (context.ValidationAttribute != null &&
                        context.ValidationAttribute.CheckAssertions)
                    {
                        Trace.WriteLine("validate");
                        // turn the message stream into an XPathDocument
                        XPathDocument doc = new XPathDocument(reader);
                        // get an navigator from the docuement
                        XPathNavigator nav = doc.CreateNavigator();

                        if (context.ValidationAttribute.SchemaValidation)
                        {
                            Trace.WriteLine("Schema Check");
                        }
                        if (context.CompleteRuleExpression != null &&
                            false == (bool)nav.Evaluate(context.CompleteRuleExpression))
                        {
                            // otherwise generate a SOAP fault indicating exactly which
                            // assertions failed
                            // make a document to construct a detail element
                            XmlDocument errorDoc = new XmlDocument();
                            // make a detail element
                            XmlElement detailElement =
                                errorDoc.CreateElement(
                                    SoapException.DetailElementName.Name,
                                    SoapException.DetailElementName.Namespace);
                            // make it the root of the document
                            errorDoc.AppendChild(detailElement);
                            // make an element that indicates that assertions failed
                            XmlElement failedRulesElement =
                                errorDoc.CreateElement("dm", "failedAssertions", ValidationNamespaces.DevInterop);
                            // add the failure elememt to the detail
                            detailElement.AppendChild(failedRulesElement);
                            // generate namespace declarations required by assert expressions
                            foreach (string prefix in context.NamespaceManager)
                            {
                                if (prefix.Equals("xml") || prefix.Equals("xmlns") || prefix.Length == 0)
                                {
                                    continue;
                                }
                                XmlAttribute nsDeclAttribute = errorDoc.CreateAttribute("xmlns", prefix, ValidationNamespaces.XmlNamespace);
                                nsDeclAttribute.Value = context.NamespaceManager.LookupNamespace(prefix);
                                failedRulesElement.Attributes.Append(nsDeclAttribute);
                            }

                            // check to see which assertions failed and list in failedRules
                            foreach (AssertAttribute assertAttribute in context.AssertAttributes)
                            {
                                // check the current assertion
                                if (false == (bool)nav.Evaluate(assertAttribute.Expression))
                                {
                                    // it faild, make an element that indicates this
                                    XmlElement assertElement = errorDoc.CreateElement("dm", "assert", ValidationNamespaces.DevInterop);
                                    failedRulesElement.AppendChild(assertElement);
                                    // make an element that will hold the xpath expression that failed
                                    XmlElement expElement = errorDoc.CreateElement("dm", "expression", ValidationNamespaces.DevInterop);
                                    assertElement.AppendChild(expElement);
                                    expElement.InnerText = assertAttribute.Rule;
                                    // make an element that holds the error expression
                                    // associated with the xpath expression business rule
                                    XmlElement descElement = errorDoc.CreateElement("dm", "description", ValidationNamespaces.DevInterop);
                                    assertElement.AppendChild(descElement);
                                    descElement.InnerText = assertAttribute.Description;
                                }
                            }

                            reader.Close();
                            // make an actor string to indicate
                            // where error was detected
                            string actor = context.CurrentEndpoint == Endpoint.Server ? HttpContext.Current.Request.Url.AbsoluteUri : "urn:ClientSide";
                            // throw soap excetion that describes error
                            // this will be returned as soap error message
                            throw new SoapException(
                                      "Business rules failed validation",
                                      SoapException.ClientFaultCode,
                                      actor,
                                      detailElement);
                        }

                        // message was validated and produced no assertion
                        if (context.CurrentEndpoint == Endpoint.Client)
                        {
                            // if we got this and this is the client then
                            // push the filer to the server
                            Filter.Position = 0L;
                            byte[] buffer = new byte[1024];
                            int    read;
                            while ((read = Filter.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                Request.Write(buffer, 0, read);
                            }
                            Request.Close();
                        }
                    }
                }
                catch (SoapException)
                {
                    // if you get to here you are catching
                    // the SoapException thrown by the assertion
                    // check, so just rethrow it.
                    throw;
                }
                catch (Exception)
                {
                    // if you get to here then the
                    // schema validator threw the exception,
                    // turn it into a SoapException
                    ThrowSchemaError();
                }
                finally
                {
                    // make sure you leave the stream the way you found it
                    if (context.CurrentEndpoint != Endpoint.Client)
                    {
                        useStream.Position = streamPosition;
                    }
                }
            }
        }
Esempio n. 20
0
	public void Encrypt (SoapMessage message)
	{
		MemoryStream mems = new MemoryStream ();
		CryptoStream encStream = new CryptoStream (mems, syma.CreateEncryptor(), CryptoStreamMode.Write);
		encStream.Write (newStream.GetBuffer (), 0, (int) newStream.Length);
		int rn = (int) newStream.Length % (syma.BlockSize/8);
		if (rn > 0) encStream.Write (filler, 0, (syma.BlockSize/8) - rn);
		encStream.FlushFinalBlock ();
		encStream.Flush ();

		// Convert the encrypted content to a base 64 string
		string encString = Convert.ToBase64String (mems.GetBuffer (), 0, (int)mems.Length);
		byte[] encBytes = Encoding.UTF8.GetBytes (encString);
		oldStream.Write (encBytes, 0, encBytes.Length);
		oldStream.Flush ();

		encStream.Close ();
		mems.Close ();
	}
        /// <summary>
        /// Receives message of specified type from DUT
        /// </summary>
        /// <param name="timeout">Time to wait</param>
        /// <param name="checkIP">if true wait from current device IP</param>
        /// <param name="checkDeviceId">if true wait for current device uuid</param>
        /// <param name="action">additional action after begin waiting</param>
        /// <returns>Message</returns>
        private SoapMessage <object> ReceiveMessageInternal(
            WaitMessageType type,
            string stepName,
            string noMessageText,
            bool checkIP,
            bool checkDeviceId,
            Action action,
            Action <SoapMessage <object> > validation,
            int timeout)
        {
            Discovery discovery = new Discovery(_nic.IP);
            bool      waitHello = (type & WaitMessageType.Hello) != 0;
            bool      waitBye   = (type & WaitMessageType.Bye) != 0;

            if (waitHello)
            {
                discovery.HelloReceived += OnHelloReceived;
            }
            if (waitBye)
            {
                discovery.ByeReceived += OnByeReceived;
            }
            discovery.ReceiveError      += OnDiscoveryError;
            discovery.DiscoveryFinished += OnDiscoveryFinished;
            _eventTimeout.Reset();
            _eventHelloReceived.Reset();
            _eventByeReceived.Reset();
            _eventDiscoveryError.Reset();
            SoapMessage <object> response = null;

            try
            {
                if (waitBye && waitHello)
                {
                    discovery.WaitByeOrHello(checkIP ? _cameraIp : null, checkDeviceId ? _cameraId : null, timeout);
                }
                else if (waitBye)
                {
                    discovery.WaitBye(checkIP ? _cameraIp : null, checkDeviceId ? _cameraId : null, timeout);
                }
                else
                {
                    discovery.WaitHello(checkIP ? _cameraIp : null, checkDeviceId ? _cameraId : null, timeout);
                }
                if (action != null)
                {
                    action();
                }
                RunStep(() =>
                {
                    int res = WaitForResponse(new WaitHandle[] {
                        _eventHelloReceived,
                        _eventByeReceived,
                        _eventDiscoveryError,
                        _eventTimeout
                    });
                    if (((res == 0) && waitHello) ||
                        ((res == 1) && waitBye))
                    {
                        response = _message;
                        if (_message != null)
                        {
                            string dump = System.Text.Encoding.UTF8.GetString(_message.Raw);
                            LogResponse(dump);
                        }
                    }
                    else if (res == 2)
                    {
                        string message = _error.Message + _error.InnerException ?? " " + _error.InnerException.Message;
                        throw new AssertException(message);
                    }
                    else if (noMessageText != null)
                    {
                        throw new AssertException(noMessageText);
                    }
                    if (validation != null)
                    {
                        validation(response);
                    }
                }, stepName);
            }
            finally
            {
                discovery.Close();
            }
            return(response);
        }
Esempio n. 22
0
    //  If the SoapMessageStage is such that the SoapRequest or
    //  SoapResponse is still in the SOAP format to be sent or received,
    //  save it out to a file.
    public override void ProcessMessage(SoapMessage message)
    {
        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize:
                //WriteOutput(message);
                xmlRequest = GetSoapEnvelope(newStream);
                Copy(newStream, oldStream);
                if (enbLogSOAPReqRes)
                {
                    logger.Info(" SOAP Response ");
                    logger.Info(xmlRequest.InnerXml);
                    logger.Info(" ######################## iSmart API Process (END) ######################## ");
                }
                else
                {
                    logger.Info(" ######################## iSmart API Process (END) ######################## ");
                }
                break;
            case SoapMessageStage.BeforeDeserialize:
                //WriteInput(message);
                Copy(oldStream, newStream);
                xmlResponse = GetSoapEnvelope(newStream);
                if (enbLogSOAPReqRes)
                {

                    logger.Info(" ######################## iSmart API Process (START) ###################### ");
                    logger.Info(" SOAP Request ");
                    logger.Info(xmlResponse.InnerXml);
                }
                else
                {
                    logger.Info(" ######################## iSmart API Process (START) ###################### ");
                }
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
            default:
                throw new Exception("invalid stage");
        }
    }
Esempio n. 23
0
	private void LogOutputMessage(SoapMessage message)
	{
		message.Stream.Seek(0, SeekOrigin.Begin);
		LogMessage(message, newStream);
		message.Stream.Seek(0, SeekOrigin.Begin);
		CopyStream(newStream, oldStream);
	}
Esempio n. 24
0
        public void AfterDeserialize(SoapMessage message)         //ObjectIn
        {
            SoapMessage mess = message;

            return;
        }
        public override IDataContainer ProcessMessage(int SCBID, EndPoint RemoteIPEndPoint, NTCPMessage.MessageFlag Flag, ushort CableId, uint Channel, uint Event, SoapMessage obj)
        {
            //Console.WriteLine(obj);
            var result = new DataContainer();

            result.Result = "1111111111";

            return(result);
        }
Esempio n. 26
0
 /// <summary>
 /// <p><strong>Purpose:</strong></p> <p>This is a simple constructor which will assign the parameter to the
 /// corresponding member variable.</p>
 /// </summary>
 /// <exception cref="ArgumentNullException">if the input parameter is null</exception>
 /// <param name="soapmessage">soap message which will be our source document</param>
 public SoapMessageReferenceLoader(SoapMessage soapmessage)
 {
     ExceptionHelper.ValidateNotNull(soapmessage, "soapmessage");
     this.soapMessage = soapmessage;
 }
 public abstract void ProcessMessageBeforeSerialize(SoapMessage message);
Esempio n. 28
0
 private void ProcessInboundResponse(SoapMessage message)
 {
     ProcessResponse(message, true);
 }
Esempio n. 29
0
 public void ReceiveResponse(SoapMessage message)
 {
     Copy(wireStream, appStream);
     appStream.Position = 0;
 }
Esempio n. 30
0
 private void ProcessOutboundRequest(SoapMessage message)
 {
     ProcessRequest(message, true);
 }
Esempio n. 31
0
        // used by the server
        internal IMessage BuildMethodCallFromSoapMessage(SoapMessage soapMessage, string uri)
        {
            ArrayList headersList = new ArrayList();

            Type[] signature = null;

            headersList.Add(new Header("__Uri", uri));
            headersList.Add(new Header("__MethodName", soapMessage.MethodName));
            string typeNamespace, assemblyName;

            if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(soapMessage.XmlNameSpace, out typeNamespace, out assemblyName))
            {
                throw new RemotingException("Could not decode SoapMessage");
            }

            // Note that we don't need to validate the type in
            // this place because MethodCall will do it anyway.

            if (assemblyName == null)             // corlib
            {
                _serverType = Type.GetType(typeNamespace, true);
            }
            else
            {
                _serverType = Type.GetType(typeNamespace + ", " + assemblyName, true);
            }

            headersList.Add(new Header("__TypeName", _serverType.FullName, false));

            if (soapMessage.Headers != null)
            {
                foreach (Header h in soapMessage.Headers)
                {
                    headersList.Add(h);
                    if (h.Name == "__MethodSignature")
                    {
                        signature = (Type[])h.Value;
                    }
                }
            }

            _xmlNamespace = soapMessage.XmlNameSpace;
            //RemMessageType messageType;

            BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            if (signature == null)
            {
                _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags);
            }
            else
            {
                _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags, null, signature, null);
            }

            if (_methodCallInfo == null && (soapMessage.MethodName == "FieldSetter" || soapMessage.MethodName == "FieldGetter"))
            {
                _methodCallInfo = typeof(object).GetMethod(soapMessage.MethodName, bflags);
            }

            // the *out* parameters aren't serialized
            // have to add them here
            _methodCallParameters = _methodCallInfo.GetParameters();
            object[] args = new object[_methodCallParameters.Length];
            int      sn   = 0;

            for (int n = 0; n < _methodCallParameters.Length; n++)
            {
                ParameterInfo paramInfo = _methodCallParameters [n];
                Type          paramType = (paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType);

                if (paramInfo.IsOut && paramInfo.ParameterType.IsByRef)
                {
                    args [n] = GetNullValue(paramType);
                }
                else
                {
                    object val = soapMessage.ParamValues[sn++];
                    if (val is IConvertible)
                    {
                        args [n] = Convert.ChangeType(val, paramType);
                    }
                    else
                    {
                        args [n] = val;
                    }
                }
            }

            headersList.Add(new Header("__Args", args, false));

            Header[] headers = (Header[])headersList.ToArray(typeof(Header));

            // build the MethodCall from the headers
            MethodCall mthCall = new MethodCall(headers);

            return((IMessage)mthCall);
        }
Esempio n. 32
0
 private void ProcessInboundRequest(SoapMessage message)
 {
     ProcessRequest(message, false);
 }
Esempio n. 33
0
        private void SetAfterExecuteMethodCounterValues(WebMethodServerCounters instance, SoapMessage message)
        {
            instance.RequestAverageDurationBase.Increment();
            instance.RequestAverageDuration.IncrementBy(this._ExecutionWatch.ElapsedMilliseconds / 100);

            if (message.Exception != null)
            {
                instance.RequestFailCount.Increment();
            }
            else
            {
                instance.RequestSuccessCount.Increment();
            }

            instance.RequestsPerSecond.Increment();
        }
Esempio n. 34
0
 private void ProcessOutboundResponse(SoapMessage message)
 {
     ProcessResponse(message, false);
 }
Esempio n. 35
0
 private void AfterExecuteMethodCounter(SoapMessage message)
 {
     this._ExecutionWatch.Stop();
     SetAfterExecuteMethodCounterValues(this._GlobalInstance, message);
     SetAfterExecuteMethodCounterValues(this._ActionInstance, message);
 }
Esempio n. 36
0
        private void ProcessRequest(SoapMessage message, Boolean isclient)
        {
            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                Guid newGuid = Guid.NewGuid();
                Trace.CorrelationManager.ActivityId = newGuid;
            }
            MessageProcessor  ctx = MessageProcessor.Instance;
            MessageCorrelator mc  = new MessageCorrelator();

            mc.MessageID = Guid.NewGuid().ToString();
            if (isclient)
            {
                mc.threadid = MessageProcessor.GetTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name);
                if (String.IsNullOrEmpty(mc.threadid))
                {
                    mc.threadid = Guid.NewGuid().ToString();
                }
                if (MessageProcessor.GetConfig.DependencyInjectionEnabled)
                {
                    message.Headers.Add(new FGSMSSoapHeaderRelatedMessageASPNET(mc.MessageID));
                    message.Headers.Add(new FGSMSSoapHeaderTransactionThreadIdASPNET(mc.threadid));
                }
            }
            else //service processing a request
            {
                IEnumerator it = message.Headers.GetEnumerator();
                while (it.MoveNext())
                {
                    SoapUnknownHeader e = it.Current as SoapUnknownHeader;
                    if (e != null)
                    {
                        //if (e.Element.Name.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Name2) && e.Element.NamespaceURI.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Namespace2))
                        //{
                        //    mc.threadid = e.Element.InnerText;
                        //}
                        if (e.Element.Name.Equals(FGSMSSoapHeaderRelatedMessageIdWCF.Name2) && e.Element.NamespaceURI.Equals(FGSMSSoapHeaderRelatedMessageIdWCF.Namespace2))
                        {
                            mc.relatedtransactionid = e.Element.InnerText;
                        }
                        if (e.Element.Name.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Name2) && e.Element.NamespaceURI.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Namespace2))
                        {
                            mc.threadid = e.Element.InnerText;
                        }
                    }
                }
            }
            if (String.IsNullOrEmpty(mc.threadid))
            {
                mc.threadid = Guid.NewGuid().ToString();
            }
            MessageProcessor.SetTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name, mc.threadid);



            try
            {
                Uri url = new Uri("urn:undeterminable");
                if (!isclient && System.Web.HttpContext.Current != null)
                {
                    url = System.Web.HttpContext.Current.Request.Url;
                }
                else
                {
                    url = new Uri(message.Url);
                }
                AgentMessageTable hashtable = AgentMessageTable.Instance;
                if (isclient)
                {
                    localhashcode = message.GetHashCode();
                }
                else if (HttpContext.Current != null)
                {
                    localhashcode = HttpContext.Current.Request.GetHashCode();
                }
                else
                {
                    //uh oh, http context is null and this is a server side request, unexpected.
                }
                if (HttpContext.Current == null)
                {
                    mc.RecievedAt     = DateTime.Now;
                    mc.RequestMessage = StreamtoString(message.Stream);
                    mc.requestsize    = mc.RequestMessage.Length;
                    mc.originalUrl    = mc.URL = url.ToString();
                    mc.RequestHeaders = new System.Collections.Specialized.NameValueCollection();
                    //   mc.RequestHeaders.Add("Content-Type", message.ContentType);
                    //  mc.RequestHeaders.Add("Content-Encoding", message.ContentEncoding);
                    mc.RequestHeaders.Add("SOAPAction", message.Action);
                    mc.soapAction = message.Action;
                    AgentMessageTable.AddRequest(mc, localhashcode);

                    /* AgentMessageTable.AddRequest(localhashcode,
                     *   DateTime.Now,
                     *   StreamtoString(message.Stream),
                     *   //InputMessageToString(message),
                     *   url.ToString()
                     *   // message.ToString()
                     * );*/
                }
                else
                {
                    mc.RecievedAt = DateTime.Now;

                    mc.RequestMessage = StreamtoString(message.Stream);
                    mc.requestsize    = mc.RequestMessage.Length;
                    mc.originalUrl    = mc.URL = url.ToString();
                    mc.RequestHeaders = new System.Collections.Specialized.NameValueCollection();
                    mc.RequestHeaders = HttpContext.Current.Request.Headers;
                    mc.userp          = HttpContext.Current.User;
                    try
                    {
                        mc.soapAction = message.Action;
                    }
                    catch { }
                    if (String.IsNullOrEmpty(mc.soapAction))
                    {
                        mc.soapAction = mc.RequestHeaders["SOAPAction"];
                    }
                    if (HttpContext.Current.Request.ClientCertificate != null)
                    {
                        mc.ClientCertificate = new X509Certificate2(HttpContext.Current.Request.ClientCertificate.Certificate);
                    }

                    AgentMessageTable.AddRequest(mc, localhashcode);

                    /*
                     * AgentMessageTable.AddRequest(localhashcode,
                     * DateTime.Now,
                     * StreamtoString(message.Stream),
                     *  //OutputMessageToString(message),
                     * url.ToString());
                     * // message.ToString()*/
                }
            }
            catch (Exception ex)
            {
                Logger.error(ex, this.GetType().FullName + " error caught processing a request ");
            }
            // PurgeOldMessages();
        }
Esempio n. 37
0
        private void ProcessResponse(SoapMessage message, Boolean isclient)
        {
            MessageProcessor ctx = MessageProcessor.Instance;

            //  if (!MessageProcessor.Enabled)
            //      return;
            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                Guid newGuid = Guid.NewGuid();
                Trace.CorrelationManager.ActivityId = newGuid;
            }

            try
            {
                AgentMessageTable ctx2      = AgentMessageTable.Instance;
                AgentMessageTable hashtable = AgentMessageTable.Instance;
                if (localhashcode == -1)
                {
                    Logger.warn(this.GetType().FullName + " ProcessResponse unable to local hash reference coresponding request message");

                    return;
                }



                if (isclient && HttpContext.Current == null)
                //if this is a standalone client processing a response, this is common
                {
                    MessageCorrelator mc = AgentMessageTable.RemoveMessage(localhashcode);
                    if (mc == null)

                    {
                        Logger.warn(
                            this.GetType().FullName + " ProcessResponse unable to reference coresponding request message");

                        return;
                    }
                    if (isclient && MessageProcessor.GetConfig.DependencyInjectionEnabled)
                    {
                        IEnumerator it = message.Headers.GetEnumerator();
                        while (it.MoveNext())
                        {
                            SoapUnknownHeader e = it.Current as SoapUnknownHeader;
                            if (e != null)
                            {
                                //if (e.Element.Name.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Name2) && e.Element.NamespaceURI.Equals(FGSMSSoapHeaderTransactionThreadIdWCF.Namespace2))
                                //{
                                //    mc.threadid = e.Element.InnerText;
                                //}
                                if (e.Element.Name.Equals(FGSMSSoapHeaderRelatedMessageIdWCF.Name2) && e.Element.NamespaceURI.Equals(FGSMSSoapHeaderRelatedMessageIdWCF.Namespace2))
                                {
                                    mc.relatedtransactionid = e.Element.InnerText;
                                }
                            }
                        }
                    }
                    if (String.IsNullOrEmpty(mc.threadid))
                    {
                        mc.threadid = MessageProcessor.GetTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name);
                        if (String.IsNullOrEmpty(mc.threadid))
                        {
                            mc.threadid = Guid.NewGuid().ToString();
                        }
                    }

                    if (!isclient && MessageProcessor.GetConfig.DependencyInjectionEnabled)
                    {
                        message.Headers.Add(new FGSMSSoapHeaderRelatedMessageASPNET(mc.MessageID));
                        message.Headers.Add(new FGSMSSoapHeaderTransactionThreadIdASPNET(mc.threadid));
                    }


                    try
                    {
                        if (String.IsNullOrEmpty(mc.soapAction))
                        {
                            string action = "urn:undeterminable";
                            if (action == "urn:undeterminable")
                            {
                                action = message.Action;
                                action = action.Replace("\"", "");
                                action = action.Replace("'", "");
                                if (String.IsNullOrEmpty(action))
                                {
                                    action = "urn:undeterminable";
                                }
                            }
                            if (action == "urn:undeterminable")
                            {
                                action = message.MethodInfo.Name;;
                                action = action.Replace("\"", "");
                                action = action.Replace("'", "");
                                if (String.IsNullOrEmpty(action))
                                {
                                    action = "urn:undeterminable";
                                }
                            }
                        }
                        string ip = "";
                        try
                        {
                            string myHost = System.Net.Dns.GetHostName();
                            System.Net.IPAddress[] list = System.Net.Dns.GetHostEntry(myHost).AddressList;
                            for (int i = 0; i < list.Length; i++)
                            {
                                if (!IPAddress.IsLoopback(System.Net.Dns.GetHostEntry(myHost).AddressList[i]))
                                {
                                    ip = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
                                    break;
                                }
                            }
                        }
                        catch { }

                        string user = System.Environment.UserName;
                        mc.identity = new List <string>();
                        mc.identity.Add(user);
                        // mc.identity.Add(ip);
                        mc.ipaddress   = ip;
                        mc.CompletedAt = DateTime.Now;
                        mc.IsFault     = AgentSoapExtension.IsFault(message);
                        mc.agenttype   = this.GetType().FullName + ".client";
                        mc.memo        = "MsgMap=" + AgentMessageTable.GetSize();
                        if (mc.ResponseHeaders == null)
                        {
                            mc.ResponseHeaders = new NameValueCollection();
                        }
                        if (HttpContext.Current != null && HttpContext.Current.Response != null && HttpContext.Current.Response.Headers != null)
                        {
                            mc.ResponseHeaders.Add(HttpContext.Current.Response.Headers);
                        }
                        else
                        {
                            mc.ResponseHeaders.Add("SOAPAction", message.Action);
                        }



                        if (message.OneWay)
                        {
                            mc.ResponseMessage = "";
                            mc.responsesize    = 0;

                            MessageProcessor.ProcessMessage(mc);

                            /*
                             * mc.ipaddress = ip;
                             * MessageProcessor.ProcessMessage((
                             *  url),
                             *  start,
                             *  DateTime.Now,
                             *  action,
                             *  req,
                             *  "",
                             *  localhashcode.ToString(),
                             *  AgentSoapExtension.IsFault(message),
                             *  null,
                             *  ip, this.GetType().FullName + ".client",
                             *  user
                             *  );*/
                        }
                        else
                        {
                            mc.responsesize = mc.ResponseMessage.Length;
                            MessageProcessor.ProcessMessage(mc);

                            /*
                             * MessageProcessor.ProcessMessage((url),
                             *  start,
                             *  DateTime.Now,
                             *  action,
                             *  req,
                             *  //InputMessageToString(message),
                             *  StreamtoString(message.Stream),
                             *  localhashcode.ToString(),
                             *  AgentSoapExtension.IsFault(message),
                             *  null,
                             *  ip, this.GetType().FullName + ".client",
                             *  user
                             *  );*/
                        }
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            AgentMessageTable.RemoveMessage(localhashcode);
                        }
                        catch { }
                        Logger.error(ex, this.GetType().FullName + " Error caught process response for clients");
                    }
                }
                else
                {
                    //this is a response from a service, either directly from the service, or a service chaining event and the caller is processing the response

                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            Logger.warn(this.GetType().FullName + " SniiferFilter failure, http context is null, this shouldn't happen please report if you see this message");
                        }
                        else
                        {
                            // HttpContext.Current.Response.Filter = new SniiferFilter(HttpContext.Current.Response.Filter);
                            HttpContext.Current.Response.Filter = new SniiferFilter(HttpContext.Current.Response.Filter);
                        }
                        // if (FGSMSConstants.log) EventLog.WriteEntry(this.GetType().FullName, "SniiferFilter success to " + System.Web.HttpContext.Current.Request.Url.ToString(), EventLogEntryType.Information);
                    }
                    catch { }
                }
                //this may be a good hook for dependency checking
                //HttpContext.Current.Items.Add(
                //need to make a container, add it to the context somehow
                //on each outbound message, grab the context container, add dependency if detected.

                //on the first inbound connection, setup the context
                //on an outbound connection, check if it's a request or response
                //if response, we are done, send dependency tree to the message processor
                //if request, get the context, add the dependency
                try
                {
                    //if (FGSMSConstants.log) EventLog.WriteEntry(this.GetType().FullName, "ProcessOutbound success", EventLogEntryType.Information);
                }
                catch { }
            }
            catch (Exception ex)
            {
                Logger.error(ex, "Process outbound");
            }
            if (!isclient)
            {
                try
                {
                    MessageProcessor.ClearTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name);
                }
                catch { }
            }
            else
            {
                try
                {
                    MessageProcessor.ClearTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name);
                }
                catch { }
            }
            //PurgeOldMessages();
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Check whether the request was already processed by another
            // formatter sink and pass the request to the next sink if so.
            if (requestMsg != null)
            {
                return(next_sink.ProcessMessage(sinkStack,
                                                requestMsg,
                                                requestHeaders,
                                                requestStream,
                                                out responseMsg,
                                                out responseHeaders,
                                                out responseStream));
            }

            // Check whether the request is suitable for this formatter
            // and pass the request to the next sink if not.
            // Note that a null content-type is handled as suitable,
            // otherwise no other sink will be able to handle the request.
            string contentType = requestHeaders["Content-Type"] as string;

            if (contentType == null || !contentType.StartsWith("text/xml") || requestHeaders["SOAPAction"] == null)
            {
                return(next_sink.ProcessMessage(sinkStack,
                                                requestMsg,
                                                requestHeaders,
                                                requestStream,
                                                out responseMsg,
                                                out responseHeaders,
                                                out responseStream));
            }

            responseMsg     = null;
            responseHeaders = null;
            responseStream  = null;

            ServerProcessing     sp;
            SoapMessageFormatter soapMsgFormatter = new SoapMessageFormatter();

            sinkStack.Push(this, soapMsgFormatter);

            try {
                string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
                string uri;
                _receiver.Parse(url, out uri);
                if (uri == null)
                {
                    uri = url;
                }
                Type serverType = RemotingServices.GetServerTypeForUri(uri);
                if (serverType == null)
                {
                    throw new RemotingException("No receiver for uri " + uri);
                }

                SoapFormatter fm          = _soapCore.GetSafeDeserializer();
                SoapMessage   soapMessage = soapMsgFormatter.CreateSoapMessage(true);
                fm.TopObject = soapMessage;
                fm.Deserialize(requestStream);

                requestMsg = soapMsgFormatter.BuildMethodCallFromSoapMessage(soapMessage, uri);

                sp = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);

                if (sp == ServerProcessing.Complete)
                {
                    if (responseMsg != null && responseStream == null)
                    {
                        object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage)responseMsg, out responseHeaders);
                        responseStream = new MemoryStream();
                        _soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
                        responseStream.Position = 0;
                    }
                }
            }
            catch (Exception e)
            {
                responseMsg = (IMethodReturnMessage) new ReturnMessage(e, (IMethodCallMessage)requestMsg);
                object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage)responseMsg, out responseHeaders);
                responseStream = new MemoryStream();
                _soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
                responseStream.Position = 0;
                sp = ServerProcessing.Complete;
            }

            if (sp == ServerProcessing.Complete)
            {
                sinkStack.Pop(this);
            }

            return(sp);
        }
Esempio n. 39
0
	public void WriteInput(SoapMessage message)
	{
		FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
		StreamWriter w = new StreamWriter(fs);

		if (message is SoapServerMessage)
		{
			w.WriteLine("METHOD CALL at " + DateTime.Now);
			int ipc = message.MethodInfo.InParameters.Length;
			if (ipc > 0) w.WriteLine ("  Parameters:");
			for (int n=0; n<ipc; n++)
				w.WriteLine ("     " + message.GetInParameterValue (n));
		}

		w.Flush();
		w.Close();
	}
Esempio n. 40
0
 public override void ProcessMessage(SoapMessage message)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Validates incoming Hello message
        /// </summary>
        /// <param name="message">Hello message</param>
        /// <param name="reason">reason why message is invalid, null if message is valid</param>
        /// <returns>true, if message is valid</returns>
        protected bool ValidateHelloMessage(SoapMessage <WSD.HelloType> message, string[] scopes, out string reason)
        {
            bool mode1 = Features.Contains(Feature.DiscoveryTypesDnNetworkVideoTransmitter);
            bool mode2 = Features.Contains(Feature.DiscoveryTypesTdsDevice);
            bool res   = true;

            reason = null;
            try
            {
                //check Types namespace

                WSD.HelloType hello = message.Object;
                if (hello.Types == null)
                {
                    reason = Resources.ErrorNoTypes_Text;
                    return(false);
                }
                if (!DiscoveryUtils.CheckDeviceHelloType(message, out reason, mode1, mode2))
                {
                    return(false);
                }
                if (hello.EndpointReference == null)
                {
                    reason = Resources.ErrorNoEndpointReference_Text;
                    return(false);
                }
                if (hello.Scopes == null)
                {
                    reason = Resources.ErrorNoScopes_Text;
                    return(false);
                }
                if (hello.Scopes.Text == null)
                {
                    reason = Resources.ErrorNoScopesText_Text;
                    return(false);
                }
                //check mandatory scopes
                string missingScope = DiscoveryUtils.GetMissingMandatoryScope(hello.Scopes.Text);
                if (!string.IsNullOrEmpty(missingScope))
                {
                    reason = string.Format(Resources.ErrorMissingMandatoryScope_Format, missingScope);
                    return(false);
                }
                //check optional scopes
                if (scopes != null)
                {
                    missingScope = DiscoveryUtils.GetMissingScope(hello.Scopes.Text, scopes);
                    if (!string.IsNullOrEmpty(missingScope))
                    {
                        reason = string.Format(Resources.ErrorMissingScope_Format, missingScope);
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                reason = e.Message;
                res    = false;
            }
            return(res);
        }
Esempio n. 42
0
        /// <summary>
        /// 执行内容解析
        /// </summary>
        ///<param name="webArgs"></param>
        /// <param name="content">要解析的内容</param>
        /// <returns>返回需要的字段对应的字典</returns>
        public override Dictionary <string, object> ResolveSearchPageContent(BaseFetchWebPageArgument webArgs, string content)
        {
            var resultBag = new Dictionary <string, object>();

            try
            {
                string jsonData = string.Empty;

                if (content.IndexOf("g_page_config") < 0)
                {
                    return(null);//无效的页面结果数据
                }


                //send request for load other data of first search page
                Task <string> tskSilcedJsonpContent = null;
                if (webArgs.PageIndex == 0)
                {
                    tskSilcedJsonpContent = Task.Factory.StartNew(() =>
                    {
                        string jsonpContent = "";
                        ////1 打开tcp 链接
                        ////2 发送参数
                        ////3 解析结果
                        if (!webArgs.SystemAttachParas.ContainsKey("SoapTcpConnectionString"))
                        {
                            return(jsonpContent);
                        }
                        var connStrConfig = webArgs.SystemAttachParas["SoapTcpConnectionString"] as WebCrawlerConnection;
                        if (null == connStrConfig)
                        {
                            return(jsonpContent);
                        }
                        //重写解析地址-首页的分片jsonp地址
                        string urlOfSlicedJsonp = this.ResolveSlicedSearchPageSilcedUrl(webArgs);
                        webArgs.ResolvedUrl     = new ResolvedSearchUrlWithParas {
                            Url = urlOfSlicedJsonp
                        };
                        using (var conn = new SoapTcpConnection(connStrConfig))
                        {
                            if (conn.State == ConnectionState.Closed)
                            {
                                conn.Open();
                            }

                            //发送soap
                            var soapCmd = new SoapMessage()
                            {
                                Head = CommandConstants.CMD_FetchPage
                            };
                            soapCmd.Body      = JsonConvert.SerializeObject(webArgs);
                            var dataContainer = conn.SendSoapMessage(soapCmd);
                            if (null != dataContainer && dataContainer.Status == 1)
                            {
                                jsonpContent = dataContainer.Result;
                            }
                            else
                            {
                                StringBuilder errMsg = new StringBuilder("抓取网页请求失败!参数:");
                                errMsg.Append(soapCmd.Body);
                                if (null != dataContainer && !string.IsNullOrEmpty(dataContainer.ErrorMsg))
                                {
                                    errMsg.Append(";服务端错误消息:")
                                    .Append(dataContainer.ErrorMsg);
                                }
                                PluginContext.Logger.Error(errMsg.ToString());
                            }
                        }

                        return(jsonpContent);
                    });
                }


                int startPos      = content.IndexOf("g_page_config");
                int endPos        = content.IndexOf("g_srp_loadCss") - startPos;
                var secondContent = content.Substring(startPos, endPos);
                int secStartPos   = secondContent.IndexOf('{');
                int secEndPos     = secondContent.IndexOf("};") - secStartPos + 1;
                jsonData = secondContent.Substring(secStartPos, secEndPos);



                TaobaoPageJsonResut pageJsonObj = JsonConvert.DeserializeObject <TaobaoPageJsonResut>(jsonData);
                if (null == pageJsonObj)
                {
                    return(null);
                }

                if (webArgs.IsNeedResolveHeaderTags == true)
                {
                    var navNode = pageJsonObj.mods.nav;
                    if (null != navNode && null != navNode.data)
                    {
                        var commonNode = navNode.data.common;
                        var advNode    = navNode.data.adv;

                        //解析common节点
                        if (null != commonNode && commonNode.Any())
                        {
                            //1 检测是否有品牌,有的话 解析品牌
                            #region 品牌解析


                            var brandNode = commonNode.FirstOrDefault(x => x.text == "品牌" && x.sub != null);
                            if (null != brandNode && brandNode.sub != null)
                            {
                                var lstBrands = new List <BrandTag>();
                                foreach (var subItem in brandNode.sub)
                                {
                                    var model = new BrandTag();
                                    model.Platform    = SupportPlatformEnum.Taobao;
                                    model.FilterField = "ppath";//使用的过滤字段参数

                                    model.BrandId   = subItem.value;
                                    model.BrandName = subItem.text;
                                    model.CharIndex = PinYin.GetFirstLetter(model.BrandName);
                                    lstBrands.Add(model);
                                }
                                //解析完毕品牌
                                resultBag.Add("Brands", lstBrands);
                            }

                            #endregion
                        }


                        //2其他筛选节点的分析

                        #region tags 解析


                        var lstTags = new List <KeyWordTagGroup>();

                        var otherFilterNode1 = commonNode.Where(x => x.text != "品牌" && x.sub != null);
                        foreach (var itemNode in otherFilterNode1)
                        {
                            //找到归属的组
                            string groupName = itemNode.text;
                            ProcessTags(lstTags, itemNode.sub, groupName);
                        }
                        ////////if (null!= advNode)----高级筛选不要了
                        ////////{
                        ////////    //advNode 的解析
                        ////////    foreach (var itemNode in advNode)
                        ////////    {
                        ////////        //找到归属的组
                        ////////        string groupName = itemNode.text;
                        ////////        ProcessTags(lstTags, itemNode.sub, groupName);
                        ////////    }
                        ////////}

                        resultBag.Add("Tags", lstTags);

                        #endregion
                    }
                }

                #region products  解析
                var lstProducts = new ProductBaseCollection();
                resultBag.Add("Products", lstProducts);

                var itemListNode = pageJsonObj.mods.itemlist;
                if (null != itemListNode && itemListNode.data != null && null != itemListNode.data.auctions)
                {
                    foreach (var itemProduct in itemListNode.data.auctions)
                    {
                        TaobaoProduct modelProduct = this.ResolverProductDom(itemProduct);

                        if (null != modelProduct)
                        {
                            lstProducts.Add(modelProduct);
                        }
                    }
                }

                //淘宝的搜索列表 - 第一页的数据是进行了分片的,在加载html ;36条数据, 后续会进行一次jsonp的请求;加载12条数据
                if (webArgs.PageIndex == 0 && null != tskSilcedJsonpContent)
                {
                    string jsonpContent = tskSilcedJsonpContent.Result;
                    if (!string.IsNullOrEmpty(jsonpContent) && jsonpContent.Contains("API.CustomizedApi"))
                    {
                        int    startIdx         = jsonpContent.IndexOf(':') + 1;
                        int    endIdx           = jsonpContent.Length - startIdx - 3;
                        string pureJsonContent  = jsonpContent.Substring(startIdx, endIdx);
                        var    slicedJsonpResut = JsonConvert.DeserializeObject <TaobaoSlicedJsonpResut>(pureJsonContent);


                        if (null != slicedJsonpResut)
                        {
                            var itemList = slicedJsonpResut.itemlist;
                            if (null != itemList && itemList.auctions != null)
                            {
                                foreach (var itemProduct in itemList.auctions)
                                {
                                    TaobaoProduct modelProduct = this.ResolverProductDom(itemProduct);

                                    if (null != modelProduct)
                                    {
                                        lstProducts.Add(modelProduct);
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                PluginContext.Logger.Error(ex);
            }
            return(resultBag);// string.Concat("has process input :" + content);
        }
 /// <summary>
 /// Handles device discovered event
 /// </summary>
 /// <param name="sender">Event sender</param>
 /// <param name="e">Event arguments</param>
 protected void OnDiscovered(object sender, DiscoveryMessageEventArgs e)
 {
     _message = e.Message.Clone() as SoapMessage <object>;
     _eventProbeMatchReceived.Set();
 }
Esempio n. 44
0
	public void Decrypt (SoapMessage message)
	{
		StreamReader sr = new StreamReader (oldStream, Encoding.UTF8);
		string encString = sr.ReadToEnd ();
		sr.Close ();

		byte[] encBytes = Convert.FromBase64String (encString);

		MemoryStream mems = new MemoryStream (encBytes);
		CryptoStream decStream = new CryptoStream (mems, syma.CreateDecryptor(), CryptoStreamMode.Write);
		decStream.Write (encBytes, 0, encBytes.Length);
		decStream.Close ();

		byte[] decArray = mems.ToArray ();
		newStream.Write (decArray, 0, decArray.Length);
		newStream.Position = 0;
		mems.Close ();
	}