by Brian Keating
Wed, September 08 2010 21:17
A sample of using SyncronizationContext to post a message back to the UX thread
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SynchronizationContext ctx = SynchronizationContext.Current;
ThreadPool.QueueUserWorkItem(_ =>
{
WebClient client = new WebClient();
string html = client.DownloadString("http://www.briankeating.net");
ctx.Post(state =>
{
tbDetails.Text = (string)state;
}, html);
});
}
by Brian Keating
Wed, September 08 2010 20:53
Hi All,
Been a while since I've writen some posts, been pretty hectic hours at work and weekends building a house so my chances to blog have been limited.
I intend over the coming few days to give a few tips and tricks on MCV2.
Here's on gottya..
Be carefull how you name your formal arguements in your controller functions.
You can see from the screenshot below that I created two args, "Name" and "name"
By default the first matching case insensitive value will be applied to both variables by MVC...
Usually this will be avoided by good naming conventions but be carefull nonetheless :-)

by Brian Keating
Wed, August 11 2010 22:34
http://url/abc.svc .svc at the end of url makes it user unfriendly. It also makes it Low REST service as it donot follow the REST URI principle.
Till date developers have to overcome this limitation by implementing URLReWrite module in IIS.
Writing custom code to implement this is error prone and needs maintenance over a period. WCF 4.0 has introduced
a feature to access WCF services using attribute called as relativeAddress.
Following .config setting depicts how a CalculatorService can be accessed using relative URL.
<system.serviceModel>
<serviceHostingEnvironment>
<serviceActivations>
<add relativeAddress="/Payment" service=“CalculatorService.svc"/>
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
88433fee-456f-4bc7-bfc0-cf2b9dc781ce|0|.0
Tags: wcf 4.0
WCF
by Brian Keating
Tue, June 29 2010 23:07
Pre .NET 4.O
Prior to ASP.NET 4.0 (and especially with MVC) when a user outputted information to a webpage they used <%= Server.HtmlEncode(modelViewStore.Content) %>
The reason for the Encoding is primiarily to prevent XSS (cross site script injection) whereby someone may try to inject some client side script or HTML Markup to vandalize a site or to steal valuable information.
This approach has a few shortcommings; like,
* Users may forget the encoding
* bit verbose
.NET 4.0
A new nugged has arrived:
<%: modelViewStore.Content %>
by Brian Keating
Thu, June 03 2010 16:43
Ever wondered how to display the correct cursor in an application that is databinded to async methods?
Pretty easy solution, just databind the cursor on the window itself.
Here's how:
- Add an IsBusy property on the DataContext (and implement INotifyPropertyChanged on it)
- Addt the following to your window xaml
xmlns:valueConverters="clr-namespace:XXX.ValueConverters"
Cursor="{Binding IsBusy, Converter={valueConverters:CursorExtensionConverter}}"
- Create the following ValueConverter
public class CursorExtensionConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && ((bool)value))
return Cursors.Wait;
else
return Cursors.Arrow;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return instance;
}
private static CursorExtensionConverter instance = new CursorExtensionConverter();
}
Note: Use of MarkupExtension
by Brian Keating
Thu, May 13 2010 21:41
Those of you that use INotifyPropertyChanged may have noticed it's easy to break the code if you choose to refactor/rename as the property name string does not get refactored.
Here is a mechanism to catch this problem at the implementation stage.
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
#region INotifyPropertyChanged Members
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion // INotifyPropertyChanged Members
by Brian Keating
Wed, May 12 2010 10:44
If you're interested to see how to attach commands to listview items for use with an implementation of the MVVM pattern, have a look at this.
<Style x:Key="Local_OpenEntityStyle"
TargetType="{x:Type ListViewItem}">
<Setter Property="acb:CommandBehavior.Event"
Value="MouseDoubleClick" />
<Setter Property="acb:CommandBehavior.Command"
Value="{Binding ElementName=uiEntityListDisplay, Path=DataContext.OpenEntityCommand}" />
<Setter Property="acb:CommandBehavior.CommandParameter"
Value="{Binding}" />
</Style>
Here the command to be fired on the MouseDoubleClick event is set, the CommandParameter, will be the data object that we click on.
59f0a853-441b-4095-bf1d-6ceba053a1ad|1|1.0
Tags:
WPF | MVVM
by Brian Keating
Tue, May 11 2010 10:38
Ever want to find out from c# where some "special" folders are located so you can use them in your desktop application?
Here's how.
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
See Environment.SpecialFolder enumeration for more locations.
9fdb9a3a-9e0a-4d00-9d5d-9334f7e36147|0|.0
Tags:
by Brian Keating
Mon, May 03 2010 21:23
I was just about to write up a little blog on the how and why of Exposing OData (Open Data Protocol) in WCF 4.0.
But seeming it being a Bank Holiday and, if you follow any of my posts, you'll know I don't spend a lot of time writing them up, they are more like mini blogs 
So I found this excellent article by Brad Abrams
http://blogs.msdn.com/brada/archive/2010/03/16/silverlight-4-ria-services-ready-for-business-exposing-odata-services.aspx
I recommend you have a read because if you've never encounted OData before you'll be amazed how easy it is to expose and consume your domain service (expecially with Excel 2010)
203ad40d-4f4a-4f4b-9ecc-de68b14237a0|0|.0
Tags:
by Brian Keating
Thu, April 29 2010 21:18
Xaml Serialization to the rescue.
The following sample code will persist the current Listview state to disk and restore it the next time the control is loaded.
Code behind
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void lvInit(object sender, EventArgs e)
{
GridView gv = lvTest.View as GridView;
gv.Columns.CollectionChanged += (s, gvE) =>
{
if (gvE.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Move)
{
SaveState();
}
};
}
private void SaveState()
{
string lvXaml = XamlWriter.Save(lvTest);
using (var s = new StreamWriter(@"c:\temp\lv.xaml"))
{
s.Write(lvXaml);
}
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
ListView li = null;
if (File.Exists(@"c:\temp\lv.xaml"))
bdr.Child = (ListView)XamlReader.Load(File.OpenRead(@"c:\temp\lv.xaml"));
}
}
}
12555ef5-cb7d-41f1-ba80-f07f90bee7b2|0|.0
Tags: