Now that i’m back on an iPhone, these settings shortcuts are quite handy – add icons for often-accessed settings to your home screen.
Tags
Categories
Archives
- Log in with
Now that i’m back on an iPhone, these settings shortcuts are quite handy – add icons for often-accessed settings to your home screen.
I’ve been looking forward to the Nokia Lumia release for several months now. I had an iPhone 3gs which was starting to drive me crazy with an unfortunate habit of restarting any time I was on the phone for longer than a few minutes, so having read overwhelmingly positive reviews of both WP7 and the just-released Nokia devices, I was keen to ditch my iPhone and give them a shot.
I’ve had my Lumia for a few weeks now, and whilst there’s several things I really like about it, and particularly the WP7 system, there’s unfortunately a number of gripes that are fast becoming showstoppers.
Positives:
Negatives:
Handset
The handset battery life sucks, to the point of being unusable. At best I’ll get around 10 hrs out of it with light-moderate use. One day I got less than 8. With the same usage for my 2 year old iPhone 3gs, I typically got around 18 hrs – still not great, but at least usable. Clearly there’s some sort of bug in the firmware or software, but I find it hard to believe they passed any sort of QA process in this state.
I use Gmail, and the interop between the WP7 mail app and Gmail is sub-standard. I’ve tried both setting up my mail with the suggested Google account setup, and as an Exchange account, but problems still make it hugely frustrating:
Various WP7 annoyances
I have fairly simple requirements for a smartphone – make calls, manage email easily, maps, alarms, and some music. Unfortunately my Lumia isn’t currently stacking up as either a mail platform (due to both aforementioned mail issues, and slowness of keyboard use), or for alarms. Of course, the battery issue is a complete showstopper – I hope it’ll get resolved soon by Nokia, but I’m certainly not going to bet anything on it.
I really wanted it to work. I don’t want to go back to iOS. But at the moment, I’m not sure I’m left with much choice!
I moved from an iPhone to a WP7 device recently, and one of niggles in the move was getting my iTunes playlists imported into Zune. Doesn’t seem like there’s a simple way to accomplish this, so I created a small windows app to do it for me.
You can download it below. Just run it (you’ll need .NET 4 framework installed), and it should detect your iTunes playlists automatically. It won’t import m4p files in your playlists, as they’re DRM protected and can only be played via iTunes.

I recently had an issue with time-dependent methods of Rx, which were adversely affected when a user changed their system clock. You can read up on the history on the Rx forums.
In the older Rx v1.0.2787 (which my current project is still using), BufferWithTime was affected, along with other methods such as Interval, Timer, and Sample.
The most problematic for my purposes was BufferWithTime. For instance, if you shift the system clock back and then push values onto the Buffer, the values are then either lost completely or they arrive late. If you shift the clock forward a significant amount, Rx overloads the CPU pushing through potentially thousands of empty updates in an effort to catch up with the new clock time. Worse still, if you shift your clock back several years then you get an UnhandledException along the lines of “Time-out interval must be less than 2^32-2″.
In the latest Rx v1.1.10621 (experimental), it seems neither Buffer nor Window are affected, but Interval, Timer, and Sample are.
In short, the issue is that all problematic methods are dependent upon IScheduler.Now. In all IScheduler implementations, this property just returns DateTimeOffset.Now, which is of course straight from the system clock. Change the system clock, and subsequent reads of IScheduler.Now will return times not in line with previous values.
The solution was to implement a custom IScheduler. I’ve quite literally copied the ThreadPoolScheduler source, and simply modified the Now property implementation.
In my implementation below, you can see that I start a Stopwatch during construction, and use this to determine the actual time in the getter for Now. From my testing it behaves correctly in all situations where I was previously missing notifications. The relevant parts are the constructor and the Now getter, all other methods are simply a copy of the ThreadPoolScheduler.
Attached here is a sample project demonstrating both the issue and the fix for the latest Rx release. Just run it and hit the “-10 secs” button to shift your system clock back.
Thoughts and comments welcome…
public class AccurateTimeScheduler : IScheduler, IDisposable
{
private static readonly object _gate = new object();
private static readonly Dictionary<Timer, object> _timers
= new Dictionary<Timer, object>();
private readonly Stopwatch _stopWatch = new Stopwatch();
private DateTimeOffset _startTime;
public AccurateTimeScheduler()
{
_startTime = DateTimeOffset.Now;
_stopWatch.Start();
}
public DateTimeOffset Now
{
get
{
var dateTimeOffset = _startTime.AddMilliseconds(
_stopWatch.ElapsedMilliseconds);
Trace.WriteLine(
string.Format("Now: Default={0}, Corrected={1}",
DateTimeOffset.Now.ToString("HH:mm:ss.fff"),
dateTimeOffset.ToString("HH:mm:ss.fff")));
return _startTime.AddMilliseconds(_stopWatch.ElapsedMilliseconds);
}
}
public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
var d = new SingleAssignmentDisposable();
ThreadPool.QueueUserWorkItem(
_ =>
{
if (d.IsDisposed)
return;
d.Disposable = action((IScheduler) this, state);
}, null);
return d;
}
public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
var dueTime1 = Scheduler.Normalize(dueTime);
if (dueTime1.Ticks == 0L)
return Schedule(state, action);
var hasAdded = false;
var hasRemoved = false;
var d = new MultipleAssignmentDisposable();
Timer timer = null;
timer = new Timer(
_ =>
{
Func<IScheduler, TState, IDisposable> localAction;
lock (_gate)
{
if (hasAdded && timer != null)
_timers.Remove(timer);
localAction = action;
}
var localTimer = timer;
if (localTimer != null)
localTimer.Dispose();
timer = null;
if (localAction != null)
{
d.Disposable = localAction((IScheduler) this, state);
Trace.WriteLine("Executing");
}
action = null;
}, null, dueTime1, TimeSpan.FromMilliseconds(-1.0));
lock (_gate)
{
if (!hasRemoved)
{
_timers.Add(timer, null);
hasAdded = true;
}
}
d.Disposable = Disposable.Create(
() =>
{
var localTimer = timer;
if (localTimer != null)
{
localTimer.Dispose();
lock (_gate)
{
_timers.Remove(localTimer);
action = null;
}
}
timer = null;
});
return d;
}
public IDisposable Schedule<TState>(
TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action == null)
throw new ArgumentNullException("action");
return Schedule(state, dueTime - Now, action);
}
public void Dispose()
{
_stopWatch.Stop();
}
}
One of the biggest causes of memory leaks in .NET applications (or any application), are event handlers remaining active beyond the lifetime of the parent object. Your object goes out of scope, but continues to listen for events on other objects, and hence can’t be garbage collected. Typically, your class would implement IDisposable, and you’d remove all your event handlers in that method. This works fine – if you keep track of all event handlers and remember to add the corresponding handler removal into your Dispose method.
Two more recent .NET developments which make this process easier to manage are the CompositeDisposable class, and of course IObservable, both of which can be found in the Reactive Extensions (Rx) assemblies.
CompositeDisposable is simple – it’s just a collection of IDisposable objects. When you call Dispose on your CompositeDisposable, all the items in the collection are disposed. If you create a BaseDisposable class to be used a base for all your business classes, then you can have something like the following:
public abstract class BaseDisposable : IDisposable
{
protected CompositeDisposable Disposables = new CompositeDisposable();
public bool IsDisposed { get; private set; }
public virtual void Dispose()
{
using (Disposables)
{
Disposables = null;
}
IsDisposed = true;
}
}
public class MyViewModel : BaseDisposable
{
public MyViewModel()
{
var timer = Observable.Interval(TimeSpan.FromSeconds(1))
.Subscribe(OnTimerCallback);
Disposables.Add(timer);
}
private void OnTimerCallback(long count)
{
Trace.WriteLine(count.ToString());
}
}
In the above sample, the MyViewModel class inherits BaseDisposable, so when it is disposed, anything that has been added to the Disposables collection during it’s lifetime will also be disposed – no need to add a new Dispose method with lots of event handler removals. I’ve just used a simple IObservable subscription in this example, and I haven’t implemented the Dispose pattern on my BaseDisposable – which would be a good idea in a real world scenario. In BaseDisposable, there’s also an IsDisposed property available – this can be useful for unit tests to confirm whether your object has been disposed as expected.
It’s not anything ground breaking, but it will mean you don’t have to add a Dispose method to each of your classes with lots of handler removals and disposing of child disposables. In short, cleaner and more maintainable.
IObservables work particularly well with this pattern, as each Rx subscription implements IDisposable. Concurrency, composition, and declarative syntax aside, this alone is a compelling reason to consider using Rx in place of regular event handlers in your application. Rather than specifying the handler removal in your Dispose method, just add your subscription to the Disposables collection, and the handler will be removed when your object is disposed.
I recently came across a project requirement for the client to create custom validation rules for retrieving data from the SQL database. The rules needed be applied against any number of member applications, and can be altered by the client at any point.
From the client perspective, the administration of the rules would look something like the following:

Simple enough concept. Historically, given such a requirement, you’d likely end up with some fudged SQL string (if querying a database), and/or a whole lot of conditional logic. The application already uses Linq2SQL, so I didn’t want to go backwards by introducing some extensive SQL string generation.
The first Linq based option I came across was the Dynamic Linq Query Library, which essentially enables you to use SQL-like strings as expressions in your conditional clauses. Nice, but it still smelled a bit like the SQL string concatenation of old.
The second option I looked at was PredicateBuilder. It’s a neat solution for the right problem, but it assumes that you know the properties/columns you’re querying against at compile time.
So, I decided to have a play around with Expression Trees, in an effort to dynamically generate my conditional expressions at runtime. I hadn’t really delved much into this area before, so I figured it’d be a good learning experience, even if it didn’t end up working out. To cut to the chase, the method I ended up with for parsing my rules into Lambda Expressions looks like the following:
public static Expression<Func<T, bool>> GetExpression<T>(
string propertyName, string operatorType, string propertyValue)
{
var isNegated = operatorType.StartsWith("!");
if (isNegated)
operatorType = operatorType.Substring(1);
var parameter = Expression.Parameter(typeof (T), "type");
var property = Expression.Property(parameter, propertyName);
// Cast propertyValue to correct property type
var td = TypeDescriptor.GetConverter(property.Type);
var constantValue = Expression.Constant(td.ConvertFromString(propertyValue), property.Type);
// Check if specified method is an Expression member
var operatorMethod = typeof(Expression).GetMethod(operatorType, new[] { typeof(MemberExpression), typeof(ConstantExpression) });
Expression expression;
if (operatorMethod == null)
{
// Execute against type members
var method = property.Type.GetMethod(operatorType, new[] {property.Type});
expression = Expression.Call(property, method, constantValue);
}
else
{
// Execute the passed operator method (e.g. Expression.GreaterThan)
expression = (Expression) operatorMethod.Invoke(null, new object[] {property, constantValue});
}
if (isNegated)
expression = Expression.Not(expression);
return Expression.Lambda<Func<T, bool>>(expression, parameter);
}
Which can be executed with a call like the following:
foreach (var rule in rules)
{
applicants = applicants.Where(
GetExpression<Applicant>(
rule.MemberName, // The Applicant property
rule.Operator, // Equals, Contains, GreaterThan, etc
rule.Value)
);
}
The rules are looped over, and Linq does its magic by combining all the separate rules with AND statements in the resulting query.
A few things to note:
Is this necessarily any better than using the Dynamic Linq library? A bit – it doesn’t really give me any compile-time type safety benefits, but I could potentially handle certain exceptions that I perhaps wouldn’t be able to detect using Dynamic Linq, such as casting the value to the correct type. On top of that, I like it more, it feels more robust, and doesn’t require external libraries to work. If nothing else, it gave me an excuse to get my head around some lower-level Expression Tree stuff :)
Reading the feature list of the upcoming Silverlight 4 release (now in beta), I am more than a bit impressed. Up to now, there has been a few glaring features by which Silverlight was trailing behind Flex – camera/mic input; printing; clipboard access; and right-to-left text being ones that spring to mind. Admittedly, all of these are fairly niche features which most applications wouldn’t require.
Silverlight 4 not only brings in all these features, but also a pile of others. Interestingly, they seem to be making a direct pitch against Adobe AIR with many of the features. The new Elevated Trust Applications feature (for out-of-browser apps), enables a host of features typically reserved for desktop applications: Local file access; Notifications API; Full-screen full-keyboard access; Cross-domain policy-free networking; and Drop targets. Of course, features aside, the huge advantage of the Silverlight desktop approach over AIR is that there is only one runtime plugin required.
At the speed Microsoft is moving forward with Silverlight, Adobe is going to have to start seriously upping their commitment to the Flash platform if they want to stay at the top of the game. Up to now, they could always give the argument of Flex being more feature-rich, and the ease of adaptation to the desktop with AIR – with both of these arguments now void, and Microsoft firmly remaining miles ahead in the developer tooling scene, Adobe’s work is cut out. They still have greater marketplace penetration with Flash player, but that lead is only going to narrow also.
You’ve got to love competition!
Just reading about the efforts to produce an Eclipse-based Silverlight development platform for the Mac – quite cool.
I have to think though, perhaps the effort would have been better spent creating a port of Blend for the Mac… it seems to me that only a tiny minority of developers would opt for Eclipse over Visual Studio; whereas I’d guess nearly all designers would prefer to work natively within MacOS.
I can kind of understand why they’ve done it, but I can only hope there’s another project underway with that Blend port…
Reading this preliminary list of the upcoming features of ReSharper 5, it makes me wonder how any .NET developer could ever be without a tool like this. Among the favorites would have to be Project Refactorings, and Call/Value Tracking. Genius.
Having used the refactoring-and-[insert feature here]-anaemic Flex Builder 3 at length on a few recent projects, life just seems to get better and better in Visual Studio land.
When it comes to video delivery, I come from a Flash background. I’ve worked on numerous streaming video projects over the years, all of which were created with Flash & Actionscript on the client side. Having been through the process several times, I know all the hurdles I’m going to have to clear well in advance.
Documentation for coding a Silverlight 3 player against IIS Smooth Streaming is a little sparse. IIS.net has several articles on the server setup, but I couldn’t find anywhere obvious regarding the client connection.
Unlike progressive video playback, you can’t just point the MediaElement.source at the video path then call play(). After a bit of searching, most people were talking about some AdaptiveStreamingSource class, which isn’t available in the base SL toolkit, but rather only found in SmoothStreaming.dll within the template players generated from Expression Encoder!
Per some handy forum posts, the steps required are:
So, once you can finally access the required assemblies, you can then invoke your IIS Smooth Streaming service with something along the lines of the following:
var mediaPath = "testClip_h1080p.ism/manifest";
var source = new AdaptiveStreamingSource
{
ManifestUrl = new Uri(mediaPath, UriKind.RelativeOrAbsolute),
MediaElement = streamElement // the xaml MediaElement
};
source.StartPlayback();
Make sure you put the trailing ‘/manifest’ after your stream path.
Simple enough, once you’ve figured out the basics! Not exactly sure what MS were thinking by not including the SmoothStreaming assemblies in the SL3 toolkit? Surely they realise not everyone wants to use a templated player. Or have I missed something here?