SpriteHand
Module Border
  Most recent blog entries
Module Border
Obfuscating Silverlight (for free)
Andy's Blog By Andy Beaulieu on 4/15/2010 5:39 PM

You might be aware that when you publish a Silverlight XAP on the web, your source code is very vulnerable to prying eyes. A XAP file is in a ZIP compressed format, and the contents are .NET Assemblies and resources which can be disassembled easily using a tool like .NET Reflector . Although there is no sure-fire way to stop someone from copying your Silverlight application logic, obfuscation can at least make it a bit more difficult to hack through.

Babel Obfuscator for .NET

There are a few obfuscators out there that support Silverlight, but they can be pricey. However, Babel Obfuscator started out as a community project and still maintains a freeware edition. Additionally, it appears that the new version of Babel has corrected some issues with obfuscating Silverlight assemblies.

Here is how you can use the free edition of Babel Obfuscator to encrypt your Silverlight assemblies: (I should mention, if you do have $149 laying about, I recommend buying the Pro version of Babel which has XAP support)

1.       Download the Free edition of Babel Obfuscator.

2.       Download the Free 7-zip compression utility. We’ll need this to update the obfuscated assemblies in our Silverlight XAP file. If you are happier with a different ZIP utility, go ahead and use it instead.

3.       Inside your Silverlight solution, right-click the Silverlight project and select Properties.

4.       Go to the “Build Events” tab and add the following inside the Post-build event command line:

"C:\Program Files\Babel\babel.exe" $(TargetPath) --noildasm --nomsil --noinvalidopcodes

"C:\Program Files\7-Zip\7z.exe" a $(TargetDir)$(ProjectName).xap $(TargetDir)BabelOut\$(TargetFileName) -y -tZIP

This post-build event will run the Babel Obfuscator against your assembly, which places it into a “BabelOut” subdirectory. Then we use 7-zip to bring that updated, obfuscated assembly back into our XAP file.

Examining the Obfuscation

We can use a tool like .NET Reflector to see what the obfuscator does for us. Here is some example before-and-after code showing an example of the obfuscation.

BEFORE OBFUSCATION

    private bool IsRagDollPart(string part);
    private void LayoutRoot_KeyDown(object sender, KeyEventArgs e);
    private void LayoutRoot_KeyUp(object sender, KeyEventArgs e);
    private void MainPage_Loaded(object sender, RoutedEventArgs e);
    private void newObstacleExplode_Exploded(ucObstacle source);
    private void newObstacleExplode_Exploding(ucObstacle source);
    private void PositionBalloon(ucObstacle obstacle);
    private void PositionEnemy(FlyingEnemyBase enemy);
    private void PositionPowerUp(PowerupBase powerUp);
    public static double RadiansToDecimalDegrees(double radians);
    private void ResetLevel();
    private void ShieldActive(bool isActive);
    private void ucExplosion1_Exploded(ucExplosion source);
    private void ucMainGame_KeyDown(object sender, KeyEventArgs e);
    private void ucMainGame_KeyUp(object sender, KeyEventArgs e); 

AFTER OBFUSCATION

    private void (bool );
    private bool (string );
    private void (object );
    private void ();   
private
void (PowerupBase );
private void (bool );
    private void (ucObstacle );
    private void (ucExplosion );
    private void ();
    private void (ucObstacle );
    private void (ucObstacle );
    private void (PowerupBase );
    private void (FlyingEnemyBase );
    private void (object , KeyEventArgs );
    private void (object , KeyEventArgs );

 

Comments (12)

Windows Phone: Silverlight for Casual Games
Andy's Blog By Andy Beaulieu on 3/28/2010 5:58 PM

Thanks to everyone who attended my session at Code Camp 13 in Waltham, "Windows Phone: Silverlight for Casual Games." It's great to see so many people sharing my excitement for Windows Phone 7!

In this session, we talked about the new hardware, Silverlight support, the Emulator, GPU Acceleration, monitoring performance, Behaviors, sound support, input, and monetization of your games.

As promised, here are my slides and demos from the talk.

[DOWNLOAD SLIDES]   [DOWNLOAD DEMOS]

And here are some links to get you started with creating fun games with Silverlight for Windows Phone 7:

Install Checklist for Windows Phone Development

Windows Phone 7 Developer Portal

Physics Games in Silverlight on Windows Phone 7

Windows Phone 7/Silverlight Performance

How To: Handle Manipulation Events

Forums on Silverlight.net

Forums on WindowsPhone

 

Comments (2)

Windows Phone 7 + Silverlight Performance
Andy's Blog By Andy Beaulieu on 3/25/2010 1:48 PM


If you’re creating a graphics intensive application (such as a game) for Windows Phone 7 (WP7) using Silverlight, you’re going to want to maximize performance for both the emulator and your Silverlight code. Let’s look at some ways to maximize both of these.

WP7/Silverlight Graphics Performance

WP7 devices have a separate GPU which is optimized for handling graphics operations such as displaying, scaling, rotating, and 3D. Silverlight on WP7 has the ability to use that GPU, which can greatly increase graphics performance. It does this by allowing a “snapshot” of a visual, called a Bitmap Cache, to be handed over to the GPU for manipulation.

  • Storyboard Animations are Automatically GPU Accelerated.
    If you create a Storyboard animation on SL for WP7, it will automatically use the GPU when it can for displaying, scaling, rotating, and rectangular Clips.  There is nothing you need to do to enable this, it is automatic. This is kind of a “bonus feature” of Silverlight 3 on the Windows Phone (it is not available in desktop Silverlight 3 or Silverlight 4).

  • Procedural Animations need a CacheMode attribute.
    If you are moving elements via code, such as for a game, they will not be automatically GPU accelerated like a Storyboard. You need to add in a CacheMode attribute like so:

    <Canvas x:Name="cnvShip" CacheMode="BitmapCache"

    But make sure you add this only on elements that do not change visually. That is, imagine that you’re taking a snapshot of the element that is cached, and handing that over to the GPU. If anything changes inside that element’s visuals, then the cache will be invalidated and you’ll lose the advantages of caching.

  • Perspective 3D Transforms can be GPU Accelerated.
    If you use a PlaneProjection in a Storyboard, it will use the GPU. You can also apply a CacheMode=”BitmapCache” attribute to a 3D Transform and it will use the GPU. This is another “bonus feature” of Silverlight 3 on the Windows Phone (it is not available in desktop Silverlight 3 but is introduced in Silverlight 4).

  • Examine Graphics Metrics.
    We can get some good graphics metrics from Silverlight on WP7 by adding the following code:

    Application.Current.Host.Settings.EnableFrameRateCounter = true;

    This will show the following metrics at the top of the device window:


    A – Render Thread Framerate
    B – UI Thread Framerate
    C – Amount of Video Memory Used
    D – Total # of Textures Used
    E – Total # of Intermediate Textures Used

    Note that Silverlight on WP7 uses two separate threads, a Render thread for visuals, and a UI thread, to handle input and application logic. Seema Ramchandani gave a great talk detailing these counters at http://live.visitmix.com/MIX10/Sessions/CL60

  • See what’s Using the GPU.
    For performance, we want as many elements to be rendered by the GPU as possible. We can see what is rendered by the GPU by using the following code:

    Application.Current.Host.Settings.EnableCacheVisualization = true;

    When this is set, any elements that are NOT cached will have a colored tint to them. If an element appears its normal color then it IS being cached and handled by the GPU.

  • See What is Being Redrawn.
    For best performance, we want to minimize what is being redrawn on each frame. We can use the following setting in code:

    Application.Current.Host.Settings.EnableRedrawRegions = true;

    … which will show a ghost copy of the visual whenever it is redrawn. If you are seeing  a lot of redraws, and they are large portions of the UI, then maybe you can add some more CacheMode attributes so it is offloaded to the CPU. (Note that when something is handled by the GPU, you will NOT see any redraw regions).

Emulator Performance

Ensure the Emulator can use your Host’s GPU.
The Emulator can take advantage of the GPU on your computer to render graphics, greatly increasing its performance… but only if it meets a couple of requirements.

1.       Make sure your video card supports at least WDDM 1.1 and DirectX 10.

a.       From the Start Menu, select Run and enter dxdiag

b.      Go to the Display tab and ensure that the DDI Version and Driver Model are 10 or better and 1.1 or better, respectively.

c.       To be extra sure the Emulator will like your video card, create an XNA Windows Phone Game. This project template is a bit pickier with GPU support.

                                                               i.       Start up Visual Studio and create a new XNA Game Studio 4.0/Windows Phone Game.

                                                             ii.      Run the project. If you get the following error, then the Emulator will not support your GPU.

Deploy failed with the following error: The current display adapter does not meet the emulator requirements to run XNA Framework applications

… However, all is not lost. It could be that you just need to upgrade your video card drivers. Visit the site for your video card manufacturer and see if they have some newer bits (This one actually worked for me J)

Enable Virtualization in your BIOS

Support for Virtualization at the CPU level is provided on newer processors. This can significantly increase the speed of emulators, allowing them to talk more directly to the CPU, instead of a software layer. Because this is a CPU-level function, you need to go into your computer’s BIOS to enable it (it will normally be OFF by default, so you will need to switch it on).

1.       Reboot your computer and look for the magic BIOS key. It could be Ins, Del, a Function Key, it all depends on the BIOS version.

2.       Once inside the BIOS, look for a category named “Virtualization” or something to that effect. Switch all of those options on.

Summary

I’m sure there are some things here I missed or just didn’t know about, so please give me your comments. Here are a few links to other resources on the topics above:

Silverlight Performance on Windows Phone – Seema Ramchandani

WP7 Developer FAQ

Silverlight 3: GPU Acceleration + Bitmap Caching – My Blog

Comments (3)

Silverlight 4 PathListBox for Motion Path Animation
Andy's Blog By Andy Beaulieu on 3/18/2010 9:03 PM

The PathListBox control is a cool new addition to the Blend 4 SDK, and allows the elements inside a ListBox to lay out along any Path control shape. You’ll need to install the Blend 4 SDK to get access to the PathListBox control, but note that this is available outside of Expression Blend 4 (you don’t need to purchase or install Blend 4).

One of the neat bonus features of the PathListBox is that you can animate the Path that it is bound to, and the items will follow the animation! This gives Silverlight functionality similar to the AnimationUsingPath class that WPF has had since .NET 3.0, and provides basic Motion Path Animation.

Let’s see how we can use PathListBox for some interesting effects.

[VIEW DEMO]  *Requires Silverlight 4*

[DOWNLOAD DEMO]

-          Open Blend 4 and expand the Asset Library. To quickly find the PathListBox control, type PathListBox into the search box.

-          Draw a PathListBox control onto the artboard, and give it a name of “pathListBox1”

-          In order for the PathListBox to determine the shape that its Items should follow, you’ll need to draw out a Path control. Select the Pen tool and draw out a shape.

-          We only want to use the Path for its shape information, so let’s hide its visual representation. Set the Fill and Stroke to “No Brush” (you can quickly do this by select “Reset” from the Advanced Property Options – that little square to the right of the brush selection).

-          Now, select the PathListBox control, and in the Properties Panel, go to the Items Layout category and click the Artboard Element Picker. Then select the Path that you created in the previous step by clicking on it in the Artboard.

-          Select the main UserControl in the Objects and Timeline Panel.

-          Go to the Events Panel in the Properties Panel and double-click the Loaded event.

-          Add a little bit of code inside the Loaded event, which fills the PathListBox with an array of characters (note that we can data bind a character array to the Items Source of a control):
private void UserControl_Loaded(object
sender,
System.Windows.RoutedEventArgs e)
{
       
// TODO: Add event handler implementation here.

   
string data = @"This is the theme to Gary's Show, the theme to Gary's show.
                                Gary called me up and asked me if I'd write his theme song."
;
    pathListBox1.ItemsSource = data.ToCharArray();
   
}

-          Run the project by hitting F5. The characters follow the Path. Weird effect, eh?

-          Let’s try animating these chars. Add a new Storyboard named sbAnimateChars.

-          Select the Storyboard (by clicking its name just above the Objects and Timeline Panel), and set its RepeatBehavior to “Forever”


-          Fast-forward the timeline for the storyboard a second or so.

-          From the toolbox, grab the Direct Selection tool and drag around the points within your Path element (Blend records changes in Path points within a Storyboard for you).

-          Add another line of code into the MainPage_Loaded event handler, to start the Storyboard up:

sbAnimateChars.Begin();

-          Run the project. You’ll see the characters animated on the Path.

Comments (5)

Physics Games in Silverlight on Windows Phone 7
Andy's Blog By Andy Beaulieu on 3/17/2010 9:11 PM


The
Physics Helper Library now supports Windows Phone Development!

[DOWNLOAD PHYSICS HELPER]

[SEE A TEASER]

[DOWNLOAD SAMPLE PHONE PROJECT]

* UPDATE 05/17/10: Fixed for April Refresh of WP7 Tools



If you want to create some fun physics-based games for this upcoming platform, you’ll first want to first visit the Windows Phone Development site and download the tools you’ll need.

The Physics Helper Library is a collection of Behaviors and UserControls that make is easier to create 2D physics games in Silverlight using the Farseer Physics Engine. The Physics Helpers have gone through several different iterations – in their original release for Silverlight 2, they were solely UserControls; in Silverlight 3 support for Behaviors was added, and later WPF support was added into the library, thanks to contributions from the community.

Now that everyone, including myself, is hyped about Silverlight on the Windows Phone, I was eager to get the library working under the new emulator, and it turns out that it didn’t take much effort at all because of the great job the Silverlight team did to make Windows Phone a “real” Silverlight (version 3) implementation!

Because Windows Phone contains a true Silverlight 3 implementation, assemblies are binary compatible, and you don’t even need to recompile the Physics Helper assemblies for the Phone. In fact, all I needed to do was remove a reference to System.Windows.Browser (as that is missing on the phone), and I was up and running.

Another Physics Sample!

Pete Blois (on the Microsoft Blend team), has also ported his Box2D Engine based samples to the Windows Phone and created a really neat physics based game which he demoed at MIX10. If you want to check out the Box2D engine instead of Farseer, you can check out Pete’s work.

Accelerometer Support

The Windows Phone doesn’t have any useful hardware buttons for games, so you can bet that the Accelerometer on the device will be very important for input. Mike Harsh gave a great presentation at MIX where he explained the axes of the Accelerometer:

As the device is tilted, you’ll usually get a value between -1 and 1 for each axis. I say usually because if you fling the device around you could actually get a bigger number – that’s because the value is based on G-force. At least, that is the idea, I haven’t had  my hands on an actual device to confirm J

The problem is that the emulator included with the Windows Phone developer tools does NOT simulate an accelerometer. But in chatting with Pete Blois, a good workaround for now is to use a mouse drag event to emulate the accelerometer “tilt.” You can see this method in the Sample project at the top of this blog post. Note that there is an “AccelerometerWrapper” class which handles the Perspective Transform and mimicking the Accelerometer with mouse movements. Again, I haven’t tested this on an actual device but from what I’ve heard this is a good simulation of the accelerometer data.

The Sample Project

Let’s dissect the sample a bit. Because of the similarities in code between browser-based Silverlight 3 and Phone-based Silverlight 3, I am taking the approach of a single solution that contains both a SL3 project AND a Windows Phone project. Then I am using a linked file to reuse the exact same code for the main game user control (ucMainGame):

I think I will stick to this approach because it will allow supporting multiple platforms (web + phone) with a single project. And to be honest I’m not all that happy with the Windows Phone Emulator’s speed so for most debugging tasks I can stick with the Silverlight 3 web project.

More Resources

If you’re new to the Physics Helper, check out the videos and info at http://physicshelper.codeplex.com.

If you’re new to Windows Phone Development (like all of us), you’ll be happy to know that 90% of the game is knowing Silverlight. But for the other 10%, check out these sessions from MIX:

Changing our Game – an Introduction to Windows Phone 7 Series

Authoring for Windows Phone, Silverlight 4 and WPF 4 with Expression Blend

Overview of the Windows Phone 7 Series Application Platform

Building Windows Phone Applications with Silverlight, Part 1

Building Windows Phone Applications with Silverlight, Part 2

Silverlight Performance on Windows Phone

 

Comments (12)

Silverlight 4: GPU Accelerated PlaneProjection
Andy's Blog By Andy Beaulieu on 3/16/2010 11:22 AM

Silverlight 4 introduces GPU Acceleration to Perspective 3D Transforms (PlaneProjection), which allows much better performance with simple 3D effects. Perspective 3D Transforms were originally introduced in Silverlight 3, and allow 2D visual elements to be rotated in 3D space. Consider the example below…



An image element, plain and simple.

The same image element, with a PlaneProjection applied to simulate 3D space.

The problem in Silverlight 3 was that PlaneProjection’s were rendered using software instead of the video card (GPU), so you could quickly peg the CPU if you overused this transform effect.

So how much faster is a PlaneProjection when using hardware acceleration? Well it all depends on your video card, but chances are it’s crazy fast J Here is a little sample that will let you compare software vs. GPU rendering in Silverlight 4:

VIEW THE SAMPLE WITHOUT GPU ACCELERATION. Add a bunch of phones and notice how the framerate starts to drop.

VIEW THE SAMPLE WITH GPU ACCELERATION. Add a bunch of phones and notice how the framerate remains consistently high.

DOWNLOAD THE SAMPLE. Requires Visual Studio 2010, Silverlight 4.

HOW TO GPU ACCELERATE A PLANEPROJECTION

We can apply hardware acceleration to a Perspective Transform in the same way as any UI element:

1.       First, enable GPU Acceleration at the plug-in level. Open you Silverlight host html page, and add the following parameters to the plug-in.

enableGpuAcceleration – required for any acceleration to take place
enableCacheVIsualization – if true, then any elements that are not cached will be tinted a color.
enableFrameRateCounter – will show a framerate counter at the top-left of the plug-in window.

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
  <param name="source" value="ClientBin/AccceleratedPersp3DSimple.xap"/>
  <param name="onError" value="onSilverlightError" />
  <param name="background" value="white" />
  <param name="minRuntimeVersion" value="4.0.50303.0" />
  <param name="autoUpgrade" value="true" />
  <param name="enableGpuAcceleration" value="true" />
  <param name="enableCacheVisualization" value="false" />
  <param name="enableFrameRateCounter" value="true" />

  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50303.0" style="text-decoration:none">
                <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
  </a>
</object>


2.       Next, apply a PlaneProjection to a visual element (in this case we’ll apply it to an Image element), and add in a CacheMode=”BitmapCache” attribute.

<Image x:Name="phoneFront" CacheMode="BitmapCache" Source="phoneSkin.png" Stretch="Fill" Width="303" Height="587" >
       <Image.Projection>
        <PlaneProjection x:Name="rotateFrontY" RotationY="0" GlobalOffsetZ="0"/>
       </Image.Projection>

</Image>

3.       That’s it! The PlaneProjection will now be rendered by the GPU.


SOME NOTES

This simple example makes it look easy, but as you get into more complicated examples you may run into issues. Keep in mind the following:

1.       Not all video cards are created equal. You will see entirely different performance and caching thresholds on different GPU’s. And on some low-end Netbooks, you may actually see worse performance when caching is turned on.

2.       The content of the PlaneProjection needs to stay static in order to keep the Cache valid. Think of the cache as a snapshot of the contents of the PlaneProjection which can be manipulated by scaling, clipping and perspective transforms. But if any of the contents are animated, it can invalidate the cache and you will lose most benefits of GPU acceleration.

3.       Be careful when setting properties on Visual elements such as Visibility. The Silverlight property system does not check if a property is “really” changed from its previous value, so if you change values often, you can incur extra rasterizations. If you look at the sample code, you’ll see that a _state flag that tells when to change Visibility to cover this issue. Thanks to David Ferguson at Microsoft for this tip!

 

Comments (4)

Silverlight on Windows Phone!
Andy's Blog By Andy Beaulieu on 3/15/2010 1:06 PM


You’ve probably heard the rumors during the past weeks, but at the
Mix10 Keynote this morning, ScottGu and Co. confirmed all of the leaks about Windows Phone 7 Series !

You can download the tools you need now, including Silverlight and XNA development libraries and a Phone Emulator.

 

Microsoft has created a stringent list of requirements for hardware manufacturers, which should keep a consistent experience across devices, while keeping competition high among manufacturers (and therefore pricing low!) Back in the day I did some Pocket PC development and it was challenging to make sure your application worked with each device and processor type. Another problem was the different hardware buttons that each device had, and the Key codes that they raised through events. New Windows Phones will have three consistent buttons: Back - Start – Search.

There will also be some great monetization opportunities. First, you can place your applications on the MarketPlace as a pay-for-download product. And in the Keynote, we saw that ads can also be displayed over your app for ad-based revenue.

So what kind of applications will the device handle? There were several sample apps shown but definitely the most hardware intensive was "The Harvest" (this was first shown at the GDC conference last week), which showed a complete 3D dynamic environment.

Needless to say I am very excited about this new Silverlight platform! I will embrace it first for casual games development using Silverlight, and will be sharing my development experiences in future blog posts!

 

Comments (0)

.toolbox: FREE Silverlight Training
Andy's Blog By Andy Beaulieu on 3/14/2010 12:17 PM


Looking for great free training in Silverlight and Expression Blend? The Expression Blend Evangelism Team at Microsoft has just released .toolbox, an online training source for designers and developers!!

One of the unique aspects of the .toolbox training is that it enlisted the talents of real-world design agencies to create the sample applications you use in the training. I think this makes for challenging and realistic training scenarios. I personally created several of the .toolbox training modules, and it was equally challenging as a trainer to pull apart the awesome creations from the top-notch design agencies and form useful training modules from them.

.toolbox has some other great features including an Avatar and progress tracker where you can earn badges as you complete different levels. I hope you'll find the .toolbox modules a great free training resource!

Here are links to the modules I created for .toolbox:

Games
This module shows you how to build two different games using Behaviors and States. You'll create a Pong style game and a Space Invaders style game as you learn about these powerful Silverlight features.

Sound Mixer
This module introduces you to the MVVM (Model-View-ViewModel) pattern. Throught the lessons, you'll implement the View portions (UI) for a Sound Mixer prototype.

Recruit
Here we'll look at how to design a Line of Business (LOB) type application. You'll use States, Databinding, Maintenance Improvements, and how to take the application Out of Browser.

Portfolio
This module breaks down an existing Silverlight site template and examines ways of improving it through using design methods, refactoring, adding a splash screen, behaviors and resources.

Comments (1)

VS2010: The "ValidateXaml" task failed unexpectedly
Andy's Blog By Andy Beaulieu on 2/11/2010 9:18 AM


As you're moving all of your Silverlight solutions into Visual Studio 2010, you might encounter an error on compile like so:

System.IO.FileLoadException: Could not load file or assembly 'file:///C:\dev\Silverlight\xxx\yyy.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///C:\dev\Silverlight\xxx\yyy.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See
http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

This error is due to referencing one or more assemblies that were downloaded from the web and perhaps extracted from a ZIP file - things such as third party controls. These assembly files have a "block" flag set on them for security.

There are a couple of ways around this:

  1. To do a one time fix for the assemblies that are firing this error, find the assembly in Windows Explorer and right-click and select Properties. Click the "Unblock" button at the bottom right of the "General" tab.

  2. UPDATE 2/11/2010: I just learned from Mark Boulter (Microsoft) that the following tweak might not be a good idea, so use at your own risk. In fact, any tweaks to devenv.exe.config are not a good idea. Anyway, I'll leave this info up in case anyone is feeling frisky.

    You can also permanently disable this security check in Visual Studio 2010. Open the VS2010 config file at this location:

     %ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.config

    ...and add the following under the <CONFIGURATION> element:

     <runtime>
      <loadFromRemoteSources enabled="true" />
     </runtime>


Comments (13)

Using RIA Services Programmatically
Andy's Blog By Andy Beaulieu on 1/7/2010 9:56 AM


Many demos of WCF RIA Services show off using the DomainDataSource Class to in a declarative manner to quickly throw together a data-enabled application. And in VS2010, there is added support for using the Data Sources Window to Drag/Drop data entities onto the designer --- this action also adds a DomainDataSource instance into your XAML.

For many applications, using a DomainDataSource in XAML is fine and enables RAD development. But some pundits (Hi Shawn!) argue that having direct interaction with the Data Layer from the UI Layer is bad for proper Model/View separation, testability, and general karma.

Luckily, there are several ways to use WCF RIA Services programmatically - without relying on the DomainDataSource controls in XAML. Let's take a look at some of these programmatic methods:

Download the Demo Code
  * requires SL4/VS2010 Beta 2, WCF RIA Services Beta

Using the DomainContext

The DomainContext class allows the Silverlight client to access the Domain Service Class you created on the server side. A new DomainContext class is automatically generated on the client side for you when you create a new Domain Service.

In the demo, our DomainContext class is named BeerContext. We can load all of the Beer rows from the database using the Load method, passing in an entity query that exists in our Domain Service:

BeerContext _beerContext = new BeerContext();


LoadOperation<Beer> loadBeers = _beerContext.Load(_beerContext.GetBeersQuery());

grdLoadFromContext.ItemsSource = loadBeers.Entities;

We can also use a LINQ query against a DomainContext, allowing us to request more specific records:

EntityQuery<Beer> beerQuery = from b in _beerContext.GetBeersQuery()

                               where b.BrewerId == 1

                               select b;

LoadOperation<Beer> loBeers = _beerContext.Load(beerQuery);

grdLoadWithLinq.ItemsSource = loBeers.Entities;

Using DomainDataSource In Code

Normally, you will see the DomainDataSource class used declaratively in XAML. But we can also utilize a DDS through code and take advantage of its paging, filtering, sorting and grouping functions . Consider this code, which creates a DDS and executes the GetBeers query, only retreiving the Beers for BrewerId == 1. Note that only the records for BrewerId == 1 are sent from the server, because the DDS creates an appropriate query for any paging, filtering, sorting, or grouping functions.

DomainDataSource dsBeers = new DomainDataSource();

dsBeers.LoadSize = 30;

dsBeers.QueryName = "GetBeers";

dsBeers.AutoLoad = true;

dsBeers.DomainContext = _beerContext;

dsBeers.SortDescriptors.Add(new SortDescriptor("BeerName", System.ComponentModel.ListSortDirection.Ascending));

dsBeers.FilterDescriptors = new System.Windows.Data.FilterDescriptorCollection();

dsBeers.FilterDescriptors.Add(new System.Windows.Data.FilterDescriptor("BrewerId", System.Windows.Data.FilterOperator.IsEqualTo, 1));

grdLoadDomainDataSource.ItemsSource = dsBeers.Data;
dsBeers.Load();

 

Comments (9)

Module Border Module Border
Module Border
  Subscribe
Module Border
RSS   Twitter
Module Border Module Border
Module Border
  Diversions
Module Border


PHYSAMAJIG
This Windows app was created using Physics Helper XAML, and the Farseer Physics Engine.
DOWNLOAD

MORE INFO



TALKING RAGDOLL
This Windows Phone app was created using Silverlight, the  Physics Helper Library,  and the Farseer Physics Engine. It gets interesting when you import your friends photos and have your way with them!

MORE INFO



BOSS LAUNCH
This physics game won first place in the Server Quest Contest. Created using Silverlight , the Physics Helper Library,  and the Farseer Physics Engine.
PLAY IT

MORE INFO



DESTROY ALL INVADERS
A scrolling shooter game where the objective is to destroy the invading UFO's flying over a neighborhood of your choosing. Imagery provided by Microsoft Virtual Earth. Created using Silverlight.
PLAY IT

INFO AND CODE



PHYSICS HELPER DEMOS
These demos were created for the Physics Helper Library, which makes it easy to create physics games and simulations using Expression Blend, Silverlight, and the Farseer Physics Engine.
PLAY IT

INFO AND CODE



HOOK SHOT
This little basketball game took first place in the TeamZoneSports Silverlight Contest. Created using Silverlight and the Farseer Physics engine.
PLAY IT

MORE INFO



SORT THE FOOBARS
A game where you need to sort the good foobars from the bad ones. Created using Silverlight and the Farseer Physics engine.
PLAY IT

MORE INFO



POLYGON PHYSICS DEMO
A demo showing polygon physics where the user draws physics objects with the mouse. Created using Silverlight and the Farseer Physics engine.
PLAY IT

MORE INFO



SILVERLIGHT ROCKS!
Destroy the asteroids before they destroy your ship! Created using Silverlight.
PLAY IT

INFO AND CODE



FISH GAME
A simple game of harpoon-the-fish. Written using the AJAX Sprite Toolkit.
PLAY IT

INFO AND CODE

Module Border Module Border
Module Border
  Search_Blog
Module Border
Module Border Module Border
Module Border
  Blog_Archive
Module Border
Module Border Module Border
Copyright (c) 2014 andy.beaulieu.com - Login
toms outlet cheap toms jordan pas cher Timberland Boots mulberry outlet portafoglio prada hollister soldes hogan scarpe mbt hogan jordan pas cher louboutin soldes jordan Homme louboutin pas cher Gucci Borse louboutin pas cher jordan pas cher lancel pas cher cheap ray ban sunglasses ray ban outlet toms outlet toms outlet scarpe mbt occhiali da sole a basso costo Louboutin Chaussures basket louboutin hollister pas cher jordan shoes sale