Accessing Web Services from Silverlight 2

by kevin 7/10/2008 10:39:00 PM

I presented tonight (10 July 2008) to the Richmond .NET User Group. We had a pretty good turnout, I'm guessing 40 to 45 developers. I gave this same presentation at my office today as a dry run and as a training opportunity within the company. It's so good to see the developer community eager to learn. I've attached my slides and the three demonstrations projects I used in this post. I'll be giving this same presentation to the Charlottesville .NET User Group next Thursday (17 July 2008). The abstract we put on both user group websites follows:

Silverlight is a client-side technology. So it’s not really a part of your SOA strategy, right? You may want to think twice about that. SOAP and WSDL support are coming to the web desktop via Silverlight. And Silverlight has good client support for REST+ JSON/POX and RSS/ATOM-based web services, too. During this discussion, we’ll dive into data serialization, security and cross-domain access policy capabilities inside Silverlight 2 Beta 2. We also talk about the nuances and pitfalls of provisioning your web services for an Internet audience. This presentation will be heavy on coding, demonstration and interactive discussion.

Powerpoint Presentation (289KB)

Twitter solution showing how to invoke a cross-domain RESTful service by way of an in-domain SOAP service bypassing the cross-domain access policy problem. (842KB)

REST solution showing how to create RESTful services in WCF and how to consume RESTful services in Silverlight (307KB)

Silverlight syndication solution showing how to consume cross-domain RSS and Atom feeds using the SyndicationFeed class. (11KB)

Silverlight Assembly Handling

by kevin 5/20/2008 9:16:00 PM
Hanu Kommalapati is blogging again! Awesome. In his latest post, he addresses the issue of assembly handling by Silverlight. With security at the forefront of everyone's mind these days, you need to be able to relate to others how Silverlight handles XAP files and their contents on the web desktop. In his post, Hanu explains how this is done. Scroll down and read his reply to a reader's question to fully understand. In essence, he says, "As of beta1, [the XAP files] won't leave any footprint on disk." This is good to know when you are selling the idea of using Silverlight to your clients or your management team.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

Silverlight | Security

Silverlight Web Services Slides and Sample Code from NOVA 2008.1 Code Camp

by kevin 5/17/2008 4:42:00 PM

This was the first time I gave this talk but the attendees seemed to be very receptive. The concerns about security in Silverlight, especially related to the protection of Intellectual Property (IP) and account access are really on peoples' minds. Based on the thoughtful question I received here and in Roanoke 2 weeks ago, I have decided to dedicate a whole chapter in my new book to Silverlight security principles.

In this talk, I discussed the various methods by which a Silverlight application can access remote web services. We didn't have time to get into RSS/Atom syndication but I'll be sure to cover it in a future talk. We also discussed cross-domain policy, another hot security topic, as it turns out. I showed how to enabled a WCF web service for RESTful delivery and then showed how to consume SOAP-based services from Silverlight. We closed by looking at the use of an in-domain, SOAP-based WCF service to act as a proxy for a cross-domain RESTful service that does not allow cross-domain access by policy. Here are the slides and sample code:

WCFRESTDEMO20080517.zip (18.89 kb) - sample code that shows how to make a WCF service RESTful; a Silverlight control is included that demonstrates how to use it; there is also a Digg.com downloader that demonstrates cross-domain functionality from Silverlight.

Twitter20080517.zip (25.59 kb) - sample code that shows how to consume an in-domain SOAP-based service from Silverlight; that SOAP-based service is really a proxy to a RESTful service at Twitter.com. And since Twitter.com's cross-domain policy doesn't allow access from my domain, this example shows how the server-side WebClient class can be used to circumvent the policy limitation.

Silverlight and WCF - NOVA Code Camp 2008.1.pptx (199.39 kb) - my PowerPoint slides from this discussion.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , , , ,

Architecture | C# | Silverlight | User Group | WCF

Excellent Post from Hanu Kommalapati on Silverlight Deployment

by kevin 5/16/2008 12:22:00 PM
Hanu Kommalapati has a fantastic blog post on Silverlight deployment from 5/11/2008 at http://blogs.msdn.com/hanuk/archive/2008/05/11/silverlight-for-the-enterprises-fundamentals.aspx. Hanu doesn't blog often but his stuff is very good. I think I'll write to him and encourage him to share more often.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Silverlight

Flow Diagram for Silverlight Cross-Domain Policy Checks

by kevin 5/9/2008 10:48:00 AM

Last week, I blogged about Overcoming Cross-Domain Issues in Silverlight which recommended the use of a proxy service for making cross-domain calls. I'll be writing more about the security considerations of using that method in the coming days. For now, here's a flow diagram I created to better understand what the WebClient class in Silverlight is doing when making cross-domain calls. If you see any problems with my interpretation, I invite corrections by commenting on this blog post.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Silverlight

Silverlight Tip - Loading XAML Fragments Dynamically

by kevin 5/5/2008 10:32:00 AM

Being able to instantiate XAML controls from text fragments at runtime is very convenient, especially when you have a lot of properties to set. Using a block of text to hydrate a new XAML control is often a much more compact and efficient alternative to dozens of lines of code that would be required in C#, for example. However, when you load XAML text up at runtime in Silverlight 2, there are a couple of things of which you should be wary. First of all, the string containing the XAML fragment must contain only one root element. And that node must include a namespace reference to http://schemas.microsoft.com/client/2007. If you forget to reference that namespace, you'll get a XamlParseException when you attempt to load the XAML.  As an example, look at the following C# code which creates a TextBlock object:

In this code, the XAML text fragment contains the necessary namespace reference and an attribute setting the Text property to "Hello world!" The XamlReader class in the System.Windows.Markup namespace is then used to load up the XAML text using the Load method which returns a System.Object. Since the root node of the XAML text was a <TextBlock/>, the resultant object is actually an instance of the System.Windows.Controls.TextBlock type. So the cast to that type succeeds, yielding a disconnected TextBlock.

I say that the new TextBlock is "disconnected" because just after it is created, it is not associated with any other UIElement. Controls are not really usable until they are connected to a canvas and ultimately to an application. Most XAML controls have a property called Children which is a UIElementCollection. That collection's Add method can be use to attach the new TextBlock and render it. Of course, casting the result of the Load method to a TextBlock isn't necessary. But to be attached via the UIElementCollection.Add method, you'll have to cast the Load result to the UIElement base class at a minimum.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | Silverlight

Overcoming Cross-Domain Issues in Silverlight

by kevin 5/2/2008 9:24:00 AM

One of the easiest ways to deal with cross-domain issues in Silverlight is to write a WCF service that acts as a proxy for the calls you want to make. For example, in my Twitter control, I want to be able to load XML from the RESTful Twitter service at the following address:

http://twitter.com/statuses/user_timeline/wkh.xml

However, when invoking the RESTful Twitter service from a WebClient in Silverlight, I get the dreaded "Download Failure" error when I call DownloadStringAsync. This is because the Twitter.com site doesn't have an entry in its clientaccesspolicy.xml file for my test domain. And that's never going to happen, right? To solve this problem, consider exposing a WCF service from the site from which the Silverlight control emanated. The WebClient class can be used on the server side without the same cross-domain control being applied by Twitter.com. For the example outlined above, I called my service TwitterProxy. The ITwitterProxy couldn't be simpler:

using System.ServiceModel;

[ServiceContract( Namespace = "urn:gotnet:biz:Services:2008:05" )]
public interface ITwitterProxy
{
    [OperationContract]
    string GetUserTimeline( string user, int count );
}

The service implementation is also quite simple. It uses the WebClient just as I would from Silverlight (if I could):

using System;
using System.Net;

public class TwitterProxy : ITwitterProxy
{
    public string GetUserTimeline(string user, int count)
    {
        user = (user != null) ? user.Trim() : String.Empty;
        count = (count < 1) ? 1 : (count > 20) ? 20 : count;
        WebClient client = new WebClient();
        Uri uri = new Uri( String.Format("http://twitter.com/statuses" +
            "/user_timeline/{0}.xml?count={1}", user, count ) );
        return client.DownloadString(uri);
    }
}

Expose an SVC file on the server to host the new service. In this example, the URL to invoke the new service is:

http://localhost/WebSite/TwitterProxy.svc

So, to invoke this service from Silverlight, add a proxy to the Silverlight control, using the service address and invoke it like this:

private void OnLayoutRootLoaded(object sender, RoutedEventArgs e)
{
    TwitterProxyClient client = new TwitterProxyClient(
        new BasicHttpBinding(), new EndpointAddress(
        "http://localhost/Website/TwitterProxy.svc"));
    client.GetUserTimelineCompleted += OnGetUserTimelineCompleted;
    client.GetUserTimelineAsync("wkh", 10);
}

void OnGetUserTimelineCompleted(object sender,
    GetUserTimelineCompletedEventArgs e)
{
    // open a Twitter Status dialog, passing the XML string
    NavigationHelper.Navigate(new FadeTransition(
        TimeSpan.FromMilliseconds(750.0d)), new Status(e.Result));
}

The dreaded "Download failure" error is gone. Nice. of course, the potentially bad side effect of this technique is that all of the Twitter service traffic will be flowing through the server that's hosting the TwitterProxy. Think about that before using this technique.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Architecture | Silverlight | WCF

Silverlight Richmond Code Camp Presentation

by kevin 4/26/2008 1:02:00 PM

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | DLR | IronPython | Richmond | Silverlight | Software Development | User Group | Visual Studio

Strange Behavior for Silverlight's HtmlPage.Window.Navigate Method

by kevin 4/21/2008 2:41:00 PM

I found some odd behavior today with respect to the way that Silverlight's HtmlPage.Window.Navigate method works. If a page is cacheable by the client, calling HtmlPage.Window.Navigate will always choose to load the cached version of the page. With IE7, it does this without attempting a cache update check. Normally, IE7 will emit a cache update check for cached content, expecting an HTTP 304 response code, meaning that the cached version is up-to-date. However, when HtmlPage.Window.Navigate references a cached resource, it honors the cached content without checking for an update. This is how Firefox normally behaves and it threw me for a loop as a result. Check out the following code.

// this one will used a cached version always
HtmlPage.Window.Navigate(new Uri("http://server/targetpage.aspx"));
// this one will ignore the cache
HtmlPage.Window.Eval("window.location.href='http://server/targetpage.aspx'");

In that code, the first method call will cause the browser to use a cached page. This is true even if the cache-control was set to private, which is the default. It also does not check for a cache update as IE7 normally does. The second call injects JavaScript into the hosting page for execution. That one seems to force the browser to ignore the cache where the target page was received with the private cache-control policy. I don't know if this is a bug but I know it's not documented that way. I should mention that this happens on Silverlight 2 Beta 1.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | Debugging | Silverlight

Silverlight as Part of Your SOA Strategy

by kevin 4/12/2008 8:47:00 PM

Silverlight is a pure client technology. So, it has nothing to do with your SOA strategy, right? Not so fast. While most Service-Oriented Architectures try to remain agnostic about the clients who will approach the system, you can't be totally ignorant of the constraints that clients might impose. There are many "potential" requirements that architects have to think about. For every requirement that gets written down, there are usually two or three other implied requirements that never get expressed on paper. Architects just make sure that the plumbing of the applications help the developers to handle these cases when they arise. Of course, this is why WCF abstracts the concept of bindings as well as it does. Being able to expose any WCF service through a variety of tuneable, standards-based and proprietary bindings is one way that an architect can remove some rigidity from the system.

Silverlight is interesting because it exposes WCF client classes like ClientBase<T> and ChannelFactory<T> to a class of users who've never drunk from the services well before, so to speak, at least not directly. There is a notable exception from Microsoft in the not-too-distant past. Remember the DHTML Web Service Behavior? This was an HTML Component (HTC) script published by Microsoft just as XML Web Services were beginning to become popular. It used the XMLHttpRequest Object exposed by the browser to allow client-side script to invoke web services using WSDL and SOAP. The HTC would automatically download the WSDL contract for a service and build dynamic objects to expose the service and its operations at runtime. What an incredibly simple and powerful tool that was! It didn't support anything but simple data types for moving information between the browser and the server. But, when you have a XML Data Islands and a JavaScript Base64 codec on the browser, there's not much data that can't be expressed as a string.

I wrote many applications using the DHTML Web Service Behavior before the term AJAX appeared on the scene. Maybe this why when AJAX started to become a movement, I wasn't all that impressed. It seemed like old news to me. I remember how I designed those services. I took great care to make sure they were stateless and load-balancer friendly. I set up security protocols that would detect and prevent malicious activity. I had all sorts of profiling and logging code in there. In short, I treated those services with the same care that a good architect applies to any real web service. However, when the AJAX movement started, a lot of the scrutiny that I would have applied to real web services didn't seem to be in fashion for the many AJAX callbacks flying about. Those AJAX callbacks were somehow second-class citizens from an architectural point of view, not because I wanted them to be so but because many of the developers encapsulating callbacks into their AJAX controls didn't think of them as real service calls. And because it was up to developers, not architects, to drag and drop AJAX controls onto a design surface, the attention just wasn't there to do what was right in all cases. Hence, a lot of poorly-structured AJAX applications were written (and are still being written today).

Today, REST and POX are becoming popular for accessing web services. This is due, in large measure, to the rise in popularity of scripting languages and the somewhat duanting complexity of WSDL and SOAP. However, Microsoft proved that SOAP 1.1 could be handled via JavaScript as described before. And you can imagine that a company like Microsoft, if it decided to pursue the refinement of its DHTML Web Service Behavior, would have been able to handle the dynamic creation of data contracts via JavaScript, too. The problem wasn't the service contracts, operation contracts, fault contracts and data contracts. The real problems with dynamic, JavaScript proxies are security, reliability and transaction management. Those are the things that differentiate SOAP from all other forms of web service access today.

Back to the premise. With the WCF client classes moving to millions of desktops via the web, there's a shift coming in the SOA world. This creates for the first time what I call the Web Desktop. Being able to extend standards-based security, reliability and transaction management to the Web Desktop means that architects will feel more comfortable moving their SOA strategy up the stack. This is a very good thing. Most serious software developers love and hate the web. The deployment model is great but what's good about it sort of stops right there. HTML and JavaScript are just awful mediums for expression. And what about debugging client-side script? Nothing short of a nightmare, that is. It's no wonder that it's taken this long and hundreds of millions of dollars of research and development across the industry to get decent DHTML/AJAX applications into circulation. Event still, the quality and reliability of those applications across so many browsers and platforms is often sketchy. And the cost to implement such an application and properly test it is out of reach for all but the wealthiest companies.

The coming changes due to WCF support in Silverlight probably won't be cataclysmic but the changes will offer useful new ways of thinking for solution architects and developers who understand how poorly all of us are exposing applications over the web today. To dampen the spin a bit here, I should tell you that the Silverlight 2 Beta 1 is still a bit weak on the WCF front. It has near nil support for metadata exchange and only supports the BasicHttpBinding. But Beta 2 promises many improvements. Stay tuned.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

Architecture | Silverlight | Software Development | WCF

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen


Kevin's on Twitter / FriendFeed

W. Kevin Hazzard Welcome to Kevin Hazzard's Blog. Kevin is a Software Architect, Professor and Microsoft MVP specializing in C#, WCF, Silverlight and IronPython.

View Kevin Hazzard's profile on LinkedIn
Microsoft MVP Award Join me at CodeStock

Calendar

<<  July 2008  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Recent posts

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Sign in