Archive
.NET String extension methods to check for array of prefixes or suffixes
Seems StartsWith and EndsWith methods of String class in .NET are missing a version that accepts multiple (as an array) prefixes or suffixes respectively when testing the string. To achieve this I just added the following extension methods to StringExtensions class (of Utils.Extensions namespace) under Utils.Silverlight project at the ClipFlair source code.
public static bool StartsWith(
this string s,
string[] suffixes,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in suffixes) if (s.StartsWith(suffix, comparisonType)) return true; return false; } public static bool EndsWith(
this string s,
string[] suffixes,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in suffixes) if (s.EndsWith(suffix, comparisonType)) return true; return false; }
To use them, you add a reference to Utils.Silverlight project to your own one and then add a using clause for the namespace that hosts a static class with these extension methods (e.g. “using Utils.Extensions;”) and then you can use them on any String at the respective source file. Can even use them on literal strings, since most .NET compilers support Boxing of literals into respective types.
I’m using a default value for the comparisonType method argument to make it optional. I use StringComparison.CurrentCulture as the default value for it (performing a word case-sensitive and culture-sensitive comparison using the current culture), as Microsoft is doing at “String.StartsWith(String)” method. However, do note the following text from that method’s documentation:
Notes to Callers
As explained in Best Practices for Using Strings in the .NET Framework, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string begins with a particular substring by using the string comparison rules of the current culture, call the StartsWith(String, StringComparison) method overload with a value of StringComparison.CurrentCulture for its comparisonType parameter.
.NET String class extensions to replace prefix or suffix
Just added the following extension methods to StringExtensions class (of Utils.Extensions namespace) under Utils.Silverlight project at the ClipFlair source code.
public static string ReplacePrefix(
this string s,
string fromPrefix,
string toPrefix,
StringComparison comparisonType = StringComparison.CurrentCulture) { return (s.StartsWith(fromPrefix, comparisonType)) ?
toPrefix + s.Substring(fromPrefix.Length) : s; } public static string ReplacePrefix(
this string s,
string[] fromPrefix,
string toPrefix,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string prefix in fromPrefix) if (s.StartsWith(prefix, comparisonType)) return toPrefix + s.Substring(prefix.Length); return s; } public static string ReplaceSuffix(
this string s,
string fromSuffix,
string toSuffix,
StringComparison comparisonType = StringComparison.CurrentCulture) { return (s.EndsWith(fromSuffix, comparisonType)) ?
s.Substring(0, s.Length - fromSuffix.Length) + toSuffix : s; } public static string ReplaceSuffix(
this string s,
string[] fromSuffix,
string toSuffix,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in fromSuffix) if (s.EndsWith(suffix, comparisonType)) return s.Substring(0, s.Length - suffix.Length) + toSuffix; return s; }
To use them, you add a reference to Utils.Silverlight project to your own one and then add a using clause for the namespace that hosts a static class with these extension methods (e.g. “using Utils.Extensions;”) and then you can use them on any String at the respective source file. Can even use them on literal strings, since most .NET compilers support Boxing of literals into respective types.
e.g.
s = s.ReplacePrefix("https://", "http://", StringComparison.OrdinalIgnoreCase);
//– converts https:// prefix to http:// ignoring character case
or
s = s.ReplacePrefix(new String[]{"https://", "http://"}, "", StringComparison.OrdinalIgnoreCase);
//– removes https:// or http:// prefix ignoring character case
Update:
I added a default value for the comparisonType method argument to make it optional. I use StringComparison.CurrentCulture as the default value for it (performing a word case-sensitive and culture-sensitive comparison using the current culture), as Microsoft is doing at “String.StartsWith(String)” method. However, do note the following text from that method’s documentation:
Notes to Callers
As explained in Best Practices for Using Strings in the .NET Framework, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string begins with a particular substring by using the string comparison rules of the current culture, call the StartsWith(String, StringComparison) method overload with a value of StringComparison.CurrentCulture for its comparisonType parameter.
HowTo: format XML output of DataContractSerializer
based on the other samples posted at StackOverflow on how to format XML created by DataContractSerializer, that use XmlWriter, here’s a version (from ClipFlair source code) that works with streams (and Ionic.Zip library in specific).
It also shows how the code is when you don’t apply formatting (using conditional compilation). Just comment out the #define (prefix it with //) to make it write unformatted XML.
#define WRITE_FORMATTED_XML
using System.Xml;
namespace ClipFlair.Windows
{
public partial class BaseWindow : FloatingWindow
{
//...
#if WRITE_FORMATTED_XML
private static XmlWriterSettings XML_WRITER_SETTINGS =
new XmlWriterSettings() { Indent=true, IndentChars=" "};
#endif
//...
public virtual void SaveOptions(ZipFile zip, string zipFolder = "")
//THIS IS THE CORE SAVING LOGIC
{
if (SavingOptions != null) SavingOptions(this, null); //notify any listeners
View.Busy = true;
try
{
ZipEntry optionsXML =
zip.AddEntry(zipFolder + "/" + View.GetType().FullName + ".options.xml",
new WriteDelegate((entryName, stream) =>
{
DataContractSerializer serializer =
new DataContractSerializer(View.GetType());
//assuming current View isn't null
#if WRITE_FORMATTED_XML
using (XmlWriter writer = XmlWriter.Create(stream, XML_WRITER_SETTINGS))
serializer.WriteObject(writer, View);
#else
serializer.WriteObject(stream, View);
#endif
}));
}
catch (Exception e)
{
MessageBox.Show("ClipFlair options save failed: " + e.Message);
}
finally
{
View.Busy = false; //in any case (error or not) clear the Busy flag
}
if (SavedOptions != null) SavedOptions(this, null); //notify any listeners
}
//...
}
}
HowTo: load CaptionElements into Silverlight Media Framework player
Trying to make CaptionsGridWindow of ClipFlair serve captions editing on-the-fly to SMF (Silverlight Media Framework [now called MMPPF]) player component, I had a real hard time, plagued by a bug at TimedTextElementStyle. It seems to be setting default FontSize for captions using a “Cell” unit instead of using a “Pixel” unit. Currently SMF only supports “Pixel” units at FontSize of TimedTextElements according to the codedoc notes.
Another issue I had was that CaptionRegion constructor sets it to be active all the time (specifying a Begin value of a min possible TimeExtent and an End value of the max possible TimeExtent), so it renders ShowBackground.WhenActive setting useless for it. That is if you want the captions background to show up only when there are captions showing (active), then you have to set the CaptionRegion’s background to Colors.Transparent and set each CaptionElement’s background to some non-transparent color (note that both CaptionRegion and CaptionElement are TimedTextElements, with the later added to the former’s Children property, forming a TimedTree that is).
public void UpdateMarkers(MediaMarkerCollection<TimedTextElement> newMarkers) { if (newMarkers == null) return; CaptionRegion region = new CaptionRegion(); region.Style.ShowBackground = ShowBackground.WhenActive;
//doesn't seem to work if other than transparent color is used region.Style.BackgroundColor = Colors.Transparent; foreach (CaptionElement marker in newMarkers) { region.Children.Add(marker); marker.CaptionElementType = TimedTextElementType.Text; marker.Style.ShowBackground = ShowBackground.WhenActive; marker.Style.BackgroundColor = Color.FromArgb(100, 0, 0, 0);
//use a semi-transparent background marker.Style.Color = Colors.White; //marker.Style.TextAlign = TextAlignment.Center; Length length = new Length { Unit = LengthUnit.Pixel, Value = 20 }; //must use this, since the default LengthUnit.Cell used
//at TimedTextStyle constructor is not supported marker.Style.FontSize = length; } Captions.Add(region); }
HowTo: Scale control arround its center using a render transform
In the context of ClipFlair development, I was recently adding independent scaling (zooming) functionality to its ZUI container’s floating windows (apart from the container zooming functionality) and came across some strange behavior, where the windows seemed to also move apart from getting scaled.
After banging my head a bit I decided to take a closer look at Microsoft’s documentation and noticed the following text at http://msdn.microsoft.com/en-us/library/system.windows.uielement.rendertransformorigin.aspx
"RenderTransformOrigin has a somewhat nonstandard use of the Point structure value, in that the Point does not represent an absolute location in a coordinate system. Instead, values between 0 and 1 are interpreted as a factor for the range of the current element in each x,y axis. For example, (0.5,0.5) will cause the render transform to be centered on the element, or (1,1) would place the render transform at the bottom right corner of the element. NaN is not an accepted value. Values beyond 0 and 1 are also accepted, and will result in more unconventional transform effects. For instance, if you set RenderTransformOrigin to be (5,5), and then apply a RotateTransform, the rotation point will be well outside the bounds of the element itself. The transform will spin your element around in a big circle that originates beyond bottom right. The origin might be somewhere inside its parent element and could possibly be possibly out of frame or view. Negative point values are similar, these will go beyond the top left bounds. Render transforms do not affect layout, and are typically used to animate or apply a temporary effect to an element."
Since ClipFlair’s FloatingWindowHostZUI template uses a Canvas to host its FloatingWindows, I obviously didn’t care about the phrase “Render transforms do not affect layout”, but the phrase “values between 0 and 1 are interpreted as a factor for the range of the current element in each x,y axis” rang a bell immediately.
Misguided by the poor Intellisense info for the RenderTransformOrigin property, I had thought that point was in the control’s coordinate system, and since I wanted to scale the control arround its center, I had used the following erroneous statement:
window.RenderTransformOrigin = new Point(window.ActualWidth/2, window.ActualHeight/2);
window.RenderTransform = new ScaleTransform().SetScale((double)e.NewValue);
…
instead of the correct one:
window.RenderTransformOrigin = new Point(0.5, 0.5);
//scale arround the window center
window.RenderTransform = new ScaleTransform().SetScale((double)e.NewValue);
That is the range 0 to 1 for x & y coordinates of RenderTransformOrigin refers to the UIElement region, whereas less or greater values are (proportionally) outside of it, useful for example if you want to rotate an object arround an external point with a RotateTransform.
Don’t get puzzled by the expression new ScaleTransform().SetScale(…), it’s a syntax I use for authoring portable source code between WPF and Silverlight (since Silverlight only has a parameter-less constructor for ScaleTransform and anyway WPF doesn’t have a constructor that takes a single parameter for both X and Y scale values).
To sum up, here’s the “Scale” property I added to the FloatingWindow class:
#region public double Scale
/// <summary> /// Gets or sets current window scale. /// </summary> /// <value>Current scale.</value>
public double Scale {
get { return (double)GetValue(ScaleProperty); }
set { SetValue(ScaleProperty, value); } } /// <summary>
/// Identifies the <see cref="FloatingWindow.Scale" /> dependency property.
/// </summary>
/// <value>
/// The identifier for the <see cref="FloatingWindow.Scale" /> dependency property.
/// </value> public static readonly DependencyProperty ScaleProperty =
DependencyProperty.Register("Scale", typeof(double), typeof(FloatingWindow),
new PropertyMetadata(1d, OnScalePropertyChanged));
//Must use 1d here, not 1 (else will get XAMLParseException at runtime)
/// <summary>
/// ScaleProperty PropertyChangedCallback call back static function.
/// </summary>
/// <param name="d">FloatingWindow object whose Scale property is changed.</param>
/// <param name="e">DependencyPropertyChangedEventArgs contains old and new values.</param> private static void OnScalePropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e) {
FloatingWindow window = (FloatingWindow)d;
if (window != null)
{
window.RenderTransformOrigin = new Point(0.5, 0.5); //scale arround the window center
window.RenderTransform = new ScaleTransform().SetScale((double)e.NewValue);
}
} #endregion
HowTo: Bind to a DataContext property named Source in XAML
While refactoring ClipFlair code to use MVVM (Model-View-ViewModel) pattern, I came across the XAML error “Object reference not set to an instance of an object.”, shown in Visual Studio when trying to bind to my ViewModel (accessed implicitly, being set as the DataContext of the XAML control) for a property named Source.
I have settled down to using the following MVVM-style pattern (of my own) at ClipFlair:
Update: Later on, at ClipFlair project, I renamed folder “Views” to “ViewModels” and folder “Components” to “Views” and moved “ViewModels” folder inside the “Views” one to keep view-related stuff in one place.
IImageViewer.cs:
ImageView.cs:
Update: Later on, I refactored this to initialize the fields directly instead of at the constructor:
//can set fields directly here or at the constructor
private Uri source = IImageViewerDefaults.DefaultSource;
ImageViewerWindow.xaml.cs (the so-called codebehind for the XAML control):
Note above how we set the "DataContext" of the control to our ViewModel, so that we can bind to its properties implicitly (without referencing it) in the XAML.
Update: There’s something very important I had forgotten to do at the implementation of the “View” property in the code above, that is to listen for PropertyChangeEvents emitted by the ViewModel. In specific, we need to listen for changes of the ViewModel’s “Source” property to keep the View’s “SourceProperty” (a DependencyProperty that is also accessed via the View’s “Source” property) in sync with the ViewModel’s “Source” property. So the code shown in the above screenshot has to be fixed by changing the “View” property’s implementation like below:
For extra safety in case you want to allow setting a null ViewModel to the View property, you could check for (value != null) before trying to add PropertyChanged event handler to it:
if (value != null)
value.PropertyChanged += new PropertyChangedEventHandler(View_PropertyChanged);
Obviously, if more DependencyProperties are added to the component (e.g. to be able to set them declaratively from XAML when instantiating the component) that have to be in sync to respective ones at the ViewModel (which is held by the View property), then the “View_PropertyChanged” method (event handler) implementation has to be extended with “else if” statements for each of those properties to set the respective dependency properties from the matching ViewModel properties.
BTW, if your ViewModel passes null to the changed property name to mark a single change event for multiple properties, then you have to also take that in mind (else you will get exception when you try to call “Equals” method on null string), by doing something like below:
if (e.PropertyName == null) {
Source = View.Source;OtherProperty = View.OtherProperty;
//…sync all properties since we are not told which ones changed
return;}
else if (e.PropertyName.Equals("Source") {
Source = View.Source;}
else if (e.PropertyName.Equals("OtherProperty")
{OtherProperty = View.OtherProperty;
}
//…
Note that instead of “.Equals” one could have also used “==” operator, since the C# compiler maps the string equality operator to string’s “.Equals” method.
Update: Another retouch I have since done to the code above is to avoid hardcoding property names and their default values and use nstead ithe proprerty name constants defined at the class IImageViewerProperties and the respective default values defined at IImageViewerDefaults. For example, I prefer to use (after adding a “using ClipFlair.Models.Views;” to the top):
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(IImageViewerProperties.PropertySource, typeof(Uri), typeof(ImageWindow), new FrameworkPropertyMetadata((Uri)IImageViewerDefaults.DefaultSource,
new PropertyChangedCallback(OnSourceChanged)));
Update: I eventually opted for using a “switch” statement instead of nested if / else if statements, to keep things cleaner when more properties are added:
protected void View_PropertyChanged(object sender,
PropertyChangedEventArgs e)
{
if (e.PropertyName == null)
{
Source = View.Source;
//...
}
else switch (e.PropertyName)
//string equality check in .NET uses ordinal (binary) comparison
//semantics by default
{
case IImageViewerProperties.PropertySource:
Source = View.Source;
break;
//...
}
}
ImageViewerWindow.xaml (the XAML control):
The issue at the last screenshot is that you can’t write Source="{Binding Source}" as you’d write Source="{Binding SomeDataContextProperty}", but need to write Source="{Binding Path=Source}" instead, since Source is a keyword at Binding expression syntax.
BTW, note that at the “edImageURL” TextBox I use Mode=TwoWay (two-way binding, the default is one way binding from source [the DataContext in our case] to target), whereas at the Image control I don’t. Both get an image URI from the ViewModel’s “Source” property, but we also want to be able to edit the URI at the textbox and update the view’s Source property (which will in turn update the Image control with the new image).
Also, note that apart from passing a URI to the Source property of an Image control there’s also a more verbose syntax one could use above, which can be handy to know of:
<Image>
<Image.Source><BitmapImage UriSource="{Binding Path=Source}" />
</Image.Source>
</Image>
The <Image.Source> tag here is using the so-called property element syntax pattern. In the snippet above it sets a value to the Source property of the Image tag. XAML can use both XML attributes and child elements to set values to properties of controls, but whereas the attribute name would be “Source”, the child element tag has to be “Image.Source”, not just “Source”, since the XML schema needs to have unique definitions for the XML tags, whereas multiple objects could define different Source properties causing naming collisions.
According to http://10rem.net/blog/2012/03/27/tip-binding-an-image-elements-source-property-to-a-uri-in-winrt-xaml this more verbose syntax is needed at Windows 8 Metro-style apps (that is for the WinRT API) for binding an Image to a URI (but since that article is back from March 2012, probably this is not an issue any more).
HowTo: Compress speech audio using CSpeex codec at Silverlight apps
Following up on my post on how to fix CSpeex (http://cspeex.codeplex.com) to compile at Silverlight 5 (see http://zoomicon.wordpress.com/2012/06/09/fix-compile-cspeex-audio-codec-at-silverlight-4-rc-and-silverlight-5/).
Initially I thought it was not working correctly, but then I noticed I was running it on Terminal Server and didn’t have an audio device available. Running SLAudioDemo included in the CSpeex distribution (after doing the fix mentioned at my post above) seems to work fine on my local PC.
The SLAudioDemo demonstrates capturing audio into memory as a compressed CSpeex stream which it can decompress and save into a .WAV file that one can play say with Windows Media Player. The WAV is uncompressed, since SLAudioDemo compresses in memory (via StreamAudioSink) and decompresses to normal PCM WAV when you save (else it would be unplayable).
Obviously the Speex codec is useful for uploading (e.g. via HSS Interlink) compressed audio to a server (or to the other end at some voice chat app) and decompress there before playback (similarly the other way around).
At the server side if you want to do audio storage too, you could also keep an extra decoded copy of the compressed Speex audio data, recoded into WMA using automation of Microsoft Expression Encoder for example (see Microsoft Transform Manager, can do this in the background if you uncompress into a .WAV file at some incoming folder). That way you could serve that audio to your Silverlight client as Speex-encoded data file, but also to other users that use Windows Media Player to get the audio file from some URL etc. Could also encode to MP4/AAC or MP3 but there are licensing issues with those from what I know.
For the CSpeex encoder see StreamAudioSink.cs. Only 2 lines are needed in MainPage.xaml.cs of SLAudioDemo:
streamAudioSink = new StreamAudioSink();
streamAudioSink.CaptureSource = _captureSource;
after you 1st declare at the top level (must have this as a top-level field, else the garbage collector can get it)
private StreamAudioSink streamAudioSink;
Here’s the decoding code that saves the WAV (from MainPage.xaml.cs):
if (sfd.ShowDialog() == true)
{
// User selected item. Only property we can get to is.
using (Stream stream = sfd.OpenFile())
{
JSpeexDec decoder = new JSpeexDec();
decoder.setDestFormat(JSpeexDec.FILE_FORMAT_WAVE);
decoder.setStereo(true);
Stream memStream = streamAudioSink.MemFile.InnerStream;
memStream.Position = 0;
decoder.decode(new RandomInputStream(memStream),
new RandomOutputStream(stream));
stream.Close();
}
}
Don’t get puzzled by the use of RandomInputStream / RandomOutputStream. These are from Java’s I/O package (java.io.*) that CSpeex has ported to .NET, since it’s in fact a port of JSpeex, a Java implementation of the Speex codec.
Gotcha: Silverlight’s Uri class constructor eats up part after last slash
Via trial and error, I recently found out that when creating a Uri combining another Uri and a suffix part (tried at Silverlight, but I guess it’s a .NET issue in general), it eats up the last part of the (first) Uri if it doesn’t end with "/".
That is, if you combine http://test.com/a with b.doc you get http://test.com/b.doc instead of http://test.com/a/b.doc that one might expect having used the Path.Combine of .NET on the local filesystem before (if hope I do remember well how that one behaves). So you have to make sure the first part of the path you combine has / at the end (e.g. http://test.com/a/ in the case above).
Personally I feel this is a bug at Uri class (since it breaks the least surprise principle [for developers with desktop experience at least]), but it may have been made so to follow some W3C suggestions or Javascript standard behaviour or whatever.
Example:
The following code will eat up part after last / (that is Uploads) instead of appending / (as Path would do on Windows).
const string STORAGE_URL = "http://test.com/Uploads"; //error: need "/" at end
Uri fileUri = new Uri(new Uri(STORAGE_URL), fileName + ".wav");
So, one can use instead:
const string STORAGE_URL = "http://test.com/Uploads";
Uri fileUri = new Uri(STORAGE_URL + "/" + fileName + ".wav");
Else fix the STORAGE_URL at the first sample to have "/" at the end (but this can break easily by changing the URL in the future and forgetting to add the trailing / or reading it from some configuration file and having the user enter a URL without a trailing / which can easily occur)
Fix: The tag ‘TimeUpDown’ does not exist in XML namespace (Silverlight Toolkit)
If you use TimeUpDown control from Silverlight Toolkit in your XAML like below (copy pasting from CaptionGrid at ClipFlair source):
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<DataTemplate x:Key="StartTimeCellTemplate">
<TextBlock Margin="4" Text="{Binding Begin}" />
</DataTemplate>
<DataTemplate x:Key="StartTimeCellEditTemplate">
<input:TimeUpDown Format="hh:mm:ss"
Value="{Binding Begin, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=true}"
/>
</DataTemplate>
…
</ResourceDictionary>
then even though it seems to not complain in the XAML designer of Visual Studio 2010, then at Build time, even if you’ve added a reference to System.Windows.Controls.Input.Toolkit assembly (the 5.0.5.0 version for the Silverlight 5 Toolkit [December 2011 release]), you get:
The tag ‘TimeUpDown’ does not exist in XML namespace ‘clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit’
Similar bad behaviour occurs if you try to drag-drop the TimeUpDown control from Visual Studio toolbar (assuming you’ve installed the Silverlight Toolkit first) onto the XAML designer, no xml namespace (named xmlns:input above) is added and you just get <TimeUpDown /> in the designer.
The solution is to also add to your project a reference to System.Windows.Controls assembly (be sure to select same version DLL as above [e.g. 5.0.5.0]). For some reason the System.Windows.Controls.Input.Toolkit doesn’t seem to pull that together and must have some internal dependency to it (although the error you get is very cryptic).
Below is the Add Reference dialog of Visual Studio 2010, you either use the “Extensions” from the right handside, or type-in “System.Windows.Controls” at the search box to quickly spot those two assemblies.
Note that If you have a Silverlight assembly project with some UserControl in it and you apply the workaround I mentioned above, then if you use that UserControl in a Silverlight app (in a Page or other UserControl) you get a RUNTIME error this time at launch saying XamlParserError at the title bar and the exception text:
The type ‘TimeUpDown’ was not found because ‘clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit’ is an unknown namespace
This time the fix is to add a reference to "System.Windows.Controls.Input.Toolkit" to the project.
The funny thing is that this project (that uses a library that hosts a control that uses TimeUpDown itself) DOESN’T NEED to have a reference to "System.Windows.Controls", as the library does need to compile.
The other funny thing is that it does compile OK without adding the "System.Windows.Controls.Input.Toolkit" reference, but it shows runtime error.
This issue has been reported for some time now at:
but hasn’t yet been fixed.
Update:
This may also be related:
http://zoomicon.wordpress.com/2012/07/02/fix-the-tag-xxx-does-not-exist-in-xml-namespace-clr-namespaceyyy/
I noticed that when I tried to compile on a machine that didn’t have Silverlight 5 Toolkit, it was eventually trying to use the Silverlight 4 Toolkit version of System.Windows.Control.Input from my Debug folder (not sure how that DLL ended up there, probably was brought in automatically via some other library’s dependencies by Visual Studio). So maybe you end up with multiple assemblies with the same name in the project and you have to remove the old ones.
You may also run into this issue if your solution was using Silverlight 5 Toolkit and you try to build the project on another machine that has Silverlight 4 Toolkit only. Solution is to install Silverlight 5 Toolkit too and then make sure the project refers to the 5.0 version of System.Windows.Controls.Input.Toolkit.dll and that the reference doesn’t have a path that points into your solution but to the program files folder instead, where Silverlight Toolkit gets installed.