News
The latest Silverlight news gathered from around the web.
Configuration in Silverlight and a Standalone File Uploader
Leblanc Meneses has published a great, very detailed post explaining configuration in Silverlight and a standalone file uploader.
ConfigurationManager, the commonly used .NET configuration API, is unavailable in Silverlight applications. The minimum code option is to deserialize an XML configuration file, or to read from initParams.
While most Silverlight applications only need Service endpoints updated in ServiceReferences.ClientConfig, there are occasions where a PRISM module may be needed to support reconfiguration. When this happens, I use an MSBuild task to create and/or merge the correct settings into a module.xml within the PRISM module, using a strongly typed object representing the XML file. I also deserialize the XML file to retrieve its values.
Building A StoryboardEventHelper Class To Create Additional Events For A Silverlight 4 Storyboard
I wrote an article on my Blog in which I describe a technique as a workaround on how to "add" additional events to a Silverlight 4 Storyboard. The Silverlight 4 Storyboard class only has one single event, which is the Completed event. There a numerous needs to add additional events to a storyboard but because the Storyboard class is sealed this isn't possible. So we need a workaround which is provided by the StoryboardEventHelper class. The StoryboardEventHeler class that is build step by step in the article implements two addititional events (OnStoryboardStarted and OnStoryboardPositionChanged) that provide for example the opportunity to easily change the VisualState of any Object at a certain timeline position of a running storyboard. In addition to the article you can view a small sample app and download the full sourcecode at the Expression Gallery.
Have fun!
Write an Online Basketball Shooting Game Using Silverlight 4 and Farseer Engine - Part 1
In this series of articles Xianzhong Zhu is going to develop an online basketball game using the famous two-dimensional physics engine - Farseer under Visual Studio 2010 and Silverlight 4.0 environments.
In particular, we will use the PhysicsHelper kit to help to achieve the goal of basketball moving and collision detection as well as other functions. In this installment, we are mainly going to make preparation work for using Physics Helper. Please note that because there are numerous new characteristics and somewhat traps in using the PhysicsHelper API compared with (and different from) the initial Farseer Engine API we plan to use more space to discuss these questions.
Silverlight and WCF RIA Services (6-Validation)
In this next Silverlight and WCF RIA Services post, Mike Taulty has a very detailed discussion on validation.
One of the strengths of WCF RIA Services is in its capabilities around the application of common validation logic on both the client tier and the service tier.
A little interface animation fun
Hannah Watkins has made a little Silverlight interface animation in Blend with a background created in Photoshop.
I had a real urge to make a little Silverlight interface animation in Blend. I wanted to create a background in Photoshop from layers of images and blending effects and then have a text area appear over the top. I guess I was influenced by game/DVD screens and the like. Because it was a fun project, I wasn't looking to spend too much time to achieve the rough effect I was after, with a hope that it could be refined at a later date.
Silverlight and WebSockets
Mike Taulty was intrigued by a post from Tomek which has links to a prototype of an application built with Silverlight but using WebSockets, so he decided to explore that matter by himself.
So, traditional sockets are great in that they allow full duplex comms such as when the server wants to notify the client that something has happened but they’re not so great in that they require an open connection which tends to limit your server side scalability. They’re also not so great when it comes to crossing boundaries that only allow HTTP on port 80 or 443.
Introduction to the Windows Phone 7 Accelerometer
In this post, Jeff Fansler discusses the accelerometer in Windows Phone 7.
Windows Phone 7 (WP7) will have an accelerometer in it. The framework namespace that covers the accelerometer is Microsoft.Devices.Sensors. The class we care about here is the Accelerometer class. This class has 2 important methods Start and Stop. As you can likely guess, start tells the system you want to start reading values from the accelerometer and stop means you are done. The Accelerometer also has an important event called ReadingChanged. This event fires once you have started the accelerometer and one of the accelerometer values has changed. The event uses the AccelerometerReadingEventArgs class to return back the values that have changed. There are 3 important values, X, Y, and Z. Each represents the force of acceleration on that axis.
Using Blend 4's new built-in TransitionEffects in Navigation and MVVM applications
Expression Blend 4 comes with some pretty cool pre-built VisualState transition-animations called TransitionEffects. A TransitionEffect is a pixel-based transition from one state to another, in other words it’s a PixelShader that has an animatable Progress property. These effects can be used in various scenarios, they are very developer/designer friendly, and they are an easy way to make your Silverlight application more attractive.
In this article I will show you two situations to use Blend 4’s built-in TransitionEffects:
- Navigating between pages in Navigation Framework and
- switching between Views in an MVVM (Light Toolkit) scenario.
Here are the two samples with the „Pixelate” and the „Slide In” effects, live demo and source codes:
Source code to MVVM Transition Demo
Live demo for Navigation Transition
Source code to Navigation Transition
VisualState and Transition recap
You probably know VisualStates from Silverlight SDK Controls and from custom Controls. The name of the concept is “Parts and State Model”. This means that every control has Parts (named elements within the Control) and States (and State Groups). Between switching from a state to another we can define transitions. VisualStateManager is the one that handles state-changes.
The States panel first appeared in Blend 2 SP1, in Blend 3 there were the pre-setted Easings for the transition storyboards, and now in the fourth version of Blend there are the TransitionEffects.
Here’s the standard Button’s States-view in Blend 4:
It’s good to know that we can use VisualStates and Transitions not just in custom Controls but in UserControls as well.
TransitionEffect in a Navigation Framework Application
To enable one of Blend 4’s new TransitionEffects in a Navigation Framework application, all we need is Blend 4 and zero coding. :)
- If you don’t have an existing navigation application in which you can test, create one using Visual Studio. Create a new project using the Silverlight Navigation Application template.
- Once you’re application is ready, open it in Blend 4. Open the main page (default is MainPage.xaml).
- Expand the LayoutRoot and put the ContentBorder in a Grid. You can do this by right clicking on the ContentBorder and selecting Group Into ->Grid. ContentBorder contains the ContentFrame. We will add the transition effect to the newly created grid.
- Luckily ContentFrame exposes both the Navigating and Navigated events. The first one fires before the navigation, the second one after the navigation is made. We will create two states according to these events, a “NavigatingState” and a “NavigatedState”.
Select the States panel, and add a VisulStateGroup by clicking on the plus icon. Add two VisualStates to the group.
- Notice the “fx” icon next to the Default Transition. Click on it and from the dropdown select the TransitionEffect you would like to use. Some effects have additional options (for “Slide In” there’s the option for slide direction).
- Next to fx icon you can set an easing and the duration of the transition, mine is 1 second long.
- So now there will be an animation between the two states we created. Next step is to wire up the states. On the Assets panel in the Behaviors, there’s a behavior called GoToStateBehavior. In this Behavior we can connect an event with a state. Just what we need. Expand the “ContentFrame” Border element in the Object and Timeline panel. Drag a GoToStateBehavior to the ContentFrame. Then drag another one.
- Using the Behaviors, we can connect the NavigatingState with the Navigating event and the NavigatedState with the Navigated event. We can do this on the Properties panel of each Behavior.
- After the events are connected with the states, we can run the application and voila, the navigation is animated.
Though you may notice that not only the content is animated, but the selected TransitionEffect is applied to the navigation links’ header also. This might be an unwanted side-effect. For a workaround, switch to XAML view, and move the whole VisualStateManager definition just inside the Grid we created in the first step. Something like this:1: <Grid x:Name="LayoutRoot" Style="{StaticResource LayoutRootGridStyle}">
2:3:4: <Grid Margin="0,0,0,0">
5:6: <!-- VisualStateManager moved from LayoutRoot, just the Content will have the TransitionEffect -->
7: <VisualStateManager.CustomVisualStateManager>
8: <ei:ExtendedVisualStateManager/>
9: </VisualStateManager.CustomVisualStateManager>
10: <VisualStateManager.VisualStateGroups>
11: <VisualStateGroup x:Name="VisualStateGroup">
12: <VisualStateGroup.Transitions>
13: <VisualTransition GeneratedDuration="0:0:1">
14: <ei:ExtendedVisualStateManager.TransitionEffect>
15: <ee:SlideInTransitionEffect/>
16: </ei:ExtendedVisualStateManager.TransitionEffect>
17: <VisualTransition.GeneratedEasingFunction>
18: <CircleEase EasingMode="EaseIn"/>
19: </VisualTransition.GeneratedEasingFunction>
20: </VisualTransition>
21: </VisualStateGroup.Transitions>
22: <VisualState x:Name="NavigatingState"/>
23: <VisualState x:Name="NavigatedState"/>
24: </VisualStateGroup>
25: </VisualStateManager.VisualStateGroups>
26:27: <Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}" Margin="0">
28: ...
For the demo I added the “Slide In” effect to the Cosmopolitan Theme Sample. Notice when there are a lot of different controls on a page the transition might not be very smooth. That’s the case in the demo on the SDK Controls and Toolkit Controls page, where the page contains a lot of different controls. Loading all the controls takes long, it’s not the effect itself that is slow. Well, nothing is perfect.
TransitionEffect in an MVVM application
The second sample for using transitions is an MVVM application. Scenario is simple; we have a few Views and a menu. The user can select between the Views, and one is visible at a time. I really like Laurent Bugnion’s MVVM Light Toolkit for its simplicity and efficiency, so I’ll be using that.
We will create a DataTemplate selector ContentControl, and will bind the Content to the selected ViewModel. Let’s create the Views and ViewModels first.
- First, we can start a new application using the MVVM Light (SL4) template. The MainPage.xaml, the MainPageViewModel and the ViewModelLocator will be automatically created.
- We can add the a few Views and their ViewModels using the MVVM Light Toolkit templates (add new item: MvvmView(SL) and MvvmViewModel (SL)). Let’s call these OneView, TwoView, ThreeView and OneViewModel, TwoViewModel, ThreeViewModel.
- In the ViewModelLocator we must set up properties for the ViewModels. We can do this by using the “mvvmlocatorproperty” snippet. Once this is done for all three ViewModels, we can set up the DataContext bindings in the Views.
1: private static OneViewModel _oneViewModel;
2:3: /// <summary>
4: /// Gets the OneVM property.
5: /// </summary>
6: public static OneViewModel OneVMStatic
7: {8: get9: {10: if (_oneViewModel == null)
11: {12: CreateOneVM();13: }14:15: return _oneViewModel;
16: }17: }18:19: /// <summary>
20: /// Gets the OneVM property.
21: /// </summary>
22: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
23: "CA1822:MarkMembersAsStatic",
24: Justification = "This non-static member is needed for data binding purposes.")]
25: public OneViewModel OneVM
26: {27: get28: {29: return OneVMStatic;
30: }31: }32:33: /// <summary>
34: /// Provides a deterministic way to delete the OneVM property.
35: /// </summary>
36: public static void ClearOneVM()
37: {38: if (_oneViewModel != null)
39: {40: _oneViewModel.Cleanup();41: _oneViewModel = null;
42: }43: }44:45: /// <summary>
46: /// Provides a deterministic way to create the OneVM property.
47: /// </summary>
48: public static void CreateOneVM()
49: {50: if (_oneViewModel == null)
51: {52: _oneViewModel = new OneViewModel();
53: }54: }
The DataTemplate selector
For the DataTemplate selector we must create a custom ContentControl.
- Add a new class (in my case it’s called MvvmDataTemplateSelector) that inherits from ContentControl.
- Add a property - type of DataTemplate - for each property.
1: /// <summary>
2: /// DataTemplate for type OneViewModel
3: /// </summary>
4: public DataTemplate OneView { get; set; }
5:6: /// <summary>
7: /// DataTemplate for type TwoViewModel
8: /// </summary>
9: public DataTemplate TwoView { get; set; }
10:11: /// <summary>
12: /// DataTemplate for type ThreeViewModel
13: /// </summary>
14: public DataTemplate ThreeView { get; set; }
- Override the OnContentChanged method. In this method connect the ViewModel with its View, as we will bind the Content to the selected ViewModel.
1: protected override void OnContentChanged(object oldContent, object newContent)
2: {3: // select ContentTemplate for ViewModel
4: if (newContent is OneViewModel)
5: {6: ContentTemplate = OneView;7: }8: else if (newContent is TwoViewModel)
9: {10: ContentTemplate = TwoView;11: }12: else if (newContent is ThreeViewModel)
13: {14: ContentTemplate = ThreeView;15: }16:17: base.OnContentChanged(oldContent, newContent);
18: } - Set up the MainPage and MainPageViewModel. We can add buttons for each view in the xaml, and in the MainPageViewModel we can add Commands. Each Command will set the SelectedViewModel property to a ViewModel.
- Finally we can host our Views in the newly created MvvmDataTemplateSelector. Now when we compile and run the application we can switch between the Views.
1: <!--DataTemplates -->
2: <DataTemplate x:Key="oneView">
3: <Views:OneView />
4: </DataTemplate>
5: <DataTemplate x:Key="twoView">
6: <Views:TwoView />
7: </DataTemplate>
8: <DataTemplate x:Key="threeView">
9: <Views:ThreeView />
10: </DataTemplate>
11: ...12: <Helpers:MvvmDataTemplateSelector
13: Content="{Binding ActiveViewModel}"
14: OneView="{StaticResource oneView}"
15: TwoView="{StaticResource twoView}"
16: ThreeView="{StaticResource threeView}"
17: HorizontalAlignment="Stretch"
18: VerticalAlignment="Stretch"
19: HorizontalContentAlignment="Stretch"
20: VerticalContentAlignment="Stretch"
21: />
TransitioningContentControl
The easiest way to add transitions to our application is to use the Silverlight Toolkit’s TransitioningContentControl:
1: <toolkit:TransitioningContentControl
2: Grid.Column="1"
3: Content="{Binding ActiveViewModel}"
4: Style="{StaticResource TransitioningContentControlStyle2}"
5: HorizontalContentAlignment="Stretch"
6: VerticalContentAlignment="Stretch">
7: <toolkit:TransitioningContentControl.ContentTemplate>
8: <DataTemplate>
9: <Helpers:MvvmDataTemplateSelector
10: Content="{Binding }"
11: OneView="{StaticResource oneView}"
12: TwoView="{StaticResource twoView}"
13: ThreeView="{StaticResource threeView}"
14: HorizontalAlignment="Stretch"
15: VerticalAlignment="Stretch"
16: HorizontalContentAlignment="Stretch"
17: VerticalContentAlignment="Stretch"
18: />
19: </DataTemplate>
20: </toolkit:TransitioningContentControl.ContentTemplate>
21: </toolkit:TransitioningContentControl>
There’s one drawback, there are only three transition animations built in the Control. Luckily we can help that by editing its template, thus enabling Blend 4’s TransitionEffect.
- Open up Blend, and on the MainPage edit the TransitioningContentControl’s template (right click, edit template, edit a copy.) It will look like this:
The Control consists of two grids, one for the previous content, and one for the current content, this way enabling a transition between them. Each Transition animation has a State, when you set the TransitionName property, you set one of the upper States. The transition will happen between the Normal state (we cannot delete this) and the selected one.
To add a new animation, you can add a new State, and set-up a Storyboard for it. This time though we will enable one of the built-in TransitionEffects, by setting the Default transition just like in the Navigation Framework example. - We can add a new State, or just edit the existing ones. I’ve edited the DefaultTransition: deleted the other States (this step is not necessary), deleted the DefaultTransition Storyboard, and in the State I set the PreviousContentPresetationSite to Collapsed, just like in the Normal state, because we will take care of this in the Default transition.
- Select the Default transition (the one with the TransitionEffect), and create a Storyboard, where you hide the PreviousContentPresentationSite halfway through the transition.
At 0:00,000 the PreviousContentPresentationSite is Visible, at 0:00,500 it is Collapsed. The full transition is 1 second long. Of course you can change the timeline, e.g. when you are using a non-linear easing for the TransitionEffect.
Here’s the code for the finished VisualStateManager:1: <VisualStateManager.CustomVisualStateManager>
2: <ei:ExtendedVisualStateManager/>
3: </VisualStateManager.CustomVisualStateManager>
4: <VisualStateManager.VisualStateGroups>
5: <VisualStateGroup x:Name="PresentationStates">
6: <VisualStateGroup.Transitions>
7: <VisualTransition GeneratedDuration="0:0:1">
8: <ei:ExtendedVisualStateManager.TransitionEffect>
9: <ee:PixelateTransitionEffect/>
10: </ei:ExtendedVisualStateManager.TransitionEffect>
11: <Storyboard>
12: <ObjectAnimationUsingKeyFrames
13: Storyboard.TargetProperty="(UIElement.Visibility)"
14: Storyboard.TargetName="PreviousContentPresentationSite">
15: <DiscreteObjectKeyFrame KeyTime="0:0:0.5">
16: <DiscreteObjectKeyFrame.Value>
17: <Visibility>Collapsed</Visibility>
18: </DiscreteObjectKeyFrame.Value>
19: </DiscreteObjectKeyFrame>
20: </ObjectAnimationUsingKeyFrames>
21: </Storyboard>
22: </VisualTransition>
23: </VisualStateGroup.Transitions>
24: <VisualState x:Name="DefaultTransition">
25: <Storyboard>
26: <ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
27: Storyboard.TargetProperty="(UIElement.Visibility)"
28: Storyboard.TargetName="PreviousContentPresentationSite">
29: <DiscreteObjectKeyFrame KeyTime="00:00:00">
30: <DiscreteObjectKeyFrame.Value>
31: <Visibility>Collapsed</Visibility>
32: </DiscreteObjectKeyFrame.Value>
33: </DiscreteObjectKeyFrame>
34: </ObjectAnimationUsingKeyFrames>
35: </Storyboard>
36: </VisualState>
37: <VisualState x:Name="Normal">
38: <Storyboard>
39: <ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
40: Storyboard.TargetProperty="(UIElement.Visibility)"
41: Storyboard.TargetName="PreviousContentPresentationSite">
42: <DiscreteObjectKeyFrame KeyTime="00:00:00">
43: <DiscreteObjectKeyFrame.Value>
44: <Visibility>Collapsed</Visibility>
45: </DiscreteObjectKeyFrame.Value>
46: </DiscreteObjectKeyFrame>
47: </ObjectAnimationUsingKeyFrames>
48: </Storyboard>
49: </VisualState>
50: </VisualStateGroup>
51: </VisualStateManager.VisualStateGroups>
Summary
I hope I could show you in this short tutorial how easy it is to add a transition-animation to your application. The possible scenarios are endless, I’m sure everybody can find his own best way. You can even create custom TransitionEffects if you are familiar with the HLSL language.
Silverlight Cream for July 27, 2010 -- #912
In this Issue: Anton Polimenov, Gill Cleeren, Jeff Fansler, Hannah Watkins, paulio, Michael S. Scherotter, Mohamed Mosallem, and Xianzhong Zhu.
From SilverlightCream.com:
- WP7: UI Concepts of Windows Phone 7
- With hardware descriptions behind him, Anton Polimenov continues his 10-part series at SilverlightShow on WP7 with this one on UI Concepts
- The duplex story: looking at duplex communication in Silverlight 4 - Part 3: Using Net.Tcp
- Gill Cleeren has part 3 of his tutorial series on Polling Duplex with WCF and is discussing Net Tcp this time around
- Introduction to the Windows Phone 7 Accelerometer
- With a nod to Bill Reiss, Jeff Fansler takes off on a discussion of the accelerometer in WP7... good discussion, description, and links
- A little interface animation fun
- Hannah Watkins has some very nice-looking animation going on in her latest post. She describes building the background in Photoshop, then taking everything into Blend and doing some animation.
- Can a developer simplify the Blend design process?
- paulio (also of clearbreeze), took Hannas animation and decided to take a shot at streamlining the xaml some from a developer's perspective.
- A Value Converter for the BALL Watch Silverlight Contest
- Michael S. Scherotter's latest post is double -- not only describing the specific value converter for the Ball Watch contest, but also gives up his Value Converter template that you can get from the Visual Studio Gallery
- Silverlight 4.0 Implicit Styles: Not so implicit after all!
- Mohamed Mosallem describes why your styles might not be all they can be... and how to resolve that problem.
- Write an Online Basketball Shooting Game Using Silverlight 4 and Farseer Engine - Part 1
- Xianzhong Zhu is beginning a series of tutorials building an "Online Basketball Shooting Game" using Physics Helper ... check it out and download the code.
Stay in the 'Light!
Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream
Join me @ SilverlightCream | Phoenix Silverlight User Group
Technorati Tags:
Silverlight  Â
Silverlight 3Â Â Â
Silverlight 4Â Â Â
Windows Phone
MIX10
The duplex story: looking at duplex communication in Silverlight 4 - Part 3: Using Net.Tcp
This article is Part 3 of the series The Duplex Story in Silverlight:
- Looking at duplex communication in Silverlight 4 - Part 1
- Looking at duplex communication in Silverlight 4 - Part 2: Using Sockets
- Looking at duplex communication in Silverlight 4 - Part 3: Using Net.Tcp
In part 2, we looked at sockets. Using pure TCP for their communication, sockets make real duplexing possible: both sides of the communication channel can initiate communication. The server as well as the client can push data to the other side. There is no need to first have a request from the client to the server (which is the case with traditional HTTP).
While sockets are extremely fast, there’s a downside to that story as well: sockets in Silverlight only work on port numbers between 4502 and 4534. Therefore, sockets are great for intranet solutions but not for internet solutions. Also, we saw that working with sockets required an extensive amount of manual coding: there’s no support for WCF, so no proxies or whatever can be used in this scenario.
In this third and final part, we are going to look at the net.tcp binding. This binding was added to the Silverlight with the release of version 4. The great thing about this binding is that it combines some advantages of the polling duplex binding with sockets. In this article, we will recreate the sockets example from part 2, but now using net.tcp. The code can be downloaded here.
Before we dive into the code, we first need to perform some setup with our machine to support this binding.
- In your Windows Features, make sure that Windows Communication Foundation Non-HTTP Activation is installed. If not, have Windows install this feature.
- Make sure that the Net.Tcp Listener adapter service is running. From Control Panel à View Local Services, search for Net.Tcp Listener and make sure that the service is started.
- Open IIS and create a new application (I’ve created the application StockService under the Default Web Site).
- Once the application is created, we can configure it to use Net.Tcp. Right-click on Default Web Site and add the net.tcp binding. For the binding information, enter 4502:*.
- Now, right-click on the StockService à Manage Application à Advanced Settings. In the dialog that appears, add net.tcp after http (which should be there already) in the Enabled Protocols field.
- Go to the root folder of your server (typically “C:\inetpub\wwwroot”). In there, add a clientaccesspolicy.xml. If you omit adding this XML file there, all requests will fail with a security exception because of cross domain restrictions.
The content of this file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<socket-resource port="4502-4534" protocol="tcp" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
- Finally, we of course have to tell Visual Studio that it has to use this IIS folder to host the service we are about to create. In your solution, in the Properties window of the web project, enter the URL of the application (here: http://localhost/StockService).
With these steps completed, your system should be OK to use the net.tcp binding. Let’s now take a look at the net.tcp binding itself!
Advantages of using net.tcp
As already mentioned net.tcp combines advantages of both polling duplex and sockets. Its programming model is, just like polling duplex, based on WCF. That means that we can take advantage of automatic proxy generation inside Visual Studio and will have full IntelliSense with our client-side coding. On the other hand, it’s built on top of TCP. If you have read part 2, you’ll know that TCP stands for the best performance. And indeed, net.tcp has the same great performance. Here you can find a comparison graph between polling duplex and net.tcp. Some of the most striking conclusions are the following:
- Throughput of net.tcp on a worker thread of a Silverlight 4 application is 870x times faster than polling duplex.
- Throughput of net.tcp on a UI thread is 5.5x faster than polling duplex.
- This results is a far better scalability with the same hardware: up to 5x more clients can be connected at the same time with the server when using net.tcp.
On the other hand, again being based on TCP, net.tcp has the same port restrictions (4502-4534), making it a good intranet solution but not an internet solution.
Server-side code
With the entire configuration done, let’s write some code and let’s begin with the server-side code.
The service code is very similar to the service we wrote with the Http Polling Duplex. It defines a CallbackContract which is used from the server code to access the client instances. The operations are marked with the IsOneWay attribute to notify that there should be no waiting for the service response. For more information, refer to part 1.
The code below shows the service contract.
[ServiceContract(Namespace = "Silverlight",
CallbackContract = typeof(IStockServiceClient))]
public interface IStockService
{
[OperationContract(IsOneWay = true)]
void Connect(string stockSymbol);
}
[ServiceContract]
public interface IStockServiceClient
{
[OperationContract(IsOneWay = true)]
void SendUpdate(Update update);
}
The service implementation code is again similar to the duplex binding. We use the GetCallbackChannel() on the OperationContext to get an instance of the client callback contract. This can then be stored in a list that we loop over when updates need to be sent to the client. Below is the relevant part of the service implementation.
public void Connect(string stockSymbol)
{
client = OperationContext.Current.GetCallbackChannel<IStockServiceClient>();
updateTimer = new Timer(new TimerCallback(TimerTick), null, 500, 5000);
}
void TimerTick(object state)
{
if (client != null)
{
try
{
RefreshUpdate();
client.SendUpdate(update);
}
catch (Exception)
{
client = null;
updateTimer.Dispose();
}
}
}
One aspect that is different from the duplex binding is the configuration code. In the web.config, you can notice that the endpoint is now configured to be used with the nettcpbinding.
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<extensions>
<bindingExtensions>
<add name="pollingDuplexBinding"
type="System.ServiceModel.Configuration.PollingDuplexHttpBindingCollectionElement,System.ServiceModel.PollingDuplex"
/>
</bindingExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="DuplexCommunicationNetTcpBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceThrottling maxConcurrentSessions="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<pollingDuplexBinding>
<binding name="DuplexNetTcpBinding" useTextEncoding="true"/>
</pollingDuplexBinding>
<netTcpBinding>
<binding name="DuplexNetTcpBinding">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services>
<service behaviorConfiguration="DuplexCommunicationNetTcpBehavior"
name="DuplexCommunication.Web.StockService">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:4502"/>
<add baseAddress="http://localhost"/>
</baseAddresses>
</host>
<endpoint address="" binding="pollingDuplexBinding"
bindingConfiguration="DuplexNetTcpBinding"
contract="DuplexCommunication.Web.IStockService"/>
<endpoint address="" binding="netTcpBinding"
bindingConfiguration="DuplexNetTcpBinding"
contract="DuplexCommunication.Web.IStockService"/>
<endpoint address="mex" binding="mexTcpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Client-side code
Because we are internally using WCF, we can now have Visual Studio create a proxy for us. Add a service reference to the StockService.svc (http://localhost/StockService/StockService.svc). Apart from the proxy that is created, some code will also be generated in the ServiceReferences.ClientConfig file, as can be seen below. Note that the net.tcp endpoint is now added here; communication will take place over net.tcp on port 4502.
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="NetTcpBinding_IStockService">
<binaryMessageEncoding />
<tcpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="net.tcp://w500:4502/StockService/StockService.svc"
binding="customBinding"
bindingConfiguration="NetTcpBinding_IStockService"
contract="StockService.IStockService"
name="NetTcpBinding_IStockService" />
</client>
</system.serviceModel>
</configuration>
With the service reference added, we can now use the service from client code as follows. Notice that this the normal way you would access a regular WCF service from in Silverlight.
private void StartButton_Click(object sender, RoutedEventArgs e)
{
StockService.StockServiceClient client =
new StockService.StockServiceClient("NetTcpBinding_IStockService");
client.SendUpdateReceived +=
new EventHandler<StockService.SendUpdateReceivedEventArgs>(client_SendUpdateReceived);
client.ConnectAsync("MSFT");
}
void client_SendUpdateReceived(object sender, StockService.SendUpdateReceivedEventArgs e)
{
StockTickingTextBlock.Text = (e.request as Update).Amount.ToString();
}
Summary
The net.tcp binding offers us a great deal for creating duplex communication from within a Silverlight application: while we still have the ability to work with WCF and benefit from all its advantages like proxy generation and IntelliSense, we also have the superb performance, courtesy of TCP on which it is based. Because of the latter, it’s only usable in intranet scenarios though, because of the port restrictions.
About the author
Gill Cleeren is Microsoft Regional Director (www.theregion.com), MVP ASP.NET, INETA speaker bureau member and Silverlight Insider. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. He’s also the author of “Silverlight 4 Data and Services Cookbook”, published by Packt Publishing. You can find his blog at www.snowball.be.
WP7: Push Notifications Peview
Saijo George made a preview of the 3 types of Push Notifications (Tile notifications, Toast notifications and Raw notifications). There is a lot of information about these notifications, but the cool thing about this preview is that there is extracted the most important information about them.
Push Notification is going to play a important role in WP7 and according to the recently published UI Design and Interaction Guide for Windows Phone 7 v2.0 there will be 3 types of Push Notification on windows phone 7
You can see the full story here.
WP7: Where Will Microsoft Find the Customers for Windows Phone 7
Brad Wasson wrote an article about the feature customers of Windows Phone 7 based on his own thoughts. He separated the feature customers in three categories:
1. Existing Customers That Switch From an Older Product to the New One
2. Customers Using Competing Products That Are Convinced to Switch
3. Customers That Don't Currently Have a Product of This Type Which Enter the Marketplace and Purchase your Product
He also describes why the customers from every category will choose Windows Phone 7 instead of some of its rivals.
You can read the full story here.
WP7: HTC Sence on Windows Phone 7?
Despite all the limitations in Windows Phone 7, from HTC are still optimistic about integrating their Sence on Windows Phone 7.
Microsoft has taken firmer control of the core experience [in Windows Phone 7], but we can still innovate.
You can read the full story here.
WP7: Microsoft releases version 2.0 of the UI Design and Interaction Guide for Windows Phone 7
If you are currently developing or you are planning to develop applications for Windows Phone 7, you should read this guide.
If you read version 1 of this guide, here are the highlights for this release:
1. Completely redesigned format to enhance presentation, readability, and highlight guidance more prominently - Layout, from left to right, on every page: image, general information in normal type, guidance in bold type
- Use of color highlights per section
- More visible page numbers
- Formatted to support a hard copy version for RTM
2. Added new content to support beta release of the Windows Phone Developer Tools
3. Reorganized content into four sections: Metro design philosophy, overview of phone UI and features, application interface controls, and miscellaneous
You can download the guide from here.
Entity Framework 4 "Code-First": Custom Database Schema Mapping
In a previous blog post, Scott Guthrie demonstrated how to use the default Entity Framework 4 mapping conventions to enable database persistence. In this post, he discusses how you can override the default persistence mapping rules, and use whatever custom database schema you want.
The CTP4 release of the “EF Code-First” functionality provides a pretty nice code-centric way to work with data. It brings with it a lot of productivity, as well as a lot of power. Hopefully these two blog posts provides a glimpse of some of the possibilities it provides.
"The Way of MEF"-UK Sessions with Glenn Block
Ian Smith has filmed the UK Sessions with Glenn Block in which he talks about the Managed Extensibility Framework (MEF).
We were very lucky to have Glenn Block in the UK recently and he did a whole morning talking about the Managed Extensibility Framework (MEF) to a fairly packed room of around 120 developers on the UK Microsoft Campus.
I was really pleased to be able to host Glenn but I also wanted to get the sessions filmed so that we could share them with people who couldn’t make it on the day.
HTML 5 vs Silverlight : Sencha - The First HTML5 Mobile App Framework
Alexey Zakharov has published the first post of a series about the future of Microsoft Silverlight in a world that is getting crazy about HTML 5.
This won't be just another "black versus white" stories and we are not HTML 5 zealots. In this series we will highlight events happened in the web industry that shows pros and cons of using Microsoft Silvelright and HTML 5.
Frame rate counters in Windows Phone
Jeff Wilcox has posted some information about the frame rate counters and graphics stats for analyzing Silverlight for Windows Phone applications.
While developing Windows Phone applications, it’s good to have some simple but important performance tips and tricks in your back pocket. Here’s a quick reference to enabling frame rate counters plus an overview of what the values represent.
WP7: UI Concepts of Windows Phone 7
This is part 4 of the Windows Phone 7 series:
- What is Windows Phone 7
- Hardware requirements for Windows Phone 7 Part 1 – Buttons, Screen, Cameras, Keyboards, Wireless, Bluetooth, CPU
- Hardware requirements for Windows Phone 7 Part 2 – Light Sensors, A-GPS, Approximate Sensors, Compass, Accelerometer
- UI Concepts of Windows Phone 7
- Software Distributions and Content Restrictions in Windows Phone 7
- Screen Considerations for Developers
- Windows Phone 7 Application Platform
- Silverlight for Windows Phone 7
- XNA for Windows Phone 7
- Getting Started With Windows Phone 7 Development. "Hello, World" Applications
Metro Style
A Windows Phone design system, codenamed Metro is used as a basis for the Windows Phone 7 User Interface. It aims at easily directing end users to the content needed. In order to reach this, its principles focus on a look that uses type to echo the visual language of airport and metro system signage. Harmonious, functional and attractive visual elements are supposed to be realized in Metro interfaces. A good User Interface design should provoke playful exploration when using the application and give users a sense of wonder and excitement. It is highly recommended that developers incorporate Metro design style whenever this is possible. Its clear and straightforward design makes an application legible, while at the same time ecnourages the usage. Based on the application, the requirements may vary, but it still provides a more consistent, fluid User Interface experience from the custom and built-in view.
User Interface elements should be authentically digital and embody harmonious, functional and attractive visual elements. Applications should grab the attention of users by promoting navigation, exploration, and exciting visuals in their design.This concept is the basis for the five principles of the Metro design:
- Clean, light, open, and fast: It is visually distinctive, contains ample white space, reduces clutter and elevates typography as a key design element.
- Content, not chrome: It accentuates focus on the content that the user cares most about, making the product simple and approachable for everyone.
- Integrated hardware and software: Hardware and software blend into each other and create a seamless user experience from single-button access to Search, Start, Back and the camera to on-board sensor integration.
- World-class motion: The Windows Phone 7 touch and gesture experiences on capacitive screens are consistent with Windows 7 on the desktop and include hardware-accelerated animations and transitions to enhance the user’s experience at every turn.
- Soulful and alive: A personalized, automatically updated view into the information that matters most to the user is enabled and brings to life a cinematic photo and video experience by having a fully integrated Zune media player experience.
Metro Style Controls
All controls, that come with Windows Phone 7 Development Tools are metro styled. The Panoramic View Control and the Pivot Control are exclusively developed for Windows Phone 7 but they are yet to be available. Nevertheless, while waiting for the official controls, a “temporary solution” has been elaborated. Here is the link to the codeplex project.
Panoramic View Control
The Panoramic View Control itself is pretty basic.
A Title and Background Image dependent properties are implemented within the Panoramic View Control. Just like a tab control, it also derives from ItemsControll. Each individual Item is of type PanoramaItem. You can think of these as visual sections. There is a default Width, provided by the control, which can be used by every section. Shall more space be needed, a custom Width can be specified. For each PanoramaItem should be assigned header and content properties.
Pivot Control

The Pivot Control is very close to the Tab Control. It can be compared to the dividers of a notebook. It allows multiple pages to be defined for the same window. Each page consists of a certain type of information or a group of controls that the application displays when the user selects the corresponding tab (Pivot Item). To navigate from one page to another you can either click the page’s Header or simply flick through pages.
Other Controls
- Progress Indicator
- Border
- Check box
- Content control
- Content presenter
- Grid
- Hyperlink
- Image
- InkPresenter
- ListBox
- MediaElement
- Multi scale image
- Password box
- Progress bar
- Radio button
- Scroll viewer
- Slider
- Stack panel
- Text block
- Text box
- Canvas
- Push button
Most of the controls have the same functionality as their corresponding controls in Silverlight.
For more info about these controls read the UI Design and Interaction Guide for Windows Phone 7 v2.0.
A Value Converter for the BALL Watch Silverlight Contest
A contestant in the BALL Watch Silverlight Contest sent a request to Michael Scherotter and asked him how to data bind to the day of the week. The solution according to Michael is to create a value converter and use that in the binding.
I create value converters so often in my Silverlight and WPF development, that I created a C# item template that I use over and over in Visual Studio. I’ve posted the item template to the Visual Studio Gallery so you can use it too. The Visual Studio Gallery is integrated with Visual Studio 2010, so you can install and start using the template right from Visual Studio.
Styles in Silverlight: an Introduction
This article is part 1 of a series in which Gergely Orosz is going to cover everything that worths knowing about styles in Silverlight 4.
Styles in Silverlight are a powerful mechanism that allow controlling the visual representation of elements in a unified way for all user interface elements. The concept is similar to using CSS to control the look and feel of HTML.
Style properties differ by element type. For example on a TextBlock (a text element) one can style the FontSize, FontFamily, Foreground and lots of other properties. On an Ellipse however none of these properties can be set, on the other hand it does provide for example the Fill property, that the TextBlock does not.
WPF Chromium WebBrowser updates
Chris Cavanagh has updated the WPF Chromium WebBrowser to use the current Awesomium beta version (1.6) and .NET 4.0.
Here are the known issues/problems:
- Resizing the WebBrowser causes the content to flicker. This appears to be an Awesomium issue, but it needs more investigation (pending support request on Awesomium forum).
- There is an artifact left behind when scrolling a page; this is a known bug in Awesomium and will be fixed by Awesomium RC1.
Windows Phone 7 Jump Start sessions
If you missed the Windows Phone 7 Jump Start live seminars, don't be sorry because now the entire 12 hour course is available for download.
The 12 hours of Windows Phone 7 Jump Start sessions—four virtual sessions to provide developers a jump start for developing Windows Phone 7 applications, presented this week by Microsoft Press authors Rob Miles and Andy Wigley—have concluded. If you missed the sessions, you can watch them via the links below. (Please note that higher quality videos of the sessions will be available in August, after some production work.)
Silverlight 4.0 and Network Authentication while performing Web Request
In this article, Mahesh Sabnis demonstrates how to make a Web request to an external service using the Network Authentication feature.
When you develop Line-of-Business (LOB) applications using Silverlight, many a times you need to make a call to a WCF service and retrieve data from it. Now this service can be a WCF REST service and to make call to this service; the credential information required to send to the service might be different from the credentials of the logged in user. So in this case, to send request to the WCF service from Silverlight 4.0 client, you need to use the ‘WebClient’ class.
Developing for the Windows Phone 7 - Part 1: The Phone
Shawn Wildermuth is one of the lucky guys who received a Windows Phone 7 phone and in this post he demonstrates the phone itself.
My overall first impression is very good. I was able to get e-mail working, XBox Live integration and play with debugging on the phone. This blog entry will exclusively tallk about the phone, not the development experience. I will add new blog entries soon on my experience developing with the phone.
Suggest a Website
If you would know of a Silverlight website that you enjoy visiting and feel others in your Silverlight community might benefit from it drop us a mail.


