<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>phdesign &#187; howto</title>
	<atom:link href="http://www.phdesign.com.au/tag/howto/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.phdesign.com.au</link>
	<description>phdesign web and application development by Paul Heasley</description>
	<lastBuildDate>Sun, 22 Jan 2012 22:17:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Delete Dependent Entities When Removed From EF Collection</title>
		<link>http://www.phdesign.com.au/programming/delete-dependent-entities-when-removed-from-ef-collection/</link>
		<comments>http://www.phdesign.com.au/programming/delete-dependent-entities-when-removed-from-ef-collection/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 11:28:06 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[ef]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=263</guid>
		<description><![CDATA[I’m using Entity Framework 4.1 Code First Fluent API. The problem. I have an Entity Framework model being used in the business layer called Patient, it has a collection of dependent entities called Responses, when a response needs to be deleted I simply remove it from the collection and expect that it’ll get deleted from [...]]]></description>
			<content:encoded><![CDATA[<p>I’m using Entity Framework 4.1 Code First Fluent API.<br />
The problem. I have an Entity Framework model being used in the business layer called Patient, it has a collection of dependent entities called Responses, when a response needs to be deleted I simply remove it from the collection and expect that it’ll get deleted from the database. It doesn’t.<span id="more-263"></span></p>
<p><img src="http://www.phdesign.com.au/wp-content/uploads/2011/09/ef-delete-relationship-models.png" alt="Response and Patient Model Diagram" title="ef-delete-relationship-models" width="249" height="91" class="alignnone size-full wp-image-268" /></p>
<pre><code>// This doesn’t work as expected, it removes the relationship but not the Response entity.
Patient.Responses.Remove(Patient.Responses.Where(r =&gt; r.Id == 1));</code></pre>
<p>If I try to save this, I get the error:</p>
<p><em>System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</em></p>
<p>What’s happening is the Response entity does not get deleted, just the relationship to the Patient. However when the relationship is removed, Entity Framework doesn’t know what to do with Response.PatientId, it can’t null it because it’s marked as not null.</p>
<p>Reading <a title="Deleting Foreign-Key Relationships in EF4" href="http://blogs.msdn.com/b/dsimmons/archive/2010/01/31/deleting-foreign-key-relationships-in-ef4.aspx" target="_blank">this blog post</a> helped me understand the issue a bit more. So one solution is to make the Response entity primary key depend on the foreign key field, i.e. PatientId, this will make Entity Framework act as expected and delete the dependent entity when the relationship is deleted.</p>
<p>We can do this by providing the following Fluent API mapping:</p>
<pre><code>modelBuilder.Entity().HasKey(m =&gt; new { m.Id, m.PatientId }); </code></pre>
<p>But if you’re not comfortable changing your database structure to suit Entity Framework there is another way. By overriding the SaveChanges method of our DbContext class, we can monitor for changes to Responses where they have been orphaned from a Patient and delete them:</p>
<pre><code>public override int SaveChanges()
{
  // Need to manually delete all responses that have been removed from the patient, otherwise they'll be orphaned.
  var orphanedResponses = ChangeTracker.Entries().Where(
    e => (e.State == EntityState.Modified || e.State == EntityState.Added) &#038;&#038;
      e.Entity is Response &#038;&#038;
        e.Reference("Patient").CurrentValue == null);
  foreach (var orphanedResponse in orphanedResponses)
  {
    Responses.Remove(orphanedResponse.Entity as Response);
  }

  return base.SaveChanges();
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/delete-dependent-entities-when-removed-from-ef-collection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conditional Validation in ASP.NET MVC3</title>
		<link>http://www.phdesign.com.au/programming/conditional-validation-in-asp-net-mvc3/</link>
		<comments>http://www.phdesign.com.au/programming/conditional-validation-in-asp-net-mvc3/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 02:43:26 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[asp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=250</guid>
		<description><![CDATA[Need to perform validation on a model&#8217;s property based on some other state of the model? Here&#8217;s a way to achieve it using the IValidatableObject interface and data annotations. In our example project we want to validate the state field is a valid Australian state if the country field is &#8220;Australia&#8221;. IValidatableObject Any model that [...]]]></description>
			<content:encoded><![CDATA[<p>Need to perform validation on a model&#8217;s property based on some other state of the model? Here&#8217;s a way to achieve it using the IValidatableObject interface and data annotations.</p>
<p>In our example project we want to validate the state field is a valid Australian state if the country field is &#8220;Australia&#8221;. </p>
<p><img src="http://www.phdesign.com.au/wp-content/uploads/2011/06/ConditionalValidationSmall.png" alt="Conditional validation of state field" title="Conditional validation of state field" width="285" height="324" class="alignnone size-full wp-image-258" /></p>
<p><span id="more-250"></span></p>
<h2>IValidatableObject</h2>
<p>Any model that implements IValidatableObject in MVC3 (note this doesn&#8217;t work in MVC2) will get it&#8217;s Validate method called when validating the object.</p>
<pre><code>public abstract class ModelBase : IValidatableObject
...
public IEnumerable Validate(ValidationContext validationContext)</code></pre>
<h2>ConditionalValidationAttribute</h2>
<p>To define the conditional validation we&#8217;ll use a ConditionalValidationAttribute which identifies a method to call to perform the validation. The method must be static, accept at least one parameter (the value of the property to be validated), optionally accept a second context parameter (this will be the object whose property is being validated) and return a ValidationResult.</p>
<pre><code>[ConditionalValidation(typeof(User), "ValidateState")]
public string State { get; set; }
...
public static ValidationResult ValidateState(string state, object context)</code></pre>
<h2>ModelBase</h2>
<p>The ModelBase class brings this all together. The constructor builds a dictionary of ConditionalValidationAttributes for each property and it implements the IValidatableObject.Validate method to loop through all the ConditionalValidationAttributes and validate them.</p>
<p>Note that the IValidatableObject.Validate method is called after all data annotations have been successfully validated. So if you have some properties with a RequiredAttribute, the required field error message will show and the user will need to fix this before our model&#8217;s Validate messages are displayed.</p>
<p>Here&#8217;s the full code for <b>ModelBase.cs</b>:</p>
<pre><code>public abstract class ModelBase : IValidatableObject
{
  /// &lt;summary&gt;
  /// The list of validations for each property
  /// &lt;/summary&gt;
  protected Dictionary&lt;string, ConditionalValidationAttribute[]&gt; Validations { get; private set; }

  protected ModelBase()
  {
    Validations = (from property in GetType().GetProperties()
             let validations = GetValidations(property)
             where validations.Length &gt; 0
             select new {PropertyName = property.Name, Validations = validations})
      .ToDictionary(a =&gt; a.PropertyName, a =&gt; a.Validations);
  }

  /// &lt;summary&gt;
  /// Validates all ConditionalValidationAttributes
  /// &lt;/summary&gt;
  /// &lt;param name=&quot;validationContext&quot;&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
  {
    return from property in Validations
         from validator in property.Value
         select validator.IsValid(GetPropertyValue(property.Key), this)
         into validationResult
         where validationResult != ValidationResult.Success
         select validationResult;
  }

  #region Private &amp; Protected Methods

  /// &lt;summary&gt;
  /// Gets the validation attributes attached to a property.
  /// &lt;/summary&gt;
  /// &lt;param name=&quot;property&quot;&gt;The property.&lt;/param&gt;
  /// &lt;returns&gt;An array of validation attributes.&lt;/returns&gt;
  private static ConditionalValidationAttribute[] GetValidations(PropertyInfo property)
  {
    return property.GetCustomAttributes(typeof(ConditionalValidationAttribute), true)
      .Cast&lt;ConditionalValidationAttribute&gt;().ToArray();
  }

  /// &lt;summary&gt;
  /// Gets the value for a property.
  /// &lt;/summary&gt;
  /// &lt;param name=&quot;propertyName&quot;&gt;The property name.&lt;/param&gt;
  /// &lt;returns&gt;The value of the property as an object.&lt;/returns&gt;
  protected object GetPropertyValue(string propertyName)
  {
    try
    {
      return GetType().GetProperty(propertyName).GetValue(this, null);
    }
    catch (TargetInvocationException exception)
    {
      if (exception.InnerException != null)
        throw exception.InnerException;
      throw;
    }
  }

  #endregion
}</code></pre>
<p>Note that when we call the ConditionalValidationAttribute.IsValid method we pass in &#8216;this&#8217; as the context so we have a reference to the object being validated. </p>
<p><b>ConditionalValidationAttribute.cs</b>:</p>
<pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class ConditionalValidationAttribute : Attribute
{
  #region Fields

  private readonly MethodInfo _methodInfo;
  private readonly bool _isSingleArgumentMethod;
  private readonly Type _valuesType;

  #endregion

  #region Properties

  public string ErrorMessage { get; set; }
  public string Method { get; private set; }
  public Type ValidatorType { get; private set; }

  #endregion

  #region Constructor

  /// &lt;summary&gt;
  /// Performs validation by calling a specified static method with one of the following signatures:
  /// ValidationResult Method(object value)
  /// ValidationResult Method(object value, object context)
  /// The value parameter may be strongly typed, if a process passes a value of a different type, type conversion will be attempted.
  /// &lt;/summary&gt;
  /// &lt;param name=&quot;validatorType&quot;&gt;The type that contains the method that performs custom validation.&lt;/param&gt;
  /// &lt;param name=&quot;method&quot;&gt;The method that performs custom validation.&lt;/param&gt;
  public ConditionalValidationAttribute(Type validatorType, string method)
  {
    if (string.IsNullOrEmpty(method))
      throw new ArgumentException(&quot;method&quot;);

    Method = method;
    ValidatorType = validatorType;
    // Find a matching method - if multiple matching methods, pick the one with 2 parameters.
    var methods = from m in validatorType.GetMethods(BindingFlags.Public | BindingFlags.Static)
            let p = m.GetParameters().Length
            where m.Name == method &amp;&amp;
              m.ReturnType == typeof(ValidationResult) &amp;&amp;
              (p == 1 || p == 2)
            orderby p descending
            select m;

    if (methods.Count() == 0)
      throw new InvalidOperationException(string.Format(&quot;No method &#39;{0}&#39; found in class &#39;{1}&#39; with a valid signature.&quot;, method, validatorType));
    _methodInfo = methods.First();
    var parameters = _methodInfo.GetParameters();
    _isSingleArgumentMethod = parameters.Length == 1;
    _valuesType = parameters[0].ParameterType;
  }

  #endregion

  #region Public Methods

  public ValidationResult IsValid(object value, object context)
  {
    object convertedValue;
    var info = _methodInfo;
    if (!TryConvertValue(value, out convertedValue))
    {
      throw new InvalidOperationException(
        string.Format(
          &quot;Unable to convert value from type {0} to type {1}&quot;,
          (value != null) ? value.GetType().ToString() : &quot;null&quot;,
          _valuesType));
    }
    try
    {
      var parameters = _isSingleArgumentMethod ? new[] { convertedValue } : new[] { convertedValue, context };
      var result = (ValidationResult)info.Invoke(null, parameters);
      if (result != ValidationResult.Success &amp;&amp; result.ErrorMessage == null)
        result.ErrorMessage = ErrorMessage;
      return result;
    }
    catch (TargetInvocationException exception)
    {
      if (exception.InnerException != null)
      {
        throw exception.InnerException;
      }
      throw;
    }
  }

  #endregion

  #region Private Methods

  private bool TryConvertValue(object value, out object convertedValue)
  {
    convertedValue = null;
    Type conversionType = _valuesType;
    if (value == null)
    {
      return (!conversionType.IsValueType || (conversionType.IsGenericType &amp;&amp; (conversionType.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;))));
    }
    if (conversionType.IsAssignableFrom(value.GetType()))
    {
      convertedValue = value;
      return true;
    }
    try
    {
      convertedValue = Convert.ChangeType(value, conversionType, CultureInfo.CurrentCulture);
      return true;
    }
    catch (FormatException)
    {
      return false;
    }
    catch (InvalidCastException)
    {
      return false;
    }
    catch (NotSupportedException)
    {
      return false;
    }
  }

  #endregion
}</code></pre>
<p>A few notes here:</p>
<ul>
<li>The constructor tries to find an appropriate method using reflection. If there are multiple overloads of the method then the one with 2 parameters will be chosen.</li>
<li>The first parameter of the validation method can be of any type. Type conversion is attempted on the value to validate to match the method signature. I.e. the first (value) parameter can be object, string, int, etc.</li>
<li>A generic error message can be supplied to the ConditionalValidationAttribute. If the validation method doesn&#8217;t set an error message when it returns a validation error, the ConditionalValidationAttribute.ErrorMessage property will be used.</li>
</ul>
<p>And a sample model <b>User.cs</b>:</p>
<pre><code>public class User : ModelBase
{
  [Required]
  public int UserId { get; set; }
  [Required]
  public string FirstName { get; set; }
  [Required]
  public string LastName { get; set; }
  [Required]
  public string Country { get; set; }
  [Required]
  [ConditionalValidation(typeof(User), &quot;ValidateState&quot;)]
  public string State { get; set; }

  public static ValidationResult ValidateState(string state, object context)
  {
    var user = context as User;
    if (user == null)
      throw new ArgumentException(&quot;context is not of type User&quot;, &quot;context&quot;);

    var australianStates = new[] {&quot;VIC&quot;, &quot;TAS&quot;, &quot;NSW&quot;, &quot;ACT&quot;, &quot;QLD&quot;, &quot;NT&quot;, &quot;WA&quot;, &quot;SA&quot;};
    if (user.Country.Equals(&quot;Australia&quot;, StringComparison.CurrentCultureIgnoreCase))
    {
      if (!australianStates.Contains(state, StringComparer.CurrentCultureIgnoreCase))
        return new ValidationResult(&quot;Not a valid Australian state&quot;, new[] {&quot;State&quot;});
    }
    return ValidationResult.Success;
  }
}</code></pre>
<p>Download the example by clicking the button below.</p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2011/06/ConditionalValidationExample.zip"><img class="alignnone size-full wp-image-126" title="Download the source for this example" src="http://www.phdesign.com.au/wp-content/uploads/2009/11/button_download_source.gif" alt="Download the source for this example" width="149" height="25"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/conditional-validation-in-asp-net-mvc3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using LINQ to list all duplicates</title>
		<link>http://www.phdesign.com.au/programming/using-linq-to-list-all-duplicates/</link>
		<comments>http://www.phdesign.com.au/programming/using-linq-to-list-all-duplicates/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 21:50:43 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=243</guid>
		<description><![CDATA[There&#8217;s plenty of examples on how to find duplicates using LINQ&#8217;s GroupBy method, but usually they use a projection to return a new object, like this: _filteredSubmissions = (from s in _filteredSubmissions group s by s.Email into g where g.Count() &#62; 1 select new { Emails = g.Key, DuplicateCount = g.Count() } Which will just [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s plenty of examples on how to find duplicates using LINQ&#8217;s GroupBy method, but usually they use a projection to return a new object, like this:</p>
<pre><code>_filteredSubmissions = (from s in _filteredSubmissions
                        group s by s.Email
                        into g
                        where g.Count() &gt; 1
                        select new { Emails = g.Key, DuplicateCount = g.Count() }</code></pre>
<p><span id="more-243"></span>Which will just return any email addresses that are duplicates and the count. But what if you want to list all the original items that are duplicates? If you just &#8216;select g&#8217; in the example above you&#8217;ll end up with an IEnumerable&lt;IEnumerable&lt;Submission&gt;&gt;, not what we want. This is where SelectMany() is perfect, it will flatten our collection of a collection back down to a single collection, perfect!</p>
<pre><code>_filteredSubmissions = (from s in _filteredSubmissions
                        group s by s.Email
                        into g
                        where g.Count() &gt; 1
                        select g).SelectMany(g =&gt; g)</code></pre>
<p>So now I want to find Submissions that have the same first and last names, I use an anonymous type.</p>
<pre><code>_filteredSubmissions = (from s in _filteredSubmissions
                        group s by new { s.FirstName, s.LastName }
                        into g
                        where g.Count() &gt; 1
                        select g).SelectMany(g =&gt; g)</code></pre>
<p>And finally I want to find all Submissions that have the same first name and last name OR the same email. Simply use Union(), this will join the two collections and remove any duplicates (that&#8217;s duplicate instances of the classes, not to be confused with the duplicates we&#8217;re trying to find).</p>
<pre><code>_filteredSubmissions = (from s in _filteredSubmissions
                        group s by new { s.FirstName, s.LastName }
                        into g
                        where g.Count() &gt; 1
                        select g).SelectMany(g =&gt; g)
    .Union(
        (from s in _filteredSubmissions
         where !string.IsNullOrWhiteSpace(s.Email)
         group s by s.Email
         into g
         where g.Count() &gt; 1
         select g).SelectMany(g =&gt; g)
    );</code></pre>
<p><code> </code><br />
Note that I also stuck in a check for blank emails, I don&#8217;t consider a Submission the same just because they both have no email address, I didn&#8217;t do this on the FirstName or LastName fields because I know they are mandatory in my system.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/using-linq-to-list-all-duplicates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WPF RadioButton Binding to IsChecked Property</title>
		<link>http://www.phdesign.com.au/programming/wpf-radiobutton-binding-to-ischecked-property/</link>
		<comments>http://www.phdesign.com.au/programming/wpf-radiobutton-binding-to-ischecked-property/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 00:08:30 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=226</guid>
		<description><![CDATA[I wasted a few development hours discovering this strange behaviour when binding to the IsChecked property of a RadioButton in WPF when using MVVM. You can read about the issue on the MSDN forum, but from my experience if you have a two way binding on the is IsChecked property of a RadioButton which is part [...]]]></description>
			<content:encoded><![CDATA[<p>I wasted a few development hours discovering this strange behaviour when binding to the IsChecked property of a RadioButton in WPF when using MVVM. You can <a title="RadioButton unchecked bindings issue still not resolved?" href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8eb8280a-19c4-4502-8260-f74633a9e2f2/">read about the issue on the MSDN forum</a>, but from my experience if you have a two way binding on the is IsChecked property of a RadioButton which is part of a group, then after you set the bound property in code a couple of times, the RadioButton loses it&#8217;s binding all together.<span id="more-226"></span></p>
<p>Here is my original code that kept losing it&#8217;s binding:</p>
<pre><code>&lt;ItemsControl ItemsSource="{Binding Elements}" Margin="0,10,0,10"&gt;
  &lt;ItemsControl.ItemTemplate&gt;
    &lt;DataTemplate&gt;
      &lt;RadioButton Content="{Binding Key}"
        GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.Title}"
        IsChecked="{Binding Path=IsSelected}"
        Margin="0,5,0,5"/&gt;
    &lt;/DataTemplate&gt;
  &lt;/ItemsControl.ItemTemplate&gt;
&lt;/ItemsControl&gt;</code></pre>
<p>There a couple of ways to solve this,</p>
<ol>
<li><a title="Binding IsChecked property of RadioButton in WPF" href="http://pstaev.blogspot.com/2008/10/binding-ischecked-property-of.html">You can subclass the RadioButton</a></li>
<li><a title="Binding IsChecked property of RadioButton in WPF" href="http://pstaev.blogspot.com/2008/10/binding-ischecked-property-of.html"></a>You could use OneWay binding on IsChecked to set the RadioButton state from code, then bind the Command property to a  Command when user clicks on the RadioButton.
<pre><code>&lt;ItemsControl ItemsSource="{Binding Elements}" Margin="0,10,0,10"&gt;
  &lt;ItemsControl.ItemTemplate&gt;
    &lt;DataTemplate&gt;
      &lt;RadioButton Content="{Binding Key}"
        GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.Title}"
        IsChecked="{Binding Path=IsSelected, Mode=OneWay}"
        Command="{Binding IsSelectedCommand}"
        CommandParameter="{Binding}"
        Margin="0,5,0,5"/&gt;
    &lt;/DataTemplate&gt;
  &lt;/ItemsControl.ItemTemplate&gt;
&lt;/ItemsControl&gt;</code></pre>
</li>
<li>My preferred option: (<a title="RadioButton unchecked bindings issue still not resolved?" href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8eb8280a-19c4-4502-8260-f74633a9e2f2/">as suggested by karliwatson</a>) use a ListBox for the grouping and bind the ListBoxItem&#8217;s IsSelected property to your ViewModel, then bind the RadioButton&#8217;s IsChecked property to the list box item&#8217;s IsSelected property. Don&#8217;t set a group on the RadioButton.
<pre><code>&lt;ListBox ItemsSource="{Binding Elements}" Margin="0,10,0,10" BorderThickness="0" Background="Transparent"&gt;
  &lt;ListBox.ItemContainerStyle&gt;
    &lt;Style TargetType="{x:Type ListBoxItem}"&gt;
      &lt;Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" /&gt;
      &lt;Setter Property="Template"&gt;
        &lt;Setter.Value&gt;
          &lt;ControlTemplate TargetType="ListBoxItem"&gt;
            &lt;ContentPresenter/&gt;
          &lt;/ControlTemplate&gt;
        &lt;/Setter.Value&gt;
      &lt;/Setter&gt;
    &lt;/Style&gt;
  &lt;/ListBox.ItemContainerStyle&gt;
  &lt;ListBox.ItemTemplate&gt;
    &lt;DataTemplate&gt;
        &lt;RadioButton Content="{Binding Key}"
            IsChecked="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"
            Margin="0,5,0,5"/&gt;
    &lt;/DataTemplate&gt;
  &lt;/ListBox.ItemTemplate&gt;
&lt;/ListBox&gt;</code></pre>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/wpf-radiobutton-binding-to-ischecked-property/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IE Autocomplete Doesn&#8217;t Fire onchange Event Handler</title>
		<link>http://www.phdesign.com.au/programming/ie-autocomplete-doesnt-fire-onchange-event-handler/</link>
		<comments>http://www.phdesign.com.au/programming/ie-autocomplete-doesnt-fire-onchange-event-handler/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 00:10:24 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=177</guid>
		<description><![CDATA[While testing an ASP validation control in Internet Explorer I found that the validation wasn&#8217;t triggered if I selected an item from the autocomplete list for a text box, this was the same in Safari for Windows, but worked fine in Mozilla Firefox. What?! Turns out that when selecting an item from the autocomplete list [...]]]></description>
			<content:encoded><![CDATA[<p>While testing an ASP validation control in Internet Explorer I found that the validation wasn&#8217;t triggered if I selected an item from the autocomplete list for a text box, this was the same in Safari for Windows, but worked fine in Mozilla Firefox. What?!</p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2010/04/autocomplete.png"><img class="alignnone size-full wp-image-185" title="IE form autocomplete feature" src="http://www.phdesign.com.au/wp-content/uploads/2010/04/autocomplete.png" alt="IE form autocomplete feature" width="152" height="66" /></a></p>
<p><span id="more-177"></span>Turns out that when selecting an item from the autocomplete list the onchange event handler doesn&#8217;t fire, therefore the validation scripts don&#8217;t fire. The onblur event does fire however, meaning we can do a check to see if the data has changed and if so, manually fire the onchange event handler.</p>
<pre><code>/*
Author:     Paul Heasley
Date:       15.04.2010
Version:    0.1
Description:
IE and safari do not trigger the onchange events for textboxes when using autocomplete,
so validation events don't trigger. The blur event does trigger however so this script
checks to see if the value has changed (by saving the value on focus) and manually
calling onchange.
*/
function onChangeFix() {
    var previousValue = [];
    // Get all input elements
    var inputs = document.getElementsByTagName('input');

    for (var i = 0; i &lt; inputs.length; i++) {
        var elt = inputs[i];

        // Only update text boxes. Depending on your application you
        // may also need to fix text areas.
        if (elt.type.toLowerCase() == "text")
        {
            // Save old value.
            addEvent(elt, 'focus', function() {
                previousValue[this] = this.value;
            });

            // Compare to old value, do we need to trigger an onchange event?
            addEvent(elt, 'blur', function() {
                if (previousValue[this] != this.value)
                {
                    if (this.onchange)
                        this.onchange();
                }
            });

            // Set old value = new value to stop the blur event triggering
            // another onchange.
            addEvent(elt, 'change', function() {
                previousValue[this] = this.value;
            });
        }
    }
}</code></pre>
<p>Alternatively, you can disable the autocomplete feature by adding the attrribute autocomplete=&#8221;off&#8221; for either a specific input or for the entire form.</p>
<pre><code>&lt;form id="theForm" name="theForm" method="post" autocomplete="off"&gt;</code></pre>
<p>Download the entire code sample including the addEvent() function.</p>
<p><a title="Download the source" href="http://www.phdesign.com.au/wp-content/uploads/2010/04/autocomplete_fix.js"><img class="alignnone size-full wp-image-126" src="http://www.phdesign.com.au/wp-content/uploads/2009/11/button_download_source.gif" alt="Download the source" width="149" height="25" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/ie-autocomplete-doesnt-fire-onchange-event-handler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No Validation Messages when Disabling &amp; Enabling ASP.Net Validator in Javascript</title>
		<link>http://www.phdesign.com.au/programming/no-validation-messages-when-disabling-enabling-asp-net-validator-in-javascript/</link>
		<comments>http://www.phdesign.com.au/programming/no-validation-messages-when-disabling-enabling-asp-net-validator-in-javascript/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 06:21:31 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[asp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=152</guid>
		<description><![CDATA[Need to validate a form field based on the value of another field in ASP.Net? The .Net Framework provides a javascript function to do just that: ValidatorEnable(val, enable) This function takes the validator control (val) and a boolean to determine whether it should be enable or disabled. The problem with this function is that it [...]]]></description>
			<content:encoded><![CDATA[<p>Need to validate a form field based on the value of another field in ASP.Net? The .Net Framework provides a javascript function to do just that:</p>
<pre><code>ValidatorEnable(val, enable)</code></pre>
<p>This function takes the validator control (val) and a boolean to determine whether it should be enable or disabled. The problem with this function is that it triggers the validator to validate itself immediately, showing any validation error messages before the user has submitted the form, which may not always be want you want.  The alternative is to set the validator&#8217;s enabled property to trigger this validator to validate itself when the user submits the form, and by using the Page_IsValid variable you can test whether the user has triggered a validation or not, then use ValidatorEnable function only after the validation has occurred when the user expects to see validation messages.<span id="more-152"></span></p>
<p>Consider a scenario where you want the user to enter their address only if they select Australia as the country, you also need to validate the address fields. Two ways to approach this are:</p>
<ol>
<li>For each address field you need to validate use a CustomValidator control, and in the ClientValidationFunction first check to see if the country is set to Australia and if it&#8217;s not then consider any response for this control as valid. The problem with this is you will have to recrete all of the validator functionality in your client validation function, which means more work.</li>
<li>Use standard validator controls for the address fields, and enable or disable them in javascript.  The code you call to enable or disable the validators could be a CustomValidation control on the country field, or a standard javascript call when the user selects a country. If the Page_IsValid variable is set to true then assume that the page has just been loaded and no validation has occured, in this case just set the validator controls enabled property so it will be validated (or not) when the user submits the form.<br />
If Page_IsValid is false then assume the user has tried to submit but failed, in this case we expect validation messages to show / hide as the user changes data on the form &#8211; this is the normal ASP.Net behaviour.</li>
</ol>
<p>Here&#8217;s an example:</p>
<pre><code>// The ClientValidationFunction of a custom validator for country
function validateCountry(source, args) {
    // We we haven't submitted the form yet
    if (Page_IsValid) {
        // Turn the postcode validator on / off, but don't validate
        requiredFieldValidatorPostcode.enabled = enable;
    } else {
        // Turn the postcode validator on / off, and immediately validate
        ValidatorEnable(requiredFieldValidatorPostcode, enable);
    }

    // Validate country is not empty
    args.IsValid = (args.Value.length &gt; 0);
}</code></pre>
<p>Don&#8217;t forget to include server side code to mimic this enabling / disabling of validators. To do this override the Validate() function, enable or disable validators depending on the country selected and call the base.Validate() function.</p>
<pre><code>public override void Validate()
{
    // Check if we need to validate the postcode.
    bool requireAddress = (dropDownListCountry.Text == "Australia");
    requiredFieldValidatorPostcode.Enabled = requireAddress;

    // Call the normal validation methods.
    base.Validate();
}

protected void customValidatorCountry_ServerValidate(object source, ServerValidateEventArgs args)
{
    // Implement the server side custom validation for country.
    args.IsValid = (args.Value.Length &gt; 0);
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/no-validation-messages-when-disabling-enabling-asp-net-validator-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting Topfield PVR Recordings</title>
		<link>http://www.phdesign.com.au/general/converting-topfield-pvr-recordings/</link>
		<comments>http://www.phdesign.com.au/general/converting-topfield-pvr-recordings/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 06:21:33 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[ipod]]></category>
		<category><![CDATA[topfield]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=148</guid>
		<description><![CDATA[This weekend I&#8217;ve been having fun moving some recording off the full hard drive of my Topfield Masterpiece and trying to convert them into the formats I want. Below is what I&#8217;ve learnt in the process, this is only going to be useful to those using Windows. Moving data off the PVR If you want [...]]]></description>
			<content:encoded><![CDATA[<p>This weekend I&#8217;ve been having fun moving some recording off the full hard drive of my Topfield Masterpiece and trying to convert them into the formats I want. Below is what I&#8217;ve learnt in the process, this is only going to be useful to those using Windows.<span id="more-148"></span></p>
<h2>Moving data off the PVR</h2>
<p>If you want to use your recordings on devices other than your Toppy, you&#8217;re going to need to get the recordings off it. Fortunately this is the simplest step. For me there were really two options:</p>
<ol>
<li>Use the provided USB link from the Toppy and the official <a title="Topfield tools, Altair USB transfer software." href="http://www.itopfield.com.au/download-utilities.asp?idx=15&amp;tb=">ALTAIR software</a> to download the recordings. For one or two recording this will be fine, although for me it took around 4 hours for a normal sized movie.</li>
<li>Attach the hard drive to your computer use <a title="TopfHD Read-Write to copy data from a Topfield hard drive" href="http://topfield.abock.de/TF5000/tf5000.html">TopfHD Read-Write</a> to copy the recordings over to your PC hard drive.<br />
WARNING! To do this you will need to open your Topfield up to remove the hard drive, in doing so you will void your warrenty. I wouldn&#8217;t recommend doing this unless your Toppy is out of warrenty anyway.<br />
You need to use the TopfHD application to transfer files because Windows won&#8217;t recognise the file format of the Toppy hard drive. Be very careful not let Windows modify the disk in any way.<br />
Transferring about 8 recorded shows and 4 movies took under 30 mins, this takes longer to set up but is well worth it if you&#8217;re trying to move a bit of data.</li>
</ol>
<h2>Watching / Converting the Recordings</h2>
<p>Once you&#8217;ve got the recordings on your PC they will be in Topfield&#8217;s .rec format, which Windows Media nor Quicktime can recognise. My traditional way of converting these files for buring to a DVD went;</p>
<ol>
<li>Use <a title="Project X - DVB demux Tool" href="http://sourceforge.net/projects/project-x/">ProjectX</a> to convert to m2v file</li>
<li>Use TMPGEnc DVD Author to convert to DVD format</li>
<li>Use Nero to burn to DVD.</li>
</ol>
<p>If you just want to watch them on your computer I&#8217;ve got some great news which took me a while to realise: the .rec files can be played directly by the ever useful <a title="VLC Media Player" href="http://www.videolan.org/">VLC Media Player</a>.</p>
<p>If you want to convert them to another format, VLC can help you there too. Use the Media &gt; Convert / Save option to convert it into many different formats. Supposedly it can convert to H264 / mp4 format  compatible with iPods, however I had real problems with this, the video would be distorted or the audio would be way out of sync. So, after playing around for a while, I thought I give it a go converting directly form <a title="Handbrake iPod video conversion" href="http://handbrake.fr/">Handbrake</a> which I do most of my iPod video conversions with&#8230; and this works great!</p>
<p>In summary,</p>
<p><strong>To convert to DVD</strong>: Probably still use ProjectX &gt; TMPGEnc DVD Author &gt; DVD.</p>
<p><strong>To convert to iPod:</strong> Use Handbrake.</p>
<p><strong>To watch or convert to other media formats:</strong> Use VLC Media Player.</p>
<p>Hope this is useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/general/converting-topfield-pvr-recordings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create a PDF using the .Net ReportViewer control</title>
		<link>http://www.phdesign.com.au/programming/create-a-pdf-using-the-net-reportviewer-control/</link>
		<comments>http://www.phdesign.com.au/programming/create-a-pdf-using-the-net-reportviewer-control/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 23:48:48 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[asp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/apps/staging/?p=61</guid>
		<description><![CDATA[Need to generate a pdf programmatically in dot net? You could purchase an HTML to PDF converter and worry about getting the page to format nicely for paper, or you could use the freely available ReportViewer control from Microsoft. Microsoft offers SQL Server Reporting Services (SSRS) with SQL Server 2005 and later editions to generate [...]]]></description>
			<content:encoded><![CDATA[<p>Need to generate a pdf programmatically in dot net? You could purchase an HTML to PDF converter and worry about getting the page to format nicely for paper, or you could use the freely available ReportViewer control from Microsoft.</p>
<p>Microsoft offers SQL Server Reporting Services (SSRS) with SQL Server 2005 and later editions to generate and publish reports using the Report Definition Language (RDL), as an alternative to Crystal Reports. SSRS requires a Report Server to publish reports to so they can be useful, however they also offer a ASP.Net or Windows Forms component called the <a title="ReportViewer Controls on MSDN" href="http://msdn.microsoft.com/en-us/library/ms251671(VS.80).aspx">ReportViewer</a> which we can use in our code without the need for any SQL database to generate reports, and these reports can be saved as Excel files, PDF&#8217;s or images.<span id="more-61"></span></p>
<p>The ReportViewer uses a modified version of RDL called RDLC, which does not save any information about the data source along with the report, which makes it perfect for generating reports from objects that aren&#8217;t a database. For instance, I recently needed to generate PDF letters with custom information in them, so this solution proved perfect.</p>
<p>I&#8217;m going to demonstrate how to pass parameters to an ASP.Net page and return a PDF with that information in it, this could just as easily be done in a Windows Forms project. I&#8217;m using Visual Studio 2005, in my preferred language of c#.</p>
<p>Start by creating a new Web Site in Visual Studio. We are going to use a collection of custom business objects as the data source for our report, so add a new class to our project and call it Person.cs. Copy the following code into your Person.cs file.</p>
<pre><code>using System;
using System.Collections.Generic;

/// &lt;summary&gt;
/// The business object we want to use in our report.
/// &lt;/summary&gt;
public class Person
{
    /// &lt;summary&gt;
    /// Some fields to hold information about this person.
    /// &lt;/summary&gt;
    private string _title;
    private string _firstName;
    private string _lastName;

    /// &lt;summary&gt;
    /// The person properties are only able to be set at instantiation.
    /// After the object is created the properties are read only.
    /// &lt;/summary&gt;
    public string Title
    {
        get { return _title; }
    }

    public string FirstName
    {
        get { return _firstName; }
    }

    public string LastName
    {
        get { return _lastName; }
    }

    /// &lt;summary&gt;
    /// The person constructor.
    /// &lt;/summary&gt;
    /// &lt;param name="title"&gt;The person's title&lt;/param&gt;
    /// &lt;param name="firstName"&gt;Their first name&lt;/param&gt;
    /// &lt;param name="lastname"&gt;Their last name&lt;/param&gt;
    public Person(string title, string firstName, string lastname)
    {
        _title = title;
        _firstName = firstName;
        _lastName = lastname;
    }
}

/// &lt;summary&gt;
/// Creates a data source for our report.
/// &lt;/summary&gt;
public class PersonDataSource
{
    /// &lt;summary&gt;
    /// This method creates a new person object and adds them to a new collection that
    /// can be used as a data source for the report.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;A collection of person objects.&lt;/returns&gt;
    public static List&lt;Person&gt; GetPerson(string title, string firstName, string lastName)
    {
        List&lt;Person&gt; people = new List&lt;Person&gt;();
        people.Add(new Person(title, firstName, lastName));
        return people;
    }
}</code></pre>
<p>Now that we have our business object we can create the report. Click add item on the project and select Report. Call this item Report.rdlc.</p>
<p>In the left hand toolbar you should see <em>Website Data Sources</em> (if not select <em>Data &gt; Show Data Sources</em> from the file menu) and in the data sources you should see our Person object. You can now build a report using the fields from our person object and the tools in the toobox. For simplicity just drag some Textboxes onto the report from the toolbox and enter any static text in them that you want, then drag on the Person&#8217;s title, firstName and lastName and arrange them appropriately.</p>
<p><img class="alignnone size-full wp-image-68" title="ReportViewer business object data source" src="http://www.phdesign.com.au/wp-content/uploads/2009/11/report_viewer_demo_1.jpg" alt="ReportViewer business object data source" width="251" height="126" /></p>
<p>Finally we need to write the code which will create the person data source and generate the report. Before we do this we need a reference to the ReportViewer control, right click on the project and <em>Add Reference</em>, in the .Net tab, select <em>Microsoft.ReportViewer.WebForms</em>.Now copy the following code into the Default.aspx source.</p>
<pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" &gt;
&lt;head runat="server"&gt;
	&lt;title&gt;Untitled Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;form id="form1" runat="server"&gt;
	&lt;div&gt;
	&lt;asp:Label ID="lblTitle" runat="server" Text="Title: "&gt;&lt;/asp:Label&gt;
	&lt;asp:TextBox ID="txtTitle" runat="server"&gt;Mr&lt;/asp:TextBox&gt;&lt;br /&gt;
	&lt;asp:Label ID="lblFirstName" runat="server" Text="First Name: "&gt;&lt;/asp:Label&gt;
	&lt;asp:TextBox ID="txtFirstName" runat="server"&gt;John&lt;/asp:TextBox&gt;&lt;br /&gt;
	&lt;asp:Label ID="lblLastName" runat="server" Text="Last Name: "&gt;&lt;/asp:Label&gt;
	&lt;asp:TextBox ID="txtLastName" runat="server"&gt;Smith&lt;/asp:TextBox&gt;&lt;br /&gt;
	&lt;asp:Button ID="Button1" runat="server" Text="Submit" /&gt;&lt;/div&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>And copy the following into the Code View of Default.aspx (Default.aspx.cs).</p>
<pre><code>using System;
using System.Web;
using Microsoft.Reporting.WebForms;
using System.IO;
using System.Text;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (Page.IsPostBack)
		{
			LocalReport report = new LocalReport();
			string reportName = "CompletionCertificate";
			string deviceInfo =
				"&lt;DeviceInfo&gt;" +
				"  &lt;OutputFormat&gt;EMF&lt;/OutputFormat&gt;" +
				"  &lt;PageWidth&gt;8.5in&lt;/PageWidth&gt;" +
				"  &lt;PageHeight&gt;11in&lt;/PageHeight&gt;" +
				"  &lt;MarginTop&gt;0.25in&lt;/MarginTop&gt;" +
				"  &lt;MarginLeft&gt;0.25in&lt;/MarginLeft&gt;" +
				"  &lt;MarginRight&gt;0.25in&lt;/MarginRight&gt;" +
				"  &lt;MarginBottom&gt;0.25in&lt;/MarginBottom&gt;" +
				"&lt;/DeviceInfo&gt;";
			Warning[] warnings;
			string[] streamids;
			string mimeType;
			string encoding;
			string extension;

			report.ReportPath = "Report.rdlc";
			report.DataSources.Add(new ReportDataSource("Person", PersonDataSource.GetPerson(txtTitle.Text, txtFirstName.Text, txtLastName.Text)));
			byte[] bytes = report.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);

			Response.Clear();
			Response.ContentType = mimeType;
			Response.AddHeader("Content-Disposition", "attachment; filename=" + reportName + "." + extension);
			Response.OutputStream.Write(bytes, 0, bytes.Length);
			Response.End();
		}
	}
}</code></pre>
<p>Now run your project, enter some person data into the form and click submit. Open the PDF file and verify that the report is addressed to your person.</p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2009/11/ReportViewerDemo.zip"><img class="alignnone size-full wp-image-126" title="Download the source for this tutorial" src="http://www.phdesign.com.au/wp-content/uploads/2009/11/button_download_source.gif" alt="Download the source for this tutorial" width="149" height="25" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/create-a-pdf-using-the-net-reportviewer-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

