Developing on Staxmanade

StatLight release (V1.2 & V1.3)

This post is coming a little late (just realized I still had it in my local drafts and had not published it)…

Although I put out these blog posts (sometimes), the best way to learn about new releases is to subscribe to any of the myriad of Codeplex rss feeds for the project.

StatLight V1.2

Released way back on Sep 25, 2010. Mostly a bug fix release, but came with a couple small features that could help out your Silverlight testing.

Features added:

  • Support to test multiple Xaps at once:
    EX: StatLight.exe -x="C:\Project1\Test1.xap" -x="C:\Project2\Test2.xap"
  • QueryString command line parameter. This will pass a querystring along to the browser instance running the StatLight Silverlight host. Allowing you to grab the querystring and pull some information (config or other) into your test.
    • EX: You may want to run some Silverlight Integration tests that talk back to some self hosted web server. Since detecting this automatically is not realistic, because the server and port your tests will detect is the StatLight server, you can’t just call back to “home base” (because that is StatLight’s web server) you need to somehow know where to configure your endpoints. With the QueryString parameter in StatLight, your build scripts can now pass in a known port of your self hosted web server, where your tests can then use to configure any test service calls.

StatLight V1.3

Released Nov 20, 2010. NOTE: This is the first build running on the .net 4.0 framework. If you need 3.5 support stick with the V1.2 build. Much like I did back on the V1.2 release, this release is marked as a “beta” build which I will change the status on the release page to stable if I don’t hear any issue come out of it in the next couple weeks.

This release comes with a feature I’ve been wishing for, for a while now. StatLight uses a web server internally to serve the content and receive messages from the Silverlight(StatLight) test runner. This web server was originally implemented with the WCF WebServiceHost. Unfortunately this required special administrative privileges to get up and running and although most developers have enough rights to not make this a problem, there are some who are not allowed to adjust these port privileges. Looking through Jeff Wilcox’s Microsoft Silverlight Testing framework server side code, I noticed he implemented a very simple web server with the HttpListener. After a quick spike I realized I could port his web server over into StatLight and gain some benefits other than just not requiring administrative privileges on a certain port.

Features added:

  • New WebServer implementation
    • No requirement for elevated privileges
    • Faster startup time
    • With easier & full control of the request/response cycle StatLight now prints out warnings if your tests are making service requests that they shouldn’t be.
  • Introductory support to run external web browsers (instead of the self hosted control)
    • Firefox
    • Chrome
  • Added support for NUnit’s TestCaseAttribute
    • Note this is not full support, but should work for many general cases.

Duplicate DOM elements with the same ID

This is a short post. Saving this snippet it for myself for later.

If you ever have a html DOM element with a duplicate ID value, how do you detect the issue? It’s sometimes hard to find/debug until you really understand what has happened.

Taking inspiration from the solution in the following stackoverflow question. http://stackoverflow.com/questions/482763/jquery-to-check-for-duplicate-ids-in-a-dom

I wrote little helper that will alert you early in the development phase if you do something that causes a DOM element with duplicate ID’s.

Place the following script at the bottom of your global master page footer during development, and you will be notified of any issues early in the process.

// Requires: jQuery
(function(document, $){
// little debug helper script to notify us when the
// dom is updated with a contains duplicate ID'd elements
$(document).bind('DOMNodeInserted', function (event) {

var duplicateDomElements = [];

$('[id]').map(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
duplicateDomElements.push(this.id);
}
});

if (duplicateDomElements.length > 0) {
alert('Recent action duplicated a dom element ID with name(s) [' + duplicateDomElements + ']');
}

});
})(document, jQuery);


How do others typically deal with the issue?

PowerShell url checker (Check if a list of url’s is valid)

Every once in a while I run across a list of url’s that for whatever reason I want to make sure are valid. I have not yet found a good way to do this in PowerShell and finally hit the case where I decided to just write what I needed.

You can download the script here.

https://github.com/staxmanade/DevMachineSetup/blob/master/GlobalScripts/Check-Url.ps1

Below is an example of how you can use it:

C:\PS>@('http://www.google.com', 'http://www.asd----fDSAWQSDF-GZz.com') | .\Check-Url.ps1


Which generates the following output:



 IsValid Url                            HttpStatus Error
------- --- ---------- -----
True http://www.google.com OK
False http://www.asd----fDSAWQSD... System.Net.WebException: T...


Hopefully someone else finds this useful. And if there are other/better ways of accomplishing this I’d love to hear about it.

OData’s DataServiceQuery and removing the .Expand(“MagicStrings”) –Part II

In a previous post I elaborated on the problem of magic strings in OData service queries, and gave a quick (but lacking in depth) statically typed helper solution.

A commenter mynkow left a note stating that my solution would not work with nested objects. I initially replied asking if he could give an example (as I hadn’t run into that scenario yet being a noob to OData). He didn’t get back to me, but it wasn’t long before I ran into the problem he was talking about.

If we go back to LinqPad and look again at the Netflix OData api. Let’s say we want to pull down the People, their related TitlesDirected and the TitlesDirected ScreenFormats. (No real world scenario there – just made it up because they’re related properties). The OData query (with magic strings) would look like:

(from x in People.Expand("TitlesDirected/ScreenFormats")
select x).Take(5)

If you tried to take the above and translate it to my “no magic string” fix from the previous post you would get something like.

(from x in People.Expand(p => p.TitlesDirected /* Now what? dead end. /ScreenFormats*/ )
select x).Take(5)

Now that the problem in my solution was apparent, and using his example as a quick guide (It wasn’t quite what I was looking for, but had the general theme). The solution became more than a few lines of code and I wanted to wrap some tests around the whole thing just to verify it was all working correctly…

ODataMuscle was born:

http://github.com/Staxmanade/ODataMuscle

Sorry for the name. Just think of “Strong Typing” your OData queries and giving them a little Muscle. I threw this little project up on github since this blog is not the best place to version code and if anyone felt inclined to extend it they could easily fork it and do so.

I hacked the initial version together, and once a co-worker of mine was done with it I think he cleaned it up nicely.

This new version now supports expanding not only child properties, but grandchild properties and grandchild properties of collections. (That doesn’t seem to translate well…)

EX: our little Netflix example from above would now look like

(from x in People.Expand(p => p.TitlesDirected.Expand(p2 => p2.ScreenFormats))
select x).Take(5)

Which would translate into the following query

http://odata.netflix.com/catalog/People()?$top=5&$expand=TitlesDirected/ScreenFormats

Thanks to mynkow for the initial feedback and I hope this helps someone else…

OData’s DataServiceQuery and removing the .Expand(“MagicStrings”)

I was experimenting recently with the .Net implementation of OData and ran across one of my pet peeves. “Magic Strings”. Apparently, the .Net community’s definition of magic strings is close but seems slightly different from Wikipedia. Therefore the magic strings I’m talking about here are what you’ll find on such posts as “Functional .Net – Lose the Magic Strings.”

I don’t want to get into the magic string debate here, just that I want to snapshot this little helper (for when I need to remember to write it again and don’t want to “figure it out”). This is also not intended to be a complete overview of OData, but I will provide some getter starter links and tips (if you haven’t touched it).

Enough background show me the code: (scroll to the bottom if you don’t care about the post)

Let’s pretend we want to request a “Title” from the NetFlix OData api.

You can do this by going to the web browser and typing the following URL

http://odata.netflix.com/catalog/Titles()?$top=1

Sweet. XML, yippie. Um, no thanks. Let’s try that again. Go download LinqPad (read up on using LinqPad for querying an OData store)

Once you’ve connected LinqPad to the NetFlix OData service (http://odata.netflix.com/catalog). Now we’re ready to play around. Our URL “query” above translates in to a C# LINQ statement that looks like the below in LinqPad.

(from title in Titles
select title).Take(1).Dump()



The .Dump() is a LinqPad extension method that displays the object in the results window.




If you execute this in LinqPad you will see some data about the first Title form the Netflix OData service. In the results window scroll all the way to the right. Notice all the properties that are supposed to be a Collection<T> but have no data? To retrieve these through OData you have to extend your LINQ query with the Expand(“{propertyName}”) method.



Let’s say we want to include AudioFormats collection when we ask for the first Title.



(from title in Titles.Expand("AudioFormats")
select title).Take(1).Dump()


Notice how we have to explicitly tell the OData service to include this property when we retrieve it form the service. Not only do we explicitly tell the property name, but it’s a magic string (gag, hack, baaa) none the less. If you click on “SQL” in LinqPad result window it will show the URL used for OData queries. Our URL shows the expanded property.



http://odata.netflix.com/catalog/Titles()?$top=1&$expand=AudioFormats




Now let’s pretend (just for the sake of pretending) that your front end application’s entire data access strategy was going to sit on top of OData. Not saying this is a good thing (or a bad thing). Just sayin…



If you have a fairly complex data model and each screen in your application requests slightly different data in a slightly different way, but in the end it all essentially comes down to a set of entities and their relationships. What would you do if you had to “.Expand” all those magic stringed property names. Now, I know we’re all great at search and replace (of the magic strings). However every little step along the way where I can avoid a refactor that will break every other screen in the app, well, I think I just might take that.



Now, if you change your LinqPad query from a “C# Expression” to a “C# Program”. Copy the helper class at the bottom of this post in to the bottom of the LinqPad code window. You can now write your linq statement as follows



(from title in Titles.Expand(x=> x.AudioFormats)
select title).Take(1).Dump();


Notice the switch from magic strings to an intellisense helping, refactoring safe lambda? This trick is not new. You’ll see it in many .Net open source projects such as mocking frameworks, asp.net MVC projects etc…



Just wanted to write this little goodie down for the next time I need it. Hope this helps someone else as well.



public static class ServiceQueryExtension
{
public static DataServiceQuery<T> Expand<T, TProperty>(
this DataServiceQuery<T> entities,
Expression<Func<T, TProperty>> propertyExpressions)
{
string propertyName = propertyExpressions.GetMemberName();
return entities.Expand(propertyName);
}

public static string GetMemberName<T, TProperty>(this Expression<Func<T, TProperty>> propertyExpression)
{
return ((MemberExpression)(propertyExpression.Body)).Member.Name;
}
}

StatLight V1.0 & V1.1 Released (Silverlight Testing Automation Tool)

About a week ago (May 21st 2010) I uploaded the v1.0 release of StatLight. You can review the list of changes on the StatLight v1.0 release page.

I knew once I marked it v1.0, I would probably have updates to it & sure enough… Microsoft’s Jeff Wilcox released a new version of the Microsoft.Silverlight.Testing.

I also incorporated some work done by Justin who recently released a version of the UnitDriven framework.

So there’s now a v1.1 build out.

Happy Silverlight Testing!

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! ;)

Silverlight Profiling PowerShell helper.

I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful.

But I didn’t know you could profile a Silverlight app.

I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say Redgate ANTS Performance Profiler. However, it’s do-able. (And with this helper script – hopefully a little simpler?)

How can I profile a Silverlight Application?

I would recommend you read the following blog, which explains one way of doing it very well.

http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx

So… what’s this script for?

If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report.

I threw together a quick little PowerShell script in an attempt to automate smooth out the process.

Hot do I use it?

  1. Download the script & save it somewhere. http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1
  2. Open the PowerShell console. cd to the directory your xap/assemblies are stored.
    (EX: {myProject}\Bin\Debug\ )
  3. Execute:
    {pathToScript}\SilverlightProfiler.ps1 -urlPath "{myProject}\Bin\Debug\TestPage.html"
  4. When your done profiling press enter to signal that your done.

    Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.
Couple of disclaimers.
  • Some paths are hard-coded to my x86 machine.
  • I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work.
  • I’m not a profiling expert – just hacked this together to get it to work for me.

I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.

Diffing tool feature request

Most of us have probably tried different versions of a file diffing tool. Some are picky about their choice. Personally I’m fond of two different tools (mostly because they’re easy to find/install and setup). Here’s a post where I talk about how I like to integrate these tools when working with TFS and Visual Studio - /2009/08/development-environment-mergecompare.html

A couple months ago, I _slowly_ started learning Git. Since that initial plunge, I’m now in a place where much of it still scary unknown; however, I know enough get what I need done. And when I get to the point where I need to do something I’ve never done, well I go figure it out, and it becomes another part of the personal Git toolbox.

I’ve been working git solely through the command line (in PowerShell actually). I know it’s not the best place to take full advantage of Git; however, it’s working for me.

The other day needed to review changes in a file back in the commit history. Up until this point I had only diff’d uncommitted files with the most recent version of that file, and I already wired a visual diffing tool where I could then use the “git difftool …” command to review differences.

However this was the first time I had to look at a file further back in time than the head. After a quick search I came across the “gitk” command. gitk is “The git repository browser”. I’ve known about this tool, however am trying to keep with the command line tools. (Except for diffing files)

Below is the UI when running the “gitk build-tasks.ps1” in the root of the StatLight project.

Notice how there’s a list of changes to the file, and under that the diff of the previous version to the selected version.

image

One thing do like about the above, is the list of revisions and how they are right there in your face. Going back in time is really easy. My only problem is I’m not accustomed to the linux style diffing, and still prefer the side/by side file diffing.

On to the feature request…

What problem is this new feature trying to solve?

The problem of having a file diff between version E & F and then needing to look at the previous version to E. (easily) AND show the different versioned files side by side AND make it easy and intuitive to go back in time.

How might this feature request look?

Maybe someone is doing this, maybe not. It would be interesting to leverage a (mouse drag – or text command [EX: Ctrl+Alt+Right Arrow]) to “pan” between versions through file diffing view. Kind of like you can drag the pictures on an iPhone to view the previous or next one. I could drag the mouse across the screen to pan to the previous/next view of the diff.

 

Below is a quick mockup of the thought – definitely far from refined.

image

One challenge to true implementation?

The main problem to solve (if you write a generic text diffing tool) is needing to interface with different SCM’s so you can retrieve the the previous/next versions of the file. Basically having to know what SCM the file is under.

 

Anyone mind taking this project on and implementing this in one of the decent open source file diffing tools out there? (ex: http://winmerge.org/)  I would love you for it. Well… I’d buy you a beer.

PowerShell – background task that speaks to me

Today I was testing a long running task where my basic scenario was to execute at the PowerShell prompt.

C:\dev> LongRunningTask.exe > Test1.txt

C:\dev> LongRunningTask.exe > Test2.txt

C:\dev> LongRunningTask.exe > Test3.txt

Change some code and do it all over again.

C:\dev> LongRunningTask.exe > Test4.txt

C:\dev> LongRunningTask.exe > Test5.txt

C:\dev> LongRunningTask.exe > Test6.txt

Although seemingly simple and really not that tough. It became really inefficient because I didn’t like sitting there waiting for it to finish. I was off reading blogs, responding to email, investigating other coding issues and generally forgetting about the long running tasks in the background. On top of that, when I came back to it I couldn’t remember what the last run was (was that test 2 or 3 or 5?) without querying disk to see what it was.

Sine I had all this time to kill in between test runs, I wrote a quick PowerShell script that would fully automate test 1,2,3 and stop. This was great and the first time I ran it was much more efficient as I didn’t have to keep checking back to see when to start it up again.

However, I not only had time to kill, but now I had 3 times that time to kill. I decided to elaborate on the script. I searched the tubes for a way to play a sound when a task was done, so I could be notified as to it’s progress, and completion.

I stumbled upon this blog, which was great for showing me how to play sounds within PowerShell.

http://scriptolog.blogspot.com/2007/09/playing-sounds-in-powershell.html

I implemented the sounds and was off and running on another batch of testing, all tuned in to the sounds of progress.

Her we go again, more time to think about how to improve the process (that I’m not even trying to improve).

What if the script talked back to me? Some more googlefoo and I found this great example blog.

http://huddledmasses.org/powershell-speaks/

Basically using the built in Microsoft speech api’s you can get PowerShell to talk to you. This was just too much fun for the day.

At the end of the day the script below is basically what I was using. Don’t have too much fun, as you might not get any real work done…

The content of this blog isn’t necessarily top notch, but I just had to blog about it, as I was very impressed as to how easy it was to work with the speech api’s. Never knew it could be so easy to make a script verbally interactive.

$Voice = new-object -com SAPI.SpVoice

function speak([string] $msg)
{
$Voice.Speak( $msg, 1 )
}

function execScriptWithNotify([string] $completionMessage, [scriptblock] $scriptToExecute)
{
. $scriptToExecute
speak $completionMessage
}

function execLongRunningTask([scriptblock] $scriptToExecute)
{
. $scriptToExecute

Write-Host "Long running task complete!"
speak "All tasks are done!"
}


# Start the long running task
execLongRunningTask {

#***************************************************************
#***************** How many times to run task? *****************
#***************************************************************
$iterationCount = 3

for ($i=1; $i -le $iterationCount; $i++)
{
execScriptWithNotify "Task $i Complete" {

#***************************************************************
#***************** Long Running Task Goes Here *****************
#***************************************************************
Write-Host "begin long running task # $i"
[System.Threading.Thread]::Sleep(3000);
Write-Host "end long running task # $i"
#***************************************************************
#***************************************************************
#***************************************************************
}
}

}