<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>THE .NET WAY &#187; asmx</title>
	<atom:link href="http://www.thedotnetway.net/tag/asmx/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.thedotnetway.net</link>
	<description>El blog Tecnológico de Emilio Torrens y Jordi Cladera</description>
	<lastBuildDate>Thu, 29 Jul 2010 08:27:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Soap Extension</title>
		<link>http://www.thedotnetway.net/2009/10/07/soap-extension/</link>
		<comments>http://www.thedotnetway.net/2009/10/07/soap-extension/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 14:41:30 +0000</pubDate>
		<dc:creator>JordiC</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asmx]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[SOAP]]></category>
		<category><![CDATA[SOAP Extension]]></category>

		<guid isPermaLink="false">http://www.thedotnetway.net/2009/10/07/soap-extension/</guid>
		<description><![CDATA[Soap Extension es un mecanismo de ASP.NET para interceptar mensages Soap cuando entran o salen de nuestro sistema. Existen cuatro puntos en todo el proceso del mensaje en los cuales podremos interceptar el mensaje: Para implementarla solo tenemos que crear una clase que herede de System.Web.Services.Protocols.SoapExtension. Aquí tienes un ejemplo sacado de la documentación de [...]]]></description>
			<content:encoded><![CDATA[<p>Soap Extension es un mecanismo de ASP.NET para interceptar mensages Soap cuando entran o salen de nuestro sistema. Existen cuatro puntos en todo el proceso del mensaje en los cuales podremos interceptar el mensaje:</p>
<p><a href="http://www.thedotnetway.net/wp-content/uploads/2009/10/esw638yk_xmlwebservicelifetimeenusVS_71.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="esw638yk_xmlwebservicelifetime(en-us,VS_71)" border="0" alt="esw638yk_xmlwebservicelifetime(en-us,VS_71)" src="http://www.thedotnetway.net/wp-content/uploads/2009/10/esw638yk_xmlwebservicelifetimeenusVS_71_thumb.gif" width="475" height="245" /></a> </p>
<p>Para implementarla solo tenemos que crear una clase que herede de System.Web.Services.Protocols.SoapExtension. Aquí tienes un ejemplo sacado de la documentación de MSDN, intercepta los mensajes en la entrada duespues de serializar (Paso 2 en el gráfico) y en la salida antes de Deserializar (Paso 4 en el gráfico) y guarda los mensajes en disco.</p>
</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">TraceExtension </span>: <span style="color: #2b91af">SoapExtension
</span>{</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code">    Stream oldStream;
    Stream newStream;
    <span style="color: blue">string </span>filename;

    <span style="color: green">// Save the Stream representing the SOAP request or SOAP response into
    // a local memory buffer.
    </span><span style="color: blue">public override </span>Stream ChainStream( Stream stream ){
        oldStream = stream;
        newStream = <span style="color: blue">new </span>MemoryStream();
        <span style="color: blue">return </span>newStream;
    }

    <span style="color: green">// When the SOAP extension is accessed for the first time, the XML Web
    // service method it is applied to is accessed to store the file
    // name passed in, using the corresponding SoapExtensionAttribute.
    </span><span style="color: blue">public override object </span>GetInitializer(LogicalMethodInfo methodInfo,
	                                   SoapExtensionAttribute attribute)
    {
        <span style="color: blue">return </span>((TraceExtensionAttribute) attribute).Filename;
    }

    <span style="color: green">// The SOAP extension was configured to run using a configuration file
    // instead of an attribute applied to a specific XML Web service
    // method.
    </span><span style="color: blue">public override object </span>GetInitializer(Type WebServiceType)
    {
      <span style="color: green">// Return a file name to log the trace information to, based on the
      // type.
      </span><span style="color: blue">return </span><span style="color: #a31515">&quot;C:\\&quot; </span>+ WebServiceType.FullName + <span style="color: #a31515">&quot;.log&quot;</span>;
    }

    <span style="color: green">// Receive the file name stored by GetInitializer and store it in a
    // member variable for this specific instance.
    </span><span style="color: blue">public override void </span>Initialize(<span style="color: blue">object </span>initializer)
    {
        filename = (<span style="color: blue">string</span>) initializer;
    }

    <span style="color: green">//  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.
    </span><span style="color: blue">public override void </span>ProcessMessage(SoapMessage message)
    {
        <span style="color: blue">switch </span>(message.Stage) {
        <span style="color: blue">case </span>SoapMessageStage.BeforeSerialize:
            <span style="color: blue">break</span>;
        <span style="color: blue">case </span>SoapMessageStage.AfterSerialize:
            WriteOutput(message);
            <span style="color: blue">break</span>;
        <span style="color: blue">case </span>SoapMessageStage.BeforeDeserialize:
            WriteInput(message);
            <span style="color: blue">break</span>;
        <span style="color: blue">case </span>SoapMessageStage.AfterDeserialize:
            <span style="color: blue">break</span>;
        <span style="color: blue">default</span>:
             <span style="color: blue">throw new </span>Exception(<span style="color: #a31515">&quot;invalid stage&quot;</span>);
        }
    }

    <span style="color: blue">public void </span>WriteOutput(SoapMessage message){
        newStream.Position = 0;
        FileStream fs = <span style="color: blue">new </span>FileStream(filename, FileMode.Append,
                                       FileAccess.Write);
        StreamWriter w = <span style="color: blue">new </span>StreamWriter(fs);

        <span style="color: blue">string </span>soapString =
          (message <span style="color: blue">is </span>SoapServerMessage) ? <span style="color: #a31515">&quot;SoapResponse&quot; </span>: <span style="color: #a31515">&quot;SoapRequest&quot;</span>;
        w.WriteLine(<span style="color: #a31515">&quot;-----&quot; </span>+ soapString + <span style="color: #a31515">&quot; at &quot; </span>+ DateTime.Now);
        w.Flush();
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
        Copy(newStream, oldStream);
    }

    <span style="color: blue">public void </span>WriteInput(SoapMessage message){
        Copy(oldStream, newStream);
        FileStream fs = <span style="color: blue">new </span>FileStream(filename, FileMode.Append,
                                       FileAccess.Write);
        StreamWriter w = <span style="color: blue">new </span>StreamWriter(fs);

        <span style="color: blue">string </span>soapString = (message <span style="color: blue">is </span>SoapServerMessage) ?
                            <span style="color: #a31515">&quot;SoapRequest&quot; </span>: <span style="color: #a31515">&quot;SoapResponse&quot;</span>;
        w.WriteLine(<span style="color: #a31515">&quot;-----&quot; </span>+ soapString +
                    <span style="color: #a31515">&quot; at &quot; </span>+ DateTime.Now);
        w.Flush();
        newStream.Position = 0;
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
    }

    <span style="color: blue">void </span>Copy(Stream from, Stream to)
    {
        TextReader reader = <span style="color: blue">new </span>StreamReader(from);
        TextWriter writer = <span style="color: blue">new </span>StreamWriter(to);
        writer.WriteLine(reader.ReadToEnd());
        writer.Flush();
    }
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>&#160;</p>
<p>Para poder insertar la SoapExtension en la entrada y salida de un WebMethod hay que crear una clase que herede de SoapExtensionAttribute cuya propiedad ExtensionType le dice al framework que clase SoapExtension utilizar. También tiene una propiedad Priority para que en caso de que haya más de un SoapExtension el sistema sepa en que orden ejecutarlas:</p>
<pre class="code"><span style="color: green">  // Create a SoapExtensionAttribute for the SOAP Extension that can be
  // applied to an XML Web service method.
 </span>[AttributeUsage(AttributeTargets.Method)]
 <span style="color: blue">public class </span>TraceExtensionAttribute : SoapExtensionAttribute {

   <span style="color: blue">private string </span>filename = <span style="color: #a31515">&quot;c:\\log.txt&quot;</span>;
   <span style="color: blue">private int </span>priority;

   <span style="color: blue">public override </span>Type ExtensionType {
       <span style="color: blue">get </span>{ <span style="color: blue">return typeof</span>(TraceExtension); }
   }

   <span style="color: blue">public override int </span>Priority {
       <span style="color: blue">get </span>{ <span style="color: blue">return </span>priority; }
       <span style="color: blue">set </span>{ priority = value; }
   }

   <span style="color: blue">public string </span>Filename {
       <span style="color: blue">get </span>{
           <span style="color: blue">return </span>filename;
       }
       <span style="color: blue">set </span>{
           filename = value;
       }
   }</pre>
<p>Para que un WebMethod utilice la SoapExtension solo queda aplicar el SoapExtensionAttribute al método:</p>
<p>&#160;</p>
<pre class="code">[WebMethod]
[TraceExtension()]
<span style="color: blue">public string </span>MetodoWeb(<span style="color: blue">string </span>str)
{
    <span style="color: blue">return </span><span style="color: #a31515">&quot;Hola&quot;</span>;
}</pre>
<p>&#160;</p>
<p><a href="http://11011.net/software/vspaste">&#160;</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thedotnetway.net/2009/10/07/soap-extension/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
