Developing on Staxmanade

Silverlight – DataBind to an Anonymous type (Who knew?)

I searched the web for the idea first. I was certain somebody had blogged about this before, and just wanted to quickly confirm it’s truth. Unfortunately all I came across were work-a-rounds and people telling you it’s not possible. So hopefully this post will help the next guy.

Since anonymous types are generated in an assembly as internal types, by default, if you try to DataBind to an anonymous type, you’ll probably receive a binding error much like the following.

System.Windows.Data Error: 
Cannot get 'Age' value (type 'System.Int32') from '{ Name = World, Age = 23 }' (type '<>f__AnonymousType0`2[System.String,System.Int32]').
BindingExpression: Path='Age' DataItem='{ Name = World, Age = 23 }' (HashCode=-172495608);
target element is 'System.Windows.Controls.TextBlock' (Name='');
target property is 'Text' (type 'System.String')..
System.MethodAccessException: Attempt by method 'System.Windows.CLRPropertyListener.get_Value()'
to access method '<>f__AnonymousType0`2<System.__Canon,System.Int32>.get_Age()' failed.

at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj,...
at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj,...
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, Bind...
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, Bind...
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, ...
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, ...
at System.Windows.CLRPropertyListener.get_Value()
at System.Windows.PropertyAccessPathStep.ConnectToPropertyInSo...


Turns out, it _IS_ possible to DataBind to an anonymous type in Silverlight.



All you have to do is expose your privates. Placing the following into your AssemblyInfo.cs will give the built in bindings the ability DataBind to your object(s).





[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Windows")]



 



I’m not going to say whether this is or is not a good idea, and I’m sure there’s many ways to abuse it.



Don’t inhale too much of this stuff.

Comments

Jason.Jarrett
W.Meints

I'm not sure I understand your question. Could you elaborate a little?
W.Meints
What about dynamics, does the same trick apply to those kind of objects as well?
Obsidience
I prefer to keep my privates unexposed, thank you very much! ;)

StatLight – Goes Open Source

Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight.

What is it? (Silverlight Testing Automation Tool)

StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing TDD/BDD/(insert your test style here) during Silverlight development.

Where can I get StatLight?

http://StatLight.CodePlex.com

 

Happy Coding !!!

StatLight (Silverlight Test Automation Tool) V0.8 Released

image

A new version of the StatLight tool has been released.

Download: http://www.statlight.net

Major Feature Updates:

  • Support for 64bit
  • Back support for previous Microsoft.Testing.Silverlight assemblies
    • By giving the tool a specific -v=[December2008 | March2009 | July2009], StatLight can now run the asynchronous tests supported by the Microsoft Testing library.
  • Xml report output.
    • By giving the tool the -r=<FilePath.xml>. StatLight will write out an xml report of the test run.
  • Update to the Silverlight 3.0 Runtime – Should be compatible with Silverlight 2.0 assemblies.

Minor Updates:

  • Support for auto-closing modal Silverlight MessageBox dialogs.
  • Update feedback to the end user for when access to run statlight web service is not allowed (Added better feedback on how to get it up and running).
  • Added a timeout monitor to detect when the StatLight browser has not communicated with the StatLight server within a reasonable amount of time. StatLight will stop running if communication (a test message) has not arrived within 5 minutes. (Will look into making this configurable)
Also to note:

Silverlight Unity & Moq backed AutoMocker

I’ve pushed the Silverlight Unity/Moq AutoMocker into the moq-contrib project.

Well the other day I need the automocker and ended up running into a bug that was in my old-old-old pre-release version of moq for Silverlight, so I took the time to get the released version and re-compile the automocker.

I published it to the moq-contrib project. Haven’t taken the time to create a binary release, but should be able to get latest build, execute the build.Silverlight.cmd and in the drops\Current-Silverlight should be Moq.Contrib.UnityAutoMocker.Silverlight.dll

Enjoy!

StatLight – V0.5 released!

A new version of StatLight has been released!

Major Features Added:

  • NUnit support
  • Further MSTest support
    • In the previous version (0.4) you could only use StatLight with the March 2009 build of Microsoft.Silverlight.Testing.dll. It will now work with any version.
      (Update: the Silverlight Asynchronous testing style is not currently supported)

Minor Tweaks:

  • The debug.assertion creates a failure test event
    • It used to write a message to the console. It will now create a failure event, similar to a test that fails.
  • Support for [Ignore]’d tests for each supported framework (MSTest, NUnit, Xunit)
Soon to come:

T4 replacement for “Add Service Reference”

My company has been developing out parts of our website using Silverlight to enable some rich client LOB scenarios. Since the companies inception, we developed in a Scrum/Agile manner 3-6 week iterations. However, recently we started experimenting with a more “feature driven” attempt at “lean” approach.

With this new development approach, we made the decision that the trunk of the project’s source will be ready to deploy to production at all times. And as such would develop features out on branches. This is where the problem lies… We started running into a “Maximum file path length…” issue when branching the source. It’s a relatively old project (5 years or so now) with layers of projects/namespaces.

We traced the issue down to files generated by the Visual Studio’s Add Service Reference dialog.
image image

In our case the generated files had the full namespace + service name which were, in some cases, greater than 90 characters long just for the file. Coupled with the fact they were already nested in a directory structure (that helped keep things organized). We ended bumping into the “Maximum file path length…” when trying to branch the project.

After researching a hunch I’d had

Most of those files generated by the tool are garbage and never used, so why does VS generate them, and have to check them into TFS?

Here’s a good post describing the meta data files.
http://www.scottseely.com/blog/09-01-26/Misunderstood_Add_Service_Reference.aspx

I found out that the only thing we cared about was the “References.cs” file in that whole batch of files.

Now, we would like to, and have thought about writing our own code in place of using the VS generated, (I know I’ve heard from the WCF pros at IDesign that you should never use the “Add Service Reference” generated stuff…) however it does what we need with the exception of the super long file names generated and…every time we update the service reference it keeps trying to add the ServiceReferences.ClientConfig back into the project. Since we are not using a config file to store the WCF connection information. We are following a similar path you can read about here (http://geekswithblogs.net/mwatson/archive/2009/02/24/129655.aspx) This way we don’t have to have separate configs for Dev/Test/Production.

The built in VS Service Reference tooling has become more of a hindrance to development than providing any benefit.

What is the solution we came up with to these two issues?

What were the problems again?

1. Files generated by “Add Service Reference” tools are too long for TFS (Not the fault of the tool, more the fault of the (TFS/.net api/win api) for not supporting longer file names…

2. Every time we update/add new service reference it tries to re-add the ServiceReferences.ClientConfig file (DON”T WANT THAT)

After about 1/2 a day looking for alternatives to using the built in tool, and since the wcf svcutil doesn’t generate code Silverlight can use. I stumbled upon this blog Command line WCF Proxy Generation for Silverlight 2 RTM where he figured out how to use the same dll VS uses to generate the source and wrapped it into a little console app… After chatting w/ him on his blog’s Live Messenger plugin, (very cool by the way) he emailed me the exe he’s using in his production app (that had a couple bug fixes since his original blog post. He told me just to use Reflector to get at the source because it was very basic.

And so I did, and ended up with a pretty good solution to the problems above. (Sucks that I spent a day of dev time on this crap, but oh well…)

I wrote a T4 template that will generate all the reference.cs code needed in our Silverlight project. Instead of describing the template itself (since this post has gotten long alredy) I’ll include a project with a sample of how it works.

Some of the features you get using this template are:

  1. It solves the two issues stated above
    1. Only one file generated.  (None of the VS generated garbage metadata files)
    2. No re-add of the ServiceReferences.ClientConfig file to the project.
  2. With the use of the T4 template (this is in our app, not in the sample below) you can put other logic needed when generating a service reference.
    1. We are using it to update the Web.Config’s WCF aspnet compatibility flag so we can get at the wsdl and setting it back when done updating the service reference…
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
  3. You can set some properties that will tell the tool to generate the types as “internal” (if you want)

    Note: you have to add the correct InternalsVisibleTo for this to work

    [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization")]

Here’s the sample project with examples of both a normal reference, and the same reference using the T4 template.

DOWNLOAD SAMPLE PROJECT

Hope this helps someone else…

Comments

Mega
How to reuse types in referenced assemblies ?
Jason.Jarrett
Nice! Thanks for the feedback!
Chris
This was great. We used the concept to modify the code dom and add DebuggerNonUser code attributes to every class. This allowed us to ignore the web service proxies when performing code coverage.

Thanks for the post.
Jason.Jarrett
I just tried it and it appears to be working (possibly you ran into a temporary skydrive issue?)

Try it again if you can.
Anonymous
than you for the article.
But the skydrive link doesn't work.
I allways end up with
"There's a temporary problem

There's a temporary problem with the service. Please try again. If you continue to get this message, try again later.
"
Anonymous
Jason,

Awesome post, thanks. I just figured out that i couldn't use overloading on my wcf service methods. But if you create the reference.cs your self it is possible. But writing the whole service ref. is to time-costly. This is the perfect solution for that. Thanks for posting!

Vincent Ottens
Jason.Jarrett
James,

I'm not sure what you're asking. If you read up on T4 templates, you should be able to find out that you can put any logic you want in there...
James
Great post, thanks. I'm interested in putting in custom logic, as you mentioned, but not sure where to start via the source provided...can you point me in the right direction? Thanks.
Anonymous
Can you please provide a VS 2010 Beta 2 sample of this, I tried but I can't get it to work, looks really promising thouhg.
Voleti
This is very useful. I was trying to figure out whether or not use Add Service Reference. Got some questions answered here. Thanks.

Introducing StatLight (Silverlight Testing Automation Tool)

 

What is it?

StatLight is your first class TDD/BDD/(Insert your testing style here) tool for Silverlight. Its main focus is developer productivity.

(The website is young, however the tool is ready to go… Download StatLight here)

In the realm of Silverlight, the tooling support has not had the chance to catch up to what you might have come to expect from normal .net development. When developing Silverlight applications using a test driven style, with the current tooling, it can become a little more tedious than one might like.

A number of testing methodologies have sprung up to enable some sort of testing for Silverlight developers; however, few actually run the tests in the browser.

Below is a short list of features StatLight currently has.

Features:

  1. In browser runner to test how your code will “actually” run in the wild.
  2. TeamCity Continuous Integration support
  3. Smooth Console Runner
    1. One time runner (screenshot below)
      image
    2. Continuous Integration runner
      1. This runner will startup and watches for any re-builds of your text xap file. Every time you re-build it will pick up the new test xap and immediately start running the tests.
      2. This feature gives the most as far as developer productivity.
      3. I will put out a video to show how best to use it soon…
  4. Tag/Filtering support (to narrow down the tests run at a given time)
  5. XUnit support leveraging XUnit (Light)
  6. MSTest support. (March 09 build)

On the way:

  1. Better Documentation and how to/help videos
  2. NUnit support leveraging Jeff Wilcox’s NUnit port
  3. CruiseControl.net support
  4. MSBuild

Download StatLight here

Silverlight DataGrid NOT sorting when binding to IEnumerable<T>

This may be common knowledge when working with a Silverlight DataGrid, or any grid control in .net. However, I fought through this lesson the other week.

We are using Prism V2 in a business application at work. When databinding several grids to a presenter I tried to enable sorting and ran into an issue where the grid wouldn’t sort if the property being bound to was an IEnumerable<T>…

Once I changed the property’s type to a List<T> on the presentation model (and all the correct sorting xaml tags were set) the grid became sortable.

The other strange thing about this was I couldn’t find anything about it on the net… Is this something that is inherent with other data grids?

Comments

Radenko Zec
IEnumerable does not have sort method but generic List have Sort method.
Jason.Jarrett
I probably left a few details out of this post...

I Set the grid's allows sorting property to true and every cell was a custom data template with the SortMember path set
Justin Chase
That is weird. How are you doing the binding? Maybe it's just calling into the IList.Sort method? Seems like it should just use Enumerable.Sort though.

Silverlight AutoMocker with Unity container and Moq

A couple weeks back I threw out a Teaser about a Silverlight AutoMocker... Here's the follow up I promised.

UPDATE: Moq 3.0 released with full Silverlight support http://moq.me/get

I've been working on this off and on for a while now, and finally decided to sit down and finalize (at least this version) of both Moq for Silverlight and an AutoMocking container backed by the Unity IoC from Microsoft.

This isn't by any means "Official", but probably not far from what will be coming out when it's done...

Below are the necessary steps (I can come up with) to get an official version of Moq.

  1. We need an "Official" build of the Castle.DynamicProxy2 dependency
    1. Create NAnt build scripts (Jonathon Rossi said he'd try to work on it this weekend 1/23) Thank God! It tried porting the NAnt build to Silverlight and each of the 3 times I got so lost I gave up... :(
    2. Fix the Castle.Core-Silverlight build (some changes have occurred to the main without being pushed to the Silverlight Version)
    3. Create an official binaries of
      1. Castle.Core
      2. Castle.DynamicProxy
  2. Port Moq to Silverlight
    1. I supplied a patch to Daniel a while ago, but he said he wouldn't include it until #1 above.

But until the official versions become available, here are what I have so far!!!

UPDATE: oops, realized I posted the files below as .7z. You can download and install the free open source zip utility here http://www.7-zip.org/

 

This contains the Moq, Moq-Contrib (w/unity AutoMocker) source

This contains all the binaries you need to run Moq...

 

Please keep in mind I'm by no means an IoC pro and the whole AutoMocker was a one afternoon attempt at throwing one together that I could use in Silverlight. It's very basic, but seems to support most of what I need for now.

Could an AutoMocking container backed by Moq and Unity be a project that the community needs?

Comments

Jason.Jarrett
@Mark

I've been disconnected from the castle dynamic proxy for quite a while. (Last I knew Mr. Rossi was going to get it into the build process) If that's true, building from src would be your best bet. If it's not possible through the NAnt script, then, the way I originally did it, was opening up the Silverlight project in VS and building that way... (I think you have to run the NAnt build at least once for it to setup the AssemblyInfo.cs stuff before you try to vs build)

Hope this helps. (sorry I don't have more info than this)
Mark
Re: the error with generic constraints - I created a test for this and it is fixed on the main build see here: http://support.castleproject.org/projects/DYNPROXY/issues/view/DYNPROXY-ISSUE-92

I'm not sure how to get this into a silverlight version - there doesn't seem to be a Silverlight build. Can you help?

Thanks

Mark
Jason.Jarrett
Any chance you could send an example test?
Anonymous
Hi Jason,
This is really cool...thanks!

I thought you might want to know about an error I received. When mocking an interface containing generic parameter constraints, I receive the error...

System.BadImageFormatException: An attempt was made to load a program with an incorrect format.

...when running the test.

Thanks!
Jason.Jarrett
@Adam - There's two things you can do.

1. Moq-contrib at google code already has an AutoMocker that uses the AutoFac IoC.

or

2. Take my source, recompile the AutoMocker in .net (make sure to get the correct full-framework dependencies)

Hope that helps...
Adam
I would really like an Automocker for the *WPF* side of things.

Silverlight Moq AutoMocker Teaser...

Although we don't have an official Moq for Silverlight yet. You can go to the email list and pull the patch I submitted to get an early version up and running.

I have, in the queue of blog posts, a Silverlight AutoMocker leveraging the new Microsoft Unity container for Silverlight.

I'll wait till we get a full Silverlight version of Moq before posting.

 

P.S.

The existing Moq automocker for the full .NET framework, over at Moq-contrib, is leveraging the Autofac contianer, and when I threw my Silverlight version together Autofac hadn't been ported (yet), however just read a blog today that said it has an early port available.

Comments

Jason.Jarrett
Not sure what you mean bout the "trick"... Mocking just works in Silverlight with Moq. There is one unit test that fails in the Silverlight version when trying to mock the System.Stream class. I didn't dig too far into the specific failure, however I'm sure there are lots of things out there that you won't be allowed to mock because of the security restrictions...
Justin Chase
In a nutshell, what's the trick to mocking with the given security constraints (on reflection) in Silverlight?

Castle.DynamicProxy2 now ported to Silverlight!!!

I know what you're thinking (or at least what I was thinking before I knew better). What is the Castle.DynamicProxy and who cares it was ported to Silverlight?

To be honest I didn't know it existed until I tried to find a mocking framework for doing Silverlight unit testing. Then I found this thread over on the Moq mocking framework's home site which talked about needing to get the Castle.DynamicProxy ported before Moq could be ported to Silverlight.

Turns out, the DynamicProxy is one of the core dependencies of the two major open source mocking frameworks out there. (Moq, and Rhino Mocks)...(I'm sure there's others out there, but for now I only care about Moq because it's what we use at work)

After sitting around for about three months since I first read the thread and not hearing any word about the DynamicProxy being ported, I thought I'd take a stab.

Joined the castle devl email group, threw a ping about the port and I was off...after a couple weeks several late nights, and a few patch submittal turn-backs by hammett I finally got the patch in a place he liked and he applied it on Jan 3 2009.

What a great feeling of relief, this was a big step forward to getting full mocking support in Silverlight.

There is still one pending thing with the DynamicProxy & all Castle.Silverlight projects to date...we need to integrate the build and testing into their NAnt builds. Once that's done and a binary release is out, Moq port to Silverlight...here I come.

p.s. I already have a patch for Moq, but Daniel said he won't apply it till he can get the "official" binaries, which is fine. I would probably do the same if I were overseeing a decent sized open source project like Moq.

Soon enough...we'll have Silverlight mocking...

Comments

timvw
Great job ;)
Anonymous
This is very good news. Thanks for the work.

What do when Silverlight is missing some Base Class Library (BCL) functionality?

If you're doing any Silverlight development you've probably run into the problem "some method/property/functionality I'm used to using doesn't exist in the core framework" provided by Microsoft.

What are your options?

  1. Write the logic yourself (you just might have to)
  2. Use reflector on the full framework to see how it's done and attempt to (go back to step 1. )
  3. Or one I've been using lately. Take a look at the Mono project.

DISCLAIMER: I'm not very familiar with much of the legal side of this option, so I highly recommend understanding Mono's licensing before going too far with their source.

However it's still a great source for learning how to implement something that was tucked away in the full framework's BCL.

And, with the power of Google, you can easily find what you're looking for...

Let's give an example:

Say, for instance, you need the IsNested property off of the System.Type object. The Silverlight version doesn't have that property, so let's go find out how it's implemented in Mono.

enter in a google serch: (we'll limit the search to the mono project's exposed svn site)

 

site:anonsvn.mono-project.com System.Type IsNested

The second link down is the one we want.

image

Then you can click on "View" in the "Links to HEAD"

image

And you end up looking at the .cs file source for System.Type. Just look in the page for the IsNested property and presto...

 

I'm beginning to love open source and the advantages it provides to the community as a whole. Thanks Mono.

i4o & Silverlight Unit Tests (A little more work than the i4o library)

Follow up to my post on i4o & Silverlight (compiles first try)...

 

I took a stab at porting the i4o unit tests to Silverlight which was quite a bit more work than I initially expected.

After creating a Silverlight Unit Test project and linking the original test files into the Silverlight project, I compiled...

  • First the VB using statement wasn't even needed, so I removed that. using Microsoft.VisualBasic;
  • Second there is no System.Diagnostics.Stopwatch() class in Silverlight, so I basically implemented a quick one using DateTime to get the unit tests to compile in Silverlight. Here's the class, except the Frequency property has been commented out (didn't spend time to figure how to make that correct, or what is correct???)
public class Stopwatch
{
private DateTime _StartUtcDateTime;
private DateTime? _EndUtcDateTime;
private bool _IsRunning = false;

//public static readonly long Frequency { get { throw new NotImplementedException(); } }
public static readonly bool IsHighResolution = false;
public Stopwatch()
{}

public TimeSpan Elapsed
{
get
{
if (_EndUtcDateTime.HasValue)
{
return new TimeSpan(_EndUtcDateTime.Value.Ticks - _StartUtcDateTime.Ticks);
}
else
{
return new TimeSpan(DateTime.UtcNow.Ticks - _StartUtcDateTime.Ticks);
}
}
}

public long ElapsedMilliseconds { get { return Elapsed.Milliseconds; } }
public long ElapsedTicks { get { return Elapsed.Ticks; } }
public bool IsRunning { get { return _IsRunning; } }

public static long GetTimestamp()
{
return DateTime.Now.Ticks;
}

public void Reset()
{
_EndUtcDateTime = null;
_StartUtcDateTime = DateTime.UtcNow;
}

public void Start()
{
_EndUtcDateTime = null;
_IsRunning = true;
this._StartUtcDateTime = DateTime.UtcNow;
}

public static Stopwatch StartNew()
{
var w = new Stopwatch();
w.Start();
return w;
}

public void Stop()
{
_EndUtcDateTime = DateTime.UtcNow;
_IsRunning = false;
}
}


The only other issue that came up was some of the Stopwatch dependent tests happened so fast that they would fail intermittently... the quick hack/solution for this was to up the iteration count of whatever they were testing.


After all the above taking care of all the above issues, I was able to get the unit tests to pass.


image

Comments

Tiaan
You might also want to look at my implementation of the Stopwatch for Silverlight, which supports resuming.
Tiaan
For the Frequency property's implementation, you probably just need to return the System.TimeSpan.TicksPerSecond value.

i4o with Silverlight (Compiles first try)

So I've been thinking lately of a problem that we will be solving at work that will require a user to follow these steps...

1. User selects some set of data to work with
2. Some number crunching has to happen to give the user a report like interface
3. User analyses that data, tweaks some value and will basically go to step 2 above...

This application is being build with Microsoft Silverlight and in thinking about how to make step 2 above as smooth and responsive as possible, I thought "Hey, what about i4o?"

A quick Google for "i4o Silverlight" and without digging too far I basically found nobody had tried it, or at least tried and told about i4o in Silverlight. So I thought I'd give a go...

 

Step 1: Go get the code from from codeplex/i4o. I downloaded the latest source bits.

Step 2: After extracting the .zip...Open up the project i4o.sln

Step 3: Add a new Silverlight class project

image

Step 4: Now use the "Add existing item" option to add files to the Silverlight project. Browse to the i4o project folder to select the 3 i4o class files. You can add those to you Silverlight project as is or use the "Add as Link" feature to share the code across the platforms.

image 

Step 5: once you've add the files to the Silverlight project final step is to "BUILD" the solution...

What's that you say? "That's all there was to it?" YA, my thoughts exactly, the project just compiled on the first try...

 

DISCLAIMER: I haven't tried to use it yet... It's late and this idea popped into my head distracting me from getting to sleep. So I tried it and am quite satisfied for now.

 

Up NEXT: Don't know if I'll do this sooner than later, if at all, but figure out how hard it would be to port the existing unit tests to see how they run in Silverlight...

WCF - Silverlight - Default constructor not called??

Can anyone explain why creating a default constructor (defined in a partial class) of an auto-generated Service References class for an object. Does not get executed when the object is created by a WCF service call?

I'll go through some of the basic steps I did to reproduce this, and I'll attach the project I created to do so. I would love if anyone had some insight into this... SilverlightWcfConstructorTest.zip

1. Create a web service that returns some complex type. (Class1)

2. Create a Silverlight app that can consume the service above. (Use the Add Service Reference so it will auto-generate a service reference file).

3. (in Silverlight) Create a partial class to extend the Class1 created by the service reference

4. Add a default constructor to this partial class.

5. Do something in this constructor to hint that it is called.

6. Run it and see that the default constructor is never called when making a WCF Silverlight service call.


WHY?


I have a full project put together that you should be able to unzip and run to see this behavior…

SilverlightWcfConstructorTest.zip


Update: I have a thread started at the silverlight forums on this topic...

WCF Service Proxy inside Silverlight with a generic type

We've implemented a silverlight 2 business application communicating through WCF and I just had to blog about something I found possible in .net in general...

On the server side we have a very simple generic object used to communicate validation issues back to our Silverlight client when a web service method is called. Here's the basic interface.

public interface IValidatedResult<T>
{
  T Result { get; set; }
  List<string> ValidationIssues { get; set; }
}

Now if you had a method that exposed this generic result object through your web service...

public ValidatedResult<long> StringLength(string param1)
{
  return new ValidatedResult<long>(param1.Length);
}

Now if you to to the silverlight project tell Visual Studio to generate a proxy for you (against the service you just created) it will give you a proxy with an object that is not generic. You end up with some autogenerated code that looks more like...

public partial class ValidatedResultOflong : object, System.ComponentModel.INotifyPropertyChanged
{

  private long ResultField;

  private System.Collections.ObjectModel.ObservableCollection<string> ValidationIssuesField;

  [System.Runtime.Serialization.DataMemberAttribute()]
  public long Result
  {
    get
    {
      return this.ResultField;
    }
    set
    {
      if ((this.ResultField.Equals(value) != true))
      {
        this.ResultField = value;
        this.RaisePropertyChanged("Result");
      }
    }
  }

  [System.Runtime.Serialization.DataMemberAttribute()]
  public System.Collections.ObjectModel.ObservableCollection<string> ValidationIssues
  {
    get
    {
      return this.ValidationIssuesField;
    }
    set
    {
      if ((object.ReferenceEquals(this.ValidationIssuesField, value) != true))
      {
        this.ValidationIssuesField = value;
        this.RaisePropertyChanged("ValidationIssues");
      }
    }
  }

  // stripped out the INotifyPropertyChanged goo
}

Notice the non generic type ValidatedResultOflong that was generated? This non generic object is great and all except when you want to do some generic processing on these objects. For things like error handling, validation handling... if we had to create different handling methods for all of these different objects, that could prove to be laborious...

Say I wanted to write an extension method to do some generic processing on all objects that are a ValidatedResult of T... Unfortunately there is no common signature we can key off of to write this method with the proxy code generated by V.S.

Then I thought I would try something... Can you have a partial class in one area which contains a common property, in this case each contains a "Result" and a "ValidationIssues" property and another partial class in a different location that declares it implements an interface which defines that "Result" and "ValidationIssues" property... and would that compile?

So I wrote my first test...

Here is our auto generated partial class simulated...

public partial class Foo
{
  public bool Result { get; set; }
}

I then wrote a generic result of T to define the object has a Result property.

public interface IResult<T>
{
  T Result { get; set; }
}

And now the specific implementation with a long Result type.

public partial class Foo : IResult<long> {}

After putting those three structures together I hit Build in VS and to my surprise (at first, but now it makes total sense) it compiled... This was great news. This meant I could create a generic processor for my wcf objects in silverlight... I'll show how on the silverlight side below...

I defined the validated result contract as follows...

public interface IResultProperty<T>
{
  T Result { get; }
}

public interface IValidatedResult<T> : IResultProperty<T>
{
  List<string> ValidationIssues { get; set; }
}

This meant I could quickly create partial class stubs for each of the wcf generated objects that looked like... ValidatedResultOf{object} and would define to the compiler that all these objects truly implemented the ValidationIssues and Result property.

Here's an example of the partial class for the ValidatedResultOflong

public partial class ValidatedResultOflong : IValidatedResult<long> { }

With that in place, this meant I could create some generic handling methods for all of my objects that now implement IValidatedResult<T>...

public static bool HasValidationIssues<T>(this T validatedResult)
where T : IValidatedResult<T>
{
  if (validatedResult != null &amp;&amp;
  validatedResult.ValidationIssues != null &amp;&amp;
  validatedResult.ValidationIssues.Count > 0)
  return true;
  else
  return false;
}

Don't know if i've very heard anyone talk about one partial class containing some property or common method and being able to create another partial class that defines the interface contract for that... Pretty cool...

Comments

Jason.Jarrett
Interesting observation. Thanks for sharing.

I haven't pushed it very far (bool, string, MyCustomObject, etc)

Boris Modylevsky
Thanks for the post. It's really exciting to receive a proxy of Generic class. It really works smoothly with "simple" classes. But more complex ones result with random names in Silverlight proxy. For example, my `_SimpleTree_` became _SimpleTreeNodeOfItemErNMAaNV_
Jason.Jarrett
Ok, I quickly threw an example together. I didn't comment much, but the code's there and "works on my box..."
Let me know if you have any troubles either understanding it, or getting it working.

I've never used this file host service, but giving it a try... I've placed the project here [ http://www.filesavr.com/validatedresultsample](http://www.filesavr.com/validatedresultsample)

Also the only concepts to really look at here are the `ValidatedResult<T>`` and the notion of the partial classes used along side the VS service reference code to get the extension methods to work... This by no means follows best practices with some of this stuff.

Good luck!</div>
greg
... very much appreciated!!
Jason.Jarrett
Greg,
I will try to put together an example and post it here soon.</div>
greg
... too many snippets for me to get the big picture... It looks promising, though. Do you have a simple working example you could post? I am interested in the generic proxy concept whether used within Silverlight or otherwise. Thanks in advance.

UnitDriven's UI Gets a Minor Makeover

I had some time to play around with and learn WPF within Silverlight. It's a modest start, but I just had to blog about it...

We've started a project at my current job using Silverlight. Researching different framework options I ran across the UnitDriven project on codeplex. After downloading and checking out the silverlight testing UI...











I decided this was a place I could take a stab at learning some silverlight UI. ok... So it's getting late and it's certainly not perfect, but here's where I am now.












The only really tricky piece was... The original UI used nested ListBox controls which threw me down a path of thinking the program was broken... basically with a ListBox inside of a ListBox you have to select the first item, then the sub item, and in this application, only then, can you select the "Run" button to execute the unit test... I spent time looking through code trying to figure out if there was a bug in the testing contexts.

The solution to this was to convert the ListBox to an ItemsControl. Which allowed me to select multiple buttons without having to first select the ListBox sub item...

I then had to wrap everything inside of a ScrollViewer because the ItemsControl doesn't create one automatically like the ListBox does.
[EDIT]
Unfortunately wrapping everything in the ScrollViewer removed a feature the older version had, namely, at the top of the control is a display of the # succeeded/# Total. Wrapping everything in the ScrollViewer removed the ability to scroll through tests while that value was being updated during tests...

So I updated the main grid in the XAML, and shifted a few things around to allow this old feature to be seen in the new UI.
[/EDIT]

after that was done, it was basically playing around with different styling elements to end up with the UI above.

It was a good simple exploratoin into some of the Silverlight's WPF capabilities.

Comments

Nermin
Your work on this patch is trully appreciated. That listbox issue was trully annoying one.
Justin Chase
Thanks for the patch, I applied it today.