UPDATE (5/11/2010)
I am changing my domain for my new Silverlight blog to be:
http://www.michaelsnow.com
I will be retiring the name silverlightdev.net so expect this link to go dead after some time.
Sorry for an inconvenience.
--Mike
After a long hiatus from Silverlight (due to my team being moved off Silverlight ☹) I am back to blogging for Silverlight!
When it comes down to technologies, Silverlight is my greatest passion. I spend a lot of my spare time experimenting with building a wide variety of applications using Silverlight.
Going forward, I will be showcasing these applications as well as regular tips and tutorials on my new blog which can be found at:
http://www.silverlightdev.net
Using my own site I will be able to include live demos and sample source code with each tip of the day. I will be cleaning up and migrating a number of tips from here that I find still to be applicable and useful for Silverlight 4 and beyond.
Thanks,
--Mike
With Silverlight you can run your Out-of-Browser applications in elevated trust mode. This will allow you to relax the normal sandboxed barrier Silverlight restricts applications to. While you still will not have full control of the local machine, the following features are made available to you in elevated trust mode:
- Clipboard Access – Retrieve items from the system clipboard without the prompt for permissions to access the clipboard as seen below:
- HTML Hosting – Display HTML Content in the WebBrowser control.
- Removal of Cross Domain Restrictions – Your application can interact with any domain bypassing the normal security check that required the ClientAccessPolicy.xml or CrossDomain.xml files.
- File Access – Your application can now directly access files without user initiated interaction that then invokes the OpenFileDialog or SaveFileDialog dialogs. However, you are still limited to user folders such as My Documents, My Videos, My Music, My Pictures and any sub folder. Example code you can execute:
if (App.Current.IsRunningOutOfBrowser && Application.Current.HasElevatedPermissions)
{
string picturesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
string path = picturesPath + @"\test.txt";
StreamReader sr = new StreamReader(path);
string line = sr.ReadLine();
while (line != null)
{
line = sr.ReadLine();
}
sr.Close();
}
- Notification Window – Also know as a “toast” window, this is a small window that pops up in the lower right corner for a specified interval of time before disappearing.
- COM Interoperability – Direct access to COM enabled applications installed on the clients machine.
In order to configure your application to run in elevated mode open your project in Visual Studio 2010. Once open, right click on your Silverlight application in the solution explorer and select Properties. Under the Silverlight tab, check “Enable running application out of the browser” and click the “Out-of-Browser settings" button as circled below in the screenshot.
Once this dialog is open check the “Require elevated trust when running outside the browser” checkbox as seen circle in the screenshot below.
Now, when a user chooses to install your Silverlight application out of browser they will get this rather intimidating security warning dialog before they can proceed. Note that you can replace this dialog with something more friendly if your XAP is digitally signed (this will be covered in the next tip of the day).
Final Notes
On a final note, you will want to make certain your application verifies it’s running in out of browser mode before making calls that are required to be in this mode before being executed. Your application can check to see if it’s running in Out-of-Browser mode through this call:
if (App.Current.IsRunningOutOfBrowser)
{
}
Also, your application can verify it has elevated permissions with this call:
if (Application.Current.HasElevatedPermissions)
{
}
Thank you,
--Mike
This morning we released Silverlight 4 Tools for Visual Studio 2010!
The link to download and installs the tools is http://go.microsoft.com/fwlink/?LinkId=177508.
The tools will install:
- Silverlight 4 RTM Developer Runtime
- Silverlight 4 Tools RC for VS 2010
- Silverlight 4 SDK RTM
- Silverlight 4 Tools RC Package
- WCF RIA Services RC
Note that this is the RC release of the Silverlight 4 tools. With these tools you can start developing Silverlight 4 applications using Visual Studio 2010.
If you are not familiar with what’s new in SL 4 check out Tim’s blog here: http://timheuer.com/blog/archive/2009/11/18/whats-new-in-silverlight-4-complete-guide-new-features.aspx
If you haven’t already downloaded VS 2010, you can get the free Express version from here: http://www.microsoft.com/web/gallery/install.aspx?appid=VWD2010.
If you are a MSDN subscriber you can get the full version here: http://www.microsoft.com/visualstudio/en-us/download
Thanks and enjoy!
--Mike
If you have the Silverlight 3 SDK RTM version (not the GDR) installed on your box you will need to first uninstall it before running Visual Studio 2010 beta 2 setup.
This is irrespective of the SDK language version or platform. The SDK GDR does not install on top of the RTM version of the SDK. This problem should be remedied by RTM.
If you proceed with install in this state you will get an error at the end of install stating that the SDK failed to install. This error does not affect your setup of beta 2 for Visual Studio but you will still need uninstall to SDK RTM and re-install the SDK GDR if you wish to get the latest version of the SDK.
To uninstall the RTM version of the SDK:
- Go to your Add/Remove programs.
- Select Microsoft Silverlight 3 SDK.
- Right click on it and choose uninstall from the context menu.
At this point you can proceed with installation of Visual Studio 2010 Beta 2 which can be downloaded from here.
Note that you can install the SL3 GDR SDK directly from here: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=1ea49236-0de7-41b1-81c8-a126ff39975b.
Thank you,
--Mike
Tomorrow, June 30th, is the release date for my book titled “Game Programming with Silverlight”. Writing this book was a great experience as it was the first book I have ever written. It was extremely time consuming mostly because it was a learning experience but I am glad I did it.
Also, I apologize for the lack of Silverlight tips these days! Finishing the book was my top priority but I am looking forward to getting back to adding Silverlight tips on a regular basis.
The book itself covers a lot of what I discuss here in this tips blog but with more detail. Here is a quick outline of what I covered in the book:
Chapter 1: Silverlight 101. I start the book off by giving a thorough introduction into Silverlight, XAML and Silverlight controls.
Chapter 2: Getting Started. This chapter covers using Visual Studio 2008 and 2010 for creating Silverlight projects.
Chapter 3: What’s new with Silverlight 3. I cover each and every new feature to Silverlight 3 that could pertain to game development.
Chapter 4: Silverlight Tips and Tricks. Mostly tips I covered here in my blog.
Chapter 5: Creating the World. Covers the map editor I created that allows you to create maps for your games. Also, I discuss resources where you can obtain game art from.
Chapter 6: Object Manager. I discuss how to use a web service to load objects from. Also, I cover the different types of objects you might have in a multi-player adventure type game.
Chapter 7: Animation. This chapter discusses the variety of ways to perform animation in Silverlight.
Chapter 8: The Client UI. I discuss the ways you can lay out your client UI in your game.
Chapter 9: Network Support: I discuss how to make your game multi-player using socket programming.
Chapter 10: Extras: In this final chapter I discuss a variety of topics such as how scrolling maps smoothly, player movement, chat boxes and reflections.
Let me know if you have any suggestions or ideas on what you would want to see in a future book (Game Programming with Silverlight 4 for example).
Thanks!
--Mike
With the release of Silverlight 3 Beta 1 GPU (Graphics Processing Unit) acceleration (or hardware acceleration) is now available. The GPU is a processor attached to your graphics card that is generally used for calculating floating point operations. In addition, it contains a number of graphics primitives that when used will save you a lot of CPU time.
By default this option is disabled and to use it you must enable it both on your Silverlight control/plug-in as well as any of the controls you want to leverage it.
To enable it on your Silverlight control open your web page that hosts the Silverlight control.
For HTML modify the Silverlight control to include the following param:
<param name="EnableGPUAcceleration" value="true" />
For ASPX add the following attribute:
<asp:Silverlight ID="Silverlight1" EnableGPUAcceleration="true" runat="server" Source="~/ClientBin/MyApp.xap" MinimumVersion="3.0.40307.0" Width="100%" Height="100%" />
Now, to apply it to a control you will need to add CacheMode="BitmapCache” to the control. The following example shows you how to add it to an Image control:
<Image CacheMode="BitmapCache" Source="MyImage.png"></Image>
Currently BitmapCache is the only option. What this does is it causes visual elements (and all their children) to be cached as bitmaps after they have already been rendered. Once cached, your application can bypass the expensive rendering phase for the cached elements and just display them.
If you want to test out what is being cached in your application add the following attribute to your Silverlight control:
<asp:Silverlight EnableCacheVisualization="true" ID="Silverlight1" EnableGPUAcceleration="true" runat="server" Source="~/ClientBin/MyAPp.xap" MinimumVersion="3.0.40307.0" Width="100%" Height="100%" />
Uncached objects will appear tinted where as cached objects will not be tinted.
This feature is supported on:
-
Windows: Both full screen and non-full screen
-
Mac: Full screen only.
This feature should be used when the following are occurring to your control:
-
Transformations (translating, rotating, stretching, etc.).
- Clipping.
- Blending.
Thank you,
--Mike Snow
Subscribe in a reader
Of the course of the last year I have been collecting links to some really good Silverlight tutorial blogs that I thought I would share with you. These are active blogs, frequently updated, that are specifically oriented to teaching Silverlight development. That is, they are all about showing you how things are done and giving you the source code you need to do it yourself. If I have missed any good links post a comment and I will add it!
Silverlight tutorial sites in alphabetical order:
Also, here is a great Silverlight Blog summary page: http://www.netvibes.com/rboarman#Silverlight
Thank you,
--Mike
When calculating the positions of objects such as Images make certain to use integer values not floating point values.
For example, take a look at this code that centers a map around a given position:
private void CenterMap(double windowWidth, double windowHeight)
{ if (null != _parentCanvas)
{ int leftPos = (int) ((windowWidth / 2) - _currentX);
int topPos = (int) ((windowHeight / 2) - _currentY);
_parentCanvas.SetValue(Canvas.LeftProperty, (double) leftPos);
_parentCanvas.SetValue(Canvas.TopProperty, (double)topPos);
}
}
Notice I converted the map layout position left and top to be integers. The following screen shot shows an example where double values were used instead of integers. The result is the images are slightly blurred and lines (or seams) appear between the image tiles.
Compare the screenshot above that used doubles with the shot below that used integers. In the screen shot below the images are crisp and the terrain tiles have no seams or lines.
Thank you,
--Mike Snow
Subscribe in a reader
Unless you have had your head under a rock you probably have heard Silverlight 3 Beta 1 has been released! If you haven’t already, please install it from http://silverlight.net/getstarted/silverlight3/default.aspx
This release comes packed with some of the greatest features to date. If you are a game developer, you will be happy to hear the following features below are now included in Silverlight 3. I will be writing detailed blogs on a number of these to help you apply them to your application.
Image Opened
In Silverlight 2 it was difficult to accurately determine when a image was completely opened. This case was often needed to determine the actual dimensions of the image. The problem occurred because the DownloadProgress is fired at 100% before the image is fully decoded. The solve this, a new event called ImageOpened is available. Now you can be guaranteed to get the right size for the image. Example:
private void LoadImage(string fileName)
{ Image img = new Image();
Uri uri = new Uri(fileName, UriKind.Relative);
img.Source = new System.Windows.Media.Imaging.BitmapImage(uri);
img.ImageOpened += new EventHandler<RoutedEventArgs>(Image_ImageOpened);
}
void Image_ImageOpened(object sender, RoutedEventArgs e)
{ Image img = (Image)sender;
BitmapImage bi = (BitmapImage)img.Source;
double width = bi.PixelWidth;
double height = bi.PixelWidth != _radius)
}
XAP Compression
Optimization were made to drastically reduce the size of the XAP file. You can expect the XAP file size to now be on par (if not better) than Windows zipping. Games often come packed with a lot of content so obviously the smaller your XAP the faster your customers will be able to download your game.
Perspective 3D
Perspective 3D transforms can now be applied to Silverlight controls via the PlaneProjection property. This allows you to rotate a 2D control in a 3D plane.
Example code that shows how to do this:
<Image Source="Man.png">
<Image.Projection>
<PlaneProjection RotationX="45"></PlaneProjection>
</Image.Projection>
</Image>
Pixel Shaders
Pixel shaders allow you to apply effects to controls such as images. There are two built in effects available by default: Drop Shadow and Blur. In addition, you can write and apply your own custom effects.
The following images show the result of applying pixel shader effects to them.
Example code to accomplish this through a built in shader:
<Image Source="dwarf.jpg">
<Image.Effect>
<BlurEffect></BlurEffect>
</Image.Effect>
</Image>
Binding
You can now bind controls to properties of each other. For example, the Text of a TextBlock can bind to the Text of a TextBox. Or, a TextBox Text can bind to the Value of Slider. Example:
<StackPanel>
<TextBox x:Name="UserText"></TextBox>
<TextBlock Text="{Binding Text, ElementName=UserText}"></TextBlock></StackPanel>
Whatever someone types in the TextBox is automatically reflected in the TextBlock.
Bitmap API
Bitmap APIs are now available through a class called WriteableBitmap. This method takes as parameters the surface width and height and the pixel format.
Example code:
WriteableBitmap wb = new WriteableBitmap(0, 0, PixelFormats.Bgr32);
wb.Render(img, new ScaleTransform());
wb.Lock();
// walk through WriteableBitmap[]
wb.Invalidate();
wb.Unlock();
Hardware Acceleration
Silverlight now makes use of the GPU (Graphics Processing Unit) for rendering which frees up CPU time for other tasks. The GPU typically sits on a video card. It is a dedicated graphics processing device that is used for a variety of tasks such as calculating floating point operations.
Animated Text Performance Improvements
A property called TextRenderingMode now allows you specify RenderForAnimation. This turns off optimizations that could directly affect text animation such as scaling, rotating, etc. The result is a smother, more peformant animation of text. Example on how to set this property:
RenderOptions.SetTextRenderingMode(MyTextbox, TextRenderingMode.RenderForAnimation);
Network Monitoring API
There are now API’s that allow you to monitor the status of the network. To see if a network is available you can call:
bool isConnected = NetworkInterface.GetIsNetworkAvailable();
You can also hook up an event that will fire when the network status changes:
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
To access these methods you will need to reference the namespace System.Net.NetworkInformation;
SaveFileDialog
Finally we are able to save files in Silverlight! Calling this method will invoke a dialog that will allow you to specify a file to save to. The method returns a pointer to a Stream that you can than write to. Example code:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "map files (*.xml)|*.xml|All files (*.*)|*.*";
sfd.ShowDialog();
System.IO.Stream stream = sfd.OpenFile();
// Save your data here
stream.Flush();
stream.Close();
Make certain to flush and close the stream or the file will not be created.
CaretBrush
The CaretBrush is useful because you can now change the appearance of the caret. This was a problem if, for example, you wanted to have a background color of a textbox set to back. The cursor was also black so it would not appear. Example on how to set it:
<TextBox Foreground="White" Background="Black" Width="200" Text="Hello">
<TextBox.CaretBrush>
<SolidColorBrush Color="White"></SolidColorBrush>
</TextBox.CaretBrush>
</TextBox>
Resulting Screenshot (notice the white caret):
Local Connection
This feature allows two separate Silverlight applications to communicate with each other on the client side without the need to roundtrip to the server.
Implementing this is fairly straight forward. Start by creating two separate Silverlight applications. To one, add this code that will listen for a message:
LocalMessageReceiver receiver = new LocalMessageReceiver("R2D2");receiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(receiver_MessageReceived);
receiver.Listen();
You will need to reference System.Windows.Messaging to make these calls. The constructor for LocalMessageReceiver takes any unique identifier.
To the other application add this code that will send a message to the first Silverlight application:
LocalMessageSender sender = new LocalMessageSender("R2D2");sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(sender_SendCompleted);
sender.SendAsync("Hello World!");
Navigation
Navigation is now supported in Silverlight. This allows you to do things like hook up navigation in your Silverlight application to the Back and Forward buttons of your browser. A new template called “Silverlight Navigation Application” is available that demonstrates how to do this.
Essentially to accomplish this you will need to put your main page in a <navigation:Frame>. You add history by this call:
this.Frame.Navigate(new Uri(currentPage, UriKind.Relative));
Then, when the back and forward buttons of your browse are clicked this frame object will intercept them and display the correct page.
System Colors
You can now get access to a users settings for their System Colors. These are available through System.Windows.SystemColors.*. Example: System.Windows.SystemColors.ActiveBorderColor. This will allow ou present a contrast that matches a user's settings.
Other
- Out of Browser Experience – Allows you to run your Silverlight application as a desktop application.
- Assembly Caching – Enables non-core runtime extensions to be cached.
- ManagedResourceDictionary – Manage resources files in separate files.
- New controls – A number of new controls have been added.
- H.264 / AAC Media Playback – Newly supported Media format.
- Animation Easing Effects – Grants more visual effects including smoother transitions.
- Media Logging – Allows you to collect data about a customer and their meda experience. The data is posted back to one or many servers for analysis.
Thanks,
--Mike Snow
Next