Silverlight 4 Nuevas Caracteristicas – Acceso a servicios cross-domain

En las anteriores versiones cuando queríamos consumir un servicio web que no estuviese en nuestro dominio debían estar  los ficheros Crossdomain.xml o ClientAccessPolicy.xml en el raíz del Sitio Web donde estuviese el Servicio a consumir por Silverlight.

La estructura de este fichero se puede consultar aquí: Cross-domain policy file specification

Silverlight hace uso de este tipo de ficheros de la misma forma que Flash, además que incluye también un nuevo tipo de fichero clientaccesspolicy.xml. Silverlight primero tratará de descargar este fichero y si no existe, tratará de descargar crossdomain.xml.

Generalmente los servicios web típicos como flickr, twitter.. tienen esos ficheros, por ejemplo

 

  • http://api.google.com/crossdomain.xml
  • http://api.flickr.com/crossdomain.xml
  • http://www.twitter.com/crossdomain.xml
  • http://www.amazon.com/crossdomain.xml
  • http://www.youtube.com/crossdomain.xml

     

    Pero que pasaba si no existían esos ficheros, no podía acceder desde Silverlight?  

    Para este caso existen alternativas.

    Una de ellas sería hacer uso de la API de integración con el navegador para acceder al objeto JavaScript XMLHttpRequest y consultar a través de él el servicio en cuestión. XMLHttpRequest no hace esta comprobación de ninguno de estos ficheros Xml, aunque podríamos tener problemas con otras características de seguridad que implementen los navegadores para evitar XSS.

    Otra alternativa es hacer que nuestro servidor nos haga de Proxy con el servicio o recurso del otro dominio. El problema de esta solución es la posible sobrecarga de nuestro servidor.

     

    Silverlight 4 nos va a permitir acceder a servicios que estén fuera de nuestro dominio aunque no tengan estos ficheros siempre y cuando se ejecuten out-of-browser y con confianza total (full-trusted)

     

    En el ejemplo que vamos a hacer utilizaremos el servicio web de twitter en este caso el código de acceso a los datos sería

     

       1:  public void GetTwitterPublic()
       2:          {
       3:              string publicTimeLine = "http://twitter.com/statuses/public_timeline.xml";
       4:              WebClient client = new WebClient();
       5:              client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
       6:              client.DownloadStringAsync(new Uri(publicTimeLine, UriKind.Absolute));
       7:          }
       8:   
       9:          void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
      10:          {
      11:              XDocument document = XDocument.Parse(e.Result);
      12:              twitterData = (from status in document.Descendants("status")
      13:                             select new Tweet
      14:                             {
      15:                                 Message = status.Element("text").Value.Trim(),
      16:                                 User = status.Element("user").Element("name").Value.Trim()
      17:                             }).ToList();
      18:   
      19:              PublicTimeLineListBox.ItemsSource = twitterData;
      20:          }

     

    Accedemos al xml de twiiter y con linq lo convertimos a nuestra clase, el ejemplo quedaría que como podéis ver no he hecho ningún esfuerzo en el diseño

     

    image

     

  • 10 comentarios sobre “Silverlight 4 Nuevas Caracteristicas – Acceso a servicios cross-domain”

    1. buenas tardes queria saber si me pueden orientar para rear mi propio administrador de correos algo como outloock pero solo de correos sin toda la funcionalidad, uso silverligth

    2. Hola buenos días

      estoy realizando mi proyecto fin de carrera y he creado una plataforma de gestión de clientes en silverlight, tengo uqe incluir la funcionalidad de envío de sms a los clientes. Para ello, he tenido que instalar un gateway sms en el IIS de windows y conectar un movil mediante cable usb al puerto com para que haga de modem para el envío.
      La cuestión es q tengo que tengo un código asp.net para enviar el sms, pero cuando intento programarlo en silverlight no sale na de na. He intentado crear un servicio y conectarme desde el cliente, pero nada de nada. Te adjunto el código asp por si me puedes orientar cómo usarlo en silverlight.

      using System;
      using System.Data;
      using System.Configuration;
      using System.Web;
      using System.Web.Security;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.Web.UI.WebControls.WebParts;
      using System.Web.UI.HtmlControls;
      using System.Net;
      using System.Text.RegularExpressions;

      public partial class _Default : System.Web.UI.Page
      {

      protected void Page_Load(object sender, EventArgs e)
      {
      textboxRecipient.Width = 400;
      textboxMessage.Width = 450;
      textboxMessage.Rows = 10;
      textboxError.Width = 400;
      textboxError.Rows = 5;

      textboxError.ForeColor = System.Drawing.Color.Red;
      textboxError.Visible = false;
      textboxError.Text = «»;

      if (!Page.IsPostBack)
      {
      textboxRecipient.Text = «+441234567»;
      textboxMessage.Text = «Hello World!»;
      }
      }

      protected void buttonSendOnClick(object sender, EventArgs e)
      {
      //are required fields filled in:
      if (textboxRecipient.Text == «»)
      {
      textboxError.Text += «Recipient(s) field must not be empty!n»;
      textboxError.Visible = true;
      return;
      }

      //we creating the necessary URL string:
      string ozSURL = «http://127.0.0.1»; //where Ozeki NG SMS Gateway is running
      string ozSPort = «9501»; //port number where Ozeki NG SMS Gateway is listening
      string ozUser = HttpUtility.UrlEncode(«admin»); //username for successful login
      string ozPassw = HttpUtility.UrlEncode(«abc123»); //user’s password
      string ozMessageType = «SMS:TEXT»; //type of message
      string ozRecipients = HttpUtility.UrlEncode(textboxRecipient.Text); //who will get the message
      string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of message

      string createdURL = ozSURL + «:» + ozSPort + «/httpapi» +
      «?action=sendMessage» +
      «&username=» + ozUser +
      «&password=» + ozPassw +
      «&messageType=» + ozMessageType +
      «&recipient=» + ozRecipients +
      «&messageData=» + ozMessageData;

      try
      {
      //Create the request and send data to Ozeki NG SMS Gateway Server by HTTP connection
      HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL);

      //Get response from Ozeki NG SMS Gateway Server and read the answer
      HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
      System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
      string responseString = respStreamReader.ReadToEnd();
      respStreamReader.Close();
      myResp.Close();

      //inform the user
      textboxError.Text = responseString;
      textboxError.Visible = true;
      }
      catch (Exception)
      {
      //if sending request or getting response is not successful Ozeki NG SMS Gateway Server may do not run
      textboxError.Text = «Ozeki NG SMS Gateway Server is not running!»;
      textboxError.Visible = true;
      }

      }
      }

      Muchas gracias por todo!!
      Saludos

    3. Hola,

      Primero felicitar por el Post.
      segundo; tengo un problema, ya he creado los archivos Crossdomain.xml y ClientAccessPolicy.xml, pero me sigue dando el mismo problema

      Se ha producido un error al intentar realizar una solicitud al URI ‘http://localhost/ServicioSilver/SampleService.svc’. Puede deberse a un intento de acceso a un servicio de configuración entre dominios sin una política entre dominios adecuada en contexto o una política no apropiada para servicios SOAP. Es posible que necesite ponerse en contacto con el propietario del servicio para publicar un archivo de política entre dominios y para asegurarse de que permite enviar encabezados HTTP relacionados con SOAP. Este error también puede deberse al uso de tipos internos en el proxy de servicios web sin utilizar el atributo InternalsVisibleToAttribute. Para obtener más información, consulte la excepción interna.

      Gracias por la ayuda.

      Saludos

      Lenin

    Deja un comentario

    Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *