Silverlight first asynchronous test run twice

I'm observing a pretty odd behaviour - the first test of my MVVM is running twice.

Exhibit Original code:

 
    [TestMethod, Asynchronous]
public void VMConnectTest() { ViewModel clientVM = CreateVM(); #region connect clientVM.Connect.Execute(null); base.EnqueueConditional(delegate { return clientVM.IsConnected; }); #endregion base.EnqueueTestComplete(); }

I have a break point in CreateVM - and it's firing twice, off the same line.

Changing the code to:

    [TestMethod, Asynchronous] 
public void VMConnectTest() { ViewModel clientVM = null; #region connect base.EnqueueCallback(delegate { clientVM = CreateVM() clientVM.Connect.Execute(null); }); base.EnqueueConditional(delegate { return clientVM.IsConnected; }); #endregion base.EnqueueTestComplete(); }

And now the CreateVM only runs once.

I suspect the Asynchronous test has a bug regarding mixing which thread is suppose to be creating the VM.  In this case, it's running twice.  Throwing everything onto the test stack seems to have fixed this, but makes the code look more complex than usual.

Silverlight Unit Testing Framework - modify/remove Tag Expressions dialog

The default Silverlight Unit Testing framework project has a lovely Tag Expressions welcome dialog that lets you decide (within 5 seconds), whether you want to run a subset.

How do you get rid of it?

image

 

Turns out it's pretty easy:

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            UnitTestSettings settings = UnitTestSystem.CreateDefaultSettings();
            settings.StartRunImmediately = true;
            settings.ShowTagExpressionEditor = false;

            RootVisual = UnitTestSystem.CreateTestPage(settings);
        }

Use UnitTestSystem.CreateDefaultSettings() to get you started quickly, if you create your own UnitTestSettings class you will have to set up your own Test Harness or you'll face this Exception:

 

Test harness was not specified on test harness settings object. If a test harness settings object was passed in, please verify that it contains a reference to a test harness.

Develop and deploy Silverlight + SharePoint 2010 Solutions (part 3 - light it up)

A quick summary of part 2:

  1. How to attach debugger, check network traffic with Fiddler
  2. Do your VIEWFIELDS, FILTER and SORT on the server
  3. LINQ is converted to CAML beneath the hood - but you can avoid CAML…  almost
  4. Trim your service call

Part 3 is all where we Light up SharePoint and take it beyond the browser.  And see why SL + SP is just pure awesome.

 

OUT OF BROWSER

There's one change in Code necessary for Out-of-browser.

        public SharePointChart()
        {
            InitializeComponent();
            sharepointContext = ClientContext.Current;

            if (sharepointContext == null)
            {
                sharepointContext = new ClientContext("http://colt-sp2010/sites/Home/");
            }

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

When you are running Out of Browser you don't have a ClientContext.Current.  No worry, we create one by giving it the Site URL.

(NOTE: this will disable our "mock-data" code, since sharepointContext won't be null anymore)

 

image

Tools in VS.NET 2010 has really improved on this front.  Making Silverlight work out of browser is simply just ticking this one check box.

Which is great - because it means I can pack more stuff into my demo :-)

image

I don't actually need to change any Out-of-Browser settings.  But the one to take note is the "Require elevated trust".  Some features of Silverlight will require full trust in OOB.

Anyway, compile the solution again, and XAP-Deploy to SharePoint document library again.

 

image

Right click to install to computer.

image

Run this from the Computer.

 

DEPLOYMENT CONSIDERATIONS

While XAP-document-library-deployment looks awesome in a demo, there are drawbacks that must be taken into consideration:

  1. Do you leave your end-users to manage versions?  Will they copy your SharePoint Silverlight component and deploy it to 20 document libraries, leaving you no way to centrally upgrade them as a single unit?
  2. In many cases, it is much better for developers to build Silverlight + SharePoint solutions as Sandbox Solutions.  You do this by adding a SharePoint project into your VS.NET, and then configure the xap file to be added to SharePoint as a feature module
  3. Finally, if you want to grant Silverlight additional capabilities that involves additional services deployed on the server, you may need to go back to full Farm-Solutions.  I don't see this as a common scenario.

So the summary version:

XAP document library deployment:

Great for IT PRO who doesn't have permissions.
Not great for version control.

 

Sandbox Solutions:

Great for site collection administrators.
Centralized deployment and good version control capabilities.

 

Farm Solutions:

Useful if you need to deploy server-side stuff, like an extra WCF service.
Build to target Sandbox.

 

SILVERLIGHT INIT-PARAMS

A question in the question time:  Can parameters be specified for Silverlight so that I don't have to hard-code the list internal name.

Yes it can:

Silverlight has a property initParam (think of void Main(string[] args))

The way you access it in code is during the Silverlight app startup.

image

In the application startup event - read the initialization parameters.

image

SharePoint web part configuration lets end-users specify the InitParams in this settings box.

 

This concludes the 3-part Silverlight + SharePoint solutions blog-series.  Let me know what you guys think and if I've made any blunders in the blog.

 

FUTURE IDEAS

A quick brain dump of the future of Silverlight + SharePoint

Silverlight Features

  • Local storage
  • Access Groove as offline storage
  • Camera or mic
  • Local event notification
  • COM access

SharePoint + Silverlight Features

  • "SharePoint-Repair" Silverlight tools
  • Dynamic Language Runtime + SharePoint <- this is going to be super awesome
  • Adding additional farm services

Development (unfortunately not written yet)

  • Full Sandbox Solutions demo
  • Full REST interface demo
  • Full old-WCF services demo

SharePoint: Do you turn off auto update on your SharePoint servers?

Cross Posted from Do you turn off auto update on your SharePoint servers?

A recent Security Hotfix has broken SharePoint WSS3 stand-alone installations.  This has prompted Microsoft SharePoint team to quickly release information regarding how to fix the issue.
http://blogs.msdn.com/b/sharepoint/archive/2010/06/22/installing-kb938444.aspx
This again reminds us that it is always not a good idea to have Windows Update automatically updating your servers.  There are a few reasons.

  1. The previously mentioned problem - where the hotfix could bring down a production environment. 
  2. In fact, even in a development environment this could be hours of lost work as the development team struggles to understand why only some of the developers' SharePoint magically and mysteriously broke overnight.
  3. Windows Update could restart your server, or put your server in a state where it requires restarting - preventing any urgent MSI installs without bringing down the server.

Windows Update remains the best thing for end-users to protect their systems.  But in a server, especially a production server environment - Windows Update patches are just like any new versions of the software that's built internally.  It should be tested and then deployed in a controlled manner.
So recommendations:

  1. Windows Updates may be critical and should be kept relatively up to date.
  2. Have a plan where your awesome Network Admins schedule time to keep the servers up to date - including testing that the servers still perform its functions.
  3. Turn off Automatic Windows Update on Windows Servers

Develop and deploy Silverlight + SharePoint 2010 Solutions (part 2)

A quick summary of part 1:

  1. Environment (tools)
  2. Creating Silverlight project
  3. Creating XAML
  4. Hooking up Silverlight databinding to mock data
  5. Implement real SharePoint query via Microsoft's Client Object Model
  6. Quick discussion of the deploy to document library deployment strategy - I dubbed this XAP-deployment

Part 2 is all about Debugging and Tuning our service calls and see how much fine-grained control we have in talking to SharePoint.  Read on - it's really awesome. 

 

TIMER UPDATE (RE-QUERY)

First problem we have is that the Silverlight application does not re-query the service.  It runs, queries SharePoint once, and then stops.

  1. Let's make it query SharePoint on a periodic basis.  There are various timers available in Silverlight, the easiest to use is the System.Windows.Threading.DispatcherTimer:
  2.         public SharePointChart()
            {
                InitializeComponent();
                sharepointContext = ClientContext.Current;
    
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = new TimeSpan(0, 0, 5);
                timer.Tick += new EventHandler(timer_Tick);
                timer.Start();
            }
            private void timer_Tick(object sender, EventArgs e)
            {
                if (sharepointContext == null)
                {
                    GetData();
                }
                else
                {
                    QueryDataFromSharePoint();
                }
            }
  3. Notes:
    • Create a DispatcherTimer, set it to tick every 5 seconds
    • On each tick - query data from SharePoint
    • By magic of the earlier work we did with databinding in XAML - there is no UI update code required.  The code (controller) updates the data (model) and the UI (view) updates automatically.  This is best practice to move towards full MVVM in Silverlight, and the least amount of headaches down the road.

DEBUGGING SILVERLIGHT

As Silverlight is running in the Browser, debugging the Silverlight application can be done via Attaching the debugger to a running browser process.

image

image

In the list of processes - look for the browser process that has Silverlight run time loaded.

image

You can attach to other browsers as well.

Key notes:

  • Client side debugging Silverlight is superior:
  • Managed Code - not Javascript
  • Browser-independent - no fiddling with different DOM or browser behaviours
  • Server-independent - you could be talking to your development, test, UAT or Production server, the server could be on-premise or in-the-cloud (SharePoint Online).  You are still, debugging the Silverlight that's running on your own machine, calling the server via published services.

 

TUNING SILVERLIGHT

Let's see what Silverlight is doing under the hood.  Run our favourite HTTP sniffer Fiddler 2 (you can also use FireBug or Wireshark - whichever you are familiar with):

image

Since our Silverlight is faithfully re-polling the server every 5 seconds, we see this particular HTTP connection repeating - for as long as the Silverlight app is running (close browser window to stop it)

image

Notice the return traffic is 1.3K - relatively tiny in the scheme of things.  By comparison:

image

  • Full page reload starts at 30k for bare page
  • AJAX web parts are about 20k (rough estimates)

 

Digging in a bit more on the traffic

image

 

 

 

The request is XML

image

The response is gzipped-compressed JSON (Javascript Object Notation)

 

TWEAKING THE QUERY IN LINQ

This next part is tricky but interesting.  The code first.

        private const string ListName = "Football";
        private const string InternalFieldName = "FavouriteCountry";
        private ListItemCollection listItems;
        private IEnumerable<ListItem> listItems2;

        private void QueryDataFromSharePoint()
        {
            Web web = sharepointContext.Web;
            // get our list
            List list = web.Lists.GetByTitle(ListName);
            // get items in our list
            listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());

            
            // still need the earlier syntax to tell sharepoint where to get it
            listItems2 = sharepointContext.LoadQuery(
                listItems.Include(
                    item => item["Title"],
                    item => item[InternalFieldName])
                );

            // but don't actually load it!
            //sharepointContext.Load(listItems);

            // execute the load asynchronously
            sharepointContext.ExecuteQueryAsync(SucceededCallback, FailedCallback);
        }

Notes:

  • We still need a reference to the ListItems Collection via List.GetItems(CamlQuery.CreateAllItemsQuery());
  • We use it as a reference point to begin our LINQ Query
  • The SharePoint ClientContext has a separate LoadQuery method, that returns a new ListItems collection - listItems2, we start from the CAML definition, and further refine it to ONLY include the Title and FavouriteCountry fields.
  • But we don't actually ever call Load on ListItems

Result:

image

We've shrunk the data load from 1.7k down to 359 bytes!

image

The returned JSON object is a lot lighter - and contains only a few of the required fields (ID, ObjectType, ObjectVersion), as well as our Title and FavouriteCountry.

 

MAKE YOUR SERVER DO WORK

Imagine the list is thousands of items.  We don't always want to bring back every list item.  What we should always consider is how to use SharePoint to do much of the work for us, and keep our connection traffic low.

            listItems2 = sharepointContext.LoadQuery(
                listItems.Include(
                    item => item["Title"],
                    item => item[InternalFieldName])                    
                .Where(
                    // add where clause for server to execute
                    item => (string)item["Title"] == "john")
                );

Notes:

  • I'm inserting here a Where clause to my LINQ query.  The Query is to be executed on the server.
  • IMPORTANT: do not use Where clause on the Load method - because that is a LINQ to objects filter and is very bad:  imagine bringing down 1000 items and then do your filtering in memory on the client side…

Result:

image

Only pulling back 1 record.

image

Check out the Request XML - includes the Where clause filter.

SUMMARY

  • How to attach debugger, check network traffic with Fiddler
  • Do your VIEWFIELDS, FILTER and SORT on the server
  • LINQ is converted to CAML beneath the hood - but you can avoid CAML…  almost
  • Trim your service call
  • You probably don't need to poll the server every 5 seconds as well

 

NEXT UP

Wrapping up in the next part for:

  • Deployment considerations
  • Out of Browser
  • REST interface
  • Silverlight initParam

Update: Part 3 (final) is now up.