It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.

How to consume WCF or Webservice from Vista Sidebar gadget by using Silverlight?

The challenge today is really simple. All we have to do is to write Silverlight Vista Sidebar Gadget, that consumes either WCF, ASMX or REST based service. Really simple, isn’t it? Let’s start

image

Build server side services

We should start from services. This is very straight forward mission. Here the logic I want to implement

public string Echo(string input)
    {
        return string.Format("ACK from {0}", input);
    }

Well, WCF? We should mark service and operation contracts. That’s all

[ServiceContract(Namespace = "")]
public class EchoService
{
    [OperationContract]
    public string Echo(string input)
    {
        return string.Format("ACK from WCF with {0}", input);
    }

}

This does not works. Why? Silverlight knows only consumes ASP.NET compatible (simplified) web services, thus we should add following attribute to the our class attributes collection

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EchoService
{

Now, the service is discoverable and accessible by Silverlight. Great news. Now let’s put it into our shared host. Hmm, we got strange error: “Deploying WCF Services: This collection already contains an address with scheme http.” What the hell is it?

This is shared hosting problem. Your host provider uses virtual IP and host addresses and has number of different web services, sitting on the same shared host. How to solve it?

Simple, all you have to do is to specify your own service host factory. Here the example of classes to put into code behind

class SLHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        SLHost customServiceHost =
          new SLHost(serviceType, new Uri("[Your URL goes here]",UriKind.Absolute));
        return customServiceHost;
    }
}

class SLHost : ServiceHost
{
    public SLHost(Type serviceType, params Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    { }
    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();
    }
}

And one attribute into your service tag

Factory="SLHostFactory"

Now it works. So what’s next? Build ASMX web service. This is even simpler

[WebMethod]
public string Echo(string input)
{
    return string.Format("ACK from web service with {0}", input);
}

We done, now either WCF and Web services are accessible from your Silverlight application. So, add Service reference and consume it

Building client side

Inside code behind of your Silverlight project, you should define two proxies – one for Web Service and another for WCF service. Bother services implements the same interface, so it should not be a problem

ServerEcho.EchoServiceClient proxy;
WebServiceEcho.EchoWebServiceSoapClient wsProxy;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    proxy = new ServerEcho.EchoServiceClient();
    proxy.EchoCompleted += new EventHandler<ServerEcho.EchoCompletedEventArgs>(proxy_EchoCompleted);

    wsProxy = new SLGadget.WebServiceEcho.EchoWebServiceSoapClient();
    wsProxy.EchoCompleted += new EventHandler<SLGadget.WebServiceEcho.EchoCompletedEventArgs>(wsProxy_EchoCompleted);
}

Silverlight work only asynchronously, thus you should begin to understand, that synchronous programming is for pussies :) . Consume it

private void WCF_Click(object sender, RoutedEventArgs e)
        {
            proxy.EchoAsync(txt.Text);
        }

        private void WS_Click(object sender, RoutedEventArgs e)
        {
            wsProxy.EchoAsync(txt.Text);
        }

And Update output

void wsProxy_EchoCompleted(object sender, SLGadget.WebServiceEcho.EchoCompletedEventArgs e)
        {
            txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
        }

        void proxy_EchoCompleted(object sender, ServerEcho.EchoCompletedEventArgs e)
        {
            txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
        }

Now let’s run it. What? Another error? Security? Access denied? Of cause you have no crossdomain.xml.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" />
</cross-domain-policy>

What? You have it and still getting the same error? Look into sniffer. You application is looking for other file, named clientaccesspolicy.xml. Why? According the documentation, you can use either… Hm, another bug with WCF consuming. Never mind, let’s put it too

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Very well, now we are ready to run our application. It works! So, the only thing we should do is to pack it into MyGadget.gadget directory and put inside %userprofile%\appdata\local\microsoft\windows sidebar\gadgets together with gadget.xml manifest.

But… It stopped working… What’s the problem?

Very client side networking in Silverlight

The problem is, that SideBar executes it’s gadgets with local path, not with network path. Silverlight cannot use any network provider, when running locally. Why? Actually I do not know (maybe to prevent local applications development). so what to do?

Simple! Microsoft SideBar knows to run cross domain AJAX without any warnings and problems. So why not to use external XmlHttp from JavaScript for network access. Let’s do it

First we should initialize XMLHttpRequest object in JavaSctipt

var xObj;

        function getEchoWCF(text) {

            if(xObj == null) {   
                xObj = new XMLHttpRequest();

                }

            else if(xObj) {

                xObj.abort();

            }

Then create SOAP request to WCF or WebService

var sURL = "[Path yo your service]";

            //Build SOAP

            var sReq = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Echo><input>"+text+"</input></Echo></s:Body></s:Envelope>";

            xObj.open("POST", sURL, true);

            xObj.setRequestHeader( "Content-Type", "text/xml; charset=utf-8" );

            xObj.setRequestHeader( "Cache-Control", "no-cache" );

xObj.send(sReq);

After the request created and send we should handle result. So we need an access from HTML page, hosting Silverlight object to Silverlight. Simple. “ScriptableMember – ScriptableType”, remember?

[ScriptableType]

    public partial class Page : UserControl

    {

[ScriptableMember]

        public void UpdateResponse(string result)

        {

Now return the result

xObj.onreadystatechange = function() {

            if (xObj.readyState === 4) {

                if (xObj.status && xObj.status === 200) {   
                    var control = document.getElementById("silverlightControl");

                    control.Content.Page.UpdateResponse(xObj.responseText);

                }

            }

But this is not enough. We also should know to call Javascript from Silverlight… This is really simple

private void JS_Click(object sender, RoutedEventArgs e)

        {

            HtmlPage.Window.Invoke("getEchoWCF", txt.Text);

        }

We done. Now you can pack your Silverlight control, together with hosting HTML and Javascript into windows sidebar gadget and use it even with external network support.

Have a good day and be nice people.

Be Sociable, Share!

13 Responses to “How to consume WCF or Webservice from Vista Sidebar gadget by using Silverlight?”

  1. Serge Kof Says:

    I have read on msdn that crossdomain.xml and crossdomain.xml files are going to save from a lot of problem like access denied in a cross-site environment. I have created a sample WCF JSON service and a simple html page that consumes it. I started debugging them with different instances of VWD so I got the both on the localhost with different ports. However, when I click a button on my page, which calls a javascript to consume the service by means of MicrosoftAjax, I keep on receiving Access Denied. :( And the pair communicate well when the client and the service folders just placed into the same directory in IIS.

  2. vista service pack 1 problems Says:

    Pingback from  vista service pack 1 problems

  3. access domain function Says:

    Pingback from  access domain function

  4. address cross reference Says:

    Pingback from  address cross reference

  5. Community Blogs Says:

    Busy Day in SL2B2-Land: Chris Cavanagh with Soft-Body Physics, Emil Stoychev on Asynchronous SL, Rich

  6. Silverlight news for June 24, 2008 Says:

    Pingback from  Silverlight news for June 24, 2008

  7. Maxim Says:

    Good post.

    As I see, silverlight will kill flash technology on field of communication and data services, but in all aspects of GFX it’s behind the flash…

  8. Charles Sears Says:

    Any chance of getting the source to this example?

    Im having issues following your post and applying it to my application.

    I would love to see all of the code in the context of the project.

  9. LizF Says:

    I’m having issues following this post as well. I keep getting errors from Silverlight when I try to use either Invoke or Eval. Is there a different method to be used for Silverlight 3?

  10. trivia baby Says:

    wonderful points altogether, you simply gained a new reader. What could you recommend in regards to your put up that you made some days in the past? Any certain?

  11. Tomoko Says:

    An intriguing discussion is definitely worth comment. I do think that
    you need to write more on this subject matter,
    it may not be a taboo subject but generally people do not discuss such subjects.

    To the next! Best wishes!!

  12. monitoring budynków przed szkodnikami Zielona Góra Says:

    Hi! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing months
    of hard work due to no backup. Do you have any solutions to
    prevent hackers?

  13. http://ge.tt/2IEiDNz1/v/0 Says:

    An intriguing discussion is definitely worth comment. I believe that you ought to wrdite more on this topic, it mmay not be a taboo subject
    but usually folks don’t discuss these topics. To
    the next! Cheers!!

    Feell free too surf to my blog … Search Engine Optimistation in St Albans (http://ge.tt/2IEiDNz1/v/0)

Leave a Reply

Recommended

 

Sponsor


Partners

WPF Disciples
Dreamhost
Code Project