private void WriteOutputStream(SoapMessage message)
		{
			this.newStream.Position = 0;
			Copy(this.newStream, this.oldStream);

			if (AccreditSection.GetConfig().AccreditSettings.SoapRecord & message is SoapServerMessage)
			{
				if (AccreditSection.GetConfig().AccreditSettings.SoapRecordOutput)
				{
					this.newStream.Position = 0;
					TextReader reader = new StreamReader(this.newStream);
					this.soapRecorder.OutputStream = reader.ReadToEnd();
				}

				this.soapRecorder.EndDate = DateTime.Now;
				if (HttpContext.Current != null)
					this.soapRecorder.HostIP = HttpContext.Current.Request.UserHostAddress;

				string sql = ORMapping.GetInsertSql<SoapRecorder>(this.soapRecorder, TSqlBuilder.Instance);
				try
				{
					OGUCommonDefine.ExecuteNonQuery(sql);
				}
				catch (DbException ex)
				{
					if (ex.Message.IndexOf("WEB_READ_LOG") > 0)
						InitDatabase(sql);
					//else
					//    throw ex;
				}
			}
		}
		public override void ProcessMessage(SoapMessage message)
		{
			switch (message.Stage)
			{
				case SoapMessageStage.BeforeDeserialize:
					Copy(_OldStream, _NewStream);
					_NewStream.Position = 0;
					break;
				case SoapMessageStage.AfterSerialize:
					if (null != message.Exception)
					{
						string sDetailNode = "<detail />";
						if (null != message.Exception)
						{
							MemoryStream cMemoryStream = new MemoryStream();
							XmlSerializer cXmlSerializer = new XmlSerializer(typeof(helpers.web.Exception));
							cXmlSerializer.Serialize(cMemoryStream, new helpers.web.Exception(message.Exception));
							cMemoryStream.Position = 0;
							sDetailNode = "<detail><exception>" + (new StreamReader(cMemoryStream)).ReadToEnd().ToBase64() + "</exception></detail>";
							cMemoryStream.Close();
						}
						_NewStream.Position = 0;
						TextReader tr = new StreamReader(_NewStream);
						string s = tr.ReadToEnd();
						s = s.Replace("<detail />", sDetailNode);
						_NewStream = new MemoryStream();
						TextWriter tw = new StreamWriter(_NewStream);
						tw.Write(s);
						tw.Flush();
					}
					_NewStream.Position = 0;
					Copy(_NewStream, _OldStream);
					break;
			}
		}
		public void BeforeSerialize(SoapMessage message) //ObjectOut
		{
			if(System.Environment.OSVersion.Platform != PlatformID.WinCE)
			{	
				//NOTE this only works if you handle StreamOut/In too
				//NOTE this only works on .NETfx
				TimestampHeader timestampHeader = new TimestampHeader(300);
				message.Headers.Add(timestampHeader);

				//if(EndPoint == EndPointType.Addressing)
				ActionHeader actionHeader = new ActionHeader(message.Action);
				//FromHeader fromHeader = new FromHeader(null);
				ReplyToHeader replyToHeader = new ReplyToHeader(null);
				MessageIdHeader messageIdHeader = new MessageIdHeader(null);
				ToHeader toHeader = new ToHeader(message.Url);
				message.Headers.Add(actionHeader);
				//message.Headers.Add(fromHeader);
				message.Headers.Add(replyToHeader);
				message.Headers.Add(messageIdHeader);
				message.Headers.Add(toHeader);
				//else //routing
				//pathHeader pHeader = new pathHeader(message.Action, message.Url, null);
				//message.Headers.Add(pHeader);
			}
			return;
		}
        public override void ProcessMessage(System.Web.Services.Protocols.SoapMessage message)
        {
            switch (message.Stage)
            {
            case SoapMessageStage.BeforeDeserialize:
                Copy(_OldStream, _NewStream);
                _NewStream.Position = 0;
                break;

            case SoapMessageStage.AfterSerialize:
                if (message.Exception != null)
                {
                    Handler ueh = new Handler();
                    string  strDetailNode;
                    //-- handle our exception, and get the SOAP <detail> string
                    strDetailNode = ueh.HandleWebServiceException(message);
                    //-- read the entire SOAP message stream into a string
                    _NewStream.Position = 0;
                    TextReader tr = new StreamReader(_NewStream);
                    //-- insert our exception details into the string
                    string s = tr.ReadToEnd();
                    s = s.Replace("<detail />", strDetailNode);
                    //-- overwrite the stream with our modified string
                    _NewStream = new MemoryStream();
                    TextWriter tw = new StreamWriter(_NewStream);
                    tw.Write(s);
                    tw.Flush();
                }
                _NewStream.Position = 0;
                Copy(_NewStream, _OldStream);
                break;
            }
        }
		private string _processSoap(SoapMessage message)
		{
			StringBuilder sb = new StringBuilder(8192);
			string result;
			try
			{
				sb.Append(message.MethodInfo.Name);
				for (int i = 0; i < message.MethodInfo.Parameters.Length; i++)
				{
					sb.Append("[" + message.MethodInfo.Parameters[i].Name + "=");
					if (message.MethodInfo.Parameters[i].ParameterType.FullName.StartsWith("System.") && !message.MethodInfo.Parameters[i].IsOut)
					{
						sb.Append((message.GetInParameterValue(i) != null) ? message.GetInParameterValue(i) : "null");
					}
					else
					{
						sb.Append(message.MethodInfo.Parameters[i].ParameterType.FullName);
					}
					sb.Append("]");
				}
				result = sb.ToString();
			}
			catch
			{
				result = null;
			}
			finally
			{
			}
			return result;
		}
		public void AfterSerialize(SoapMessage message) //StreamOut
		{
			if(onClientOrServer == OnClientOrServer.Unknown)
				onClientOrServer = OnClientOrServer.Client;

			/*
			//HACK because .NETcf does not add Headers in BeforeSerialize above
			if(Environment.OSVersion.Platform == PlatformID.WinCE)
			{				
				newStream.Position = 0;
				//Hack MemoryStream below because of XmlDocument bug closing stream
				byte [] tempBa = new byte[newStream.Length];
				int bytesRead = newStream.Read(tempBa, 0, (int) newStream.Length);
				MemoryStream ms = new MemoryStream(tempBa);
				//BUG NOTE this closes the underlying stream on .NETcf
				XmlDocument xd = new XmlDocument();
				xd.Load(ms); //MemoryStream will be closed now

				HeadersHandler.AddHeaders(xd, message.Action, message.Url);

				newStream.Position = 0;
				XmlTextWriter xtw = new XmlTextWriter(newStream, System.Text.Encoding.UTF8);
				xtw.Namespaces = true;
				xd.WriteTo(xtw);
				xtw.Flush();
				//xtw.Close();
			} //END WinCE HACK
			*/

			//these 2 lines have be called at a minimum
			newStream.Position = 0;
			Copy(newStream, oldStream); //for next guy
			return;
		}
		/// <summary>
		/// 处理消息。
		/// BeforeDeserialize和AfterDeserialize是发生在服务内代码执行之前。
		/// BeforeSerialize和AfterSerialize是发生在服务内代码执行之后。
		/// 整个执行时序是:ChainStream,BeforeDeserialize,AfterDeserialize,BeforeSerialize,AfterSerialize
		/// </summary>
		/// <param name="message"></param>
		public override void ProcessMessage(SoapMessage message)
		{
			//仅处理Server端
			if (message is SoapServerMessage)
			{
				switch (message.Stage)
				{
					case SoapMessageStage.BeforeDeserialize:
						break;
					case SoapMessageStage.AfterDeserialize:
						//进入
						InitParameters(message);
						InitializeCounters(this._InstanceName);
						BeforeExecuteMethodCounter(message);
						break;
					case SoapMessageStage.BeforeSerialize:
						break;
					case SoapMessageStage.AfterSerialize:
						//离开
						AfterExecuteMethodCounter(message);
						break;
					default:
						throw new Exception("Error Message Stage");
				}
			}
		}
 private void AfterSerialize(SoapMessage message)
 {
     newStream.Position = 0;
     WriteOutput(message);
     newStream.Position = 0;
     Copy(newStream, oldStream);
 }
        /// <summary>
        /// ASP.Net web-service specific exception handler, to be called from UnhandledExceptionHandlerSoapExtension
        /// </summary>
        /// <returns>
        /// string with "<detail></detail>" XML element, suitable for insertion into SOAP message
        /// </returns>
        /// <remarks>
        /// existing SOAP detail message, prior to insertion, looks like:
        ///
        ///   <soap:Fault>
        ///     <faultcode>soap:Server</faultcode>
        ///     <faultstring>Server was unable to process request.</faultstring>
        ///     <detail />    <==
        ///   </soap:Fault>
        /// </remarks>
        public string HandleWebServiceException(System.Web.Services.Protocols.SoapMessage sm)
        {
            HandleException(sm.Exception);

            XmlDocument doc        = new XmlDocument();
            XmlNode     DetailNode = doc.CreateNode(XmlNodeType.Element,
                                                    SoapException.DetailElementName.Name,
                                                    SoapException.DetailElementName.Namespace);

            XmlNode TypeNode = doc.CreateNode(XmlNodeType.Element,
                                              "ExceptionType",
                                              SoapException.DetailElementName.Namespace);

            TypeNode.InnerText = _strExceptionType;
            DetailNode.AppendChild(TypeNode);

            XmlNode MessageNode = doc.CreateNode(XmlNodeType.Element,
                                                 "ExceptionMessage",
                                                 SoapException.DetailElementName.Namespace);

            MessageNode.InnerText = sm.Exception.Message;
            DetailNode.AppendChild(MessageNode);

            XmlNode InfoNode = doc.CreateNode(XmlNodeType.Element,
                                              "ExceptionInfo",
                                              SoapException.DetailElementName.Namespace);

            InfoNode.InnerText = _strException;
            DetailNode.AppendChild(InfoNode);

            return(DetailNode.OuterXml.ToString());
        }
Exemple #10
0
        /// <inheritdoc />
        /// <summary>
        /// ProcessMessage processes the soap message.
        /// </summary>
        /// <param name="message">
        /// The incoming soap message.
        /// </param>
        public override void ProcessMessage(SoapMessage message)
        {
            // Log some informational items for reviewing in this sample application.
            Logger.Debug($"Stage : {message.Stage}");

            switch (message.Stage)

            {
            case SoapMessageStage.BeforeSerialize:
                break;

            case SoapMessageStage.AfterSerialize:
                this.WriteOutput(message);
                break;

            case SoapMessageStage.BeforeDeserialize:
                this.WriteInput(message);
                break;

            case SoapMessageStage.AfterDeserialize:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemple #11
0
    public override void ProcessMessage(
        System.Web.Services.Protocols.SoapMessage message)
    {
        switch (message.Stage)
        {
        case System.Web.Services.Protocols.SoapMessageStage.BeforeSerialize:
            if (level > 2)
            {
                WriteToLog(message.Stage.ToString(),
                           EventLogEntryType.Information);
            }
            break;

        case System.Web.Services.Protocols.SoapMessageStage.AfterSerialize:
            LogOutputMessage(message);
            break;

        case System.Web.Services.Protocols.SoapMessageStage.BeforeDeserialize:
            LogInputMessage(message);
            break;

        case System.Web.Services.Protocols.SoapMessageStage.AfterDeserialize:
            if (level > 2)
            {
                WriteToLog(message.Stage.ToString(),
                           EventLogEntryType.Information);
            }
            break;
        }
    }
            /// <summary>
            /// Processs the message.
            /// </summary>
            /// <param name="message">Message.</param>
            public override void ProcessMessage(SoapMessage message)
            {
                switch (message.Stage)
                {
                    case SoapMessageStage.BeforeSerialize:
                        break;

                    case SoapMessageStage.AfterSerialize:
                        StoreRequestMessage(message);
                        // Pass it off as the actual stream
                        //Copy(newStream, oldStream);
                        // Indicate for the return that we don't wish to chain anything in
                        break;

                    case SoapMessageStage.BeforeDeserialize:
                        StoreResponseMessage(message);
                        // Pass it off as the actual stream
                        break;

                    case SoapMessageStage.AfterDeserialize:
                        break;

                    default:
                        throw new ArgumentException("Invalid message stage [" + message.Stage + "]", "message");
                }
            }
        public override void ProcessMessage(System.Web.Services.Protocols.SoapMessage message)
        {
            switch (message.Stage)
            {
            case SoapMessageStage.BeforeSerialize:
                break;

            case SoapMessageStage.AfterSerialize:

                xmlRequest = GetSoapEnvelope(newStream);

                CopyStream(newStream, oldStream);

                RecordLog(message.Action);

                break;

            case SoapMessageStage.BeforeDeserialize:

                CopyStream(oldStream, newStream);
                xmlResponse = GetSoapEnvelope(newStream);

                break;

            case SoapMessageStage.AfterDeserialize:
                break;
            }
        }
Exemple #14
0
 public void WriteRequest(SoapMessage message)
 {
     newStream.Position = 0;
     if(_textBox != null)
     {
         _textBox.Text += string.Format("-----SoapRequest at {0}\r\n\r\n", DateTime.Now);
         _textBox.Text += new StreamReader(newStream).ReadToEnd() + "\r\n\r\n";
     }
     newStream.Position = 0;
     Copy(newStream, oldStream);
 }
        /// <summary>
        /// Process the soap message and try validate calling party authentication
        /// by examing the message headers. We are searching for custom message header 
        /// containing a WRAP authentication token.
        /// This method is automatically called by the ASMX WebService infrastructure
        /// </summary>
        /// <param name="message">The <see cref="T:System.Web.Services.Protocols.SoapMessage"/> to process.</param>
        public override void ProcessMessage(SoapMessage message)
        {
            if (message.Stage == SoapMessageStage.AfterDeserialize && message is SoapServerMessage)
            {
                // we need to catch the message after it has come from the client
                // and has been deserialized
                if (message.Headers.Count < 1)
                {
                    // the number of message headers is less than 1, for sure there is no authentication
                    throw new ApplicationException("You are not authorized to use this resource");
                }

                foreach (SoapHeader header in message.Headers)
                {
                    if (header is SoapUnknownHeader)
                    {
                        // The custom header sent will be unknown header.
                        // Get the token value from the InnerText proprety of the header
                        string tokenHeaderValue = ((SoapUnknownHeader)header).Element.InnerText;

                        // Parse the token string to real token instance
                        SimpleWebToken token = SimpleWebToken.Parse(tokenHeaderValue);

                        // Check token validity - checks token Signature, Expire date
                        // and, because included as parameter - the token Audience
                        SimpleWebTokenValidationResult result =
                            SimpleWebToken.Validate(token, this._tokenHelper.ACSSigningKey,
                            expectedAudience: ConfigurationManager.AppSettings["SiAudience"]);
                        if (result == SimpleWebTokenValidationResult.Valid)
                        {
                            var server = ((SoapServerMessage)message).Server;
                            if (server is IClaimsAwareService)
                            {
                                // inject the ClaimsPrincipal to the instance of the service
                                // thus the method can perform additional checks
                                ((IClaimsAwareService)server).SetClaimsPricipal(token.ToPrinciple());
                            }

                            foreach (var claim in token.Claims.AllKeys)
                            {
                                // debugging purposes only - printout the claims collection
                                System.Diagnostics.Debug.WriteLine(string.Format("{0} => {1} ", claim, token.Claims[claim]));
                            }
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("Authentication failed: {0}",result.ToString()));
                        }

                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        public override void ProcessMessageBeforeDeserialize(System.Web.Services.Protocols.SoapMessage message)
        {
            StreamEncryptor compressor = StreamEncryptor.Create(EncryptionMode);

            try
            {
                compressor.ProcessStream(previousStream, currentStream, StreamProcessMode.Decrypt);
            }
            catch (Exception e)
            {
                throw new SoapException(e.Message, SoapException.ServerFaultCode, e);
            }
        }
		public override void ProcessMessage(SoapMessage message)
		{
			try
			{
				if (message.Stage == SoapMessageStage.AfterDeserialize)
				{
					string _mtd = this._processSoap(message);
					string _userExecute = string.Format("USERID '{0}'  ", "unknown");
					foreach (SoapHeader header in message.Headers)
					{
						if (header is AuthHeader)
						{
							AuthHeader credentials = (AuthHeader)header;
							try
							{
								switch (credentials.CryptoAlgorithm)
								{
								case AuthHeader.CryptoAlgorithmEnum.NONE:
									_userExecute = string.Format("USERID '{0}'  ", credentials.AuthKey.Split(new char[]
									{
										'|'
									})[0]);
									break;
								case AuthHeader.CryptoAlgorithmEnum.TRIPLEDES:
									_userExecute = string.Format("USERID '{0}'  ", CryptorEngineTripleDES.Decrypt(SAFConfiguration.readConnectionStringCoreEncrypted(), new SecurityInfo(SAFConfiguration.readMasterKey(), SAFConfiguration.readInfoKey(), SAFConfiguration.readInfoIV()), true).Split(new char[]
									{
										'|'
									})[0]);
									break;
								}
							}
							catch (SoapException ex)
							{
								SAFLOGGER.Write(SAFLOGGER.LOGGEREventID.EXCEPTION, "SAFAPILOGGER", new string[]
								{
									"http://sfexpand.SAFBusiness.AuthExtension.softfinanca.com/",
									ex.ToString()
								});
							}
						}
					}
					SAFLOGGER.dump(SAFLOGGER.LOGGEREventID.INFORMATION, "SAFAPILOGGER", new string[]
					{
						_userExecute + _mtd
					});
				}
			}
			catch
			{
			}
		}
Exemple #18
0
        /// <summary>
        /// Write the input of the incoming soap response.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        public void WriteInput(SoapMessage message)
        {
            CopyStream(this.oldStream, this.newStream);
            this.newStream.Position = 0;
            var reader     = new StreamReader(this.newStream);
            var requestXml = reader.ReadToEnd();

            // Trimming the end of the string b/c some of my requests and responses had newlines :-(
            Logger.Debug($"Response | {requestXml.TrimEnd('\r', '\n') }");

            // Example of the using PrettyXml
            // Logger.Debug(this.PrettyXml(requestXml));
            this.newStream.Position = 0;
        }
Exemple #19
0
        public void WriteOutput(SoapMessage message)
        {
            newStream.Position = 0;
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            StreamWriter w = new StreamWriter(fs);

            string soapString = (message is SoapServerMessage) ? "SoapResponse" : "SoapRequest";
            w.WriteLine("-----" + soapString + " at " + DateTime.Now);
            w.Flush();
            Copy(newStream, fs);
            w.Close();
            newStream.Position = 0;
            Copy(newStream, oldStream);
        }
        public override void ProcessMessage(SoapMessage message)
        {
            if (GlimpseManager.IsGlimpseActive() == false)
                return;

            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    _result.RequestArgs = GetRequestArgs(message);
                    break;
                case SoapMessageStage.AfterSerialize:
                    _result.RequestXml = GetXml(_newStream);

                    CopyStream(_newStream, _oldStream);
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    CopyStream(_oldStream, _newStream);
                    _result.ResponseXml = GetXml(_newStream);
                    break;
                case SoapMessageStage.AfterDeserialize:
                    TimerResult dt = GlimpseManager.GetExecutionTimer().Stop(_timer);

                    bool hasError = (message.Exception != null);
                    object retVal;
                    if (hasError)
                        retVal = message.Exception;
                    else if (message.MethodInfo.IsVoid)
                        retVal = "The SOAP call is to a void method";
                    else
                        retVal = message.GetReturnValue();

                    _result.Url = message.Url;
                    _result.Method = message.MethodInfo.Name + (hasError ? " - ERROR" : "");
                    _result.ResponseResult = retVal;
                    _result.Duration = dt.Duration.Milliseconds + "ms";
                    _result.Stacktrace = new StackTrace(4, true).ToString();
                    GlimpseManager.LogMessage(_result);

                    var timeline = new SoapTimelineMessage();
                    timeline.EventName = message.MethodInfo.Name + (hasError ? " - ERROR" : "");
                    timeline.EventSubText = message.Url + "\n" + retVal;
                    timeline.Offset = dt.Offset;
                    timeline.Duration = dt.Duration;
                    timeline.StartTime = dt.StartTime;
                    timeline.EventCategory = SoapTimelineCategory;
                    GlimpseManager.LogMessage(timeline);
                    break;
            }
        }
		public void BeforeSerialize(SoapMessage message) //ObjectOut
		{
			if(onClientOrServer == OnClientOrServer.Unknown)
				onClientOrServer = OnClientOrServer.Client;
			if(System.Environment.OSVersion.Platform != PlatformID.WinCE)
			{	
				//NOTE this only works if you handle StreamOut/In too
				//NOTE this only works on .NETfx
				//TimestampHeader timestampHeader = new TimestampHeader(300);
				//message.Headers.Add(timestampHeader);
				if(onClientOrServer == OnClientOrServer.Server)
				{
					ActionHeader actionHeader = new ActionHeader(message.Action + "Response");
					//else check what the inAction is
					RelatesToHeader relatesToHeader = null;
					if(inMessageId != null)
						relatesToHeader = new RelatesToHeader(inMessageId);
					ToHeader toHeader = null;
					if(inReplyTo != null)
						toHeader = new ToHeader(inReplyTo);
					//TODO ReferenceProperties
					message.Headers.Add(actionHeader);
					if(relatesToHeader != null)
						message.Headers.Add(relatesToHeader);
					if(toHeader != null)
						message.Headers.Add(toHeader);
				}
				else
				{
					//if(EndPoint == EndPointType.Addressing)
					ActionHeader actionHeader = new ActionHeader(message.Action);
					FromHeader fromHeader = new FromHeader(null);
					MessageIdHeader messageIdHeader = new MessageIdHeader(null);
					ToHeader toHeader = new ToHeader(message.Url);
					//TODO Subscription would need a ReplyTo header for asynch web services
					//ReplyToHeader replyToHeader = new ReplyToHeader("http://tempuri.org/RespondToClientCall/");
					ReplyToHeader replyToHeader = new ReplyToHeader(message.Url); //just respond normally?
					message.Headers.Add(replyToHeader);
					message.Headers.Add(actionHeader);
					message.Headers.Add(fromHeader);
					message.Headers.Add(messageIdHeader);
					message.Headers.Add(toHeader);
				}
				//else //routing
				//pathHeader pHeader = new pathHeader(message.Action, message.Url, null);
				//message.Headers.Add(pHeader);
			}
			return;
		}
		public override void ProcessMessage(SoapMessage message)
		{
			int num = -1;
			if (message.Stage == SoapMessageStage.AfterDeserialize)
			{
				foreach (SoapHeader soapHeader in message.Headers)
				{
					if (soapHeader is AuthHeader)
					{
						AuthHeader arg_33_0 = (AuthHeader)soapHeader;
					}
				}
				throw new SoapException("[" + num.ToString() + "] " + this._authRespMsg, SoapException.ClientFaultCode);
			}
		}
Exemple #23
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);
             break;
         case SoapMessageStage.BeforeDeserialize:
             WriteInput(message);
             break;
         case SoapMessageStage.AfterDeserialize:
             break;
     }
 }
        public override void ProcessMessage(SoapMessage message)
        {
            string messageAsString;
            StreamReader reader;
            StreamWriter writer;

            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    break;

                case SoapMessageStage.AfterDeserialize:
                    break;

                case SoapMessageStage.BeforeDeserialize:

                    reader = new StreamReader(_streamOut);
                    writer = new StreamWriter(_streamIn);
                    messageAsString = reader.ReadToEnd();

                    switch (message.MethodInfo.Name)
                    {
                        case "getWorklogs":
                        case "addWorklogWithNewRemainingEstimate":
                        case "addWorklogAndAutoAdjustRemainingEstimate":
                        case "addWorklogAndRetainRemainingEstimate":
                            messageAsString = messageAsString
                                .Replace("IssueServiceImpl$RemoteWorklogImpl", "RemoteWorklog")
                                .Replace("service", "beans");
                            break;
                    }

                    writer.Write(messageAsString);
                    writer.Flush();
                    _streamIn.Position = 0;
                    break;

                case SoapMessageStage.AfterSerialize:
                    _streamIn.Position = 0;
                    reader = new StreamReader(_streamIn);
                    writer = new StreamWriter(_streamOut);
                    messageAsString = reader.ReadToEnd();
                    writer.Write(messageAsString);
                    writer.Flush();
                    break;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        public override void ProcessMessageBeforeDeserialize(System.Web.Services.Protocols.SoapMessage message)
        {
            StreamCompressor compressor = StreamCompressor.Create(CompressorMode);

            try
            {
                //对于处理BeforeDeserialize过程时,因为系统会按照优先级从高到低逐个调用SOAP扩展(跟上述过程刚好相反)
                //的ProcessMessage方法,因此输入流必须是previousStream所指向的对象,该对象是优先级别更高的SOAP扩展的
                //currentStream所指向的内存流对象,或者当前SOAP扩展自身是个最高优先级别的扩展时,其previousStream所
                //指向的对象是个来自网络的输入流对象,而该函数所接受的输出流对象则应该是currentStream所指向的流对象。
                compressor.ProcessStream(previousStream, currentStream, StreamProcessMode.Decompress);
            }
            catch (Exception e)
            {
                throw new SoapException(e.Message, SoapException.ServerFaultCode, e);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        public override void ProcessMessageAfterSerialize(System.Web.Services.Protocols.SoapMessage message)
        {
            StreamCompressor compressor = StreamCompressor.Create(CompressorMode);

            try
            {
                //对于处理AfterSerialize过程时,因为系统按优先级从低到高逐个调用SOAP扩展的ProcessMessage方法,
                //因此输入流必须是currentStream指向的对象,该对象就是在ChainStream方法中定义的MemoryStream对象,
                //而输出流是previousStream所指向的对象,该对象是更高优先级的SOAP扩展的输入流对象或者当前SOAP扩展
                //自身是最高优先级别的扩展时,其previousStream所指向的对象是个SoapExternalStream对象,这个对象只
                //是一个包装类对象而已,它底层包含了一个用于将构成Http/Soap协议所必要的信息发送到网络中输出流。
                compressor.ProcessStream(currentStream, previousStream, StreamProcessMode.Compress);
            }
            catch (Exception e)
            {
                throw new SoapException(e.Message, SoapException.ServerFaultCode, e);
            }
        }
Exemple #27
0
 public override void ProcessMessage(SoapMessage message)
 {
     switch (message.Stage)
     {
         case SoapMessageStage.BeforeSerialize:
             break;
         case SoapMessageStage.AfterSerialize:
             WriteRequest(message);
             break;
         case SoapMessageStage.BeforeDeserialize:
             WriteResponse(message);
             break;
         case SoapMessageStage.AfterDeserialize:
             break;
         default:
             throw new Exception("invalid stage");
     }
 }
Exemple #28
0
 public void WriteInput(SoapMessage message)
 {
     Copy(oldStream, newStream);
     Stream resp = new MemoryStream();
     newStream.Position = 0;
     Copy(newStream, resp);
     resp.Position = 0;
     using (TextReader reader = new StreamReader(resp))
     {
         try
         {
             //string response = reader.ReadToEnd();
             Context.Current.Response = reader.ReadToEnd();
         }
         catch { }
     }
     newStream.Position = 0;
 }
		/// <summary>
		/// Soap消息的不同状态处理
		/// </summary>
		/// <param name="message">内部传输的Soap消息【带有状态】</param>
		public override void ProcessMessage(SoapMessage message)
		{
			switch (message.Stage)
			{
				case SoapMessageStage.BeforeSerialize:
					break;
				case SoapMessageStage.BeforeDeserialize:
					this.WriteInputStream(message);
					break;
				case SoapMessageStage.AfterSerialize:
					this.WriteOutputStream(message);
					break;
				case SoapMessageStage.AfterDeserialize:
					break;
				default:
					throw new Exception("Error Message Stage");
			}
		}
        public override void ProcessMessage(SoapMessage message)
        {
            switch (message.Stage)
            {
                case SoapMessageStage.BeforeDeserialize:
                    // Incoming message
                    LogMessageFromStream(message.Stream);
                    break;

                case SoapMessageStage.AfterDeserialize:
                    break;

                case SoapMessageStage.BeforeSerialize:
                    break;

                case SoapMessageStage.AfterSerialize:
                    break;
            }
        }
		public override void ProcessMessage(SoapMessage message) 
		{
			switch (message.Stage) 
			{
				case SoapMessageStage.BeforeSerialize:
					BeforeSerialize(message);
					break;
				case SoapMessageStage.AfterSerialize:
					AfterSerialize(message);
					break;
				case SoapMessageStage.BeforeDeserialize:
					BeforeDeserialize(message);
					break;
				case SoapMessageStage.AfterDeserialize:
					AfterDeserialize(message);
					break;
				default:
					throw new Exception("invalid SoapExtension.ProcessMessage stage");
			}
		}
 public override void ProcessMessage(SoapMessage message)
 {
     switch (message.Stage)
     {
         case SoapMessageStage.BeforeSerialize:
             //Add the CustomSoapHeader to outgoing client requests
             if (message is SoapClientMessage)
             {
                 AddHeader(message);
             }
             break;
         case SoapMessageStage.AfterSerialize:
             AfterSerialize(message);
             break;
         case SoapMessageStage.BeforeDeserialize:
             BeforeDeserialize(message);
             break;
         case SoapMessageStage.AfterDeserialize:
             break;
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public override void ProcessMessage(SoapMessage message)
        {
            if (message.Stage == SoapMessageStage.AfterSerialize)
            {
                _newStream.Position = 0;

                if (message.Exception != null && message.Exception.InnerException != null)
                {
                    InsertDetailIntoOldStream(message.Exception.InnerException);
                }
                else
                {
                    CopyStream(_newStream, _oldStream);
                }
            }
            else if (message.Stage == SoapMessageStage.BeforeDeserialize)
            {
                CopyStream(_oldStream, _newStream);
                _newStream.Position = 0;
            }
        }
        public override void ProcessMessage(SoapMessage message)
        {
            switch (message.Stage)
            {

                case SoapMessageStage.BeforeSerialize:
                    break;

                case SoapMessageStage.AfterSerialize:
                    Encrypt();
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    Decrypt();
                    break;

                case SoapMessageStage.AfterDeserialize:
                    break;

                default:
                    throw new Exception("invalid stage");
            }
        }
		public override void ProcessMessage(SoapMessage message) 
		{
			//	bool bIsServer;
			//	if(message.GetType() == typeof(SoapServerMessage))
			//	{
			//		bIsServer = true;
			//	} 
			//	else
			//	{
			//		bIsServer = false;
			//	}

			switch (message.Stage) 
			{
				// Incomming from client
				case SoapMessageStage.BeforeDeserialize:
					ReceiveStream();
					ReverseIncomingStream();
					LogInput(message);
					break;

				// About to call methods
				case SoapMessageStage.AfterDeserialize:
					break;

				// After Method call
				case SoapMessageStage.BeforeSerialize:
					break;

				// Outgoing to client
				case SoapMessageStage.AfterSerialize:
					ReverseOutgoingStream();
					LogOutput(message);
					ReturnStream();
					break;
				default:
					throw new Exception("No stage such as this...");
			}
		}
		public void AfterDeserialize(SoapMessage message) //ObjectIn
		{
			SoapMessage mess = message;
			return;
		}
Exemple #37
0
        SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            SoapClientMethod method = clientType.GetMethod(methodName);

            if (method == null)
            {
                throw new ArgumentException(Res.GetString(Res.WebInvalidMethodName, methodName));
            }

            // Run BeforeSerialize extension pass. Extensions are not allowed
            // to write into the stream during this pass.
            SoapReflectedExtension[] allExtensions     = (SoapReflectedExtension[])CombineExtensionsHelper(clientType.HighPriExtensions, method.extensions, clientType.LowPriExtensions, typeof(SoapReflectedExtension));
            object[]          allExtensionInitializers = (object[])CombineExtensionsHelper(clientType.HighPriExtensionInitializers, method.extensionInitializers, clientType.LowPriExtensionInitializers, typeof(object));
            SoapExtension[]   initializedExtensions    = SoapMessage.InitializeExtensions(allExtensions, allExtensionInitializers);
            SoapClientMessage message = new SoapClientMessage(this, method, Url);

            message.initializedExtensions = initializedExtensions;
            if (initializedExtensions != null)
            {
                message.SetExtensionStream(new SoapExtensionStream());
            }
            message.InitExtensionStreamChain(message.initializedExtensions);

            string soapAction = UrlEncoder.EscapeString(method.action, Encoding.UTF8);

            message.SetStage(SoapMessageStage.BeforeSerialize);
            if (this.version == SoapProtocolVersion.Soap12)
            {
                message.ContentType = ContentType.Compose(ContentType.ApplicationSoap, RequestEncoding != null ? RequestEncoding : Encoding.UTF8, soapAction);
            }
            else
            {
                message.ContentType = ContentType.Compose(ContentType.TextXml, RequestEncoding != null ? RequestEncoding : Encoding.UTF8);
            }
            message.SetParameterValues(parameters);
            SoapHeaderHandling.GetHeaderMembers(message.Headers, this, method.inHeaderMappings, SoapHeaderDirection.In, true);
            message.RunExtensions(message.initializedExtensions);

            // Last chance to set request headers
            request.ContentType = message.ContentType;
            if (message.ContentEncoding != null && message.ContentEncoding.Length > 0)
            {
                request.Headers[ContentType.ContentEncoding] = message.ContentEncoding;
            }

            request.Method = "POST";
            if (this.version != SoapProtocolVersion.Soap12 && request.Headers[Soap.Action] == null)
            {
                StringBuilder actionStringBuilder = new StringBuilder(soapAction.Length + 2);
                actionStringBuilder.Append('"');
                actionStringBuilder.Append(soapAction);
                actionStringBuilder.Append('"');
                request.Headers.Add(Soap.Action, actionStringBuilder.ToString());
            }

            return(message);
        }
 public override void ProcessMessage(System.Web.Services.Protocols.SoapMessage message)
 {
     var resultado = StreamToString(message.Stream);
 }
Exemple #39
0
        public override void ProcessMessage(System.Web.Services.Protocols.SoapMessage message)
        {
            AgentMessageTable ab = AgentMessageTable.Instance;
            //  if (AgentMessageTable.GetSize() >= 100)
            //      ;
            AgentMessageTable a = AgentMessageTable.Instance;

            System.Console.WriteLine("Tread " + Thread.CurrentThread.ManagedThreadId + " Message Table:" + AgentMessageTable.GetSize());
            try
            {
                if (HttpContext.Current == null)
                {
                }
                else
                {
                    //depends.Push(HttpContext.Current.Request.Url);
                }
                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }


                if (message.GetType() == typeof(SoapClientMessage))
                {
                    switch (message.Stage)
                    {
                    case SoapMessageStage.BeforeSerialize:
                        //outbound message client
                        this.ProcessOutboundRequest(message);
                        //this.InsertHeadersOutbound(message, true);
                        return;

                    case SoapMessageStage.AfterSerialize:
                        //outbound message client

                        return;

                    case SoapMessageStage.BeforeDeserialize:
                        this.GrabClientResponseMessageBeforeDeserialization(message);
                        //inbound message client
                        //4-16-2012 moved call to after deserialization to obtain soap headers for dependency detection
                        return;

                    case SoapMessageStage.AfterDeserialize:
                        this.ProcessInboundResponse(message);
                        return;
                    }
                }
                else if (message.GetType() == typeof(SoapServerMessage))
                {
                    switch (message.Stage)
                    {
                    case SoapMessageStage.BeforeSerialize:
                        //outbound server
                        this.InsertHeadersOutbound(message, false);
                        return;

                    case SoapMessageStage.AfterSerialize:
                        //outbound server
                        this.ProcessOutboundResponse(message);
                        return;

                    case SoapMessageStage.BeforeDeserialize:
                        //this.ProcessInboundRequest(message);  //this yields no access to soap headers
                        return;

                    case SoapMessageStage.AfterDeserialize:
                        this.ProcessInboundRequest(message);
                        //just moved this
                        return;
                    }
                }
                else
                {
                    try
                    {
                        Logger.warn(this.GetType().FullName + "unknown message type was not handled: " + message.GetType().FullName);
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                Logger.error(ex, this.GetType().FullName + "error caught when processing a message");

                /*   String s = "";
                 * while (ex != null)
                 * {
                 *     s += ex.Message + System.Environment.NewLine + ex.StackTrace + System.Environment.NewLine + ex.InnerException + System.Environment.NewLine + System.Environment.NewLine;
                 *     ex = ex.InnerException;
                 * }
                 * try
                 * {
                 *     if (FGSMSConstants.log) EventLog.WriteEntry(this.GetType().FullName, "error caught " + message.GetType().FullName + s, EventLogEntryType.Error);
                 * }
                 * catch { }*/
            }
        }
Exemple #40
0
        internal override bool Initialize()
        {
            // try to guess the request version so we can handle any exceptions that might come up
            GuessVersion();

            message             = new SoapServerMessage(this);
            onewayInitException = null;

            serverType = (SoapServerType)GetFromCache(typeof(SoapServerProtocol), Type);
            if (serverType == null)
            {
                lock (Type){
                    serverType = (SoapServerType)GetFromCache(typeof(SoapServerProtocol), Type);
                    if (serverType == null)
                    {
                        serverType = new SoapServerType(Type, versionsSupported);
                        AddToCache(typeof(SoapServerProtocol), Type, serverType);
                    }
                }
            }

            // We delay throwing any exceptions out of the extension until we determine if the method is one-way or not.
            Exception extensionException = null;

            try {
                message.highPriConfigExtensions = SoapMessage.InitializeExtensions(serverType.HighPriExtensions, serverType.HighPriExtensionInitializers);
                // For one-way methods we rely on Request.InputStream guaranteeing that the entire request body has arrived
                message.SetStream(Request.InputStream);

                Debug.Assert(message.Stream.CanSeek, "Web services SOAP handler assumes a seekable stream.");

                message.InitExtensionStreamChain(message.highPriConfigExtensions);
                message.SetStage(SoapMessageStage.BeforeDeserialize);
                message.ContentType     = Request.ContentType;
                message.ContentEncoding = Request.Headers[ContentType.ContentEncoding];
                message.RunExtensions(message.highPriConfigExtensions);
            }
            catch (Exception e) {
                extensionException = e;
            }

            // set this here since we might throw before we init the other extensions
            message.allExtensions = message.highPriConfigExtensions;

            // maybe the extensions that just ran changed some of the request data so we can make a better version guess
            GuessVersion();
            try {
                this.serverMethod = helper.RouteRequest();

                // the RouteRequest impl should throw an exception if it can't route the request but just in case...
                if (this.serverMethod == null)
                {
                    throw new SoapException(Res.GetString(Res.UnableToHandleRequest0), new XmlQualifiedName(Soap.ServerCode, Soap.Namespace));
                }
            }
            catch (Exception) {
                if (helper.RequestNamespace != null)
                {
                    SetHelper(SoapServerProtocolHelper.GetHelper(this, helper.RequestNamespace));
                }

                // version mismatches override other errors
                CheckHelperVersion();

                throw;
            }

            this.isOneWay = serverMethod.oneWay;
            if (extensionException == null)
            {
                try {
                    SoapReflectedExtension[] otherReflectedExtensions = (SoapReflectedExtension[])CombineExtensionsHelper(serverMethod.extensions, serverType.LowPriExtensions, typeof(SoapReflectedExtension));
                    object[] otherInitializers = (object[])CombineExtensionsHelper(serverMethod.extensionInitializers, serverType.LowPriExtensionInitializers, typeof(object));
                    message.otherExtensions = SoapMessage.InitializeExtensions(otherReflectedExtensions, otherInitializers);
                    message.allExtensions   = (SoapExtension[])CombineExtensionsHelper(message.highPriConfigExtensions, message.otherExtensions, typeof(SoapExtension));
                }
                catch (Exception e) {
                    extensionException = e;
                }
            }

            if (extensionException != null)
            {
                if (isOneWay)
                {
                    onewayInitException = extensionException;
                }
                else
                {
                    throw new SoapException(Res.GetString(Res.WebConfigExtensionError), new XmlQualifiedName(Soap.ServerCode, Soap.Namespace), extensionException);
                }
            }

            return(true);
        }
Exemple #41
0
        internal override bool Initialize()
        {
            this.GuessVersion();
            this.message             = new SoapServerMessage(this);
            this.onewayInitException = null;
            this.serverType          = (SoapServerType)base.GetFromCache(typeof(SoapServerProtocol), base.Type);
            if (this.serverType == null)
            {
                lock (ServerProtocol.InternalSyncObject)
                {
                    this.serverType = (SoapServerType)base.GetFromCache(typeof(SoapServerProtocol), base.Type);
                    if (this.serverType == null)
                    {
                        this.serverType = new SoapServerType(base.Type, this.protocolsSupported);
                        base.AddToCache(typeof(SoapServerProtocol), base.Type, this.serverType);
                    }
                }
            }
            Exception innerException = null;

            try
            {
                this.message.highPriConfigExtensions = SoapMessage.InitializeExtensions(this.serverType.HighPriExtensions, this.serverType.HighPriExtensionInitializers);
                this.message.highPriConfigExtensions = this.ModifyInitializedExtensions(PriorityGroup.High, this.message.highPriConfigExtensions);
                this.message.SetStream(base.Request.InputStream);
                this.message.InitExtensionStreamChain(this.message.highPriConfigExtensions);
                this.message.SetStage(SoapMessageStage.BeforeDeserialize);
                this.message.ContentType     = base.Request.ContentType;
                this.message.ContentEncoding = base.Request.Headers["Content-Encoding"];
                this.message.RunExtensions(this.message.highPriConfigExtensions, false);
                innerException = this.message.Exception;
            }
            catch (Exception exception2)
            {
                if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException))
                {
                    throw;
                }
                if (Tracing.On)
                {
                    Tracing.ExceptionCatch(TraceEventType.Warning, this, "Initialize", exception2);
                }
                innerException = exception2;
            }
            this.message.allExtensions = this.message.highPriConfigExtensions;
            this.GuessVersion();
            try
            {
                this.serverMethod = this.RouteRequest(this.message);
                if (this.serverMethod == null)
                {
                    throw new SoapException(System.Web.Services.Res.GetString("UnableToHandleRequest0"), new XmlQualifiedName("Server", "http://schemas.xmlsoap.org/soap/envelope/"));
                }
            }
            catch (Exception exception3)
            {
                if (((exception3 is ThreadAbortException) || (exception3 is StackOverflowException)) || (exception3 is OutOfMemoryException))
                {
                    throw;
                }
                if (this.helper.RequestNamespace != null)
                {
                    this.SetHelper(SoapServerProtocolHelper.GetHelper(this, this.helper.RequestNamespace));
                }
                this.CheckHelperVersion();
                throw;
            }
            this.isOneWay = this.serverMethod.oneWay;
            if (innerException == null)
            {
                try
                {
                    SoapReflectedExtension[] reflectedExtensions = (SoapReflectedExtension[])CombineExtensionsHelper(this.serverMethod.extensions, this.serverType.LowPriExtensions, typeof(SoapReflectedExtension));
                    object[] extensionInitializers = (object[])CombineExtensionsHelper(this.serverMethod.extensionInitializers, this.serverType.LowPriExtensionInitializers, typeof(object));
                    this.message.otherExtensions = SoapMessage.InitializeExtensions(reflectedExtensions, extensionInitializers);
                    this.message.otherExtensions = this.ModifyInitializedExtensions(PriorityGroup.Low, this.message.otherExtensions);
                    this.message.allExtensions   = (SoapExtension[])CombineExtensionsHelper(this.message.highPriConfigExtensions, this.message.otherExtensions, typeof(SoapExtension));
                }
                catch (Exception exception4)
                {
                    if (((exception4 is ThreadAbortException) || (exception4 is StackOverflowException)) || (exception4 is OutOfMemoryException))
                    {
                        throw;
                    }
                    if (Tracing.On)
                    {
                        Tracing.ExceptionCatch(TraceEventType.Warning, this, "Initialize", exception4);
                    }
                    innerException = exception4;
                }
            }
            if (innerException != null)
            {
                if (!this.isOneWay)
                {
                    if (innerException is SoapException)
                    {
                        throw innerException;
                    }
                    throw SoapException.Create(this.Version, System.Web.Services.Res.GetString("WebConfigExtensionError"), new XmlQualifiedName("Server", "http://schemas.xmlsoap.org/soap/envelope/"), innerException);
                }
                this.onewayInitException = innerException;
            }
            return(true);
        }
		public void AfterSerialize(SoapMessage message) //StreamOut
		{
			newStream.Position = 0;
			//Hack MemoryStream below because of XmlDocument bug closing stream
			byte [] tempBa = new byte[newStream.Length];
			int bytesRead = newStream.Read(tempBa, 0, (int) newStream.Length);
			MemoryStream ms = new MemoryStream(tempBa);
			//BUG NOTE this closes the underlying stream on .NETcf
			XmlDocument xd = new XmlDocument();
			xd.Load(ms); //MemoryStream will be closed now
			
			//outgoing
			//timestamp and routing
			HeadersHandler.AddHeaders(xd, message.Action, message.Url); 
			//XmlEncHandler.EncryptXml(xd);
			XmlSigHandler.SignXml(xd); //or before XmlEnc.
			//Trace
			
			newStream.Position = 0;
			XmlTextWriter xtw = new XmlTextWriter(newStream, System.Text.Encoding.UTF8);
			xtw.Namespaces = true;
			xd.WriteTo(xtw);
			xtw.Flush();
			//xtw.Close();

			//these 2 lines have be called at a minimum
			newStream.Position = 0;
			Copy(newStream, oldStream); //for next guy
			return;
		}
		public void BeforeSerialize(SoapMessage message) //ObjectOut
		{
			//NOTE this only works if you handle StreamOut/In too
			//NOTE this only works on .NETfx
			return;
		}
Exemple #44
0
 public abstract void ProcessMessage(SoapMessage message);
		public void BeforeSerialize(SoapMessage message) //ObjectOut
		{
			if(onClientOrServer == OnClientOrServer.Unknown)
				onClientOrServer = OnClientOrServer.Client;
			
			return;
		}