Daniel Vaughan

free range code

CodeProject MVP 2011

clock January 4, 2011 11:02 by author Daniel Vaughan

I'm humbled to be re-awarded the status of CodeProject MVP for 2011. Considering that there are millions of Codeproject members, yet only 40 MVPs, it's a huge honour. Congratulations to my fellow awardess including Sacha Barber, Josh Smith, Pete O'Hanlon, and Michael Washington, and all of these great people:


 

Dalek Dave

Abhijit Jana

Abhishek Sur

Brij

Abhinav S

logicchild

Sandeep Mewara

Marcelo Ricardo de Oliveira

aspdotnetdev

Aescleal

OriginalGriff

William Winner

Kunal_Chowdhury

Alan Beasley

thatraja

Christ Kennedy

Al-Farooque Shubho

Henry Minute

Apriorit Inc

Sauro Viti

Arik Poznanski

Omar Al Zabir

Daniel Vaughan

Josh Smith

Pete O'Hanlon

John Simmons / outlaw programmer

Christian Graus

Mark Nischalke

«_Superman_»

Nishant Sivakumar

Shivprasad koirala

Md. Marufuzzaman

defwebserver

E.F. Nijboer

CPallini

Ajay Vijayvargiya

Dave Kreskowiak

Sacha Barber

Richard MacCutchan

Luc Pattyn

 



Custom Application Bar to Feature in Chapter

clock December 20, 2010 21:10 by author Daniel Vaughan

I've created a custom Windows Phone 7 application bar for a chapter entitled Taming the Application Bar. It supports data-binding, ICommands, button and menu item visibility, toggle buttons, and even multiple application bars for Pivots. 

I'll be releasing the source soon, and I'm really looking forward to getting it out there.

Windows Phone 7 Unleashed



Photo Location: a Windows Phone 7 Marketplace Application

clock November 19, 2010 19:50 by author Daniel Vaughan

 

Katka has just published a new application to the Windows Phone Marketplace. It's called Photo Location, and it allows you to visualise the geographical location of any photo that is stored on your phone. Here's the blurb:

You can browse through your photos on the Pictures Hub, and if you are ever wondering where a particular photo was taken, simply select Photo Location from the extras menu option in the application bar, and Photo Location will pinpoint the geographical location of your photo on the map. If you launch the application from the application list, Photo Location will take you directly to the Pictures Hub, where you can select any photo, and visualise where it was taken on a map. Not all photos will include GPS information, and Photo Location will only be able to show the location of photos that do include this information. The good news is, however, that the camera on your phone can be configured to include the location information whenever you take a photo, and is probably already setup to do so.

If you have the Zune software installed, you can take a look.

 

 

 



Debugging the PhotoChooserTask and other Media Hub Related Tasks on WP7

clock November 14, 2010 15:56 by author Daniel Vaughan

Using the device debugger is a snap in Windows Phone 7. There are many benefits, and you can see your app executing in a real world environment, with most of the launchers and choosers available for testing. Some choosers, however, rely on the Windows Phone Media Hub; such as the PhotoChooserTask. Trying to debug across a call to that bad boy, with the Zune software running, will lock up your app.

Fortunately there's an easy to use tool that solves the problem by removing the need to have the Zune software running while debugging. It's called the Windows Phone Connect Tool. It was released as part of the recent update to the Windows Phone Developer Tools. This tool allows you to close the Zune software, after your phone device is connected; which means that choosers such as the PhotoChooserTask are able to function correctly while you are debugging.

There are a few steps to launching the tool. Opening a command prompt, navigating to a directory, launching the tool. So I've wrapped these steps up into a batch file which takes care of detecting the platform, locating the path to the WPConnect executable, and launching the tool. The steps for using the batch file are as follows:

  1. Connect your Windows Phone to your computer and ensure that it is detected by the Zune software.
  2. Close the Zune software after your Windows Phone is connected.
  3. Double click on the batch file.

Download it here (1 Kb) [Updated 24 Mar 2011)

Alternatively, to use the Windows Phone Connect Tool manually, follow these steps:

  1. Open a command prompt and navigate to the directory containing the Windows Phone Connect Tool (WPConnect.exe). The location of this file will be %ProgramFiles%\Microsoft SDKs\Windows Phone\v7.0\Tools\WPConnect.
  2. Connect your Windows Phone to your computer and ensure that it is detected by the Zune software.
  3. Close the Zune software after your Windows Phone is connected.
  4. At the command prompt, enter the command WPConnect.exe.


Work-Around for DataContractJsonSerializer ArgumentNullExceptions

clock October 25, 2010 00:50 by author Daniel Vaughan

If you've tried using a DataContractJsonSerializer or a DataContractSerializer with Push Notification for the Windows Phone, you may have experienced an ArgumentNullException during deserialization. This can happen because the MemoryStream is buffered with null characters '\0' that prevent deserialization. A solution is to create a new array and copy all bytes except for the trailing nulls, as shown in the following excerpt from the downloadable sample code in my upcoming book Windows Phone 7 Unleashed:

using (BinaryReader reader = new BinaryReader(bodyStream))
{
byte[] bodyBytes = reader.ReadBytes((int)bodyStream.Length);

int lengthWithoutNulls = bodyBytes.Length;
for (int i = bodyBytes.Length - 1; i >= 0 && bodyBytes[i] == '\0'
i--, lengthWithoutNulls--)
{
/* Intentionally left blank. */
}

byte[] cleanedBytes = new byte[lengthWithoutNulls];
Array.Copy(bodyBytes, cleanedBytes, lengthWithoutNulls);

DataContractJsonSerializer serializer
new DataContractJsonSerializer(typeof(StockQuote));

using (MemoryStream stream = new MemoryStream(cleanedBytes))
{
StockQuote = (StockQuote)serializer.ReadObject(stream);
}
}

Have a great day!

 



Windows Phone Developer Tools October 2010 Update

clock October 22, 2010 23:53 by author Daniel Vaughan

In case you haven't heard, there's an update for the Windows Phone Developer Tools that was released on 21 October (yesterday as I write this).

The Windows Phone Developer Tools October 2010 Update includes:

  • Windows Phone Capability Detection Tool – Detects the phone capabilities used by your application. When you submit your application to Windows Phone Marketplace , Microsoft performs a code analysis to detect the phone capabilities required by your application and then replaces the list of capabilities in the application manifest with the result of this detection process. This tool performs the same detection process and allows you to test your application using the same list of phone capabilities generated during the certification process. For more information, see How to: Use the Capability Detection Tool.
  • Windows Phone Connect Tool – Allows you to connect your phone to a PC when Zune® software is not running and debug applications that use media APIs. For more information, see How to: Use the Connect Tool.
  • Updated Bing Maps Silverlight Control – Includes improvements to gesture performance when using Bing™ Maps Silverlight® Control.

 

Download Page



Netflix WP7 Browser

clock October 15, 2010 21:19 by author Daniel Vaughan

 

 

Katka has published a great new article http://www.codeproject.com/KB/windows-phone-7/NetflixBrowser.aspx

Learn how to use the Pivot and Panorama controls, page navigation, OData and more!




Countdown to Global Silverlight Firestarter Event

clock October 15, 2010 17:11 by author Daniel Vaughan

Silverlight Firestarter is a one day global event, streamed live with Scott Guthrie and others. It will be held in Redmond on 2nd December 2010 from 8am to 5pm PST.

 

alt

 

The whole session will be conducted by Scott Guthrie, Jaime Rodriguez, Jesse Liberty, Pete Brown, John Papa, Tim Heuer, Mike Cook, and Jossef Goldberg. Join the session in-person or online, and learn more about Silverlight.

 

Here is the Agenda of the Event:

 

alt

 

When?

December 2, 2010 8am to 5pm PT

 

How much I have to pay for attending the Event?

It is a FREE Event. You don’t have to pay anything for it.

 

Register for the In-Person Event in Redmond

Register for the Online Event

 

Read more about it


Thanks to Fons Sonnemans for the gnarly timer.



Windows Phone Experts Group

clock September 14, 2010 18:30 by author Daniel Vaughan

 

There's a new group on LinkedIn: Windows Phone Experts

It's a group of professionals interested in delivering the next generation of rich mobile applications for the Windows Phone platform.



ReaderWriterLockSlim: Conquering Mismatched Enter and Exit Calls

clock August 14, 2010 13:43 by author Daniel Vaughan

The ReaderWriterLockSlim class is used to protect a resource that is read by multiple threads and written to by one thread at a time. The class exists in the desktop FCL, but is noticeably absent from the Silverlight FCL. To readily support both platforms, some time ago, I incorporated the open-source mono implementation of the ReaderWriterLockSlim class into the Silverlight version of my core library, which is downloadable from http://calcium.codeplex.com/SourceControl/list/changesets

ReaderWriterLockSlim is a light-weight alternative to the Monitor class, for providing for concurrency. I say light-weight because the Monitor class only provides for exclusive access; where only a single thread can enter, regardless of the kind of operation.

The Monitor class, however, has an advantage: its syntax can be simplified using the lock statement, as shown in the following code snippet:

System.Object resourceLock = new System.Object();
System.Threading.Monitor.Enter(resourceLock);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(resourceLock);
}

 

Which is equivalent to the following, when using a lock statement:

lock (x)
{
DoSomething();
}

 

Using the lock statement means that we never get caught out forgetting to exit the lock, which could lead to a thread being blocked indefinitely.

No such baked-in infrastructure exists for the ReaderWriterLockSlim. So, I've created a number of extension methods to simulate the lock statement for the ReaderWriterLockSlim.

Using Extension Methods to Simulate Lock Syntax

If you've used the ReaderWriterLockSlim a lot, you'll know that mismatching Enter and Exit calls can be easy to do, especially when pasting code. For example, in the following excerpt we see how a call to enter a write protected section of code is mismatched with a call to exit a read section:

ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();

try
{
lockSlim.EnterWriteLock();
DoSomething();
}
finally
{
lockSlim.ExitReadLock();
}

 

This code will result in a System.Threading. SynchronizationLockException being raised.

The extension methods that have been written, allow a Func or an Action to be supplied, which will be performed within a try/finally block. The previous excerpt can be rewritten more concisely as:

ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();
lockSlim.PerformUsingWriteLock(() => DoSomething);

 

In the downloadable code I have included a unit test to demonstrate how the ReaderWriterLockSlim extension methods are used, (see Listing 1).

Listing 1: LockSlimTests Class

[TestClass]
public class LockSlimTests : SilverlightTest
{
readonly static List<string> sharedList = new List<string>();

[TestMethod]
public void ExtensionsShouldPerformActions()
{
ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();

string item1 = "test";

// Rather than this code:
// try
// {
// lockSlim.EnterWriteLock();
// sharedList.Add(item1);
// }
// finally
// {
// lockSlim.ExitWriteLock();
// }
// We can write this one liner:
lockSlim.PerformUsingWriteLock(() => sharedList.Add(item1));

// Rather than this code:
// string result;
// try
// {
// lockSlim.EnterReadLock();
// result = sharedList[0];
// }
// finally
// {
// lockSlim.ExitReadLock();
// }
// We can write this one liner:
string result = lockSlim.PerformUsingReadLock(() => sharedList[0]);

Assert.AreEqual(item1, result);

string item2 = "test2";

// Rather than this code:
// try
// {
// lockSlim.EnterUpgradeableReadLock();
// if (!sharedList.Contains(item2))
// {
// try
// {
// lockSlim.EnterWriteLock();
// sharedList.Add(item2);
// }
// finally
// {
// lockSlim.ExitWriteLock();
// }
// }
// }
// finally
// {
// lockSlim.ExitUpgradeableReadLock();
// }
// We can write this:
lockSlim.PerformUsingUpgradeableReadLock(() =>
{
if (!sharedList.Contains(item2))
{
lockSlim.PerformUsingWriteLock(() => sharedList.Add(item2));
}
});

// Rather than this code:
// try
// {
// lockSlim.EnterReadLock();
// result = sharedList[1];
// }
// finally
// {
// lockSlim.ExitReadLock();
// }
// We can write this:
result = lockSlim.PerformUsingReadLock(() => sharedList[1]);

Assert.AreEqual(item2, result);
}

}

 

The result of executing this test is shown in Figure 1.

 

Figure 1: Result of running the ReaderWriterLockSlimExtension tests.

 

The ReaderWriterLockSlimExtensions accept a simple Action or a Func to return value, and take care of calling the appropriate Enter and Exit methods, inside a try/finally block, (see Listing 2).

Listing 2: ReaderWriterLockSlimExtensions Class

public static class ReaderWriterLockSlimExtensions
{
public static void PerformUsingReadLock(this ReaderWriterLockSlim readerWriterLockSlim, Action action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterReadLock();
action();
}
finally
{
readerWriterLockSlim.ExitReadLock();
}
}

public static T PerformUsingReadLock<T>(this ReaderWriterLockSlim readerWriterLockSlim, Func<T> action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterReadLock();
return action();
}
finally
{
readerWriterLockSlim.ExitReadLock();
}
}

public static void PerformUsingWriteLock(this ReaderWriterLockSlim readerWriterLockSlim, Action action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterWriteLock();
action();
}
finally
{
readerWriterLockSlim.ExitWriteLock();
}
}

public static T PerformUsingWriteLock<T>(this ReaderWriterLockSlim readerWriterLockSlim, Func<T> action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterWriteLock();
return action();
}
finally
{
readerWriterLockSlim.ExitWriteLock();
}
}

public static void PerformUsingUpgradeableReadLock(this ReaderWriterLockSlim readerWriterLockSlim, Action action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterUpgradeableReadLock();
action();
}
finally
{
readerWriterLockSlim.ExitUpgradeableReadLock();
}
}

public static T PerformUsingUpgradeableReadLock<T>(this ReaderWriterLockSlim readerWriterLockSlim, Func<T> action)
{
ArgumentValidator.AssertNotNull(readerWriterLockSlim, "readerWriterLockSlim");
ArgumentValidator.AssertNotNull(action, "action");
try
{
readerWriterLockSlim.EnterUpgradeableReadLock();
return action();
}
finally
{
readerWriterLockSlim.ExitUpgradeableReadLock();
}
}
}

 

The ArgumentValidator class is present in my base library. Calls to its AssertNotNull can be replaced with a null check, and if null throw an ArgumentNullException. If you'd like the code for the ArgumentValidator etc., you can find it in the Core class library in the source available at http://calcium.codeplex.com/SourceControl/list/changesets

Conclusion

In this post we have seen how extension methods can be used to ensure that the ReaderWriterLockSlim class is correctly exited after a thread critical region. This avoids the problem of mismatched Enter and Exit calls, which can result in exceptions and indefinite blocking.

I hope you have enjoyed this post, and that you find the code and ideas presented within it useful.

 

Download code: ReaderWriterLockSlimExtensions.zip (1.14 mb)



Order the Book

Ready to take your Windows Phone development skills to the next level? My book is the first comprehensive, start-to-finish developer's guide to Microsoft's Windows Phone 8. In it I teach through complete sample apps that illuminate each key concept with fully explained code and real-world context. Windows Phone 8 Unleashed

Windows Phone Experts Windows Phone Experts
LinkedIn Group

 

Bio

Daniel VaughanDaniel Vaughan is co-founder and president of Outcoder, a Swiss software and consulting company dedicated to creating best-of-breed user experiences and leading-edge back-end solutions, using the Microsoft stack of technologiesin particular WPF, WinRT, and Windows Phone. 

Daniel is a four-time Microsoft MVP for Client Application Development, with experience across a wide range of industries including finance, e-commerce, and digital media. 
Daniel is the author of Windows Phone 7.5 Unleashed and Windows Phone 8 Unleashed, published by SAMS.

Daniel is a Silverlight and WPF Insider, a member of the WPF Disciples, and a member of the Microsoft Developer Guidance Advisory Council.
Daniel also sits on the advisory board of PebbleAge, a Swiss Financial Software company.

While originally from Australia and the UK, Daniel is currently based in Zurich Switzerland. 

Daniel is the developer behind several acclaimed Windows Phone apps including Intellicam and Splashbox; and is the creator of a number of popular open-source projects including the Calcium and Clog.

Daniel also manages the Windows Phone Experts group on LinkedIn; a group that has over 3000 independent developers, Microsoft employees, and Windows Phone enthusiasts.


E-mail Send mail

 

Microsoft MVP logo Disciple
WPF and Silverlight Insiders
 

 

 

Sign in