<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>wcf &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/wcf/</link>
	<description>Feed of posts on WordPress.com tagged "wcf"</description>
	<pubDate>Tue, 01 Dec 2009 11:32:59 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Microsoft Forums]]></title>
<link>http://frenk.wordpress.com/2009/12/01/microsoft-forums/</link>
<pubDate>Tue, 01 Dec 2009 07:50:49 +0000</pubDate>
<dc:creator>Frenk</dc:creator>
<guid>http://frenk.wordpress.com/2009/12/01/microsoft-forums/</guid>
<description><![CDATA[Microsoft is doing a lot of great things recently but their support forum is not one of them. In fac]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Microsoft is doing a lot of great things recently but their support forum is not one of them. In fact half of the time if you are asking something not obvious you get completely unrelated answers from people that are looking for MVP points or whatever, so they copy &#38; paste the first code snippet that looks remotely related to the question.</p>
<p>Other times you have the impression that moderators are paid in function of the number of reply they mark as “answer”, so they scan through threads without even bothering to read them.</p>
<p>Fortunately there are smart people too, and they are often helpful.</p>
<p>Microsoft, if you are listening, please address this issue as right now in my opinion it’s the real weak link in the .NET development ecosystem.</p>
<p>Rant over.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[WCF DataContractSerializer problems with dynamic proxies in Entity framework 4]]></title>
<link>http://daniel.wertheim.se/2009/12/01/wcf-datacontractserializer-problems-with-dynamic-proxies-in-entity-framework-4/</link>
<pubDate>Tue, 01 Dec 2009 01:34:42 +0000</pubDate>
<dc:creator>Daniel Wertheim</dc:creator>
<guid>http://daniel.wertheim.se/2009/12/01/wcf-datacontractserializer-problems-with-dynamic-proxies-in-entity-framework-4/</guid>
<description><![CDATA[This article was produced for Beta 2 &amp; CTP2 Download the code I were having trouble with seriali]]></description>
<content:encoded><![CDATA[This article was produced for Beta 2 &amp; CTP2 Download the code I were having trouble with seriali]]></content:encoded>
</item>
<item>
<title><![CDATA[Silverlight: Consumindo serviços WCF em outros domínios]]></title>
<link>http://flaviomoraes.wordpress.com/2009/11/30/silverlight-consumindo-servicos-wcf-em-outros-dominios/</link>
<pubDate>Mon, 30 Nov 2009 20:41:50 +0000</pubDate>
<dc:creator>flaviomoraes</dc:creator>
<guid>http://flaviomoraes.wordpress.com/2009/11/30/silverlight-consumindo-servicos-wcf-em-outros-dominios/</guid>
<description><![CDATA[Olá a todos,                 Nesse post demonstraremos como uma consumir um serviço WCF a partir de ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá a todos,</p>
<p>                Nesse post demonstraremos como uma consumir um serviço WCF a partir de uma aplicação desenvolvida em Silverlight no contexto em que estão hospedados em domínios diferentes. A explicação de como <a href="http://flaviomoraes.wordpress.com/2009/11/12/consumindo-servicos-wcf-em-silverlight/">consumir um serviço WCF em Silverlight</a> já foi abordada em outro post, porém nele nos limitamos hospedando o serviço e o consumidor no mesmo local de origem. Para montar a estrutura necessária para esse exemplo utilizarei duas roles do Windows Azure, portanto também demonstraremos como hospedar aplicações WCF e Silverlight no Windows Azure com o CTP de novembro, que trouxe algumas mudanças.</p>
<p>                Antes de iniciarmos nosso exemplo precisamos entender o motivo e como funciona a restrição no consumo de aplicações em outros domínios. Na verdade a restrição não é apenas para outros domínios, mas sim para outros “locais de origem”. Um local de origem nesse contexto é o conjunto de domínio, protocolo de comunicação e porta acessada. Essa regra existe nos browsers como medida de segurança para códigos JavaScript não acessarem recursos de outros locais de origem que possam ser maliciosos. Portanto ela é aplicada para aplicações desenvolvidas em Silverlight, Flash ou qualquer outra ferramenta que faça uso de JavaScript para acessar recursos na web. Logo quando temos uma aplicação desenvolvida em Silverlight e desejarmos acessar um serviço WCF ou outro recurso que esteja exposto em outro domínio, porta ou que utilize outro protocolo de comunicação nos depararemos com essa medida de segurança.</p>
<p>                Para lidarmos com essa restrição temos duas alternativas. A primeira é colocarmos um serviço WCF ou outro recurso no mesmo local de origem da aplicação Silverlight que consuma o serviço original que está no outro local de origem. A segunda alternativa é possibilitarmos o consumo desse recurso através da inclusão dos arquivos <em>crosssdomain.xml</em> e <em>clientaccesspoliciy.xml</em>. Porém esses arquivos devem ser adicionados no servidor que expõem o serviço, logo deveremos ter acesso a esse servidor ou ao publicador do serviço para adicioná-lo, caso contrário nos restará somente a primeira opção. O arquivos <em>clientaccesspolicy.xml</em> é exclusivo para aplicações escritas em Silverlight, já o arquivo <em>crossdomain.xml</em> pode ser utilizado para permitir ou restringir o acesso a qualquer aplicação que tente acessar o recurso através de JavaScript.</p>
<p>                Vamos agora iniciar o nosso exemplo que será um projeto do tipo <em>Windows Azure Cloud Service</em> e terá uma <em>ASP .Net Web Role</em> para hospedar a aplicação escrita em Silverlight e uma <em>WCF Service Web Role</em> para hospedar o serviço WCF. A aplicação será a mesma utilizada na demonstração de <a href="http://flaviomoraes.wordpress.com/2009/11/12/consumindo-servicos-wcf-em-silverlight/">consumo de serviço WCF por aplicações em Silverlight no mesmo local de origem</a>.</p>
<div id="attachment_356" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio1.jpg"><img class="size-medium wp-image-356" title="SilverlightDominio1" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio1.jpg?w=300" alt="" width="300" height="213" /></a><p class="wp-caption-text">Criando o projeto principal</p></div>
<div id="attachment_357" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio2.jpg"><img class="size-medium wp-image-357" title="SilverlightDominio2" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio2.jpg?w=300" alt="" width="300" height="187" /></a><p class="wp-caption-text">Adicionando as web roles na solucao</p></div>
<div id="attachment_377" class="wp-caption aligncenter" style="width: 173px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio31.jpg"><img class="size-medium wp-image-377" title="SilverlightDominio3" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio31.jpg?w=163" alt="" width="163" height="300" /></a><p class="wp-caption-text">Estrutua inicial da solucao</p></div>
<p>Após criada a solução com os projetos devemos adicionar também o projeto da aplicação Silverlight. Durante esse processo devemos indicar para o <em>Visual Studio</em> que desejamos hospedar esse projeto na <em>ASP .Net Web Role</em>:</p>
<div id="attachment_359" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio4.jpg"><img class="size-medium wp-image-359" title="SilverlightDominio4" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio4.jpg?w=300" alt="" width="300" height="191" /></a><p class="wp-caption-text">Adicionando o projeto da aplicacao Silverlight</p></div>
<div id="attachment_360" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio5.jpg"><img class="size-medium wp-image-360" title="SilverlightDominio5" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio5.jpg?w=300" alt="" width="300" height="268" /></a><p class="wp-caption-text">Hospedando a aplicacao Silverlight na Web Role</p></div>
<div id="attachment_363" class="wp-caption aligncenter" style="width: 139px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio61.jpg"><img class="size-medium wp-image-363" title="SilverlightDominio6" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio61.jpg?w=129" alt="" width="129" height="300" /></a><p class="wp-caption-text">Estrutura da solucao com o projeto silverlight</p></div>
<p>Em seguida vamos modificar a página principal do projeto Web para expor a aplicação Silverlight. Vamos utilizar o mesmo código já desenvolvido em outro <a href="http://flaviomoraes.wordpress.com/2009/11/12/consumindo-servicos-wcf-em-silverlight/">post</a>.</p>
<div id="attachment_364" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio7.jpg"><img class="size-medium wp-image-364" title="SilverlightDominio7" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio7.jpg?w=300" alt="" width="300" height="73" /></a><p class="wp-caption-text">Codigo da pagina que hospeda a aplicacao Silverlight</p></div>
<div id="attachment_366" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio81.jpg"><img class="size-medium wp-image-366" title="SilverlightDominio8" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio81.jpg?w=300" alt="" width="300" height="120" /></a><p class="wp-caption-text">XAML da aplicacao Silverlight</p></div>
<p>Partiremos agora para a construção do Serviço WCF que será hospedado na outra <em>Web Role</em> e que será disponibilizado em outra porta, portanto estará em outro local de origem. Nesse serviço teremos o mesmo método do <a href="http://flaviomoraes.wordpress.com/2009/11/12/consumindo-servicos-wcf-em-silverlight/">post anterior sobre consumo de serviços WCF por aplicações Silverlight</a>. Para essa tarefa vamos remover o serviço inicial disponibilizado pelo <em>template</em> e adicionar outro item do tipo <em>Silverlight-enabled WCF Service</em>: </p>
<div id="attachment_367" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio9.jpg"><img class="size-medium wp-image-367" title="SilverlightDominio9" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio9.jpg?w=300" alt="" width="300" height="180" /></a><p class="wp-caption-text">Adicionando o servico na Web Role</p></div>
<div id="attachment_368" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio10.jpg"><img class="size-medium wp-image-368" title="SilverlightDominio10" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio10.jpg?w=300" alt="" width="300" height="130" /></a><p class="wp-caption-text">Codigo do servico WCF</p></div>
<p>Para finalizar a estrutura devemos adicionar a referência do serviço WCF na aplicação Silverlight. Para isso clique com o botão da direita sobre o projeto Silverlight e selecione a opção <em>Add Service Reference</em> e em seguida clique no botão <em>Discover</em>:</p>
<div id="attachment_369" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio11.jpg"><img class="size-medium wp-image-369" title="SilverlightDominio11" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio11.jpg?w=300" alt="" width="300" height="241" /></a><p class="wp-caption-text">Adicionando a referencia do servico na aplicacao Silverlight</p></div>
<p>Agora adicionaremos o código para consumir o serviço a partir da aplicação Silverlight e em seguida tentaremos consumir o serviço. </p>
<div id="attachment_370" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio12.jpg"><img class="size-medium wp-image-370" title="SilverlightDominio12" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio12.jpg?w=300" alt="" width="300" height="107" /></a><p class="wp-caption-text">Codigo da aplicacao Silverlight</p></div>
<p>Porém como ainda não adicionamos os arquivos que permitem o consumo do serviço por código JavaScript de outros locais de origem nos deparamos com a seguinte exceção: <em>System.ServiceModel.CommunicationException was unhandled by user code  Message=&#8221;An error occurred while trying to make a request to URI &#8216;http://localhost:8080/TesteSL.svc&#8217;. </em><em>This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.&#8221;</em></p>
<div id="attachment_371" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio13.jpg"><img class="size-medium wp-image-371" title="SilverlightDominio13" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio13.jpg?w=300" alt="" width="300" height="116" /></a><p class="wp-caption-text">Mensagem de erro ao consumir recurso em outro local de origem</p></div>
<p> A origem dessa exceção não o nosso código Silverlight ou WCF, mas sim a segurança do browser que não permite que um código JavaScript consuma recursos de outros locais de origem. Para permitir o consumo do serviço por nossa aplicação deveremos colocar os arquivos <em>crossdomain.xml</em> e <em>clientaccesspolicy.xml </em>no diretório raiz do site/aplicação que hospeda o serviço, no nosso caso a web role.</p>
<div id="attachment_373" class="wp-caption aligncenter" style="width: 234px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio16.jpg"><img class="size-full wp-image-373" title="SilverlightDominio16" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio16.jpg" alt="" width="224" height="244" /></a><p class="wp-caption-text">Arquivos clientaccesspolicy.xml e crossdomain.xml adicionados no projeto</p></div>
<div id="attachment_374" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio141.jpg"><img class="size-medium wp-image-374" title="SilverlightDominio14" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio141.jpg?w=300" alt="" width="300" height="183" /></a><p class="wp-caption-text">Conteudo do arquivo clientaccesspolicy.xml</p></div>
<p>Note que no arquivo <em>clientaccesspolicy.xml</em> podemos definir quais URIs poderão acessar o recurso, no nosso caso o serviço WCF, além de configurar também quais os diretórios estarão acessíveis a essas URIs. Já no arquivo <em>crossdomain.xml</em> configuramos somente quais domínios terão acesso aos nossos recursos. </p>
<div id="attachment_375" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio15.jpg"><img class="size-medium wp-image-375" title="SilverlightDominio15" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio15.jpg?w=300" alt="" width="300" height="39" /></a><p class="wp-caption-text">Conteudo do arquivos crossdomain.xml</p></div>
<p>Adicionados os arquivos no projeto vamos testar novamente a solução, que funcionará corretamente.</p>
<div id="attachment_376" class="wp-caption aligncenter" style="width: 310px"><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio17.jpg"><img class="size-medium wp-image-376" title="SilverlightDominio17" src="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio17.jpg?w=300" alt="" width="300" height="180" /></a><p class="wp-caption-text">Aplicacao funcionando corretamente</p></div>
<p>Com isso temos nossa aplicação Silverlight consumindo um serviço WCF em outro local de origem, que poderia ser em outro domínio também, desde que no servidor que hospeda o serviço tenhamos os arquivos para permitir o seu consumo. Como sempre deixei no meu <a href="http://cid-a968bff8abeea565.skydrive.live.com/browse.aspx/Fontes%20do%20Blog?authkey=vXJ2zoIesLo%24">Sky Drive</a> os fontes utilizados para escrever o post, nesse caso o arquivo está com o nome LocaisOrigem.zip</p>
<p>Abraço a todos e até o próximo post.</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p><a href="http://flaviomoraes.wordpress.com/files/2009/11/silverlightdominio6.jpg"></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Explicit Interface Implementation and WCF]]></title>
<link>http://nirajrules.wordpress.com/2009/11/30/explicit-interface-implementation-and-wcf/</link>
<pubDate>Mon, 30 Nov 2009 15:22:12 +0000</pubDate>
<dc:creator>nirajrules</dc:creator>
<guid>http://nirajrules.wordpress.com/2009/11/30/explicit-interface-implementation-and-wcf/</guid>
<description><![CDATA[You are inheriting from 2 contracts to create a contract. Both contracts that you are inheriting fro]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>You are inheriting from 2 contracts to create a contract. Both contracts that you are inheriting from have a method with same name and signature. You don’t have much control over these interfaces as they are tightly coupled with your subsystem. You create an implementation class with help of explicit interface implementations and dispatch calls to subsystem. Now you have a challenge of invoking the right implementation from client side? Will WCF work even when we can&#8217;t have any config files? Fortunately YES, WCF supports such scenarios. Below is a  code sample on same, hope it helps you when you have a sharp knife against your throat <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  :</p>
<p>//Contracts<br />
<code>[ServiceContract]<br />
    public interface IIPV4Location<br />
    {<br />
        [OperationContract]<br />
        string GetLocationId();<br />
    }</p>
<p>    [ServiceContract]<br />
    public interface IIPV6Location<br />
    {<br />
        [OperationContract(Name = "IIPV6Location")] //A must for WCF to distinguish<br />
        string GetLocationId();<br />
    }</p>
<p>    [ServiceContract]<br />
    public interface ILocation : IIPV4Location, IIPV6Location<br />
    { }</code></p>
<p>//Server Side<br />
<code>class LocationImpl : ILocation<br />
    {<br />
        string IIPV4Location.GetLocationId()<br />
        {<br />
            return "Ipv4";<br />
        }</p>
<p>        string IIPV6Location.GetLocationId()<br />
        {<br />
            return "Ipv6";<br />
        }<br />
    }</p>
<p>    class Program<br />
    {<br />
        static void Main(string[] args)<br />
        {<br />
            ServiceHost host = new ServiceHost(typeof(LocationImpl), new Uri("http://localhost:9999/"));<br />
            var behavior = new ServiceMetadataBehavior();<br />
            behavior.HttpGetEnabled = true;<br />
            host.Description.Behaviors.Add(behavior);</p>
<p>            host.AddServiceEndpoint(typeof(ILocation), new BasicHttpBinding(), "Location");            </p>
<p>            host.Open();<br />
            Console.WriteLine("Running...");<br />
            Console.ReadLine();<br />
            host.Close();<br />
        }<br />
    }</code><br />
//Client Side<br />
<code>class Program<br />
    {<br />
        static void Main(string[] args)<br />
        {<br />
            ILocation location = new ChannelFactory(new BasicHttpBinding(),<br />
                                                                   "http://localhost:9999/Location")<br />
                                                                   .CreateChannel();</p>
<p>            var ipv4Location = ((IIPV4Location)location).GetLocationId();<br />
            Console.WriteLine(ipv4Location);</p>
<p>            var ipv6Location = ((IIPV6Location)location).GetLocationId();<br />
            Console.WriteLine(ipv6Location);<br />
        }<br />
    }</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Silverlight 4  ]]></title>
<link>http://flamoreira.wordpress.com/2009/11/28/silverlight-4-a/</link>
<pubDate>Sun, 29 Nov 2009 00:24:23 +0000</pubDate>
<dc:creator>Flavia Moreira</dc:creator>
<guid>http://flamoreira.wordpress.com/2009/11/28/silverlight-4-a/</guid>
<description><![CDATA[Se você não conhece Silverlight, aproveite esta vídeo aula, onde você irá aprender os princípios bás]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Se você não conhece Silverlight, aproveite esta vídeo aula, onde você irá aprender os princípios básicos de como iniciar uma <strong>aplicação em Silverlight 4</strong> , utilizando a ferramenta Microsoft <strong>Blend 4</strong> e <strong>Visual Studio 2010</strong> <strong>Beta 2</strong>. Assim, conhecer a interação entre as duas ferramentas. Você poderá aplicar os mesmos conceitos utilizando o <strong>Silverlight 3</strong> com <strong>o Blend 3 e Visual Studio 2008</strong>.</p>
<p>Você ainda não conhece Silverlight ? O que está esperando para aprender também?</p>
<p>veja a vídeo aula:</p>
<p><a href="http://www.dowhile.com.br/videos/silverlight/115-video-aula-aplicacao-em-silverlight.html">http://www.dowhile.com.br/videos/silverlight/115-video-aula-aplicacao-em-silverlight.html</a></p>
<p>abraços,</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[BizTalk, WCF and the Bad Gateway]]></title>
<link>http://santoshbenjamin.wordpress.com/2009/11/28/biztalk-wcf-and-the-bad-gateway/</link>
<pubDate>Sat, 28 Nov 2009 16:52:20 +0000</pubDate>
<dc:creator>santoshbenjamin</dc:creator>
<guid>http://santoshbenjamin.wordpress.com/2009/11/28/biztalk-wcf-and-the-bad-gateway/</guid>
<description><![CDATA[We ran into an interesting problem a couple of days ago and I decided it would be worth posting the ]]></description>
<content:encoded><![CDATA[We ran into an interesting problem a couple of days ago and I decided it would be worth posting the ]]></content:encoded>
</item>
<item>
<title><![CDATA[Per-Session Instance Management in WCF]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/per-session-instance-management-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 13:03:59 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/per-session-instance-management-in-wcf/</guid>
<description><![CDATA[Objective This article is part # 2 of Instance Management in WCF. This article will explain Session ]]></description>
<content:encoded><![CDATA[Objective This article is part # 2 of Instance Management in WCF. This article will explain Session ]]></content:encoded>
</item>
<item>
<title><![CDATA[Session Id in WCF]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/session-id-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 12:08:11 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/session-id-in-wcf/</guid>
<description><![CDATA[Objective  This article is part # 4 of Instance Management in WCF. This article will explain how to ]]></description>
<content:encoded><![CDATA[Objective  This article is part # 4 of Instance Management in WCF. This article will explain how to ]]></content:encoded>
</item>
<item>
<title><![CDATA[Single Instance Management in WCF]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/single-instance-management-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 11:37:51 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/single-instance-management-in-wcf/</guid>
<description><![CDATA[Objective This article is part # 3 of Instance Management in WCF. This article will explain about Si]]></description>
<content:encoded><![CDATA[Objective This article is part # 3 of Instance Management in WCF. This article will explain about Si]]></content:encoded>
</item>
<item>
<title><![CDATA[Streaming in WCF ]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/streaming-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 11:16:54 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/streaming-in-wcf/</guid>
<description><![CDATA[Objective In this article, I am going to explain various aspects of streaming of messages in WCF. Fo]]></description>
<content:encoded><![CDATA[Objective In this article, I am going to explain various aspects of streaming of messages in WCF. Fo]]></content:encoded>
</item>
<item>
<title><![CDATA[Data Transfer in WCF ]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/data-transfer-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 11:03:08 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/data-transfer-in-wcf/</guid>
<description><![CDATA[Objective I have seen on web many people talking about, how to deal with DTO classes and business cl]]></description>
<content:encoded><![CDATA[Objective I have seen on web many people talking about, how to deal with DTO classes and business cl]]></content:encoded>
</item>
<item>
<title><![CDATA[Transport level Security in WCF]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/transport-level-security-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 10:06:37 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/transport-level-security-in-wcf/</guid>
<description><![CDATA[Objective  This article will give a very brief introduction of transport level security in WCF When ]]></description>
<content:encoded><![CDATA[Objective  This article will give a very brief introduction of transport level security in WCF When ]]></content:encoded>
</item>
<item>
<title><![CDATA[Data Contract Hierarchy in WCF]]></title>
<link>http://dhananjay25.wordpress.com/2009/11/28/data-contract-hierarchy-in-wcf/</link>
<pubDate>Sat, 28 Nov 2009 09:33:37 +0000</pubDate>
<dc:creator>Dhananjay Kumar</dc:creator>
<guid>http://dhananjay25.wordpress.com/2009/11/28/data-contract-hierarchy-in-wcf/</guid>
<description><![CDATA[Objective  This article will explain Data Contract hierarchy How base class and sub class are gettin]]></description>
<content:encoded><![CDATA[Objective  This article will explain Data Contract hierarchy How base class and sub class are gettin]]></content:encoded>
</item>
<item>
<title><![CDATA[Refrescando WCF]]></title>
<link>http://davidlinan.wordpress.com/2009/11/27/refrescando-wcf/</link>
<pubDate>Fri, 27 Nov 2009 11:24:27 +0000</pubDate>
<dc:creator>David Liñán</dc:creator>
<guid>http://davidlinan.wordpress.com/2009/11/27/refrescando-wcf/</guid>
<description><![CDATA[WCF es una tecnología que no debe tomarse a la ligera, por una buena razón: es demasiado útil. Permi]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>WCF es una tecnología que no debe tomarse a la ligera, por una buena razón: es demasiado útil. Permite desarrollar aplicaciones distribuidas de forma relativamente fácil. En este post crearemos una aplicación WCF muy básica.</p>
<p>Como cualquier aplicación basada en servicios, la finalidad de un servicio WCF es permitir la ejecución de sus métodos (posiblemente devolviendo resultados) a aplicaciones cliente, las cuales pueden estar corriendo en otras máquinas. La estructura básica de un servicio es simple y consta de dos partes: un contrato de servicio y el servicio propiamente dicho.</p>
<h4>Contratos de servicio y de datos</h4>
<p>El contrato de servicio es en realidad un interfaz con algunos métodos que habrá que implementar más tarde en la clase del servicio. Este interfaz tiene la particularidad de estar decorado con atributos.</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;

namespace Acme.Contracts
{
 [ServiceContract]
 public interface ITestService
 {
 [OperationContract]
 UserData getUserData(int userId);
 }
}
</pre>
<p>El atributo <em>ServiceContract</em> indica que el interfaz es un contrato de servicio WCF, mientras que <em>OperationContract</em> indica que la operación está expuesta como parte del servicio. Estos atributos están definidos en el ensamblado <em>System.ServiceModel</em>, de modo que es necesario tenerlo referenciado.</p>
<p>Adicionalmente el servicio puede requerir contratos de datos. Se trata de tipos definidos (clases, tipos enumerados, estructuras&#8230;) para el intercambio de datos con los clientes. También están decorados con atributos especiales:</p>
<pre class="brush: csharp;">
using System;
using System.Runtime.Serialization;

namespace Acme.Contracts
{
 [DataContract]
 public class UserData
 {
 [DataMember]
 public int userId { get; set; }

 [DataMember]
 public string userName { get; set; }
 }
}
</pre>
<p>El atributo <em>DataContract</em> indica que la clase es un contrato de datos WCF y  <em>DataMember</em> que la propiedad a la que se aplica es un miembro de datos expuesto. Ambos están definidos en el ensamblado <em>System.Runtime.Serialization</em>, que debe estar referenciado.</p>
<p>Lo más práctico es poner los contratos en un ensamblado aparte, a fin de facilitar el posterior mantenimiento. Para ello hay dos opciones:</p>
<ul>
<li>Crear un nuevo proyecto de librería de servicios WCF (y posteriormente eliminar el fichero de configuración y de servicio creados por el asistente).</li>
<li>Crear un nuevo proyecto de librería de clases y agregar manualmente referencias a los ensamblados  <em>System.ServiceModel</em> y (de ser necesario) <em>System.Runtime.Serialization</em>.</li>
</ul>
<h4>Implementar el servicio</h4>
<p>El servicio WCF es una clase que implementa el contrato de servicio correspondiente. No se ejecuta por sí solo, sino que debe ser hospedado por otra aplicación cuyo tipo dependerá de los requerimientos de nuestra solución. Por ejemplo, un servicio de Windows es lo más apropiado para una ejecución desatendida del servicio.</p>
<pre class="brush: csharp;">
using System;
using Acme.Contracts;

namespace Acme.Services
{
 public class TestService : ITestService
 {
 public UserData getUserData(int userId)
 {
 if (userId == 1)
 {
 UserData data = new UserData() { userId = 1, userName = &#34;David Liñán&#34; };
 return data;
 }
 else
 return null;
 }
 }
}
</pre>
<p>El servicio debería estar en un ensamblado aparte si se pretende que pueda ser hospedado por distintos tipos de aplicación. De lo contrario podría incluirse en el propio proyecto de la aplicación contenedora como una clase más.</p>
<h4>Hospedar el servicio</h4>
<p>La aplicación contenedora puede ser casi de cualquier tipo: una aplicación Winforms, un servicio de Windows, una aplicación de consola, incluso podría ser IIS. En cualquier caso, es necesaria una referencia a <em>System.ServiceModel</em> y otra al ensamblado del servicio (si es que reside en otro distinto).</p>
<p>La forma más fácil de hospedar el servicio es usando la clase <em>ServiceHost</em>, definida en <em>System.ServiceModel</em>. Los métodos a usar invariablemente son <em>Open()</em> y <em>Close()</em>, para arrancar y detener el servicio.</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;

namespace Acme.Services
{
 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 ServiceHost sHost = new ServiceHost(typeof(TestService));
 sHost.Open();
 Console.WriteLine(&#34;Cualquier tecla para finalizar...&#34;);
 Console.Read();
 sHost.Close();
 }
 catch (Exception ex)
 {
 Console.WriteLine(&#34;Excepción inesperada: &#34; + ex.Message);
 }
 }
 }
}
</pre>
<p>Además<em></em> de esta forma se toman automáticamente los datos de configuración del servicio, que deben estar en en fichero de configuración de la aplicación contenedora. En nuestro ejemplo es el siguiente:</p>
<pre class="brush: csharp;">
&#60;configuration&#62;
 &#60;system.serviceModel&#62;
 &#60;services&#62;
 &#60;service name=&#34;Acme.Services.TestService&#34;&#62;
 &#60;endpoint name=&#34;testEndpoint&#34;
 address=&#34;net.tcp://localhost:7000/TestService&#34;
 binding=&#34;netTcpBinding&#34;
 contract=&#34;Acme.Contracts.ITestService&#34; /&#62;
 &#60;/service&#62;
 &#60;/services&#62;
 &#60;/system.serviceModel&#62;
&#60;/configuration&#62;
</pre>
<p>En este fichero cada servicio viene identificado por su nombre completo, incluyendo su espacio de nombres (<em>Acme.Services.TestService</em>). Adicionalmente hacen falta tres datos: una dirección (<em>net.tcp://localhost:7000/TestService</em>), el tipo de canal a usar (en nuestro caso es TCP, indicado por <em>netTcpBinding</em>) y el nombre completo del contrato.</p>
<h4>Implementar el cliente</h4>
<p>Una aplicación cliente necesita conocer tres cosas de un servicio: su contrato, su dirección y el tipo de canal a usar. La primera la obtenemos añadiendo una referencia al ensamblado del contrato. Las otras dos las podemos definir en el fichero de configuración de la aplicación cliente y sus valores deben coincidir con los definidos en el fichero de configuración del servicio (para ser exactos, de la aplicación que lo hospeda). El cliente debe tener además una referencia a <em>System.ServiceModel</em>.</p>
<pre class="brush: csharp;">
&#60;configuration&#62;
 &#60;system.serviceModel&#62;
 &#60;client&#62;
 &#60;endpoint name=&#34;testEndpoint&#34;
 address=&#34;net.tcp://localhost:7000/Testservice&#34;
 binding=&#34;netTcpBinding&#34;
 contract=&#34;Acme.Contracts.ITestService&#34; /&#62;
 &#60;/client&#62;
 &#60;/system.serviceModel&#62;
&#60;/configuration&#62;
</pre>
<p>La clase <em>ChannelFactory</em> (en <em>System.ServiceModel</em>) nos permite crear un proxy para invocar a los métodos del servicio desde el cliente. El nombre del endPoint a usar viene definido en el fichero de configuración del cliente.</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;
using Acme.Contracts;

namespace Acme.Clients
{
 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 // Inicia la comunicación
 ChannelFactory&#60;ITestService&#62; factory = new ChannelFactory&#60;ITestService&#62;(&#34;testEndpoint&#34;);
 factory.Open();
 ITestService proxy = factory.CreateChannel();
 // Invocando métodos del servicio
 bool fin = false;
 while (!fin) {
 Console.Write(&#34;Introduzca un id de usuario o &#60;Intro&#62; para terminar:&#34;);
 string sUserId = Console.ReadLine();
 int userId;
 if (!Int32.TryParse(sUserId, out userId) )
 {
 fin=true;
 }
 else
 {
 UserData userData = proxy.getUserData(userId);
 if (userData == null)
 Console.WriteLine(&#34;Usuario no encontrado&#34;);
 else
 Console.WriteLine(&#34;Usuario: &#34; + userData.userName);
 }
 }
 // Finaliza la comunicación
 factory.Close();
 }
 catch (Exception ex)
 {
 Console.WriteLine(&#34;Excepción no esperada: &#34; + ex.Message);
 }
 }
 }
}
</pre>
<h4>Aplicación de ejemplo</h4>
<p>Consiste en una solución con tres proyectos:</p>
<ul>
<li>una librería de clases que contiene los contrato de servicio y de datos</li>
<li>una aplicación de consola que hospeda al servicio, implementado como parte de ella</li>
<li>y una aplicación de consola para invocar al servicio</li>
</ul>
<p>Aviso: durante la ejecución es posible que aparezca el siguiente error:</p>
<p>&#8220;The target assembly contains no service types. You may need to adjust the Code Access Security policy of this assembly&#8221;</p>
<p>Esto puede ser debido a que hayamos creado un proyecto separado para el contrato de servicio. Si lo hemos hecho mediante la plantilla de proyecto WCF Library tenemos que borrar de ese proyecto el fichero de configuración (de todas formas no tendría sentido dejarlo ahí).</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Workshop: WPF &amp; WCF]]></title>
<link>http://arkcore.wordpress.com/2009/11/26/workshop-wpf-wcf-2/</link>
<pubDate>Thu, 26 Nov 2009 20:20:41 +0000</pubDate>
<dc:creator>Danijel Malik</dc:creator>
<guid>http://arkcore.wordpress.com/2009/11/26/workshop-wpf-wcf-2/</guid>
<description><![CDATA[After a few busy weeks (Mondays and Thursdays) our workshop has reached the end. I hope that guys wh]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>After a few busy weeks (Mondays and Thursdays) our workshop has reached the end. I hope that guys who had attended this workshop had some joy and got some knowledge/experience with these technologies <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I’d be glad to repeat it, but there are some other interesting areas to cover, so keep reading my blog to find out when’s the next workshop.</p>
<p>Best wishes!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SharePoint 2010 Beta - ConfigurationErrorsException]]></title>
<link>http://techpunch.wordpress.com/2009/11/26/sharepoint-2010-beta-configurationerrorsexception/</link>
<pubDate>Thu, 26 Nov 2009 14:47:58 +0000</pubDate>
<dc:creator>Stuart</dc:creator>
<guid>http://techpunch.wordpress.com/2009/11/26/sharepoint-2010-beta-configurationerrorsexception/</guid>
<description><![CDATA[If you&#8217;ve installed the SharePoint 2010 public beta, you&#8217;ve likely run into the WCF bug.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>If you&#8217;ve installed the SharePoint 2010 public beta, you&#8217;ve likely run into the WCF bug. This following errors occur when provisioning Service Applications or when accessing pages that make service calls. <strong></strong></p>
<p>System.Configuration.ConfigurationErrorsException: Unrecognized attribute &#8216;allowInsecureTransport&#8217;. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\&#60;Service Area&#62;\client.config line &#60;Line Number&#62;).</p>
<p>The service application proxy &#8220;User Profile Service Application&#8221; could not be provisioned because of the following error: Unrecognized attribute &#8216;allowInsecureTransport&#8217;. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56).</p>
<p>You may see this error in the ULS logs after installing SharePoint 2010, or displayed on the page as an error message when provisioning service applications or accessing SharePoint pages that make WCF service calls.</p>
<h4>How To Fix It</h4>
<p>This is a known WCF issue when installing SharePoint 2010 on Windows 7, Windows Server 2008, or Windows Server 2008 R2.  It’s, lovingly called the WCF Sharepoint Shared Services Roll-up issue. To fix it, install a WCF OS patch:</p>
<p>KB971831: WCF fix for Windows Server 2008 and Vista only<br />
<a href="http://support.microsoft.com/kb/971831">http://support.microsoft.com/kb/971831</a></p>
<p>KB976462: WCF fix for Windows 2008 R2 and Windows 7<br />
<a href="http://support.microsoft.com/kb/976462">http://support.microsoft.com/kb/976462</a> <br />
Note:  This link is not activated yet, but you can download the WCF fix at <a href="http://go.microsoft.com/fwlink/?LinkID=166231">http://go.microsoft.com/fwlink/?LinkID=166231</a></p>
<p>If you have already installed Microsoft SharePoint Server 2010 on a server running Microsoft Windows Server 2008 R2 or Microsoft Windows 7, Microsoft SharePoint Server 2010 does not need to be reinstalled. You can install the WCF fix afterward. However, Service Applications that have been provisioned without the update installed may need to be removed and re-provisioned once the update has been successfully applied.</p>
<h4>References</h4>
<p><a href="http://blogs.msdn.com/sharepoint/archive/2009/11/19/installation-notice-for-the-sharepoint-server-public-beta-on-microsoft-windows-server-2008-r2-and-microsoft-windows-7.aspx" target="_blank">SharePoint Team Blog: Installation Notice for the SharePoint Server Public Beta on Microsoft Windows Server 2008 R2 and Microsoft Windows 7</a></p>
<p><a href="http://blogs.msdn.com/opal/archive/2009/10/25/sharepoint-2010-pre-requisites-download-links.aspx" target="_blank">Jie Lie’s GeekWorld: SharePoint 2010 Pre-Requisites Download Links</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[enabling Async methods for wcf in wpf]]></title>
<link>http://dotnettrails.wordpress.com/2009/11/26/enabling-async-methods-for-wcf-in-wpf/</link>
<pubDate>Thu, 26 Nov 2009 09:08:14 +0000</pubDate>
<dc:creator>dotnettrails</dc:creator>
<guid>http://dotnettrails.wordpress.com/2009/11/26/enabling-async-methods-for-wcf-in-wpf/</guid>
<description><![CDATA[By default when you add a WCF Service reference in WPF, it does not give async functions. If your ap]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>By default when you add a WCF Service reference in WPF, it does not give async functions. If your application needs async features, while adding a reference to the service, lookout for a ‘Advanced’ button on Add service reference window at bottom right corner. On clicking on that button, a new window appears. There is a checkbox called ‘Generate Asynchronous Operations’. Hit Ok and you are done!</p>
<p>Simple isn’t it <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:ba4182f1-2519-4893-a5e2-5d663dcc669b" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/WCF" rel="tag">WCF</a>,<a href="http://technorati.com/tags/WPF" rel="tag">WPF</a>,<a href="http://technorati.com/tags/Enable+Async+Methods" rel="tag">Enable Async Methods</a>,<a href="http://technorati.com/tags/Tweak" rel="tag">Tweak</a>,<a href="http://technorati.com/tags/Configuration" rel="tag">Configuration</a>,<a href="http://technorati.com/tags/Simple+settings" rel="tag">Simple settings</a></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Refrescando WCF: un ejemplo básico]]></title>
<link>http://microcodigos.wordpress.com/2009/11/25/refrescando-wcf-un-ejemplo-basico/</link>
<pubDate>Wed, 25 Nov 2009 17:45:06 +0000</pubDate>
<dc:creator>microcodigos</dc:creator>
<guid>http://microcodigos.wordpress.com/2009/11/25/refrescando-wcf-un-ejemplo-basico/</guid>
<description><![CDATA[WCF es una tecnología que no se debe tomar a la ligera, por una buena razón: es demasiado útil. Perm]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>WCF es una tecnología que no se debe tomar a la ligera, por una buena razón: es demasiado útil. Permite desarrollar aplicaciones distribuidas de forma relativamente fácil, incluso con otras plataformas distintas de .Net. En este post crearemos una aplicación WCF sencilla.</p>
<p>La utilidad de un servicio WCF es permitir la ejecución de sus métodos, posiblemente devolviendo resultados, a aplicaciones cliente que pueden estar corriendo en otras máquinas. La estructura básica de un servicio es simple y consta de dos partes: un contrato de servicio y el servicio propiamente dicho.</p>
<h4>Contratos de servicio y de datos</h4>
<p>El contrato de servicio es realmente un interfaz con una serie de métodos. Estos métodos son los que habrá que implementar más tarde, en la clase del servicio. El atributo <em>ServiceContract</em> determina que el interfaz es un contrato de servicio WCF, mientras que <em>OperationContract</em> determina que la operación está expuesta como parte de ese contrato. Estos atributos están definidos en el ensamblado <em>System.ServiceModel</em>, de modo que es necesario tenerlo referenciado.</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;

namespace Acme.Contracts
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        UserData getUserData(int userId);
    }
}
</pre>
<p>Adicionalmente el servicio puede incluir contratos de datos: se trata de tipos definidos para el intercambio de datos con los clientes (clases, tipos enumerados, estructuras&#8230;). De manera similar, el atributo <em>DataContract</em> determina que la clase es un contrato de datos WCF y <em>DataMember</em> que la propiedad a la que se aplica es un miembro de datos expuesto. Ambos están definidos en el ensamblado <em>System.Runtime.Serialization</em>, que habrá que tener referenciado.</p>
<pre class="brush: csharp;">
using System;
using System.Runtime.Serialization;

namespace Acme.Contracts
{
    [DataContract]
    public class UserData
    {
        [DataMember]
        public int userId { get; set; }

        [DataMember]
        public string userName { get; set; }
    }
}
</pre>
<p>Lo más práctico es poner los contratos en un ensamblado separado, a fin de facilitar el posterior mantenimiento. Para ello hay dos opciones:</p>
<ul>
<li>Crear un nuevo proyecto de librería de servicios WCF (y posteriormente eliminar el fichero de configuración y de servicio creados por el asistente).</li>
<li>Crear un nuevo proyecto de librería de clases y agregar manualmente referencias a los ensamblados  <em>System.ServiceModel</em> y (de ser necesario) <em>System.Runtime.Serialization</em>.</li>
</ul>
<h4>Implementar el servicio</h4>
<p>Un servicio WCF es simplemente una clase que implementa el contrato de servicio correspondiente. Y no se ejecuta por sí solo, sino que debe ser hospedado por otra aplicación cuyo tipo dependerá de los requerimientos de nuestra solución. Por ejemplo, un servicio de Windows es lo más apropiado para una ejecución desatendida.</p>
<pre class="brush: csharp;">
using System;
using Acme.Contracts;

namespace Acme.Services
{
    public class TestService : ITestService
    {
        public UserData getUserData(int userId)
        {
            if (userId == 1)
            {
                UserData data = new UserData() { userId = 1, userName = &#34;David Liñán&#34; };
                return data;
            }
            else
                return null;
        }
    }
}
</pre>
<p>El servicio también debería estar en un ensamblado aparte si se pretende que pueda ser hospedado por distintos tipos de aplicación. Si no, puede incluirse en el propio proyecto de la aplicación que lo hospeda como una clase más.</p>
<h4>Hospedar el servicio</h4>
<p>La aplicación contenedora puede ser casi de cualquier tipo: una aplicación Winforms, un servicio de Windows, una aplicación de consola&#8230; También se puede hospedar bajo IIS. En el ejemplo lo haremos en una aplicación de consola que al arrancar hará lo propio con el servicio. Es necesario tener una referencia a <em>System.ServiceModel</em> y otra al ensamblado del servicio (si es que reside en otro distinto).</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;

namespace Acme.Services
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ServiceHost sHost = new ServiceHost(typeof(TestService));
                sHost.Open();
                Console.WriteLine(&#34;Cualquier tecla para finalizar...&#34;);
                Console.Read();
                sHost.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(&#34;Excepción inesperada: &#34; + ex.Message);
            }
        }
    }
}
</pre>
<p>La forma más fácil de hospedar el servicio es usando la clase ServiceHost, definida en System.ServiceModel. Los métodos a usar invariablemente se Open() y Close(), para arrancar y detener el servicio. Además esta clase toma automáticamente los datos de configuración del servicio, que deben estar en en fichero de configuración de la aplicación contenedora. En nuestro ejemplo es el siguiente:</p>
<pre class="brush: csharp;">
&#60;configuration&#62;
  &#60;system.serviceModel&#62;
    &#60;services&#62;
      &#60;service name=&#34;Acme.Services.TestService&#34;&#62;
        &#60;endpoint name=&#34;testEndpoint&#34;
                  address=&#34;net.tcp://localhost:7000/TestService&#34;
                  binding=&#34;netTcpBinding&#34;
                  contract=&#34;Acme.Contracts.ITestService&#34; /&#62;
      &#60;/service&#62;
    &#60;/services&#62;
  &#60;/system.serviceModel&#62;
&#60;/configuration&#62;
</pre>
<p>Cada servicio viene identificado por su nombre completo, incluyendo su espacio de nombres (<em>Acme.Services.TestService</em>). Adicionalmente hacen falta tres datos: una dirección (<em>net.tcp://localhost:7000/TestService</em>), el tipo de canal a usar (en nuestro caso es TCP, definido por <em>netTcpBinding</em>) y el contrato (su nombre completo, incluyendo el espacio de nombres).</p>
<p>El proyecto que define los contratos debe ser una librería de clases y debe referenciar System.ServiceModel para usar los atributos ServiceContract, OperationContract, etc.. Los contratos de datos requieren además de System.Runtime.Serialization.</p>
<h4>El cliente</h4>
<p>La aplicación cliente necesita conocer tres cosas del servicio: su contrato, su dirección y el tipo de canal a usar. La primera la obtenemos añadiendo una referencia al ensamblado del contrato. Las otras dos las podemos definir en el fichero de configuración de la aplicación cliente y sus valores deben coincidir con los definidos en el fichero de configuración del servicio (para ser exactos, de la aplicación que lo hospeda). El cliente debe tener además una referencia a <em>System.ServiceModel</em> y también al ensamblado que contiene el contrato de servicio.</p>
<pre class="brush: csharp;">
using System;
using System.ServiceModel;
using Acme.Contracts;

namespace Acme.Clients
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Inicia la comunicación
                ChannelFactory&#60;ITestService&#62; factory = new ChannelFactory&#60;ITestService&#62;(&#34;testEndpoint&#34;);
                factory.Open();
                ITestService proxy = factory.CreateChannel();
                // Invocando métodos del servicio
                bool fin = false;
                while (!fin) {
                    Console.Write(&#34;Introduzca un id de usuario o &#60;Intro&#62; para terminar:&#34;);
                    string sUserId = Console.ReadLine();
                    int userId;
                    if (!Int32.TryParse(sUserId, out userId) )
                    {
                        fin=true;
                    }
                    else
                    {
                        UserData userData = proxy.getUserData(userId);
                        if (userData == null)
                            Console.WriteLine(&#34;Usuario no encontrado&#34;);
                        else
                            Console.WriteLine(&#34;Usuario: &#34; + userData.userName);
                    }
                }
                // Finaliza la comunicación
                factory.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(&#34;Excepción no esperada: &#34; + ex.Message);
            }
        }
    }
}
</pre>
<p>La clase <em>ChannelFactory</em> (en <em>System.ServiceModel</em>) nos permite crear un proxy para invocar a los métodos del servicio desde el cliente. El nombre del endPoint a usar viene definido en el fichero de configuración del cliente:</p>
<pre class="brush: csharp;">
&#60;configuration&#62;
  &#60;system.serviceModel&#62;
    &#60;client&#62;
      &#60;endpoint name=&#34;testEndpoint&#34;
                address=&#34;net.tcp://localhost:7000/Testservice&#34;
                binding=&#34;netTcpBinding&#34;
                contract=&#34;Acme.Contracts.ITestService&#34; /&#62;
    &#60;/client&#62;
  &#60;/system.serviceModel&#62;
&#60;/configuration&#62;
</pre>
<h4>Aplicación de ejemplo</h4>
<p>Consiste en una solución con tres proyectos:</p>
<ul>
<li>una librería de clases que contiene los contrato de servicio y de datos,</li>
<li>una aplicación de consola que hospeda al servicio, implementado como parte de ella,</li>
<li>y una aplicación de consola para invocar al servicio.</li>
</ul>
<div id="attachment_29" class="wp-caption aligncenter" style="width: 687px"><a href="http://microcodigos.wordpress.com/files/2009/11/ejecutando-el-cliente.png"><img class="size-full wp-image-29" title="Ejecutando el cliente" src="http://microcodigos.wordpress.com/files/2009/11/ejecutando-el-cliente.png" alt="" width="677" height="342" /></a><p class="wp-caption-text">Ejecutando el cliente</p></div>
<p>Aviso: durante la ejecución es posible que aparezca el siguiente error:</p>
<p>&#8220;The target assembly contains no service types. You may need to adjust the Code Access Security policy of this assembly&#8221;</p>
<p>Esto puede ser debido a que hayamos creado un proyecto separado para el contrato de servicio. Si lo hemos hecho mediante la plantilla de proyecto WCF Library tenemos que borrar de ese proyecto el fichero de configuración (de todas formas no tendría sentido dejarlo ahí).</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using JSONP with WCF and jQuery]]></title>
<link>http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/</link>
<pubDate>Tue, 24 Nov 2009 15:31:22 +0000</pubDate>
<dc:creator>bendewey</dc:creator>
<guid>http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/</guid>
<description><![CDATA[In the new release of .NET 4, the WCF team has added support for JSONP.  There are many resource out]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In the new release of .NET 4, the WCF team has added support for <a href="http://en.wikipedia.org/wiki/JSON#JSONP">JSONP</a>.  There are many resource out on the internet about the need for JSONP, if you are reading this article I&#8217;m assuming your familar with the concept of JSONP.  Essentially, JSONP utilitzes the &#60;script /&#62; tag as a work around to the cross domain access limitations of web browsers.  This new feature is exposed as an CrossDomainScriptAccessEnabled setting on the WebHttpBinding, and as such is configurable through code or through configuration.</p>
<h3>Download</h3>
<p>The full source code is available for download from my website</p>
<ul>
<li><a href="http://www.bendewey.com/code/JsonpWithWcfAndJquery.zip" target="_blank">JsonpWithWcfAndJquery.zip (46kb)</a></li>
</ul>
<p>This code requires the latest download of <a href="msdn.microsoft.com/en-us/vstudio/dd582936.aspx" target="_blank">.NET 4 Beta 2 with Visual Studio 2010</a></p>
<h3>Example</h3>
<p>In this example we are returning a list of sample customers.  In a standard JSON service using the WebHttpBinding you would recieve this result:</p>
<p><a href="http://localhost:65025/CustomersService.svc/GetCustomers">http://localhost:65025/CustomersService.svc/GetCustomers</a></p>
<pre class="brush: jscript;">
[{&#34;Email&#34;:&#34;bob@example.com&#34;,&#34;Name&#34;:&#34;Bob&#34;},
{&#34;Email&#34;:&#34;mark@example.com&#34;,&#34;Name&#34;:&#34;Mark&#34;},
{&#34;Email&#34;:&#34;john@example.com&#34;,&#34;Name&#34;:&#34;John&#34;}]
</pre>
<p>Now using the same service you can supply the optional callback parameter like this <a href="http://localhost:65025/CustomersService.svc/GetCustomers">http://localhost:65025/CustomersService.svc/GetCustomers?callback=JsonpCallback</a>, which would return the results as the first argument to a function call with a name equal to the one supplied in the query parameter.</p>
<pre class="brush: jscript;">
JsonpCallback([{&#34;Email&#34;:&#34;bob@example.com&#34;,&#34;Name&#34;:&#34;Bob&#34;},
{&#34;Email&#34;:&#34;mark@example.com&#34;,&#34;Name&#34;:&#34;Mark&#34;},
{&#34;Email&#34;:&#34;john@example.com&#34;,&#34;Name&#34;:&#34;John&#34;}])</pre>
<p>So, if you have a javascript function setup on the page, the function will be called successfully without violating the cross-site scripting exceptions.</p>
<pre class="brush: jscript;">

function JsonpCallback(customers) {
     alert(cutomers.length);
}
</pre>
<h3>WCF Service with CrossDomainScriptAccessEnabled</h3>
<p>Creating the WCF Service with CrossDomainScriptAccessEnabled is the same as it would be for any other web enabled WCF service.  In our example we are exposing a simple CustomersService</p>
<pre class="brush: csharp;">
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomersService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List GetCustomers()
    {
        return Customer.GetSampleData().ToList();
    }
}</pre>
<p>The new JSONP feature is exposed via the WebHttpBinding.  The configuration for the CustomersService would looks like this:</p>
<pre class="brush: xml;">
&#60;system.serviceModel&#62;
  &#60;behaviors&#62;
    &#60;endpointBehaviors&#62;
      &#60;behavior name=&#34;webHttpBehavior&#34;&#62;
        &#60;webHttp /&#62;
      &#60;/behavior&#62;
    &#60;/endpointBehaviors&#62;
  &#60;/behaviors&#62;
  &#60;bindings&#62;
    &#60;webHttpBinding&#62;
      &#60;binding name=&#34;webHttpBindingWithJsonP&#34; crossDomainScriptAccessEnabled=&#34;true&#34; /&#62;
    &#60;/webHttpBinding&#62;
  &#60;/bindings&#62;
  &#60;services&#62;
    &#60;service name=&#34;ServiceSite.CustomersService&#34;&#62;
      &#60;endpoint address=&#34;&#34; binding=&#34;webHttpBinding&#34;
                bindingConfiguration=&#34;webHttpBindingWithJsonP&#34;
                contract=&#34;ServiceSite.CustomersService&#34;
                behaviorConfiguration=&#34;webHttpBehavior&#34;/&#62;
    &#60;/service&#62;
  &#60;/services&#62;
&#60;/system.serviceModel&#62;</pre>
<p>Notice that we&#8217;ve created a new bindingConfiguration for webHttpBindingWithJsonP, in this new binding configuration we&#8217;ve set the new property of crossDomainScriptAccessEnabled to true.  This enables the new callback parameter and under the covers attaches the JavascriptCallbackMessageInspector.  I&#8217;ve choosen to explicitly setup my binding configuration, but it should be noted that .NET 4 has created default configuration features, a sample of this is available for download with the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=35ec8682-d5fd-4bc3-a51a-d8ad115a8792&#38;displaylang=en" target="_blank">WCF Samples for .NET 4 Beta2</a>.</p>
<h3>Consuming JSONP with jQuery</h3>
<p>Now, consuming this JSONP endpoint with jQuery couldn&#8217;t be easier.  jQuery ships with an <a href="http://docs.jquery.com/Ajax/jQuery.ajax" target="_blank">ajax</a> convenience function called <a href="http://docs.jquery.com/Ajax/jQuery.getJSON" target="_blank">getJSON</a> that accepts a url, data, and a callback function.  In the url property you can provide a ? following a query parameter and the ajax function will replace it with a dynamic function to handle the JSONP callback.  With that being said this is what the code to access the customers would look like.</p>
<pre class="brush: jscript;">
// Get the JsonP data
$.getJSON('http://localhost:65025/CustomersService.svc/GetCustomers?callback=?', null, function (customers) {
    alert('Received ' + customers.length + ' Customers');
});</pre>
<h3>Conclusion</h3>
<p>Many of the code samples above use an abridged version of the code in the sample, so for more detail you should download the source code above.  Additionally this article and samples are based on the .NET 4 Beta 2 product.  I&#8217;ll do my best to update the code and ensure everything is in order with the official release.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Programming WCF services]]></title>
<link>http://dennisv.net/2009/11/24/programming-wcf-services/</link>
<pubDate>Tue, 24 Nov 2009 11:43:02 +0000</pubDate>
<dc:creator>dennisv</dc:creator>
<guid>http://dennisv.net/2009/11/24/programming-wcf-services/</guid>
<description><![CDATA[The last few days i&#8217;ve been reading the book &#8220;Programming WCF Services&#8221; by Juval L]]></description>
<content:encoded><![CDATA[The last few days i&#8217;ve been reading the book &#8220;Programming WCF Services&#8221; by Juval L]]></content:encoded>
</item>
<item>
<title><![CDATA[if you need to send more data to wcf service]]></title>
<link>http://dotnettrails.wordpress.com/2009/11/24/if-you-need-to-send-more-data-to-wcf-service/</link>
<pubDate>Tue, 24 Nov 2009 09:01:55 +0000</pubDate>
<dc:creator>dotnettrails</dc:creator>
<guid>http://dotnettrails.wordpress.com/2009/11/24/if-you-need-to-send-more-data-to-wcf-service/</guid>
<description><![CDATA[For example, you need to upload log file in case of error from desktop application to remote site us]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>For example, you need to upload log file in case of error from desktop application to remote site using WCF service and if the log file is too big, you might have to tweak your WCF service’s Web.config.</p>
<p>By default the configuration for the service will be </p>
<p>&#160;&#160;&#160;&#160;&#160; &#60;services&#62;   <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;service behaviorConfiguration=&#34;ServiceBehavior&#34; name=&#34;Service&#34;&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;endpoint address=&#34;&#34; binding=&#34;basicHttpBinding&#34; contract=&#34;IService&#34;&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/endpoint&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;endpoint address=&#34;mex&#34; binding=&#34;mexHttpBinding&#34; contract=&#34;IMetadataExchange&#34;/&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/service&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/services&#62;</p>
<p>You need to specify the binding manually and add binding reference as highlighted below.&#160;&#160;&#160; </p>
<p>&#160;</p>
<p>&#160;&#160;&#160; &#60;services&#62;   <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;service behaviorConfiguration=&#34;ServiceBehavior&#34; name=&#34;Service&#34;&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;endpoint address=&#34;&#34; binding=&#34;basicHttpBinding&#34; <strong>bindingConfiguration=&#34;BasicHttpBinding_IService&#34;</strong> contract=&#34;IService&#34;&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/endpoint&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;endpoint address=&#34;mex&#34; binding=&#34;mexHttpBinding&#34; contract=&#34;IMetadataExchange&#34;/&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/service&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/services&#62;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <strong>&#60;bindings&#62;     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;basicHttpBinding&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;binding name=&#34;BasicHttpBinding_IService&#34; closeTimeout=&#34;00:01:00&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; openTimeout=&#34;00:01:00&#34; receiveTimeout=&#34;00:10:00&#34; sendTimeout=&#34;00:01:00&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; allowCookies=&#34;false&#34; bypassProxyOnLocal=&#34;false&#34; hostNameComparisonMode=&#34;StrongWildcard&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; maxBufferSize=&#34;2147483647&#34; maxBufferPoolSize=&#34;2147483647&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; maxReceivedMessageSize=&#34;2147483647&#34; messageEncoding=&#34;Text&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; textEncoding=&#34;utf-8&#34; transferMode=&#34;Buffered&#34; useDefaultWebProxy=&#34;true&#34;&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;readerQuotas maxDepth=&#34;32&#34; maxStringContentLength=&#34;2147483647&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; maxArrayLength=&#34;2147483647&#34; maxBytesPerRead=&#34;4096&#34; maxNameTableCharCount=&#34;16384&#34; /&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;security mode=&#34;None&#34;&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;transport clientCredentialType=&#34;None&#34; proxyCredentialType=&#34;None&#34;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; realm=&#34;&#34; /&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;message clientCredentialType=&#34;UserName&#34; algorithmSuite=&#34;Default&#34; /&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/security&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/binding&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/basicHttpBinding&#62;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;/bindings&#62;</strong></p>
<p>That&#8217;s it <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Simple isn’t it?</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:7882d4ef-1a1a-40c1-8c73-223623e744a1" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/C%23" rel="tag">C#</a>,<a href="http://technorati.com/tags/WCF" rel="tag">WCF</a>,<a href="http://technorati.com/tags/Handle+More+Data" rel="tag">Handle More Data</a>,<a href="http://technorati.com/tags/web.config" rel="tag">web.config</a>,<a href="http://technorati.com/tags/binding" rel="tag">binding</a>,<a href="http://technorati.com/tags/Service" rel="tag">Service</a>,<a href="http://technorati.com/tags/Buffersize" rel="tag">Buffersize</a>,<a href="http://technorati.com/tags/Tweak" rel="tag">Tweak</a></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[WCF - next generation platform for distributed applications]]></title>
<link>http://aspnettutorial.wordpress.com/2009/11/22/wcf-next-generation-platform-for-distributed-applications/</link>
<pubDate>Mon, 23 Nov 2009 01:08:58 +0000</pubDate>
<dc:creator>aspnettutorial</dc:creator>
<guid>http://aspnettutorial.wordpress.com/2009/11/22/wcf-next-generation-platform-for-distributed-applications/</guid>
<description><![CDATA[This is a series of articles where we will look how to develop WCF based service development and its]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong><em>This is a series of articles where we will look how to develop WCF based service development and its hosting.</em></strong></p>
<p>Service based applications changed the development practices. Service oriented architecture provided a new way to look at the application development and took it one step ahead in development world.</p>
<p>Web service and Simple Object Access Protocol (SOAP) has made data transmission between different applications very easy without worrying about underlying architecture and platform detail. SOAP architecture provides good platform for secured data transmission over HTTP with that said, if you have to develop an application that is going to run over TCP then you would have to determine and develop application that is going to support that kind of network.</p>
<p>Windows Communication Foundation (WCF) supports various protocols like TCP/IP, HTTP and even Peer networking using mesh network topology. In other words, WCF contains everything that modern service oriented application need.</p>
<p>Lets start with some basic ABC of WCF:</p>
<p>ABC of WCF: <strong>A</strong>ddress, <strong>B</strong>inding, <strong>C</strong>ontract.</p>
<p>Address: is the location. It defines endpoint where the message should be sent by the client like: <a class="linkification-ext" title="Linkification: http://www.example.com/service1/" href="http://www.example.com/service1/">http://www.example.com/service1/</a></p>
<p>Binding: is channel. It defines the way by which messages will pass over the network like: TCP,HTTP or Named Pipes etc.</p>
<p>Contract: is methods or features. It defines what all methods or functions are available for client to use. It also defines message format.</p>
<p><strong>Lets build our first WCF application:</strong></p>
<p>1) Create new project in Visual Studio 2008 by selecting: File-&#62;New-&#62;Project -&#62; Visual C# -&#62; WCF -&#62; WCF Service Library.</p>
<p>2) Visual Studio will create a number of files for you automatically, at this point as we are building our first application so we will not go into the detail of those files but there are two files we are interested in: IService1.cs and Service1.cs as shown:</p>
<p><a href="http://aspnettutorial.wordpress.com/files/2009/11/12.png"><img class="aligncenter size-full wp-image-37" title="1" src="http://aspnettutorial.wordpress.com/files/2009/11/12.png" alt="" width="213" height="119" /></a></p>
<p>3) IService1.cs is the interface that will define method that will be accessible to the client.</p>
<p>4) Replace your interface IService1 with the code below:</p>
<p><strong>[ServiceContract]<br />
public interface IService1<br />
{<br />
[OperationContract]<br />
string GetProduct(int productID);<br />
}</strong></p>
<p><a href="http://aspnettutorial.wordpress.com/files/2009/11/24.png"><img class="aligncenter size-medium wp-image-40" title="2" src="http://aspnettutorial.wordpress.com/files/2009/11/24.png?w=300" alt="" width="300" height="169" /></a></p>
<p>4) Now its time to implement our interface. I have created a conditional branch to return results in my code.</p>
<p>5) Save all changes in IService1.cs and open Service1.cs to implement the interface. Replace code of Service1.cs from the code below:</p>
<p><strong>public class Service1 : IService1<br />
{<br />
private string result;</p>
<p>#region IService1 Members</p>
<p>public string GetProduct(int productID)<br />
{</p>
<p>switch (productID)<br />
{<br />
case 1:<br />
result= string.Format(&#8220;Chai has ProductID: {0}&#8221;, productID);<br />
break;</p>
<p>case 2:<br />
result = string.Format(&#8220;Coffee has ProductID: {0}&#8221;, productID);<br />
break;</p>
<p>default:<br />
result = string.Format(&#8220;Invalid entry: {0}&#8221;, productID);<br />
break;<br />
}<br />
return result;<br />
}</p>
<p>#endregion<br />
}</strong></p>
<p><a href="http://aspnettutorial.wordpress.com/files/2009/11/3.png"><img class="aligncenter size-medium wp-image-39" title="3" src="http://aspnettutorial.wordpress.com/files/2009/11/3.png?w=300" alt="" width="300" height="232" /></a></p>
<p>6) Now its time to run the application. Run your application this will bring up WCF Test Client which is an internal hosting environment from VS2008.</p>
<p>7) Double click on your method &#8220;GetProducts()&#8221;. In the request section in the value field enter &#8220;1&#8243; and click &#8220;invoke&#8221;. This will invoke the service and result will returned back in response section as shown:</p>
<p><a href="http://aspnettutorial.wordpress.com/files/2009/11/4.png"><img class="aligncenter size-medium wp-image-41" title="4" src="http://aspnettutorial.wordpress.com/files/2009/11/4.png?w=300" alt="" width="300" height="189" /></a>Congratulations!!! you have just created your very first WCF based application.</p>
<p>In the next article we will explore WCF in more detail. Till than stay tuned and Happy Coding!!!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Artigos e Vídeos em Silverlight]]></title>
<link>http://flamoreira.wordpress.com/2009/11/21/artigos-e-videos-em-silverlight/</link>
<pubDate>Sat, 21 Nov 2009 23:35:10 +0000</pubDate>
<dc:creator>Flavia Moreira</dc:creator>
<guid>http://flamoreira.wordpress.com/2009/11/21/artigos-e-videos-em-silverlight/</guid>
<description><![CDATA[Olá pessoal. Como eu estou mudando o meu blog para um site, então atualizei as informações. Segue al]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Olá pessoal.</p>
<p>Como eu estou mudando o meu blog para um site, então atualizei as informações.</p>
<p>Segue alguns artigos e vídeos sobre Silverlight.</p>
<p><strong>Usando Javascript e Silverlight</strong></p>
<p><a href="http://www.dowhile.com.br/artigos/silverlight/63-usando-funcao-javascript-em-silverlight-.html">http://www.dowhile.com.br/artigos/silverlight/63-usando-funcao-javascript-em-silverlight-.html</a></p>
<p>Usando e-mail e Webservice</p>
<p><a href="http://www.dowhile.com.br/artigos/silverlight/60-enviando-e-mail-com-silverlight-parte-ii-.html">http://www.dowhile.com.br/artigos/silverlight/60-enviando-e-mail-com-silverlight-parte-ii-.html</a></p>
<p><a href="http://www.dowhile.com.br/artigos/silverlight/59-enviando-e-mail-com-silverlight-parte-i-.html">http://www.dowhile.com.br/artigos/silverlight/59-enviando-e-mail-com-silverlight-parte-i-.html</a></p>
<p>Usando linq to sql</p>
<p><a href="http://www.dowhile.com.br/artigos/silverlight/58-populando-datagrid-usando-linq-to-sql-em-silverlight-parte-ii.html">http://www.dowhile.com.br/artigos/silverlight/58-populando-datagrid-usando-linq-to-sql-em-silverlight-parte-ii.html</a></p>
<p><a href="http://www.dowhile.com.br/artigos/silverlight/57-populando-datagrid-usando-linq-to-sql-em-silverlight-parte-i.html">http://www.dowhile.com.br/artigos/silverlight/57-populando-datagrid-usando-linq-to-sql-em-silverlight-parte-i.html</a></p>
<p><strong>vídeo</strong></p>
<p><strong>Usando Javascript e Silverlight</strong></p>
<p><a href="http://www.dowhile.com.br/videos/silverlight/64-acessando-metodo-csharp-pelo-javascript.html">http://www.dowhile.com.br/videos/silverlight/64-acessando-metodo-csharp-pelo-javascript.html</a></p>
<p>Abraços</p>
<p>Flávia Moreira</p>
<p><a href="http://www.dowhile.com.br">http://www.dowhile.com.br</a></p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
