<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>josemiguel.torres</title>
	
	<link>http://josemigueltorres.net/boresight</link>
	<description>Off-Boresight .NET Technologies</description>
	<lastBuildDate>Mon, 14 May 2012 21:07:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/josemigueltorres/rXsu" /><feedburner:info uri="josemigueltorres/rxsu" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Diez + dos librerias Open Source recomendables para .NET</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/PkUVC2eicUI/</link>
		<comments>http://josemigueltorres.net/boresight/?p=493#comments</comments>
		<pubDate>Mon, 14 May 2012 21:07:00 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Collections]]></category>
		<category><![CDATA[DbC]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[librerias]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=493</guid>
		<description><![CDATA[Hace poco me topé con un post en el que enumeraba las librerias y herramientas más interesantes para desarrollo con .NET y tenia ya ganas de crear mi propia lista de librerias recomendables para .NET. Esta lista de librerías son sólo un conjunto de las que, o bien más utilizo o he utilizado y las [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img alt="libreria " src="http://img.genbetadev.com/2011/04/libreria.jpg" /></p>
<p>Hace poco me topé con un post en el que enumeraba las <strong>librerias y herramientas más interesantes para desarrollo con .NET</strong> y tenia ya ganas de crear mi propia lista de librerias recomendables para .NET. Esta lista de librerías son sólo un conjunto de las que, o bien más utilizo o he utilizado y las que <strong>creo</strong>, bajo mi punto de vista, que todo desarrollador debería, como mínimo conocer.</p>
<p>Dicho esto, a continuación detallo estas diez + dos librerías esperando vuestra opinión y feedback tanto para las que expongo como para las tantas otras que me he dejado en el tintero (la lista, afortunadamente, es cada vez más grande). Espero que os resulte útil:</p>
<h4>Collections/Generics</h4>
<p><a href="http://powercollections.codeplex.com/">PowerCollections</a> – Es una libreria de colecciones genéricas complementarias a la que proporciona el CLR de .NET Framework desarrollada por Intellect las cuales conocí en el libro “CLR via C# 4.0” de <strong>Jeffrey Richter</strong>. Algunas de las clases que proporciona son <em>Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary, Set, OrderedSet u OrderedMultiDictionary</em>, además de las que extienden las que el propio CLR proporciona. </p>
<h4>Dependency Injection/Inversion of Control</h4>
<p><a href="http://structuremap.net/structuremap/">StructureMap </a>- Además de StructureMap, <strong>Castle Windsor </strong>o <strong>Unity </strong>son otras de las librerias IoC que he utilizado. El motivo del uso de StructureMap fue quizás la mayor facilidad de uso [Opinión Personal] respecto a otras. De cualquier forma, en este punto es más importante el beneficio de la Inyección de Dependencias que el propio framework. <strong>StructureMap </strong>fue inicialmente desarrollada y mantenida por by Jeremy D. Miller, The Shade Tree Developer y Joshua Flanagan.</p>
<h4>Design by Contract</h4>
<p><a href="http://research.microsoft.com/en-us/projects/contracts/">Microsoft Code Contracts</a>: Code Contracts facilita la adopción de la programación por contratos de forma agnostica al lenguaje mediante precondiciones, poscondiciones e invariantes. Esta bajo licencia Microsoft Research License Agreement.</p>
<h4>Logging</h4>
<p><a href="http://logging.apache.org/log4net/">Log4Net</a> – Desde que conocí Log4net, despues de una <del>muy mala, malísima vamos</del> experiencia con otro tipo de librerias, tambien Open Source, me parece la apuesta más facil y eficaz para el logging de aplicaciones. Log4net forma parte del proyecto Apache Logging Services.</p>
<h4>ORM</h4>
<p><a href="http://www.nhforge.org/">NHibernate</a>/<a href="http://fluentnhibernate.org/">FluentNHibernate</a>: No tengo mucha experiencia en este campo pero por lo poco que he tocado y por la experiencia, todas las librerias que surgen de la comunidad como necesidad acaban convirtiendose en un must-have, o must-use en este caso. Cabe decir que tampoco he mirado alternativas. NHibernate no es mas que la adaptación a .NET de la famosa libreria ORM para Java. FluentNHiberante facilita el, a veces, tedioso mapeo de entidades y objetos a través de los archivos hbm.xml. FluentNHibernate se define como una libreria XML-less ya que permite todo este mapeo a través de código. </p>
<h4>No-SQL Database</h4>
<p><a href="http://www.mongodb.org/display/DOCS/Home">MongoDB</a>: Se trata de una de las bases de datos No-SQL más extendidas y pese a que no es una librería en sí, el conocimiento de sus posibilidades, sus pros y sus contras es obligatorio. Su modelo de datos por documentos está basado en <strong>JSON </strong>y <strong>BSON</strong> y por tanto es <em>schema-less</em>. Es una alternativa a las bases de datos relacionales gracias a la escalabilidad horizontal que proporcionan este tipo de herramientas. Está bajo Free Software Foundation’s GNU AGPL v3.0.</p>
<h4>Unit Testing/Mocking/BDD</h4>
<p><a href="http://www.nunit.org/">NUnit</a>: Inicialmente basada en la libreria JUnit de Java, NUnit 2.5 es la sexta versión basda en xUnit. Está escrita en C# y fue totalmente rediseñada para sacar el máximo provecho a la plataforma .NET. Se integra estupendamente tanto con las <strong>MS Test Tools </strong>como con <strong>Resharper 5.x</strong>.</p>
<p><a href="http://code.google.com/p/moq/">Moq</a>: Muy útil especialmente para desarrolladores sin un gran bagaje en Mocking. Ofrece soporte a muchas de las características de .NET como LINQ Trees Expressions o expresiones lambda y se caracteriza por su facilidad de uso y su forma natural de escrbir stubs y mocks.</p>
<p><a href="http://www.specflow.org/">BDD specflow</a>: Distribuida bajo licencia BSD e inspirada en <strong>Cucumber </strong>y su comunidad, esta libreria abarca las diferentes posibilidades del desarrollo orientado a comportamiento o BDD y resalta, entre otros, su uso con aplicaciones ASP.NET MVC. </p>
<h4>Framework </h4>
<p><a href="http://www.nservicebus.com/">nServiceBus</a>: Framework de comunicaciones para arquitecturas SOA distribuidas, nServiceBus es un proyecto que surge de la necesidad en base a la experiencia personal de <strong>Udi Dahan</strong>, precursor y principal coordinador del proyecto. Recientemente ha incorporado nueva política de licencias y se anunció, y así hicimos en Genbeta dev, las novedades que traerá incorporada en la proxima versión 3.0.<br />
<h4>Otras</h4>
<p>Añado estas dos librerias por recomendación de un buen amigo y con las que todavia no he tenido la oportunidad de trabajar pero que estan haciéndose un hueco importante entre la comunidad de desarrolladores. Se trata de:
<p><a href="http://code.google.com/p/elmah/">Elmah</a>: ELMAH (Error Logging Modules and Handlers), es una libreria de logging específicamente desarrolada para aplicaciones ASP.NET y es especialmente útil para el registro de errores en Modulos y Manejadores de ASP.NET MVC.</p>
<p><a href="http://nuget.codeplex.com/">NuGet</a>: Otra de las librerias Open Source hospedada en Codeplex y miembro de la ASP.NET Gallery. Su intención es la de facilitar la integración y despliegue de librerias de terceros a los desarrollos .NET, evitando el tedioso proceso de referenciación y modificación de referencias en el app.config. </p>
<p>Foto | Tomada por <a href="http://www.flickr.com/photos/lenore-m/">L.Marie</a> y hospedada en <a href="http://www.flickr.com/photos/lenore-m/2515800654/in/photostream/">flickr</a>.</p>
<div class="shr-publisher-493"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=493</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=493</feedburner:origLink></item>
		<item>
		<title>Videos, recursos y laboratorios para empezar a desarrollar en Office 365</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/i7V_bqPcFdc/</link>
		<comments>http://josemigueltorres.net/boresight/?p=490#comments</comments>
		<pubDate>Mon, 07 May 2012 21:04:00 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Office]]></category>
		<category><![CDATA[Office 365]]></category>
		<category><![CDATA[Recursos]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=490</guid>
		<description><![CDATA[En el Professional Developer Conference que se celebró el año pasado en Redmond se anunció Office 365, como apuesta por parte de Microsoft de aplicaciones de productividad en la nube. Pues bien, ya ha aparecido el Developer Training Course oficial del MSDN para el desarrollo de aplicaciones Office 365, tras la publicación de la primera [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img src="http://img.genbetadev.com/2011/04/microsoft-office-365.jpg" alt="ms office 365" /></p>
<p>En el <strong>Professional Developer Conference </strong>que se celebró el año pasado en Redmond se anunció Office 365, como apuesta por parte de Microsoft de aplicaciones de productividad en la nube. Pues bien, ya ha aparecido el Developer Training Course oficial del MSDN para el desarrollo de aplicaciones Office 365, tras la publicación de la primera Beta y la petición de muchos desarrolladores de un espacio de recursos e información.</p>
<p>El curso consta de <strong>7 módulos, 10 horas de video y 17 hands-on-labs </strong>que cubren casi la totalidad de productos en términos de integración, desarrollo y despliegue. El índice completo y contenido del curso es:</p>
<p><a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-1_unit">Developing in the Cloud with Office 365</a></p>
<ul>
<li>Video: Developing in the Cloud with Office 365</li>
<li>Video: SharePoint Online Overview</li>
<li>Video: Exchange Online Overview</li>
<li>Video: Lync Online Overview <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-2_unit">Developing for SharePoint Online with Sandbox Solutions</a></li>
<li>Hands-On-Labs: Creating a Visual Web Part Sandboxed Solution for SharePoint Online</li>
<li>Hands-On-Labs: Creating Custom Lists</li>
<li>Hands-On-Labs: Custom Actions and Event Receivers</li>
<li>Hands-On-Labs: Resource Points</li>
<li>Video: Developing for SharePoint Online with Sandbox Solutions</li>
<li>Video: Sandboxed Solutions – Deploying a List</li>
<li>Video: Sandboxed Solutions – Event Receivers</li>
<li>Video: Sandboxed Solutions – Resource Monitoring <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-3_unit">Building Workflow Solutions for SharePoint Online </a></li>
<li>Hands-On-Labs: Building Workflow Solutions</li>
<li>Hands-On-Labs: Implementing a Custom Workflow Action in Visual Studio</li>
<li>Video: Building Workflow Solutions for SharePoint Online</li>
<li>Video: Implementing Workflows in SharePoint Designer 2010</li>
<li>Video: Developing Custom Workflow Actions with Visual Studio 2010 <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-4_unit">Developing SharePoint Online Solutions with the Client Object Model </a></li>
<li>Hands-On-Labs: Using the Client Object Model in Silverlight</li>
<li>Hands-On-Labs: Using the Client Object Model in JavaScript</li>
<li>Hands-On-Labs: Accessing SharePoint Online List Data using SharePoint Web Services</li>
<li>Video: Developing SharePoint Online Solutions with the Client Object Model</li>
<li>Video: Using the Client Object Model with JavaScript <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-5_unit">Leveraging Excel and Access Services in SharePoint Online </a></li>
<li>Hands-On-Labs: Excel Services</li>
<li>Hands-On-Labs: Access Services</li>
<li>Video: Leveraging Excel and Access Services in SharePoint Online</li>
<li>Video: Leveraging Access Services in SharePoint Online</li>
<li>Video: Leveraging the Excel REST API</li>
<li>Presentacion: Leveraging Excel and Access Services in SharePoint Online <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-9_unit">Developing Communication Solutions for Lync Online </a></li>
<li>Hands-On-Labs: Integrating Microsoft Lync 2010 Functionality into your Applications</li>
<li>Hands-On-Labs: Launching Contextual Conversations from the Microsoft Lync Controls</li>
<li>Hands-On-Labs: Introduction to the Microsoft Lync 2010 Managed API – Working with Automation</li>
<li>Hands-On-Labs: Introduction to the Microsoft Lync 2010 Managed API – Exploring the Lync API Object Model</li>
<li>Video: Developing Communication Solutions for Lync Online</li>
<li>Video: Developing Contextual Conversation Solutions for Lync Online</li>
<li>Video: Lync API Automation with Lync Online</li>
<li>Video: Building Custom Communication Clients for Lync Online via the Lync API <a href="http://msdn.microsoft.com/en-us/office365trainingcourse_session-10_unit">Developing Messaging Solutions for Exchange Online </a></li>
<li>Hands-On-Labs: Getting Started with Exchange Web Services Managed API 1.1 – Working with Mailbox Items</li>
<li>Hands-On-Labs: Getting Started with Exchange Web Services Managed API 1.1 – Working with Extended Properties</li>
<li>Hands-On-Labs: Working with the Exchange Services – Free-Busy Service</li>
<li>Video: Developing Messaging Solutions for Exchange Online</li>
<li>Video: Development with Extended Properties with Exchange Online</li>
<li>Video: Developing for Exchange Online Using the Free/Busy Service</li>
</ul>
<p>Como soporte además se puede hacer uso de una <a href="http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&amp;FamilyID=751fa0d1-356c-4002-9c60-d539896c66ce">maquina virtual de evaluación con Microsoft Sharepoint 2010 instalado </a>para lo que no tienen un entorno de test. Por último necesitamos acceder a la Beta de Office 365 inscribiéndonos desde <a href="http://www.microsoft.com/en-us/office365/small-business/beta.aspx">aqui</a>.</p>
<p>Sitio oficial | <a href="http://blogs.msdn.com/b/cmayo/archive/2011/04/18/new-office-365-developer-training-course-on-msdn.aspx">Blog de Chris Mayo</a></p>
<div class="shr-publisher-490"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=490</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=490</feedburner:origLink></item>
		<item>
		<title>Open Data Protocol: una alternativa a la exposición de datos entre plataformas</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/FKF51FZpi1Q/</link>
		<comments>http://josemigueltorres.net/boresight/?p=487#comments</comments>
		<pubDate>Mon, 30 Apr 2012 21:02:00 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Data Access]]></category>
		<category><![CDATA[OData]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF Data Services]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=487</guid>
		<description><![CDATA[Open Data Protocol, (aka OData), es una iniciativa impulsada por Microsoft para la exposición de datos como Servicio basándose en estándares de Internet y es la evolución de lo que era anteriormente conocido como ADO.NET Data Services (proyecto Astoria). Desde su aparición a principios del año pasado son ya muchos los productos, Web Sites y [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img alt="OData logo" src="http://img.genbetadev.com/2011/04/odata_logo_ms_650.png" /></p>
<p>Open Data Protocol, (aka <strong>OData</strong>), es una iniciativa impulsada por Microsoft para la exposición de datos como Servicio basándose en estándares de Internet y es la evolución de lo que era anteriormente conocido como ADO.NET Data Services (proyecto Astoria). Desde su aparición a principios del año pasado son ya muchos los productos, Web Sites y tecnologias que exponen sus datos utilizando este protocolo. En el caso de Microsoft lo podemos enconatrar ya en <strong>Sharepoint 2010</strong>, <strong>SQL Azure</strong>, <strong>Azure Storage</strong>, hasta ahora recientemente en <strong>Team Foundation Server </strong>(del que hablaremos en el proximo post). </p>
<p>Sobre la estandarización, OData está construido sobre <strong><a href="http://en.wikipedia.org/wiki/Atom_(standard)">Atom Publishing Protocol</a> </strong>o AtomPub especificado en RFD 5023 quien a su vez está sontruido sobre <strong>Atom Syndication Format </strong>o Atom especificado en RFC4287.</p>
<p>OData tratar de dar solución a la exposición de orígenes de datos, relacionales o no, a través de un Servicio Web ejecutando operaciones con un lenguaje “estándar” basandose en:</p>
<ul>
<li>La creación de una forma uniforme de representación de datos estructurados a través de Atom o JSON (JavaScript Object Notation) </li>
<li>La utilización de convenciones URL uniformes tanto para la navegación, filtrado, orden y paginación de datos (entre otros) </li>
<li>La creación de operaciones uniformes dirigidas por dirección mediante las acciones GET, POST, PUT y DELETE.</li>
</ul>
<p>Desde <a href="http://odata.org">http://odata.org</a> podemos encontrar API’s de creación y consumo de Servicios OData. Entre el abanico de librerías cliente podemos encontrar:
<ul>
<li>OData Javascript Library </li>
<li>OData SDK for PHP </li>
<li>Restlet extension for OData (Java) </li>
<li>ruby_odata: OData client library for ruby </li>
<li>OData Client Library for Windows Phone 7 series </li>
<li>OData client for Objective-C </li>
<li>Silverlight 4 </li>
<li>OData Extension for Joomla </li>
<li>OData Drupal</li>
</ul>
<p>En cuanto a librerias de servidor, es decir API’s para la generación de datos, se encuentran:
<ul>
<li>odata4j (Java) </li>
<li>OData on Rails (prerelease for ruby) </li>
<li>MySQL OData </li>
<li>.NET Framework</li>
</ul>
<p>Productos como Excel 2010, a través de <strong>PowerPivot</strong>, <strong>LINQPad</strong>, la mayoria de exploradores Web así como controles <strong>Telerik</strong> o <a href="http://www.tableausoftware.com/"><strong>Tableau</strong></a> ya dan soporte como consumidores compatibles con OData.
<p>Por otro lado, entre las empresas que empiezan a exponer sus propios datos por OData se encuentran destacadas a <strong>eBay, Facebook Insight, IBM WebSpehere, Netflix, twitpic, GeoREST, Nuget, Windows Live o Dbpedia </strong>entre otras en el sector privado y <strong>Open Government Data Initiative</strong> (OGDI), <strong>The City of Edmonton Open Data Catalogue</strong> o <strong>Public Transit Data Community</strong>, por destacar algunas.</p>
<p><img alt="eBay OData" src="http://img.genbetadev.com/2011/04/ebay-odata_650.png" /></p>
<p>Más información | <a href="http://odata.org">OData.org</a></p>
<div class="shr-publisher-487"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=487</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=487</feedburner:origLink></item>
		<item>
		<title>How to Convert byte array to BitmapImage</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/sMcufpSd53M/</link>
		<comments>http://josemigueltorres.net/boresight/?p=512#comments</comments>
		<pubDate>Wed, 25 Apr 2012 21:38:00 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Visual C#]]></category>
		<category><![CDATA[BitmapImage]]></category>
		<category><![CDATA[Byte[]]]></category>
		<category><![CDATA[Converter]]></category>
		<category><![CDATA[Image]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=512</guid>
		<description><![CDATA[Recently, I came across a interesting question on how to convert from a byte array to BitmapImage. The typicall scenario is when given an image represented by BitmapImage object it should be stored in a database as byte[]. The code I&#8217;m going to show below has been extracted from Stackoverflow.com but I found it in [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Recently, I came across a interesting question on how to convert from a byte array to BitmapImage. The typicall scenario is when given an image represented by BitmapImage object it should be stored in a database as byte[].</p>
<p>The code I&#8217;m going to show below has been extracted from <strong>Stackoverflow.com</strong> but I found it in several sites after googling, therefore I can&#8217;t point out the author. </p>
<p>The code is quite simple just use:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">byte</span>[] GetBytes(BitmapImage bi) </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span> { </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>     WriteableBitmap wbm = <span style="color: #0000ff">new</span> WriteableBitmap(bi); </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>     <span style="color: #0000ff">return</span> wbm.ToByteArray(); </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span> } </pre>
</p></div>
</div>
<p>&#160;</p>
<p>Where ToByteArray method is:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">byte</span>[] ToByteArray(<span style="color: #0000ff">this</span> WriteableBitmap bmp) </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span> { </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>     <span style="color: #008000">// Init buffer </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>     <span style="color: #0000ff">int</span> w = bmp.PixelWidth; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>     <span style="color: #0000ff">int</span> h = bmp.PixelHeight; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>     <span style="color: #0000ff">int</span>[] p = bmp.Pixels; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>     <span style="color: #0000ff">int</span> len = p.Length; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>     <span style="color: #0000ff">byte</span>[] result = <span style="color: #0000ff">new</span> <span style="color: #0000ff">byte</span>[4 * w * h]; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>  </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span>     <span style="color: #008000">// Copy pixels to buffer </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  11:</span>     <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0, j = 0; i &lt; len; i++, j += 4) </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  12:</span>     { </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  13:</span>         <span style="color: #0000ff">int</span> color = p[i]; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  14:</span>         result[j + 0] = (<span style="color: #0000ff">byte</span>)(color &gt;&gt; 24); <span style="color: #008000">// A </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  15:</span>         result[j + 1] = (<span style="color: #0000ff">byte</span>)(color &gt;&gt; 16); <span style="color: #008000">// R </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  16:</span>         result[j + 2] = (<span style="color: #0000ff">byte</span>)(color &gt;&gt; 8);  <span style="color: #008000">// G </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  17:</span>         result[j + 3] = (<span style="color: #0000ff">byte</span>)(color);       <span style="color: #008000">// B </span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  18:</span>     } </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  19:</span>  </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  20:</span>     <span style="color: #0000ff">return</span> result; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  21:</span> } </pre>
</p></div>
</div>
<p>Another way to achieve it is using <a href="http://imagetools.codeplex.com/" target="_blank">ImageTools for Silverlight</a>. I have used it in several <strong>Windows Phone</strong> projects, specially animating gif images, and it contains a method that could be used in order to convert BitmapImage from and to byte[] by just using a few lines of code:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">using</span> (var writingStream = <span style="color: #0000ff">new</span> MemoryStream()) </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span>                         { </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>                             var encoder = <span style="color: #0000ff">new</span> PngEncoder </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>                             { </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>                                 IsWritingUncompressed = <span style="color: #0000ff">false</span> </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>                             }; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>                             encoder.Encode(bitmapImageInstance, writingStream); </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>                             <span style="color: #008000">// ...</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>                         } </pre>
</p></div>
</div>
<p>Both solutions works fine. The first one does not need any kind of library reference meanwhile the second one needs ImageTools library (that could be reached in Nuget). </p>
<div class="shr-publisher-512"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=512</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=512</feedburner:origLink></item>
		<item>
		<title>[RestSharp] and RestClient’s ContentTypes</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/cpkK49kdJAM/</link>
		<comments>http://josemigueltorres.net/boresight/?p=517#comments</comments>
		<pubDate>Tue, 24 Apr 2012 14:50:44 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Visual C#]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[RestSharp]]></category>
		<category><![CDATA[Windows Phone 7]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=517</guid>
		<description><![CDATA[My life is easier since I met RestSharp library. Since then, all my Windows Phone app use such library, and excluding some issues on behalf of Newtonsoft.Json version, the truth is that RestSharp is quite helpful. Well, one of the issues I would like to talk about is concerning to the Content Types that RestSharp [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>My life is easier since I met RestSharp library. Since then, all my Windows Phone app use such library, and excluding some issues on behalf of Newtonsoft.Json version, the truth is that RestSharp is quite helpful. Well, one of the issues I would like to talk about is concerning to the Content Types that RestSharp supports. There are <strong>6 types of content</strong> and we may find them in <strong>AcceptTypes</strong> property of the RestClient object.</p>
<p>In the following example, we aim to achieve some kind of xml based data and perform some actions like xml deserialization.</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #008000">//endpoint: http://www.someurl.com/someResource/orWhatever</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span> <span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> RestSample() </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span> {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>     var client = <span style="color: #0000ff">new</span> RestClient</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>     {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>         BaseUrl = <span style="color: #006080">&quot;http://www.someurl.com/&quot;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>     };</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>&#160; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>     var request = <span style="color: #0000ff">new</span> RestRequest</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span>     {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  11:</span>         Resource = <span style="color: #0000ff">string</span>.Format(<span style="color: #006080">&quot;someResource/orWhatever&quot;</span>)</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  12:</span>     };</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  13:</span>&#160; </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  14:</span>     client.ExecuteAsync(request, (a) =&gt;</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  15:</span>     {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  16:</span>         var serializer = <span style="color: #0000ff">new</span> XmlSerializer(<span style="color: #0000ff">typeof</span>(MyFeedType));</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  17:</span>         <span style="color: #0000ff">if</span> (a.StatusCode == HttpStatusCode.OK)</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  18:</span>         {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  19:</span>             var document = XDocument.Parse(a.Content); <span style="color: #008000">//let's play</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  20:</span>         }</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  21:</span>         <span style="color: #0000ff">else</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  22:</span>         {</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  23:</span>             <span style="color: #008000">//something was wrong</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  24:</span>         }</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  25:</span>     });</pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  26:</span> }</pre>
</p></div>
</div>
<p>We assume that this endpoint provides xml content and therefore this snippet code will work correctly. The issue here is when that endpoint does not explicity address to a given content type and supports more than one content type. Let’s say this endpoint provides both “application/xml” and “application/json”. Then the code above will not work since the <strong>a.Content</strong> given from the request will contain json based content. Well, we may use <strong>JsonDeserializer</strong> class in order to turn this json string into a C# objects, however I would like to share with you the reason because it happens.</p>
<p>The reason comes from the RestClient’s <strong>AcceptTypes</strong> property I pointed out above. If we breakpoint <strong>client</strong> object before the call we can see the 6 content types that RestSharp providers per default.</p>
<p><a href="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2012/04/image.png"><img style="background-image: none; border-right-width: 0px; margin: 5px 5px 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2012/04/image_thumb.png" width="604" height="304" /></a></p>
<p>RestClient will try the first one which is “application/json” and as the endpoint provides json then the RestClient object call&#160; named client will retrieve json content in the RestRequest callback. </p>
<p>The only way I figured out in order to force explicity xml call is by removing the “application/json” content as follows:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> client.RemoveHandler(<span style="color: #006080">&quot;application/json&quot;</span>); </pre>
</p></div>
</div>
<p>Maybe there would be another way to achieve it, if so and you know it, drop me a comment.</p>
<div class="shr-publisher-517"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=517</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=517</feedburner:origLink></item>
		<item>
		<title>El Principio de Sustitución de Liskov y su relación con la Programación por Contratos</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/3UtGMaDR0PM/</link>
		<comments>http://josemigueltorres.net/boresight/?p=485#comments</comments>
		<pubDate>Mon, 23 Apr 2012 21:00:07 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Visual C#]]></category>
		<category><![CDATA[Liskov]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=485</guid>
		<description><![CDATA[El Principio de Sustitución de Likov fue acuñado por Barbara Liskov en el año 1987 durante una conferencia sobre Jerarquía y Abstraccióbn de datos. Su principal cometido es la de asegurar en la herencia entre clases de la Programación Orientada a Objetos que una clase derivada no únicamente es sino que debe comportarse como la [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img alt="LSP" src="http://img.genbetadev.com/2011/04/liskov_substitution_principle.jpg" /></p>
<p>El <strong>Principio de Sustitución de Likov </strong>fue acuñado por <strong>Barbara Liskov </strong>en el año 1987 durante una conferencia sobre <strong>Jerarquía y Abstraccióbn de datos</strong>. Su principal cometido es la de asegurar en la herencia entre clases de la Programación Orientada a Objetos que una clase derivada no únicamente <strong>es </strong>sino que debe <strong>comportarse como </strong>la clase base. Su definición es:</p>
<blockquote><p>Si por cada objeto o1 del tipo S existe un objeto o2 del tipo T tal que para todos los programas P definidos en términos de T y el comportamiento de P permanece invariable cuando o1 es sustituido por o2, entonces S es un subtipo de T.</p></blockquote>
<p>Pese a lo complejo que pueda llegar a parecer la definición en la practica lo podemos ver con algo más de claridad con el típico ejemplo del cuadrado y el rectángulo. En el siguiente snippet de código en C# se muestran las clases.</p>
<pre><code>public abstract class Rectangulo
{
   public virtual int Ancho { get; set; }
   public virtual int Alto { get; set; }
   public abstract float Area();
}
</code></pre>
<pre><code>public class Cuadrado : Rectangulo
{
    public override int Ancho  {
        get {
            return base.Ancho;
        }
        set {
            base.Ancho = value;
            base.Alto = value;
        }
    }
    public override int Alto  {
        get {
            return base.Alto;
        }
        set {
            base.Ancho = value;
            base.Alto = value;
        }
    }
    public override float Area()
    {
        return Ancho*Alto;
    }
}</code></pre>
<p>Aparentemente a simple vista puede parecernos que la herencia es correcta, al menos desde el punto de vista técnico su implementación lo es, sin embargo el comportamiento es bien distinto. Mientras que en un Rectangulo el Ancho y el Alto pueden contener cualquier valor, un Cuadrado, por definición, el Ancho y el Alto debe ser del mismo valor, de otra forma seria no seria un cuadrado. Fijémonos en el setter de las propiedades Ancho y Alto de la clase Cuadrado; ambas se anulan entre sí. Podemos verlo más claro con un Test Unitario.</p>
<pre><code>
[TestFixture]
public class Test
{
    [Test]
    public void AreaRectangulo()
    {
        Rectangulo r = new Cuadrado
                            {
                                Ancho = 5,
                                Alto = 2
                            };
        Assert.AreEqual(10.0f, r.Area());
    }
}
</code></pre>
<p>Basicamente comprobamos que, si un objecto Cuadrado con Ancho = 5 y Alto = 2, su Area, ya que asumimos que es un Rectangulo, es Ancho * Alto, es decir igual 10. El Test falla pues el setter de Alto impone además de éste el Ancho a 2, con lo cual el Area es 4.</p>
<p><img alt="Unitest_LSP" src="http://img.genbetadev.com/2011/04/unitest_lsp_650.png" /></p>
<h4>Diseño por Contratos</h4>
<p>Por otro lado, Bertrand Meyer acuñó el <strong>Diseño por Contratos </strong>(DbC) en el que se especifica un contrato a nivel de método para establecer los valores/tipos aceptables de entrada y de retorno, las condiciones de valor o de tipo para los errores y excepciones que puedan ocurrir, la precondición y postcondición y la invariantes.</p>
<p>Para cumplir con el Principio de Substitución de Liskov, la implementación de la clase derivada <strong>debe</strong>:</p>
<ul>
<li><strong>Ser menos restrictivas en la precondición</strong>. </li>
<li><strong>Ser más restrictivas en la postcondición.</strong></li>
<li><strong>Preservar la invariancia.</strong></li>
</ul>
<p>En nuestro ejemplo podriamos decir que el contrato de las propiedad <strong>Ancho </strong>de <strong>Rectangulo </strong>seria:</p>
<pre>[Precondicion(Ancho &amp;#62; 0)]
[Poscondicion(&amp;#34;$after(Ancho)&amp;#62;0&amp;#34;)]
[Poscondicion(&amp;#34;$after(Alto)=$before(Alto)&amp;#34;)]</pre>
<p>Y el de Cuadrado:</p>
<pre>[Precondicion(Ancho &amp;#62; 0)]
[Poscondicion(&amp;#34;$after(Ancho)&amp;#62;0&amp;#34;)]</pre>
<p>En primer lugar, la propia naturaleza de la clase Cuadrado implica, precisamente para preservar la Invariancia, que la propiedad Ancho modifique, además, la propiedad Alto y esto deriva en que la postcondición de Cuadrado para el setter sea menos restrictiva que en Rectangulo y por tanto no cumpla con El Principio de Substitución de Liskov.</p>
<h4>Conclusión</h4>
<p>El Principio de Substitución de Liskov no dicta tanto el qué sino el cómo debe heredarse tipos. El uso de DbC está estrechamente ligado y puede ser de utilidad en herencias de tipos más complejos para preservar el comportamiento en la tipo derivado. El impacto de este principio en los nuevos lenguajes de desarrollo los podemos ver por ejemplo en el contravariancia de los argumentos de métodos para los subtipos o la covariancia para el retorno, tanto en delegados como en interfaces como es el caso de C#.</p>
<div class="shr-publisher-485"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=485</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=485</feedburner:origLink></item>
		<item>
		<title>Lambda Expression and Single Responsability Principle</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/Kl4-lLYgs54/</link>
		<comments>http://josemigueltorres.net/boresight/?p=479#comments</comments>
		<pubDate>Thu, 02 Feb 2012 14:52:03 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Visual C#]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=479</guid>
		<description><![CDATA[I have to recognize that I really like Lambda Expression (LE) since this feature appeared with .NET Framework 3.5 release. I actually use to apply it in a wide variety of aspects into my developments. I think that it becomes clearly useful when I have to hand some event or async call that involves just one [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>I have to recognize that I really like <strong>Lambda Expression</strong> (LE) since this feature appeared with .NET Framework 3.5 release. I actually use to apply it in a wide variety of aspects into my developments. I think that it becomes <strong>clearly useful</strong> when I have to hand some <strong>event or async</strong> call that involves just one or two statements.</p>
<p>However, and as often happens in these scenarios, what begins being just a single statement <strong>becomes a entire method</strong> with a bunch of statements. It arises then in something ugly, such code becomes <strong>hard to maintain</strong>. The code in question could be like this:</p>
<div>
<div style="line-height: 12pt; background-color: #f4f4f4; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;">
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 1:</span> var _watcher = <span style="color: #0000ff;">new</span> GeoCoordinateWatcher(GeoPositionAccuracy.Default)</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 2:</span> {</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 3:</span>     MovementThreshold = 20</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 4:</span> };</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 5:</span></pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 6:</span> _watcher.PositionChanged += (((s, p) =&gt;</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 7:</span>                                     {</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 8:</span>                                         <span style="color: #0000ff;">if</span> (!p.Position.Location.IsUnknown)</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 9:</span>                                             App.ViewModel.Pushpins[0].Location =</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 10:</span>                                             p.Position.Location;</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 11:</span>                                         <span style="color: #0000ff;">else</span></pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 12:</span>                                             PerformeSomeAction();</pre>
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 13:</span>                                     }</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 14:</span>                                 ));</pre>
</div>
</div>
<p>Which <em>PositionChanged</em> event initial implementation was:</p>
<div>
<div style="line-height: 12pt; background-color: #f4f4f4; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;">
<pre style="line-height: 12pt; background-color: white; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 1:</span> _watcher.PositionChanged += ((s, p) =&gt; App.ViewModel.Pushpins[0].Location =</pre>
<pre style="line-height: 12pt; background-color: #f4f4f4; margin: 0em; width: 100%; font-family: consolas, 'Courier New', courier, monospace; color: black; font-size: 8pt; overflow: visible; border-style: none; padding: 0px;"><span style="color: #606060;"> 2:</span>                                         p.Position.Location);</pre>
</div>
</div>
<p>Now, let&#8217;s come across <strong>Single Responsability Principle </strong>(SRP). In my opinion SRP is one of the <strong>most relevant principles</strong> not just in OO but in other fields of software engineering thus I use to take it into consideration before starting to write code. After I wrote this code, I went back to it two weeks later and realized that the meaning of having an Lambda Expression there was no longer <strong>reasonable</strong>. The modification of this code made me spend some additional time refactoring and I decided <strong>to move it entirely to a classic method</strong>.</p>
<p>Beyond theory, whether it violates or not the SRP, I took a pragmatic point of view that made me realize about the requirement of turning the anonymous method into a classic method, and it was to make this method more maintainable, cointaining just <strong>one responsability</strong>, however, SRP states that a class or interface, method or package <strong>may contain two different responsibilities</strong> if, and only if, there is <strong>no coupling</strong> between them. <a href="http://www.google.es/url?sa=t&amp;rct=j&amp;q=see%20uncle%20bob's%20modem%20interface%20sample&amp;source=web&amp;cd=1&amp;ved=0CCUQFjAA&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fsrp.pdf&amp;ei=hKIqT8qZBob_8gO3sOzkDg&amp;usg=AFQjCNHQQ1Aw-2yCciEbERpJn3VdHBCmQw" target="_blank">See Uncle Bob&#8217;s Modem Interface sample</a>. That rule did not fit into my code.</p>
<p>I don&#8217;t want <strong>to coin a rule</strong> about using either Lambda Expression or anonymous methods in your code regarding to the accomplishment of SRP but I would say that if you write <strong>more than one or two statements</strong> into an anonymous method or Lambda Expression it&#8217;s <strong>likely </strong>that you are violating, in some way or another, the SRP and if so then the benefits of anonymous methods or Lambda Expression  clearly have no sense.</p>
<p>Obviously, that was in my case and it&#8217;s my honest opinion. I’m sure you may have your own about it based on your own experience. That’s why SRP is just it, a Principle.</p>
<div class="shr-publisher-479"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=479</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=479</feedburner:origLink></item>
		<item>
		<title>Principio Open/Closed</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/dirw8Sthly4/</link>
		<comments>http://josemigueltorres.net/boresight/?p=476#comments</comments>
		<pubDate>Wed, 14 Dec 2011 12:27:48 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Visual C#]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=476</guid>
		<description><![CDATA[Artículo con copyright. Se permite su reproducción citando al autor. Publicado en dotNetMania Este es el segundo de un total de cinco artículos sobre programación con los principio SOLID. Después de ver en profundidad el Principio de Responsabilidad Única, vamos a adentrarnos en conocer otro de los principios que además guarda una estrecha relación con [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p style="text-align: justify"><span style="font-size:9pt"><strong><em>Artículo con copyright. Se permite su reproducción citando al autor. Publicado en dotNetMania<br />
</em></strong></span></p>
<p style="text-align: justify">Este es el segundo de un total de cinco artículos sobre programación con los principio SOLID. Después de ver en profundidad el Principio de Responsabilidad Única, vamos a adentrarnos en conocer otro de los principios que además guarda una estrecha relación con el primero: el Principio Open/Closed.
</p>
<p style="text-align: justify">
<h1>Introducción<br />
</h1>
</p>
<p style="text-align: justify">Todas las aplicaciones cambian durante su ciclo de vida y siempre vendrán nuevas versiones tras la primera <em>release</em> y no por ello debemos adelantarnos a desarrollar características que el cliente podría necesitar en el futuro; si nos pusiéramos en el papel de adivinos fallaríamos seguro y  probablemente desarrollaríamos características que el cliente nunca necesitaría. El principio YAGNI (You aint&#8217;t gonna to need it) o &#8220;No vas a necesitarlo&#8221; utilizado en la Programación Extrema, previene de implementar nada más que lo que realmente se requiera. La idea es desarrollar ahora sobre los actuales requisitos funcionales, no sobre los que supongamos que aparecerán dentro de un mes. La actitud de adelantarnos a los acontecimientos es un mecanismo de defensa que en ocasiones acusamos los desarrolladores para prevenir lo que tarde o temprano será inevitable: la modificación.
</p>
<p style="text-align: justify">Lo único que podemos hacer es minimizar el impacto de una modificación en nuestro sistema y para ello es imprescindible empezar con un buen diseño ya que la modificación de una clase o módulo de una aplicación mal diseñada generará unos cambios en cascada sobre las clases dependientes que derivará en unos efectos indeseables. La aplicación se convierte, así, en rígida, impredecible y no reutilizable.
</p>
<p style="text-align: justify">Ahora bien, ¿cómo debemos plantear nuestras aplicaciones para que se mantengan estables ante cualquier modificación?
</p>
<p style="text-align: justify">
<h1>El Principio de Open/Closed<br />
</h1>
</p>
<p style="text-align: justify">El Principio Open/Closed u <em>Open/Closed Principle</em> en inglés, OCP en adelante, fue acuñado por el Dr. Bertrand Meyer en el año 1988 en su libro <em>Object Oriented Software Construction</em> y afirma que:
</p>
<p style="text-align: center"><strong><em>Una clase debe estar abierta a extensiones pero cerrada a las modificaciones.<br />
</em></strong></p>
<p style="text-align: justify">OCP es la respuesta a la pregunta que hacíamos anteriormente ya que argumenta que deberíamos diseñar clases que <em>nunca cambien</em>, y cuando un requisito lo hace debemos extender el comportamientos de dichas clases añadiendo código, no modificando el existente.
</p>
<p style="text-align: justify">Las clases que cumplen con OCP tienen dos características:
</p>
<ul>
<li>
<div style="text-align: justify">Son Abiertas para la extensión, es decir que la lógica o el comportamiento de la clase pueden ser extendidas en nuevas clases.
</div>
</li>
<li>
<div style="text-align: justify">Son Cerradas para la modificación y por tanto el código fuente de dicha clase debería permanecer inalterado.
</div>
</li>
</ul>
<p style="text-align: justify">Sin embargo, y aparentemente, parece que ambas características sean incompatibles y eso no es así. Veamos un ejemplo de clase que rompe con OCP.
</p>
<p style="text-align: justify">Supongamos un sistema de gestión de proyectos estilo Microsoft Project. Obviemos la complejidad real que existe en dicho sistema y centrémonos únicamente en la entidad Tareas tal y como muestra la Figura 1. Dicha clase viene determinada por los estados: <em>Pendiente</em>, <em>Finalizada</em> o <em>Cancelada</em> representados por el enumerador <em>TareasEstadosEnum</em>. Además implementa dos métodos Cancelar y Finalizar que cambian, si es posible, el nuevo estado de la tarea. En la Fuente 2 podemos la implementación del método Finalizar.
</p>
<p style="text-align: justify"><img src="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2011/12/121411_1227_PrincipioOp1.png" alt=""/>
	</p>
<p style="text-align: justify">Figura 1.
</p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">   1:<span style="color:black"><br />
				<span style="color:blue">public<span style="color:black"><br />
						<span style="color:blue">void<span style="color:black"> Finalizar()<br />
</span></span></span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">   2:<span style="color:black"> {<br />
</span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">   3:<span style="color:black"><br />
				<span style="color:blue">switch<span style="color:black"> (_estadoTarea)<br />
</span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">   4:<span style="color:black">     {<br />
</span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">   5:<span style="color:black"><br />
				<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Pendiente:<br />
</span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">   6:<span style="color:black"><br />
				<span style="color:green">//finalizamos<span style="color:black"><br />
					</span></span></span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">   7:<span style="color:black"><br />
				<span style="color:blue">break<span style="color:black">;<br />
</span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">   8:<span style="color:black"><br />
				<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Finalizada:<br />
</span></span></span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">   9:<span style="color:black"><br />
				<span style="color:blue">throw<span style="color:black"><br />
						<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">&#8220;Ya esta finalizada&#8221;<span style="color:black">);<br />
</span></span></span></span></span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">  10:<span style="color:black"><br />
				<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Cancelada:<br />
</span></span></span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">  11:<span style="color:black"><br />
				<span style="color:blue">throw<span style="color:black"><br />
						<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">&#8220;Imposible finalizar. Tarea cancelada&#8221;<span style="color:black">);<br />
</span></span></span></span></span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">  12:<span style="color:black"><br />
				<span style="color:blue">default<span style="color:black">:<br />
</span></span></span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">  13:<span style="color:black"><br />
				<span style="color:blue">throw<span style="color:black"><br />
						<span style="color:blue">new<span style="color:black"> ArgumentOutOfRangeException();<br />
</span></span></span></span></span></span></p>
<p style="background: #f4f4f4"><span style="color:#606060; font-family:Consolas; font-size:8pt">  14:<span style="color:black">     }<br />
</span></span></p>
<p style="background: white"><span style="color:#606060; font-family:Consolas; font-size:8pt">  15:<span style="color:black"> }<br />
</span></span></p>
<p style="text-align: justify">Fuente 2.
</p>
<p style="text-align: justify">Un cambio típico solicitado por el cliente de la aplicación seria la agregación de un nuevo estado para controlar las tareas que se han pospuesto, con lo que la adaptación a esta modificación seria la expuesta en la Fuente 3.
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   1:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   2:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   3:<span style="color:black">
						<span style="color:blue">switch<span style="color:black"> (_estadoTarea)
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   4:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   5:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Pendiente:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   6:<span style="color:black">
						<span style="color:green">//finalizamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   7:<span style="color:black">
						<span style="color:blue">break<span style="color:black">;
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   8:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Finalizada:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   9:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Ya esta finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  10:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Cancelada:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  11:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible finalizar. Tarea cancelada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  12:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Pospuesta:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  13:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible finalizar. Tarea no completada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  14:<span style="color:black">
						<span style="color:blue">default<span style="color:black">:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  15:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ArgumentOutOfRangeException();
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  16:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  17:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">Fuente 3.
</p>
<p style="text-align: justify">Aparentemente parece una modificación trivial, sin embargo este cambio puede replicarse en otros métodos o clases que utilicen el enumerador <em>TareasEstadosEnum</em> de forma que en nuestro caso también deberíamos modificar el método Cancelar (ver Fuente 4).
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   1:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   2:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   3:<span style="color:black">
						<span style="color:blue">switch<span style="color:black"> (_estadoTareas)
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   4:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   5:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Pendiente:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   6:<span style="color:black">
						<span style="color:green">//cancelamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   7:<span style="color:black">             _estadoTareas = TareasEstados.Cancelada;
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   8:<span style="color:black">
						<span style="color:blue">break<span style="color:black">;
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   9:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Finalizada:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  10:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible cancelar. Tarea finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  11:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Cancelada:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  12:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Tarea ya cancelada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  13:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> TareasEstadosEnum.Pospuesta:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  14:<span style="color:black">
						<span style="color:green">//cancelamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  15:<span style="color:black">             _estadoTareas = TareasEstados.Cancelada;
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  16:<span style="color:black">
						<span style="color:blue">break<span style="color:black">;
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  17:<span style="color:black">
						<span style="color:blue">default<span style="color:black">:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  18:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ArgumentOutOfRangeException();
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  19:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  20:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">Fuente 4.
</p>
<p style="text-align: justify">En definitiva, por cada nuevo estado que implementemos tenemos que identificar todas las clases que lo implementan y modificarlas tanto en la clase Tareas como en las clases lógicamente involucradas violando no únicamente OCP sino también el DRY (Don&#8217;t Repeat Yourself) &#8220;No te repitas&#8221;, otro principio que pretende reducir al máximo cualquier tipo de duplicación. En este tipo de modificaciones existe una alta probabilidad de olvidar modificar algún método relacionado con el nuevo estado implementado en el enumerador TareasEstadosEnum, lo que elevaría la probabilidad de aparición de un nuevo <em>bug</em>.
</p>
<h1>Fundamentos de la Orientación a Objetos<br />
</h1>
<p style="text-align: justify">La cuestión se centra en cómo minimizamos el impacto de una modificación en nuestro sistema, sin comprometer OCP, esto es, manteniendo la &#8220;simbiosis&#8221; entre las dos características del principio: abierto en extensión y cerrado en modificación.
</p>
<p style="text-align: justify">Volvamos a la entidad Tareas del ejemplo anterior. Por lo que hemos podido ver, los métodos dependen en gran medida del estado de la tarea. Así, una tarea podrá finalizarse o cancelarse dependiendo de su estado previo, pues no podremos cancelar una tarea que haya sido finalizada. De la misma forma, introduciendo el nuevo estado <em>TareasEstadoEnum.Pospuesta</em> implementaríamos un nuevo método llamado Posponer. La lógica del método sería obvia: únicamente podría posponerse una tarea que estuviera en estado pendiente. En definitiva todo gira alrededor del estado de la tarea y por tanto el comportamiento de la misma dependerá del estado en que se encuentre. Una opción sería encapsular dicho estado e implementar los métodos (Finalizar, Cerrar y Posponer) mediante los cuales definimos el comportamiento y por otro lado delegamos los métodos del objeto Tarea hacia dicha clase tal y como se muestra en la Fuente 5.
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   1:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> EstadosTareas
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   2:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   3:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">virtual<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar(EstadoTareasEnum estadoTareasEnum)
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   4:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   5:<span style="color:black">
						<span style="color:blue">switch<span style="color:black"> (estadoTareasEnum) {
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   6:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> EstadoTareasEnum.Pendiente:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   7:<span style="color:black">
						<span style="color:green">//finalizamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   8:<span style="color:black">
						<span style="color:blue">case<span style="color:black"> EstadoTareasEnum.Pospuesta:
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   9:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible finalizar. Tarea no completada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  10:<span style="color:black">                 . . . .
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  11:<span style="color:black">
						<span style="color:blue">default<span style="color:black">:
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  12:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ArgumentOutOfRangeException();
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  13:<span style="color:black">         }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  14:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  15:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  16:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">virtual<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar(EstadoTareasEnum estadoTareasEnum)
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  17:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  18:<span style="color:black">
						<span style="color:blue">switch<span style="color:black"> (estadoTareasEnum){
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  19:<span style="color:black">                 . . . .
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  20:<span style="color:black">
						<span style="color:green">//cancelamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  21:<span style="color:black">         }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  22:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  23:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  24:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">virtual<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer(EstadoTareasEnum estadoTareasEnum)
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  25:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  26:<span style="color:black">
						<span style="color:blue">switch<span style="color:black"> (estadoTareasEnum){
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  27:<span style="color:black">                 . . . .
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  28:<span style="color:black">
						<span style="color:green">//posponemos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  29:<span style="color:black">         }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  30:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  31:<span style="color:black"> }
</span></span></code></pre>
</p>
<p>Fuente 5.
</p>
<p style="text-align: justify">Pese a que hayamos extraído y aislado el estado de la entidad Tareas aún no hemos resuelto el problema; de hecho ahora hemos aislado la responsabilidad a la clase EstadosTareas, sin embargo estamos algo más cerca de la solución. Estudiemos de nuevo los estados -métodos- de la clase EstadoTareas; la lógica de cada uno está escrita en todos los métodos y por tanto se repite, es decir, todos los estados -métodos- contemplan la opción de Finalizar una tarea y en base a ello actúa de una forma y otra. La operación Posponer no podrá ejecutarse si el estado de la tarea es cancelado o la operación Cancelar únicamente podrá ejecutarse si el estado es Pendiente. A través de este razonamiento hemos detectado un patrón: un mismo contrato -los métodos- y diferentes comportamientos en base un estado. Esto en OO puede ser solucionado mediante polimorfismo. (Ver Fuente 6)
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   1:<span style="color:black">
						<span style="color:blue">abstract<span style="color:black">
								<span style="color:blue">class<span style="color:black"> EstadosTareasBase
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   2:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   3:<span style="color:black">
						<span style="color:blue">protected<span style="color:black"> Tareas _tarea;
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   4:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   5:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">abstract<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar();
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   6:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">abstract<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar();
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   7:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">abstract<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer();
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   8:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">   9:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  10:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> EstadoTareaPendiente : EstadosTareasBase
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  11:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  12:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  13:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  14:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  15:<span style="color:black">
						<span style="color:green">//finalizamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  16:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  17:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  18:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  19:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  20:<span style="color:black">
						<span style="color:green">//cancelamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  21:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  22:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  23:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  24:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  25:<span style="color:black">
						<span style="color:green">//posponemos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  26:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  27:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  28:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  29:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> EstadoTareaFinalizada : EstadosTareasBase
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  30:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  31:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  32:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  33:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  34:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Tarea ya Finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  35:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  36:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  37:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  38:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  39:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible cancelar. Tarea finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  40:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  41:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  42:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  43:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  44:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible posponer. Tarea finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  45:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  46:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  47:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  48:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> EstadoTareaCancelada : EstadosTareasBase
</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  49:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  50:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  51:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  52:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  53:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible finalizar. Tarea Cancelada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  54:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  55:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  56:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  57:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  58:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Tarea ya Cancelada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  59:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  60:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  61:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  62:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  63:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible posponer. Tarea Cancelada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  64:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  65:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  66:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  67:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> EstadoTareaPospuesta : EstadosTareasBase
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  68:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  69:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  70:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  71:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Imposible posponer. Tarea finalizada"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  72:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  73:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  74:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  75:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  76:<span style="color:black">
						<span style="color:green">//cancelamos<span style="color:black">
							</span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  77:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  78:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  79:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">override<span style="color:black">
										<span style="color:blue">void<span style="color:black"> Posponer()
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  80:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  81:<span style="color:black">
						<span style="color:blue">throw<span style="color:black">
								<span style="color:blue">new<span style="color:black"> ApplicationException(<span style="color:#006080">"Tarea ya Pospuesta"<span style="color:black">);
</span></span></span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  82:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  83:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  84:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  85:<span style="color:black">
						<span style="color:blue">class<span style="color:black"> Tareas
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  86:<span style="color:black"> {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  87:<span style="color:black">
						<span style="color:blue">private<span style="color:black"> EstadosTareasBase _estadosTareas;
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  88:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  89:<span style="color:black">
						<span style="color:blue">public<span style="color:black"> Tareas()
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  90:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  91:<span style="color:black">         _estadosTareas = <span style="color:blue">new<span style="color:black"> EstadoTareaPendiente();
</span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  92:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  93:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  94:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">void<span style="color:black"> Finalizar()
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  95:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  96:<span style="color:black">         _estadosTareas.Finalizar();
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  97:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  98:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt">  99:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">void<span style="color:black"> Cancelar()
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 100:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 101:<span style="color:black">         _estadosTareas.Cancelar();
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 102:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 103:<span style="color:black">
					</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 104:<span style="color:black">
						<span style="color:blue">public<span style="color:black">
								<span style="color:blue">void<span style="color:black"> Posponer()
</span></span></span></span></span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 105:<span style="color:black">     {
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 106:<span style="color:black">         _estadosTareas.Posponer();
</span></span></code></pre>
</p>
<p style="background: white">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 107:<span style="color:black">     }
</span></span></code></pre>
</p>
<p style="background: #f4f4f4">
<pre><code><span style="color:#606060; font-family:Consolas; font-size:8pt"> 108:<span style="color:black"> }
</span></span></code></pre>
</p>
<p style="text-align: justify">Fuente 6.
</p>
<p style="text-align: justify">Básicamente lo que hemos hecho es crear una clase por cada estado en lugar de tener una única clase cuyos métodos están basados en sentencias condicionadas por el estado de la tarea (con Switch o if). Además, con esta nueva implementación hemos delegado la responsabilidad de Finalizar, Cancelar o Posponer a una nueva clase EstadosTareasBase y la hemos marcado como abstracta. La clase Tareas implementará sus propios métodos y delegará la responsabilidad a través de las clases estados que implementan EstadosTareasBase. Debido a que la clase Tarea gira en torno a un estado, asumimos que el estado inicial  por defecto es Pendiente y así lo especificamos en el constructor instanciando EstadoTareaPendiente.
</p>
<p style="text-align: justify">En realidad, hemos aplicado un patrón ya conocido, el patrón de diseño State, ya que el comportamiento de la clase cambia dependiendo del estado -en este caso de la tarea- y por lo tanto hemos abstraído cada una de los estados como entidades independientes. Ante un nuevo requisito en la que intervenga un nuevo estado, lo único que deberemos hacer es crear una nueva clase que herede de EstadosTareasBase e implementar las acciones, extendiendo el comportamiento de la aplicación si comprometer el código existente.
</p>
<h1>Conclusión<br />
</h1>
<p style="text-align: justify">Cuando hablamos del Principio de Responsabilidad Única, argumentamos la importancia de que cada clase tuviera una y solo una responsabilidad dentro del sistema, de forma que cuanto menos impacto tenga una clase en el conjunto global del sistema, menos repercusión global tendrá una modificación en dicho sistema y este mismo argumento es la línea que pretende seguir el Principio Open/Closed. La clave para la correcta aplicación de este principio es la abstracción y el polimorfismo, como hemos podido ver en el ejemplo. Pese a que conceptualmente es relativamente sencillo de comprender, no sucede lo mismo cuando se aplica.</p>
<div class="shr-publisher-476"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=476</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=476</feedburner:origLink></item>
		<item>
		<title>SOAPUI: Error consumiendo un servicio WCF</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/RIvEZsq57QU/</link>
		<comments>http://josemigueltorres.net/boresight/?p=474#comments</comments>
		<pubDate>Wed, 07 Dec 2011 15:17:09 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[SOAPUI]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=474</guid>
		<description><![CDATA[Para los que no la conozcáis, SoapUI es una herramienta que se utiliza típicamente para el test de servicios Web y brilla por su alta versatilidad en cualquier tipo de plataforma y protocolos. Desarrollada en Java y OpenSource (aunque tiene una versión Pro de paganini), la utilizo para el test de comportamiento y de carga [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Para los que no la conozcáis, <strong><a href="http://www.soapui.org/" target="_blank">SoapUI</a></strong> es <a href="http://sourceforge.net/projects/soapui/files/" target="_blank">una herramienta</a> que se utiliza típicamente para el <strong>test de servicios Web</strong> y brilla por su alta versatilidad en cualquier tipo de plataforma y protocolos. Desarrollada en Java y OpenSource (aunque tiene una versión Pro de paganini), la utilizo para el test de comportamiento y de carga dado un <strong>WSDL</strong>.</p>
<p>En este post pretendo mostrar un par de “errores” típicos de <strong>SoapUI</strong> cuando testeamos un servicio <strong>WCF</strong>, en mi caso WCF 4.0.</p>
<h1>“The message could not be processed” con wsHttpBinding</h1>
<p>El primer error da como resultado de hacer un Request al método expuesto <em>Method</em> del servicio <em>IService</em> y es el siguiente:</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Envelope</span> <span style="color: #ff0000">xmlns:s</span><span style="color: #0000ff">=&quot;http://www.w3.org/2003/05/soap-envelope&quot;</span> <span style="color: #ff0000">xmlns:a</span><span style="color: #0000ff">=&quot;http://www.w3.org/2005/08/addressing&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span>    <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Header</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">a:Action</span> <span style="color: #ff0000">s:mustUnderstand</span><span style="color: #0000ff">=&quot;1&quot;</span><span style="color: #0000ff">&gt;</span>http://www.w3.org/2005/08/addressing/soap/fault<span style="color: #0000ff">&lt;/</span><span style="color: #800000">a:Action</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Header</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>    <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Body</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Fault</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>          <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Code</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span>s:Sender<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Subcode</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span>                <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Value</span> <span style="color: #ff0000">xmlns:a</span><span style="color: #0000ff">=&quot;http://schemas.xmlsoap.org/ws/2005/02/sc&quot;</span><span style="color: #0000ff">&gt;</span>a:BadContextToken<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  11:</span>             <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Subcode</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  12:</span>          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Code</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  13:</span>          <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Reason</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  14:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Text</span> <span style="color: #ff0000">xml:lang</span><span style="color: #0000ff">=&quot;es-ES&quot;</span><span style="color: #0000ff">&gt;</span>The message could not be processed. This is most likely because the action </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  15:</span> 'http://tempuri.org/IService/Method' is incorrect or because the message contains an invalid or </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  16:</span> expired security context token or because there is a mismatch between bindings. The security context token would </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  17:</span> be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  18:</span> prematurely increase the Receive timeout on the service endpoint's binding.<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Text</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  19:</span>          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Reason</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  20:</span>       <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Fault</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  21:</span>    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Body</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  22:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Envelope</span><span style="color: #0000ff">&gt;</span></pre>
</p></div>
</div>
<div>&#160;</div>
<div>El error se produce puesto que el enlace <strong>wsHttpBinding</strong> implementa de forma nativa el <a href="http://www.devx.com/codemag/Article/33342/1954" target="_blank">security context token</a><strong></strong>, el cual no está soportado por <strong>SoapUI</strong>. De este modo si modificamos el <strong>web.config</strong> del servicio indicandole de forma explícita que no haga uso del mismo solucionaremos el problema.</div>
<div>&#160;</div>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">bindings</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span>   <span style="color: #0000ff">&lt;</span><span style="color: #800000">wsHttpBinding</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">binding</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;wsHttpBindingConfig&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">security</span> <span style="color: #ff0000">mode</span><span style="color: #0000ff">=&quot;None&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>         <span style="color: #0000ff">&lt;</span><span style="color: #800000">transport</span> <span style="color: #ff0000">clientCredentialType</span><span style="color: #0000ff">=&quot;None&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>         <span style="color: #0000ff">&lt;</span><span style="color: #800000">message</span> <span style="color: #ff0000">establishSecurityContext</span><span style="color: #0000ff">=&quot;false&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>       <span style="color: #0000ff">&lt;/</span><span style="color: #800000">security</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>     <span style="color: #0000ff">&lt;/</span><span style="color: #800000">binding</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>   <span style="color: #0000ff">&lt;/</span><span style="color: #800000">wsHttpBinding</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">bindings</span><span style="color: #0000ff">&gt;</span></pre>
</p></div>
</div>
<p>&#160;</p>
<h1>Consideraciones con el WS-Addressing </h1>
<p>Otro de los quebraderos de cabeza es si tenemos habilitado el <a href="http://msdn.microsoft.com/en-us/magazine/cc163412.aspx" target="_blank">WS-Addressing</a><strong></strong>. En este caso el header del mensaje únicamente contiene el valor de <strong>Action</strong> (no el <strong>To</strong>)con lo que al ejecutar el <strong>Request</strong> desde <strong>SoapUI</strong> nos encontramos con el siguiente error.</p>
<div>
<div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Envelope</span> <span style="color: #ff0000">xmlns:s</span><span style="color: #0000ff">=&quot;http://www.w3.org/2003/05/soap-envelope&quot;</span> <span style="color: #ff0000">xmlns:a</span><span style="color: #0000ff">=&quot;http://www.w3.org/2005/08/addressing&quot;</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   2:</span>    <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Header</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   3:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">a:Action</span> <span style="color: #ff0000">s:mustUnderstand</span><span style="color: #0000ff">=&quot;1&quot;</span><span style="color: #0000ff">&gt;</span>http://www.w3.org/2005/08/addressing/soap/fault<span style="color: #0000ff">&lt;/</span><span style="color: #800000">a:Action</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   4:</span>    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Header</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   5:</span>    <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Body</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   6:</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Fault</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   7:</span>          <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Code</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   8:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span>s:Sender<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">   9:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Subcode</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  10:</span>                <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span>a:DestinationUnreachable<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Value</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  11:</span>             <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Subcode</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  12:</span>          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Code</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  13:</span>          <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Reason</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  14:</span>             <span style="color: #0000ff">&lt;</span><span style="color: #800000">s:Text</span> <span style="color: #ff0000">xml:lang</span><span style="color: #0000ff">=&quot;es-ES&quot;</span><span style="color: #0000ff">&gt;</span>The message with To '' cannot be processed at the receiver, due to </pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  15:</span> an AddressFilter mismatch at the EndpointDispatcher.  Check that the sender and receiver's EndpointAddresses agree.<span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Text</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  16:</span>          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Reason</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  17:</span>       <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Fault</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  18:</span>    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Body</span><span style="color: #0000ff">&gt;</span></pre>
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: white; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #606060">  19:</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">s:Envelope</span><span style="color: #0000ff">&gt;</span></pre>
</p></div>
</div>
<p>
  <br />Si nos dirigimos al apartado de <strong>WS-A Setting</strong> desde el “<em>Request 1</em>” en cuestión se desplegará las diferentes opciones habilitadas. Una de ellas está desactivada por defecto y es precisamente la que hace referencia a <strong>wsa:to</strong>, podemos seleccionar “<em>Add default wsa:to</em>” (como he hecho yo en este ejemplo) mediante el <em>check</em> correspondiente o bien podemos añadir directamente la dirección del servicio hospedado.</p>
<p><a href="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2011/12/image.png"><img style="background-image: none; border-right-width: 0px; margin: 5px 5px 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2011/12/image_thumb.png" width="891" height="703" /></a></p>
<p>Espero que sea de utilidad.</p>
<div class="shr-publisher-474"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=474</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=474</feedburner:origLink></item>
		<item>
		<title>Principio de Responsabilidad Única</title>
		<link>http://feedproxy.google.com/~r/josemigueltorres/rXsu/~3/fiZu9HvxI9c/</link>
		<comments>http://josemigueltorres.net/boresight/?p=471#comments</comments>
		<pubDate>Tue, 22 Nov 2011 10:39:50 +0000</pubDate>
		<dc:creator>josemiguel.torres</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://josemigueltorres.net/boresight/?p=471</guid>
		<description><![CDATA[Autores: Hadi Hariri, José Miguel TorresArtículo con copyright. Se permite su reproducción citando al auto. Publicado en dotNetMania Entradilla El Principio de Responsabilidad Única pretende ser el primero de un total de cinco artículos que responden a las siglas de S.O.L.I.D. y que descubren cinco principios fundamentales en el paradigma de la Programación Orientado a [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Autores: Hadi Hariri, José Miguel Torres<br/><span style="color:#666666; font-family:Verdana; font-size:8pt"><em>Artículo con copyright. Se permite su reproducción citando al auto. Publicado en dotNetMania</em></span>
	</p>
<p style="text-align: justify">
<h1>Entradilla<br />
</h1>
</p>
<p style="text-align: justify">El Principio de Responsabilidad Única pretende ser el primero de un total de cinco artículos  que responden a las siglas de S.O.L.I.D. y  que descubren cinco principios fundamentales en el paradigma de la Programación Orientado a Objetos.
</p>
<p style="text-align: justify">
<h1>Introducción<br />
</h1>
</p>
<p style="text-align: justify">Fue en los preparativos del Code Camp de Tarragona cuando Hadi propuso una sesión acerca de programación SOLID y pese a que en mayor o menor medida muchos de nosotros hemos sentido hablar de, sino todos, la mayoría de estos principios nunca los había visto –al menos yo- bajo dichas siglas.
</p>
<p style="text-align: justify">Y es que la comprensión de dichos principios nos permitirá mejorar la percepción del no siempre fácil campo de la programación orientada a objetos y evitar así las malas prácticas que la flexibilidad de esta metodología otorga a través de los lenguajes que la soportan. Las herramientas de desarrollo rápido (<em>Rapid ApplicationDevelopment</em> –RAD-), como Visual Studio, ofrecen al desarrollador un conjunto de funcionalidades que aumentan, ya sea a través de asistentes o Drag&#8217;n'Drop,  la productividad en el desarrollo de aplicaciones y permiten  focalizarse únicamente en el desarrollo de las propiedades o eventos específicos sin tener que preocuparse, en muchas ocasiones, del código generado &#8220;por debajo&#8221;.
</p>
<p style="text-align: justify">Sin embargo acabamos pagando un precio en ocasiones muy elevado ya que estas herramientas dejan cajas negras lógicas de código tras de sí y cualquier modificación o reutilización de un componente se traduce en un elevado coste de desarrollo ya que los conceptos clave de la Orientación a Objetos son sacrificados por la productividad, y hablar de productividad es hablar del mantenimiento y calidad del software con lo que dicho sacrificio, sencillamente, no tiene o debería tener cabida.
</p>
<h1>Cohesión<br />
</h1>
<p style="text-align: justify">Para tratar de comprender el término de nivel de cohesión vamos a utilizar el ejemplo del teléfono móvil. Como todos sabéis, un dispositivo móvil está compuesto de una serie de componentes tales como la pantalla, el teclado, la radio GPRS/3G, el módulo Bluetooth, etc. Todos estos componentes tienen una responsabilidad específica ya sean los módulos de entrada y salida de datos o los módulos de conectividad y comunicación, etcétera y por tanto existe una cohesión entre todos los componentes ya que no hay ningún componente que haga funciones que se solapen con la de otros componentes ni ninguna función básica que no quede descubierta por un determinado componente. A la hora de buscar un nuevo móvil miraremos las características y especificaciones técnicas del dispositivo y además de contemplar las especificaciones que deseamos también esperamos que los componentes sean de alta calidad; no es viable que un móvil esté compuesto con los últimos componentes electrónicos del mercado y se venda con una pantalla no táctil en &#8220;blanco y negro&#8221; de 3 pulgadas o que por ejemplo no tenga algo tan básico como un micrófono.
</p>
<p style="text-align: justify">En un sistema informático también tenemos componentes &#8211; además de módulos, clases, etc. &#8211; y todos estos componentes lógicos tienen su responsabilidad dentro del sistema. Pensemos pues en el nivel de cohesión de una aplicación no como una suma de los componentes sino como el conjunto de los mismo.
</p>
<h1>Acoplamiento<br />
</h1>
<p style="text-align: justify">Siguiendo con el ejemplo del teléfono móvil, un ejemplo de acoplamiento lo encontramos en los cargadores de nuestros móviles. Son cada vez más los fabricantes que optan por adaptadores de corriente estándar en lugar de crear adaptadores propietarios que casi siempre acaban tirados en el contenedor de reciclaje cuando sustituimos el móvil. Se entiende que se opta por la universalidad de los dispositivos de corriente para su reaprovechamiento en otros dispositivos, incluso de diferentes fabricantes. En la ingeniería del software, el acoplamiento entre módulo, clases o cualquier otro tipo de entidad lógica es el grado de dependencia entre ellos. Cuán más estándar sea la relación de una entidad lógica con otras mayor reaprovechamiento podremos hace de ella.
</p>
<h1>Encapsulación<br />
</h1>
<p style="text-align: justify">Seguramente nos habremos dado cuenta que la parte interna de un móvil no es fácilmente accesible, es decir, no tenemos acceso a la electrónica interna. La idea de la encapsulación es la de abstraer determinadas funciones para que, además de ser reutilizables, no requieran que los usuarios tengan los conocimientos del diseñador. La complejidad de un dispositivo móvil o de cualquier otro dispositivo electrónico es muy elevada y la gran mayoría de usuarios son capaces de sacar el máximo provecho sin tener nociones específicas sobre su arquitectura interna. La radio Bluetooth o el módem GPRS/3G es el mismo para varios modelos incluso de diferente fabricantes. Esta es precisamente la idea de la encapsulación de funciones o características ya que lo único que requiere es que el usuario sepa qué se puede hacer con esa función no cómo está diseñada.
</p>
<h1>Aplicaciones SOLIDas<br />
</h1>
<p style="text-align: justify">Siguiendo el modelo del teléfono móvil y siguiendo la idea subyacente de estos tres aspectos afirmamos que mi teléfono ideal sería aquél que estuviera compuesto por los mejores componentes del mercado, aquél cuyas interfaces de conexión para la sincronización de datos y recarga de la batería fuera estándar y aquél cuyas funcionalidades conozca en profundidad sin la necesidad de tener que consultar la documentación técnica para saber cómo ha sido diseñado y así poder sacar el máximo provecho.
</p>
<p style="text-align: justify">Extrapolando este ejemplo a nuestro mundo, el mundo del software, tenemos que tener siempre presente estos tres aspectos fundamentales desde el mismo momento que empezamos con un diseño de una nueva aplicación y es ahí donde entran a escena los cinco principios descritos por el acrónimo mnemotécnico SOLID y presentados a principio de esta década por Robert C. Martin. (Ver Figura 1)
</p>
<p style="text-align: justify"><img align="left" src="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2011/11/112211_1039_Principiode1.png" alt=""/>
	</p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">
 </p>
<p style="text-align: justify">Figura 1. Los cinco principios SOLID
</p>
<p style="text-align: justify">Los principios SOLID pretenden ser una guía a seguir durante la fase de desarrollo para facilitar el mantenimiento de aplicaciones y tratar de eliminar el impacto de las inevitables modificaciones que sufren durante el ciclo de vida de la aplicación además de facilitar el uso de las unidades de testeo, entre las más destacadas.
</p>
<h1>Principio de Responsabilidad Única<br />
</h1>
<p style="text-align: justify">El Principio de Responsabilidad Única o Single Responsability Principle en inglés (SRP en adelante), fue acuñado por <strong>Robert C. Martin</strong> a través de un artículo del mismo título y popularizado a través de su libro <em>Agile Software Development: Principles, Patterns, and Practices</em>. SRP está basado en el Principio de Cohesión y describe el nivel de acoplamiento ordinal entre módulos dentro de la ingeniería del Software.
</p>
<p style="text-align: justify">En términos prácticos, Robert C. Martin declara a través de SRP que:
</p>
<p style="text-align: center"><strong><em>Una clase debe tener una y sólo una única causa por la cual puede ser modificada<br />
</em></strong></p>
<p style="text-align: justify"> Si una clase tiene dos responsabilidades entonces asume dos motivos por los cuales puede ser modificada. Por ejemplo, supongamos una clase llamada <strong>Factura</strong>, la cual dentro de un contexto determinado ofrecerá un método para calcular el total de una factura tal y como muestra la Figura 2.
</p>
<p style="text-align: justify"><img src="http://jtorresd.brinkster.net/boresight/wp-content/uploads/2011/11/112211_1039_Principiode2.png" alt=""/>
	</p>
<p style="text-align: justify">Figura 2.
</p>
<h1>Detectando responsabilidades<br />
</h1>
<p style="text-align: justify">La piedra angular de este principio es la identificación de la responsabilidad real de la clase. Según SRP una responsabilidad es &#8220;un motivo de cambio&#8221;, sin embargo es difícil de ver ya que estamos acostumbrados a pensar un conjunto de operaciones como una sola responsabilidad.
</p>
<p style="text-align: justify">Si implementamos la clase Factura tal y como muestra la Fuente 1 podríamos decir que la responsabilidad de esta clase es la de calcular el total de la factura -y efectivamente cumple con su cometido-, sin embargo no es cierto que contenga una única responsabilidad. Si nos fijamos detenidamente en la implementación del método CalcularTotal() podemos ver que, además de calcular el importe base de la factura, se está aplicando sobre el importe a facturar un descuento o deducción y un 16% de IVA de impuestos. El problema está en que si en el futuro tuviéramos que modificar la tasa de IVA o bien tuviéramos que aplicar una deducción en base a una tarifa por cliente deberíamos modificar la clase Factura por cada una de las razones y por lo tanto las responsabilidades quedan acopladas entre sí y disminuye la cohesión. La clase Factura pues violaría el principio SRP.
</p>
<p><span style="font-family:Courier New; font-size:10pt"><span style="color:blue">public</span><br />
			<span style="color:blue">class</span> Factura<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">{<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">string</span> _codigo;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:teal">DateTime</span> _fechaEmision;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeFactura;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeIVA;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeDeducir;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeTotal;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">ushort</span> _porcentageDeduccion;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//método que calcula el Total de la factura<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">void</span> CalcularTotal()<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    {<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//Calculamos la deducción<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeDeducir = (_importeFactura*_porcentageDeduccion)/100;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//Calculamos el IVA<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeIVA = _importeFactura * 0.16m;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//calculamos el total<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeTotal = (_importeFactura &#8211; _importeDeducir) + _importeIVA;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    }<br />
</span></p>
<p style="text-align: justify"><span style="font-family:Courier New; font-size:10pt">}</span>
	</p>
<p style="text-align: justify"><span style="font-family:Courier New; font-size:10pt">Fuente 1. Clase Factura.</span>
	</p>
<h1>Separando responsabilidades<br />
</h1>
<p style="text-align: justify">El primer paso para solucionarlo es separar las responsabilidades y para separarlas primero hay que identificarlas.
</p>
<p style="text-align: justify">Enumeremos de nuevos los pasos que realiza el método CalculaTotal():
</p>
<ul>
<li>
<div style="text-align: justify">Aplica una deducción. En base a la base imponible se calcula un descuento porcentual.
</div>
</li>
<li>
<div style="text-align: justify">Aplica la tasa de IVA del 16% en base a la base imponible
</div>
</li>
<li>
<div style="text-align: justify">Calcula el total de la factura teniendo en cuenta el descuento y el impuesto.
</div>
</li>
</ul>
<p style="text-align: justify">En este método se identifican tres responsabilidades. Recordamos, una responsabilidad no es una acción, es un motivo de cambio y por lo tanto deberían extraer las responsabilidades de deducción e impuestos en dos clases específicas para ambas operaciones estableciendo por un lado la clase IVA y por otro la clase Deduccion tal y como muestra la Fuente 2.
</p>
<p><span style="font-family:Courier New; font-size:10pt"><span style="color:blue">public</span><br />
			<span style="color:blue">class</span> IVA<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">{<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">readonly</span><br />
			<span style="color:blue">decimal</span> _iva = 0.16m;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> CalcularIVA(<span style="color:blue">decimal</span> importe)<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    {<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">return</span> importe*_iva;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    }<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">}<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><span style="color:blue">public</span><br />
			<span style="color:blue">class</span> Deduccion<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">{<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">readonly</span><br />
			<span style="color:blue">decimal</span> _deduccion;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span> Deduccion(<span style="color:blue">ushort</span> porcentage)<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    {<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _deduccion = porcentage;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    }<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> CalcularDeduccion(<span style="color:blue">decimal</span> importe)<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    {<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">return</span> (importe*_deduccion)/100;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    }<br />
</span></p>
<p style="text-align: justify"><span style="font-family:Courier New; font-size:10pt">}</span>
	</p>
<p style="text-align: justify">Fuente 2.
</p>
<p style="text-align: justify">Ambas clases contienen datos y un método y se responsabilizan únicamente en calcular el IVA y la deducción de un importe, es decir existe una encapsulación pese a lo trivial del ejemplo. Además, con esta separación obtenemos una mayor cohesión y un menor acoplamiento al aumentar la granularidad de la solución.
</p>
<p style="text-align: justify">Las ventajas de la correcta aplicación del SRP simplifica el código y se traduce en facilidad en el mantenimiento, permite la reutilización de clases y nos permite crear unidades de testeo específicas orientadas a dicha clase/responsabilidad.
</p>
<p><span style="font-family:Courier New; font-size:10pt"><span style="color:blue">public</span><br />
			<span style="color:blue">class</span> Factura<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">{<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">string</span> _codigo;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:teal">DateTime</span> _fechaEmision;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeFactura;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeIVA;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeDeducir;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">decimal</span> _importeTotal;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">ushort</span> _porcentageDeduccion;<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:blue">public</span><br />
			<span style="color:blue">void</span> CalcularTotal()<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    {<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//calculamos el IVA<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        IVA iva = <span style="color:blue">new</span> IVA();<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeIVA = iva.CalcularIVA(_importeFactura);<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//calculamos la deducción a aplicar<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        Deduccion deduccion = <span style="color:blue">new</span> Deduccion(_porcentageDeduccion);<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeDeducir = deduccion.CalcularDeduccion(_importeFactura);<br />
</span></p>
<p>
 </p>
<p><span style="font-family:Courier New; font-size:10pt"><br />
			<span style="color:green">//calculamos el total<br />
</span></span></p>
<p><span style="font-family:Courier New; font-size:10pt">        _importeTotal = (_importeFactura &#8211; _importeDeducir) + _importeIVA;<br />
</span></p>
<p><span style="font-family:Courier New; font-size:10pt">    }<br />
</span></p>
<p style="text-align: justify"><span style="font-family:Courier New; font-size:10pt">}<br />
</span></p>
<p style="text-align: justify">Fuente 3. Clase Factura definitiva.
</p>
<h1>Ampliando el abanico de &#8220;responsabilidades&#8221;<br />
</h1>
<p>Comentábamos anteriormente que no es fácil detectar las responsabilidades ya que siempre tendemos a agruparlas, sin embargo existen escenarios o casuísticas en las que &#8220;se permite&#8221; cierta flexibilidad. Robert C.  Martin expone un ejemplo a través de la interfaz Modem (Fuente 3).
</p>
<p>interface Modem<br/>{<br/>  void dial(int pNumber);<br/>  void hangup();<br/>  void send(char[] data);<br/>  char[] receive();<br/>}
</p>
<p>Fuente 3.
</p>
<p style="text-align: justify">En este ejemplo se detectan dos responsabilidades, las relacionadas con la gestión de la comunicación (dial y hangup) y la comunicación de datos (send y receive). Efectivamente cada una de las funciones pueden cambiar por diferentes motivos pero sin embargo ambas funciones se llamaran desde distintos puntos de la aplicación y no existe una dependencia entre ellas con lo que no perderíamos la cohesión del sistema.
</p>
<h1>Conclusión<br />
</h1>
<p style="text-align: justify">Pensemos en el ciclo de vida de una aplicación, no únicamente en su diseño y desarrollo. La aplicación sufre modificaciones  a causa de los cambios de requisitos o arreglo de fallos existentes, el equipo de desarrollo puede variar y si a ello le sumamos que el código es poco <em>mantenible</em> los costes de mantenimiento se disparan y cualquier modificación se presenta como un causa potencial de errores en entidades relacionadas dentro del sistema. </p>
<div class="shr-publisher-471"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://josemigueltorres.net/boresight/?feed=rss2&amp;p=471</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://josemigueltorres.net/boresight/?p=471</feedburner:origLink></item>
	</channel>
</rss>

