Shawn Oster, Program Manager of Silverlight for Window Phone team, confirmed that this is a known issue that they are currently working on fixing for next update. The workaround for this issue is that you need to ensure that the solution is not highlighted in Solution Explorer.
Archive for April 11th, 2010
Tip: “Object reference not set to an instance of an object” Error in Silverlight for Windows Phone 7
Pluralcast 13 : Women in Technology
Listen to this episode! [41:37]
In this episode, I visited with several women who shared their stories of simply being women in our field.
Meagon Marshall
Meagon Marshall is the Director of Marketing for Pluralsight. Meagon focuses on market strategy & execution, public relations, community & partner building to evangelize Pluralsight training within the developer community at large. Meagon joined Pluralsight in 2009 and worked on MSDN and TechNet Magazine prior to joining Pluralsight.
Meagon is also a mother, yoga guru and spends her time finding new ways to spread the .NET training love with disjointed media channels. When she isn’t mothering, stretching or spreading the .NET love, Meagon enjoys wine, writing, traveling and discovering new music.
Meagon’s Links
Carey Payette
My name is Carey Payette, and I am a technology junkie. I am married and have three young sons that never cease to amaze me and that I completely adore. I am one of the unfortunately decreasing numbers of women in technology. This is something that myself and a group of passionate women are looking to turn around, as the great blue monster once said “Change the world or go home”, and this is exactly what we intend to do.
Born and raised in Sudbury Ontario, I am a Canadian living in the US since 2000. I am a 1999 graduate of Laurentian University with a bachelor of science in computer science. In my day job I work as a Senior Software Developer, holding leadership/mentor roles surrounding distributed computing technology in the JEE and .Net space. I am passionate about my work and am willing to share my experiences openly with others, as such I am very active in the developer community at large. I serve as the current president of the Central Ohio .Net Developer’s group and am on the organizing committee for the Central Ohio Day of .Net (CODODN), and for the charitable local Give Camp. I also try to speak at numerous regional conferences in order to connect with as many people as I can.
Carey’s Links
- Blog: Coding Bandit
- linked in
Sarah Dutkiewicz
Sarah Dutkiewicz has worn many hats in the past decade – including technical support tech, technical support manager, database administrator, system administrator, programmer, report writer, editor, and now developer. She graduated in 2002 with her Bachelor of Science in Computer Science and Engineering Technology from the University of Toledo, Toledo, Ohio. When she isn’t working on database-driven websites, she’s reading up on the latest technologies and networking with other developers. Sarah is a Microsoft MVP in Visual C#.
Sarah’s Links
Sarah Gray
I work as a web developer, and my technical domain is database-driven web apps. For the past few years I’ve been coding Ruby on Rails and JavaScript, both of which I love, though Rails is a moving target and JavaScript, speaking through the browser as it must, is fickle. Prior to that (programming-wise) I worked with PHP for about six years, peeked at Java, and dabbled in lingo.
Sarah’s Blog: http://www.fabled.net/blog/
Alex McFerron
I work as a programmer and I enjoy doing math circles for fun. I’m currently doing research regarding poker programming.
Alex’s Blog: http://iwanttolearnmath.blogspot.com/
Introducing jLight – Talking to the DOM using Silverlight and jQuery.
Introduction
With the recent news about Silverlight on the Windows Phone and all the great Out-Of-Browser features in the upcoming Silverlight 4 you almost forget Silverlight is a browser plugin. It most often runs in a web browser and often as a control. In many cases you need to communicate with the browser to get information about textboxes, events or details about the browser itself. To do this you can use JavaScript from Silverlight. Although Silverlight works the same on every browser, JavaScript does not and it won’t be long before problems arise. To overcome differences in browser I like to use jQuery. The only downside of doing this is that there’s a lot more code needed that you would normally use when you write jQuery in JavaScript.
Lately, I had to catch changes is the browser scrollbar and act to the new position. I also had to move the scrollbar when the user dragged around in the Silverlight application. With jQuery it was peanuts to get and set the right attributes, but I found that I had to write a lot of code on Silverlight side. With a few refactoring I had a separated out the plumbing into a new class and could call only a few methods on that to get the same thing done. The idea for jLight was born.
jLight vs. jQuery
The main purpose of jLight is to take the ease of use of jQuery and bring it into Silverlight for handling DOM interaction. For example, to change the text color of a DIV to red, in jQuery you would write:
jQuery("div").css("color","red");
In jLight the same thing looks like so:
jQuery.Select("div").Css("color","red");
Another example. To change the offset in of the last SPAN you could write this in jQuery :
jQuery("span:last").offset({left : 10, top : 100});
In jLight this would do the same:
jQuery.Select("span:last").Offset(new {left = 10, top = 100 });
Callbacks
Nothing too special so far. To get the same thing done using the “normal” HtmlPage.Window.Eval, it wouldn’t require too much effort. But to wire up a handler for events from the browser it’s a whole different story. Normally you need to register ScriptMembers, ScriptableTypes or write some code in JavaScript. jLight takes care of the plumbing and provide you with an simple interface in the same way jQuery would.
If you would like to handle the scroll event of the BODY of your html page, you’ll have to bind the event using jQuery and have a function call back to a registered function in Silverlight. In the example below I assume there’s a method “SomeMethod” and it is registered as a ScriptableObject as “RegisteredFromSilverlight” from Silverlight.
jQuery("body:first").scroll(function()
{
var sl = document.getElementbyId("SilverlightControl");
sl.content.RegisteredFromSilverlight.SomeMethod($(this));
});
Using jLight in Silverlight the code would be even simpler. The registration of RegisteredFromSilverlight as ScriptableObject can be omitted. Besides that, you don’t have to write any JavaScript or evaluate strings with JavaScript.
jQuery.Select("body:first").scroll(SomeMethod);
Lambdas
Using a lambda in Silverlight can make it even simpler. Each is the jQuery equivalent of foreach in C#. It calls a function for every element found by jQuery. In this example all INPUT elements of the text type are selected. The FromObject method is used to create a jQueryObject from an object containing a ScriptObject. The Val method from jQuery is used to get the value of the INPUT elements.
jQuery.Select("input:text").Each((element, index) =>
{
textBox1.Text += jQueryObject.FromObject(element).Val();
return null;
});
Ajax
One thing jQuery is often used for is making Ajax calls. Making calls to services to external services can be done from Silverlight, but as easy as using jQuery. As an example I would like to show how jLight does this. Below is the entire code behind. It searches my name on twitter and shows the result. This example can be found in the source of the project. The GetJson method passes a Silverlight JsonValue to a callback. This callback instantiates Twit objects and adds them to a ListBox called TwitList.
public partial class DemoPage2 : UserControl
{
public DemoPage2()
{
InitializeComponent();
jQuery.Load();
}
private void CallButton_Click(object sender, RoutedEventArgs e)
{
jQuery.GetJson("http://search.twitter.com/search.json?lang=en&q=sorskoot",
Done);
}
private void Done(JsonValue arg)
{
var tweets = new List<Twit>();
foreach (JsonObject result in arg["results"])
{
tweets.Add(new Twit()
{
Text = (string)result["text"],
Image = (string)result["profile_image_url"],
User = (string)result["from_user"]
}
);
}
TwitList.ItemsSource = tweets;
}
}
public class Twit
{
public string User { get; set; }
public string Image { get; set; }
public string Text { get; set; }
}
Conclusion
Although jLight is still in development it can be used already.There isn’t much documentation yet, but if you know jQuery jLight isn’t very hard to use. If you would like to try it, please let me know what you think and report any problems you run in to.
A demo of accessing text elements can be found here. The Twitter demo can be found here.
jLight itself can be found at:
Detecting Global Pollution with the JScript RuntimeObject
This article is about debugging with JScript's RuntimeObject
(msdn). All of the examples work in IE 5.5+, though most do not work in any other browser.
Leaked Global Identifiers
Say you accidentally created a global property, as in the following:
function playRugby(players) {
var items,
i;
len = items.length; // Global.
}
function kick() {
var x = 10
y = 11; // ASI makes y global.
}
When playRugby is called, a global property len is created, if it does not already exist,
and then assigned the value of items.length. Likewise, when kick is called, a global
property y is created.
These globals are unintentional. They break encapsulation and leak implementation details. This can result in conflict and awkward dependency issues.
To detect accidentally created global identifiers, we can loop over the global object using
for in. Firebug provides this convenient global inspection under the "DOM" tab.
Everybody's Favorite Browser
Unfortunately, in IE, the for in won't enumerate any global variables or function declarations,
as seen in the example below.
Example Enumerating the Global Object
// Property of global variable object.
var EX1_GLOBAL_VARIABLE = 10;
// Property of global object.
this.EX1_GLOBAL_PROPERTY = 11;
// Property of global variable object.
function EX1_GLOBAL_FUNCTION(){}
(function(){
var results = [];
for(var p in this) {
results.push(p);
}
alert("Leaked:\n" + results.join("\n"));
})();
The result in IE contains a mix of window properties and one the four user-defined properties:
EX1_GLOBAL_PROPERTY.
So what happened to the other three user-defined properties? Why didn't they show up in the for in loop?
It turns out that enumerating over the global object will enumerate properties assigned to the global object and will not enumerate global variables.
An educated guess as to why global properties are enumerated but global variables are not might be that JScript gives global variables (declared with var), the DontEnum flag. Since the global object is specified as being the global Variable object, this seems like a likely explanation. It would be nonstandard, but it would explain the behavior in IE. Eric Lippert, however, provided a different explanation: The global object and the global variable object are
two different objects in IE.
According to MS-ES3:
JScript 5.x variable instantiations creates properties of the global object that have the DontEnum attribute.
Enumeration Solution: The JScript RuntimeObject
To enumerate over global properties, use the JScript RuntimeObject method.
Instead of enumerating over the global object, as you would use in a normal implementation,
enumerate over an object returned by the global RuntimeObject method.
var GLOBAL_VAR1,
GLOBAL_VAR2,
GLOBAL_VAR3 = 1;
GLOBAL_PROP1 = 12;
function GLOBAL_FUNCTION(){}
if(this.RuntimeObject){
void function() {
var ro = RuntimeObject(),
results = [],
prop;
for(prop in ro) {
results.push(prop);
}
alert("leaked:\n" + results.join("\n"));
}();
}
IE Result
The result in IE 8 and below includes (among other things, including window) GLOBAL_FUNCTION, GLOBAL_VAR3,
and GLOBAL_PROP1, in that order, as they were evaluated in.
Notice that neither GLOBAL_VAR1 nor GLOBAL_VAR2 were included.
It appears that RuntimeObject does not accumulate any variables that were
unassigned to. According to Microsoft's documentation, this is not the specified behavior
(more on this below).
Microsoft RuntimeObject Documentation
The JScript RuntimeObject is a built-in extension to JScript. JScript
defines seven additional built-in global methods: ScriptEngine,
ScriptEngineBuildVersion, ScriptEngineMajorVersion,
ScriptEngineMinorVersion, CollectGarbage,
RuntimeObject, and GetObject. These objects are
all native JScript objects, not to be confused with
host objects.
For RuntimeObject, Microsoft JScript Extensions [MS-ES3EX] states:
TheRuntimeObjectfunction is used to search a global object for properties with names that match a specified pattern. The function only locates properties of the global object that were explicitly created byVariableStatementorFunctionDeclarationfunctions, or that were implicitly created by appearing as an identifier on the left side of an assignment operator. The function does not locate properties that were created by means of explicit property access on the global object.
Superficial testing indicates that Microsoft's documentation is wrong.
The returned object does not includes all identifiers that were added to the Variable object;
only those identifiers that have been assigned a value. Whether or not they were created from
VariableDeclaration, FunctionDeclaration, or assignment as global properties
does not matter.
Example of Finding Identifiers Created By FunctionBindingList
All identifiers in a FunctionBindingList of a JScriptFunction
will become properties of the containing Variable object, so, for example:
var foo = {}, undef, ro;
(function(){ function foo.bar, baz(){} })();
ro = RuntimeObject();
alert([ro.foo.bar, "undef" in ro].join("\n"));
IE elerts
function foo.bar(){}
false
Browsers other than IE running JScript can be expected to throw
SyntaxError upon parsing the FunctionBindingList of
JScriptFunction production. This is to be expected, as
it is a syntax extension.
Bookmarklet
As a bookmarklet:
javascript:(function() {var ro=RuntimeObject(),r=[],i=0,p;for(p in ro){r[i++]=p;}alert('leaked:\n'+r.join('\n'));})();
JScript Syntax Extension
The earlier example "Finding Identifiers Created By FunctionBindingList" mentioned
the JScript Extension JScriptFunction. In case the name is not a dead
giveaway, this is a JScript language extension. The production for JScriptFunction is:
JScriptFunction :
function FunctionBindingList ( FormalParameterListopt ) { FunctionBody }
RuntimeObject(filterString): The filterString Parameter
The RuntimeObject method accepts an optional filter string to match
identifiers. Unfortunately, filterString is not converted to a regular expression
but is used for substring matching with optional leftWild and rightWild, defaulting to *.
This means that, for example: filterString = "a*" would match
identifiers a and a1 but not ba.
Conclusion
Documentation bugs and shortcomings aside, the RuntimeObject
provides a useful alternative to the problem
of enumerating global properties in JScript. An advantage with
RuntimeObject is that it only includes user-defined
properties, with the exception of the global window property.
The aforementioned bookmarklet provides a convenient way to check a page to see the globals that have been accidentally created (it also shows that this site is not a shining example of keeping the global object clean).
Other Applications for RuntimeObject
Cross Browser Identifier Leak Bookmarklet
Writing a cross-browser identifier leak detector is the next logical step to an IE-only identifier leak detector.
Automated Identifier Leak Detection
Checking for accidental global identifiers should be automated.
The YUI Test unit test framework provides hooks for TEST_CASE_BEGIN_EVENT
and TEST_CASE_COMPLETE_EVENT . These events can be used to
inspect the RuntimeObject and catch global identifier leaks
that occur througout the runtime execution of program code.
In TEST_CASE_BEGIN_EVENT, inspect the RuntimeObject and save the result.
In TEST_CASE_COMPLETE_EVENT, inspect the RuntimeObject again and compare
the results with results saved during TEST_CASE_BEGIN_EVENT.
Next, for each property that appeared in TEST_CASE_COMPLETE_EVENT but was not present
in the result saved from TEST_CASE_BEGIN_EVENT , a global identifier has been
leaked and a test case warning can be logged.
References
- [MS-ES3EX]: Microsoft JScript Extensions to the ECMAScript Language Specification Third Edition.
Ruby
After a disappointing first of April I decided to look over the fence and see what other exciting areas of software development there are (Ok I am joking). Ruby has been something that I wanted to learn for quite some time, and I finally took the plunge. So now you can expect some posts about that in the near future
I am currently working / playing with the following:
- Ruby
- Sinatra, because I want to actually learn Ruby and not just Rails
- Haml
- Sass
- Compass
- jQuery, lots of it
- CouchDB
- MongoDB
- Cucumber
- RSpec
- QUnit
- JsTestDriver
- RubyMine, still in the evaluation time, but looks promising
I can tell you that there is a lot of new stuff here for me, and the list keeps on growing, so very exciting, very exciting indeed.

