ObservableDeveloper - Leonid Sorokin's Blog

.NET, Silverlight, ASP.NET, Web Services, SQL Server, Cloud Computing, and much more...

About the author

I am a .NET Software Developer, Consultant, and Trainer from Toronto, Canada specializing in web development with Rich Internet Applications on the Microsoft development tool chain.

My Photo

Microsoft Certified Professional Developer

System.MarshalByRefObject attributes in Silverlight 3

Once in a while, I create a web service using WCF and attempt to create a service reference to it from my Silverlight client application.

Most of the time, my Silverlight app compiles fine and the generated service proxy client code is indeed correct. However, there are times when certain operations on my service contract generate methods decorated with the attribute: [System.ServiceModel.ServiceKnownTypeAttribute(typeof(System.MarshalByRefObject))] – an unsupported attribute in Silverlight.

In fact, a colleague of mine also had exactly the same problem, and after scouring the web, both of us came up empty. Therefore, I decided to write a quick blog post about this strange and rather annoying issue.

Of course, you could just erase/comment out this line and rebuild your service proxy in Silverlight, but remember, that every time that the proxy is updated, your compilation will fail until you have removed any reference to MarshalByRefObject from your code.

First, check if you have any of these attributes listed as well (on the same method as System.MarshalByRefObject):
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(byte[]))]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(MemoryStream))]

Most likely, your method is referencing, either directly or indirectly, a MemoryStream type, and Silverlight is trying to figure out how it is going to serialize/deserialize it. You need to do a little bit of detective work to find out exactly which type (and property on that type) is the culprit, by checking your service code.

When you find the culprit, you need to change the type of the property to a type that Silverlight can readily serialize/deserialize, or avoid serializing that property altogether.

Disclaimer: I don’t know why Silverlight generates a System.MarshalByRefObject reference for the client service proxy since it does not support it anyway. Perhaps we can forward this question to the Silverlight team.

Hope this helps.


Categories: Silverlight
Permalink | Comments (0) | Post RSSRSS comment feed

Reusing .NET Framework 3.5 code in Silverlight 3

Over the past couple of days, I have been trying to port pieces of .NET code that I have written to the Silverlight runtime.

First, I have to clarify what I mean by reusing. In this case, reusing simply means using C# code from the full .NET Framework verbatim in Silverlight.

I want to simply be able to add a file as a link in Visual Studio 2008 – this will enable me to re-use .NET Framework code in Silverlight hassle-free.

Here are a few suggestions that you may find useful, if, for example, the code that you are re-using in Silverlight is not compiling. All of the suggestions below make it necessary for you to go back to your “server” code (i.e. .NET Framework code), and alter it so that it compiles under Silverlight.

  1. Make the problematic class a partial class. As such, you can port only a part of that class and leave out that portion of the class that would not be necessary in Silverlight.
  2. Use extension methods. Extension methods allow you to easily re-use bits of code while maintaining clarity. For example, I was using a .NET Framework method ConvertAll that was missing in Silverlight. I decided to create an extension method with slightly different parameters than the .NET Framework-based method, and changed my “server” code to use the extension method.
  3. Use partial methods. Although I rarely use partial methods, you can definitely use them when reusing code. However, many methods cannot be made partial (such as if a method does not return void, or if it has the override keyword. Because of these severe restrictions, partial methods are not always appropriate.
  4. Finally, if all else fails, you can use the good ol’ #IF…#ENDIF preprocessor directive to tell the compiler to include/exclude source code at compile time. For example, you can set the conditional compilation symbol on the “server” – so that when compiling under Silverlight, the bits of code that are only server bound will not get compiled.

Hope this helps.


Permalink | Comments (0) | Post RSSRSS comment feed

Unit Test Framework for Silverlight 3 uses port 8000

It appears that the Silverlight Unit Test Framework automatically calls http://localhost:8000/… when you load the Silverlight control in the web browser.

If Port 8000 is already in use, you will receive an error message from the Silverlight control stating that it received a 404 error page when it issued a web request (or something similar – I don’t remember the exact error message).

Bottom line, make sure that no web service or other application is using Port 8000 on your machine. Furthermore, note that Fiddler will not display any outgoing requests to “localhost”, so you will not see this particular request in Fiddler.

Unfortunately, I cannot explain why the Silverlight Unit Test Framework uses Port 8000 but just keep this mind! If you want to know why ask Jeff Wilcox.

Happy Unit Testing!


Permalink | Comments (0) | Post RSSRSS comment feed

Solving cross domain issues with Silverlight 2

We all know that Silverlight and Flash follow a similar security model and run in the browser sandbox. These RIA platforms essentially request a cross domain policy file when a request is sent from the RIA application to a web service. If the policy file is not present or does not list your domain as an allowed domain then you have three choices:

  • Call, write, and ask the company/person to list your domain (i.e. the domain from which your Silverlight application is downloaded) as an allowed domain in the client policy file (clientaccesspolicy.xml or crossdomain.xml) – may not be very reasonable
  • Create your own proxy – the proxy will sit on your domain, and will make calls to the external domain. Hence, your Silverlight app will call the proxy on the same domain, so the Silverlight runtime will avoid asking for the cross domain policy file. Your proxy will simply call the external service and pass the response back to the Silverlight application
  • Use a 3rd party proxy service instead of rolling your own – such as Yahoo Pipes @ http://pipes.yahoo.com/pipes or the Google AJAX Feed API @ http://code.google.com/apis/ajaxfeeds
  • Trick the browser and avoid using any proxy whatsoever. This only works if the Silverlight application can access the Html Bridge and inject a JavaScript element into the head tag of the page. Also, you need to understand how to pass the response into a Silverlight control. If you don’t know how this can be accomplished then this approach will not work for you. This is the option I will discuss further, since the other ones are self explanatory

I am not sure if I would recommend using such an approach because it feels like a hack, but it does indeed work. This approach may not work at all, if, for example, you are loading your Silverlight application XAP file from a different domain than the web page that is hosting the Silverlight content. I am not sure if the Silverlight control will be able to modify the head Html element of the host page.

Here is the most important snippet of code you need in order to implement this trick:

HtmlElement head = HtmlPage.Document.GetElementsByTagName("head")[0] as HtmlElement;
HtmlElement javascriptContent = HtmlPage.Document.CreateElement("script"); 
javascriptContent.SetProperty("type", "text/javascript"); 
javascriptContent .SetProperty("src", "http://aWebServiceSomeWhere"); 
head.AppendChild(javascriptContent);

 

Do you see the trick? The browser’s javascript engine will say, “oh, look, we have a new script element that has been added to the header, and it has a URL as the src property – I need to download and then execute that javascript!” Since the request is made from the browser’s DOM and has no relevance to any RIA technology, all outbound requests will succeed an no cross domain policy file is requested. After the javascript is returned, it is necessary to pass the results back to the Silverlight control. Clearly, the only reasonable way to do it is to force the javascript to contain a method call into your Silverlight control. For instance, Twitter allows you to specify a callback=YourJavascriptFunction in the request, and the resulting JavaScript returned from the Twitter service will contain YourJavascriptFunction in the response.

Bryant Likes wrote a Silverlight Twitter control that demonstrates using this trick, and a fall-back mechanism that uses Yahoo Pipes. Have a look @ http://blogs.sqlxml.org/bryantlikes/archive/2009/01/23/twilight-a-silverlight-twitter-badge.aspx and http://www.codeplex.com/Twilight

By the way, I am currently using Bryant’s excellent Silverlight Twitter badge on my blog. 


Permalink | Comments (0) | Post RSSRSS comment feed

Architecting Silverlight 2 Applications with Prism (Composite Application Guidance)

Many people who have worked with enterprise applications over the years have realized that building maintainable applications that naturally evolve over time is quite challenging. If the application consists of many modules, it is paramount that each module be as self-contained and decoupled from other modules as possible. Otherwise, over time, the modules become more and more tightly-coupled which generally results in spaghetti code.

Prism is a codename for the Composite Application Guidance package which consists of libraries (DLLs) that you can reference in your Silverlight/WPF projects. As such, Microsoft Patterns & Practices is providing documentation, written tutorials, videos, etc., in order for software developers to get up to speed with it. You can check out the CodePlex site for Prism @ http://www.codeplex.com/CompositeWPF

Prism empowers developers to create modules that encapsulate a certain piece of functionality. Each module would be responsible for emitting a view, which would then be injected into a particular region that is present inside a containing shell. The bootstrapper is responsible for initializing the shell and enumerating the available modules in the ModuleCatalog. There is also an EventAggregator that essentially acts as a Mediator, and all event publishers and subscribers use the EventAggregator to publish and subscribe to events. As such, one module may fire an event, and a multitude of subscribers may handle that event. Therefore, the modules are truly decoupled from each other. In addition each module uses a Model-View-ViewModel (M-V-VM) architecture to separate the View from the underlying model using data binding and the Command pattern. I have previously blogged about a fully unit-tested sample application that showcases the M-V-VM pattern and the Ninject (Inversion of Control) IoC container @ http://www.leonidsorokin.com/blog/post/Architecting-Designing-Silverlight-2-Applications.aspx. By the way, Prism includes the Unity IoC (Inversion of Control) container out-of-the-box although you are free to plug-in other IoC containers in replace of Unity.

In my opinion, the real power of the Prism framework is that it uses a large number of popular design patterns, with the hope that the composite applications that you build as a developer are as maintainable and scale well over time. In most documents, design patterns are presented in isolation, but the beauty of Prism is that it amalgamates these design patterns in a form of libraries, reference implementation (Stock Trader WPF application), and written guidance documentation. You can find an excellent introductory series of screencasts that showcase Prism @ http://compositewpf.codeplex.com/Wiki/View.aspx?title=Learn%20Prism

On a side note, I have found another framework that Microsoft appears to be developing with the developer community, although so far it is only in a preview state - it called MEF (Managed Extensibility Framework). As far as I understand, this framework will ship with .NET Framework 4.0. I believe MEF is some kind of grandiose Publish/Subscribe & component discovery mechanism which by decorating properties/methods with Import/Export attributes enables a developer to basically dump a bunch of modules in a folder and have them discover other modules during run-time and not during design time, and actually use them. Also, unlike Prism, which relies of WPF, MEF has no requirement on XAML, so theoretically, it can be used with other-non WPF stacks, such as Windows Forms. MEF is still early in its development but it feels rather promising. Hopefully, MEF will be ported over to Silverlight at some point. You can check out MEF on CodePlex @ http://mef.codeplex.com


Permalink | Comments (0) | Post RSSRSS comment feed

Persisting state during asynchronous calls

When using Silverlight you are pretty much forced to use asynchronous requests to web services. In most cases, this is not a problem, but sometimes you may need to be aware of the "context" of the response. In other words, in your callback event handler, you process the response from the server but you need that extra bit of information so you know what do to with the response.

Suppose you have a tree-view control. Every time a user selects a tree-view item you make an asynchronous web request, and when the response arrives you would like to pop-up a balloon over that selected tree-view item with the response (perhaps a detailed explanation of that tree-view item). Sounds simple right? Well, it is. Except that by the time the response has been received, the user may have already selected another tree-view item. Clearly, when the response is received, it is necessary to know who the response is for. In our case, the response event handler needs to receive the tree-view item reference, or better yet, the appropriate data-bound object if you are using data binding.

In Silverlight you can use the WebClient class or the more advanced HttpWebRequest class for making HTTP calls. Either way, when you make the call, you need to pass in an object reference, and when the response is received, that same object can be accessed.

For instance, WebClient has a method named DownloadStringAsync that is used to download non-stream data with two overloads. The difference between them is that one of them takes a userToken object. Here is the method signature:

public void DownloadStringAsync(Uri address, Object userToken)


You can access the user token in the response via the UserState property of the response object. The same mechanism exists for the HttpWebRequest class.

Now you should be able to successfully work with asynchronous requests in Silverlight and the .NET Framework.


Permalink | Comments (0) | Post RSSRSS comment feed

Expression Blend 2 SP1 does not support async HTTP web requests

Expression Blend is very useful. However, it would be even more useful if a designer was able to see data in the controls which he/she is using. That way, changing the font of a grid will show the changes right away. The key is to have dummy data in the grid so that the designers' changes are reflected in real-time. This would result in a much better experience for the UI/UX designer working in Blend.

However, by default, there is no data in controls used in Blend, and the designer has to live with that.

In order to achieve this "dummy data" behavior, I am currently including Mock data as part of the XAP file that users will eventually receive. This is not so good since users will have to wait for a larger Silverlight XAP file to be downloaded. You can find an application I wrote that uses this technique @ http://www.leonidsorokin.com/blog/post/Architecting-Designing-Silverlight-2-Applications.aspx

In order to avoid having to include potentially large dummy data in the XAP file I wanted to download it dynamically during runtime. In the browser, there is no problem, but the same code in Blend results in the error: WebException: BrowserHttpWebRequest_WebException_RemoteServer.

Here is a thread I posted on this issue in the Expression Blend Forum: http://social.expression.microsoft.com/Forums/en-US/blend/thread/fe5b251f-e54e-4d6a-b442-5cf45fa00e86

By the way, you can debug a Silverlight application running under Expression Blend by simply attaching to the Blend.exe process while your application solution is open in Visual Studio 2008, and setting breakpoints.


Permalink | Comments (0) | Post RSSRSS comment feed

Architecting & Designing Silverlight 2 Applications

Many people write code that is not re-usable, testable, and basically, totally unmaintainable.

Let's face reality - writing "good code" is not trivial, and software developers often find themselves in a position where time is limited and they have to deliver a piece of software.

The question is not only "will they deliver the software on time", but perhaps "what will they end-up delivering"?

Over the past month of research and development, I have read numerous blog posts, MSDN articles, white papers, and conducted my own development to try to answer one question: what are the best patterns & practices known today in order to build maintainable line-of-business Silverlight 2 applications?

I have written a sample Silverlight application called "SilverList" that uses most of the results of my extensive research.

Here are the key Silverlight design concepts:

  • M-V-VM (Model-View-ViewModel) design pattern + Silverlight Commanding in order to allow a more seamless developer/designer relationship. You can read Shawn Wildermuth's article on the subject @ http://msdn.microsoft.com/en-us/magazine/dd458800.aspx
  • Unit Testing (because if you don't write unit tests - you should start, trust me, it provides many benefits). You can find it @ http://code.msdn.microsoft.com/silverlightut
  • Dependency Injection (forget about hardwiring dependencies and start injecting them using Ninject - the ninja of dependency injection!) Ninject can be found @ http://ninject.org/
  • Isolated Storage (think "Google Gears"  - cache, cache, cache!) Why make a round-trip to the server if you don't really need to?
  • Blendability (your UI/UX designer is complaining that when he/she is working in Expression Blend, all the ListBoxes appear empty with no data, same with all the DataGrids and TextBoxes. Well, with M-V-VM and IoC (Inversion of Control), you can inject dummy data so that when your beloved designer wants to change the font, color, or the style of a control, the dummy data is there to reflect the change in real-time! There isn't a need to run the application in the browser just so see the effect of a simple change - very useful for RAD (Rapid Application Development) scenarios.
  • LINQ (Language Integrated Query). Why implement IComparable/IComparer on your custom objects when you can simply write a couple of lines of LINQ code to search/sort a list of data by a given property?

Here is what the the application actually does:

  • Add name-value pairs to the list in the format: name=value (e.g. Hello = World). The name can be comprised of any alpha-numeric characters, following by an equal sign, followed by another set of alpha-numeric characters
  • Delete a name-value pair from the list
  • Sort the list in ascending order either by name or by value
  • Filter the list by either Name or Value. For filtering, the name portion has to be "Name" or "Value". For example, to display all entries in the list with the name Hello, type in "Name = Hello" (no quotes). To filter by value, type in "Value = World" (no quotes).
  • Clear the filter to return to the main list
  • When adding/sorting/deleting name-value pairs, SilverList automatically saves the current data into IsolatedStorage. So if you close the browser and visit the page again, you will see your latest data in the ListBox right away. Filtering, however, is a temporary operation, and does not cause the list data to be saved into IsolatedStorage

As you can see, the application is simple, yet is mainly used to show good design patterns and practices.

Here is a link to the SilverList Unit Testing page: SilverList Unit Tests . Be patient while the XAP is downloaded and the Unit Testing Framework is initialized. You will be able to see how the Silverlight Unit Testing framework executes my unit tests for SilverList live in your brower. Let's hope all the tests pass! Embarassed

This was an introductory post and I will write about this application and plan on dissecting it in more detail in future posts. For now, however, you can grab all the code, and play with it live below.

Here is a link to all the code:

Here is the application live (you need to have the Silverlight plugin installed to use it):

[silverlight:source=/blog/ClientBin/SilverList.xap;width=500;height=600]


Permalink | Comments (0) | Post RSSRSS comment feed