<?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</title>
	<atom:link href="http://www.phdesign.com.au/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>Fri, 20 Apr 2012 01:38:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>TFS undo checkout of unedited files</title>
		<link>http://www.phdesign.com.au/programming/tfs-undo-checkout-of-unedited-files/</link>
		<comments>http://www.phdesign.com.au/programming/tfs-undo-checkout-of-unedited-files/#comments</comments>
		<pubDate>Thu, 12 Apr 2012 23:09:13 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[tfs]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=298</guid>
		<description><![CDATA[It bugs me when developers check in files to TFS that haven&#8217;t been modified. It&#8217;s easy to do, you open a file, edit it, change your mind and ctrl-z it. Now you have a checked out file with no changes and when you do your next check in you&#8217;ll probably check that file in too, [...]]]></description>
			<content:encoded><![CDATA[<p>It bugs me when developers check in files to TFS that haven&#8217;t been modified. It&#8217;s easy to do, you open a file, edit it, change your mind and ctrl-z it. Now you have a checked out file with no changes and when you do your next check in you&#8217;ll probably check that file in too, unless you&#8217;re really on the ball and compare each file manually first. TFS makes no distinction between checked in files that were modified and those that weren&#8217;t, which makes the job of reviewing code that much harder.<span id="more-298"></span></p>
<p>Now I&#8217;ve found the resolution and it&#8217;s so easy it&#8217;s stupid, just<strong> undo your changes</strong>. That&#8217;s right, go on, right click your solution and select Undo Pending Changes</p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2012/04/tfs-undo-unedited-1.png"><img class="alignnone size-medium wp-image-302" title="Undo Pending Changes" src="http://www.phdesign.com.au/wp-content/uploads/2012/04/tfs-undo-unedited-1-148x300.png" alt="Selecting Undo Pending Changes from the right click menu in Solution Explorer" width="148" height="300" /></a></p>
<p>You&#8217;ll see see the Undo Pending Changes dialog, <strong>make sure you only select edited files</strong> (e.g. uncheck add / delete actions), then go ahead and click Undo Changes.</p>
<p>Now the catch is TFS will go ahead and undo the checkout for any unmodified files, when it hits a modified file it&#8217;ll prompt you with Confirm Undo Checkout, select <strong>No to All</strong>.</p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2012/04/tfs-undo-unedited-2.png"><img class="alignnone size-medium wp-image-301" title="Confirm Undo Changes" src="http://www.phdesign.com.au/wp-content/uploads/2012/04/tfs-undo-unedited-2-300x81.png" alt="Confirm Undo Changes prompt" width="300" height="81" /></a></p>
<p>TFS will continue to undo all unmodified files but leave your modified files alone, now you&#8217;re left with only your modified files checked out. Hooraah.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/tfs-undo-checkout-of-unedited-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create branch of modified working copy in TFS</title>
		<link>http://www.phdesign.com.au/programming/create-branch-of-modified-working-copy-in-tfs/</link>
		<comments>http://www.phdesign.com.au/programming/create-branch-of-modified-working-copy-in-tfs/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 10:30:30 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[tfs]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=292</guid>
		<description><![CDATA[Scenario: You&#8217;ve been working on your code from Team Foundation Server (TFS), made changes then realised you should really have started a branch for it. I couldn&#8217;t find a good tutorial anywhere for doing this so here&#8217;s how I stumbled through it. Create a shelveset of your current working copy File &#62; Source Control &#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Scenario: You&#8217;ve been working on your code from Team Foundation Server (TFS), made changes then realised you should really have started a branch for it.</p>
<p>I couldn&#8217;t find a good tutorial anywhere for doing this so here&#8217;s how I stumbled through it.<span id="more-292"></span></p>
<ol>
<li><strong>Create a shelveset of your current working copy</strong><br />
File &gt; Source Control &gt; Shelve Pending Changes<br />
Uncheck &#8216;Preserve pending changes locally&#8217;. This sill undo all your pending changes.</li>
<li><strong>Create branch</strong><br />
One way to do this is go to the Team Explorer tab &gt; Source Control. Right click on the branch, trunk or root folder and select Branching and Merging &gt; Branch.<br />
In Branch From Version, select By Workspace Version.</li>
<li><strong>Map branch to a working folder</strong><br />
Right click on new branch and select Map to Local Folder.</li>
<li><strong>Unshelve your changes to the new branch</strong><br />
To do this you need TFS Power Tools &#8216;unshelve&#8217;. More info here:<br />
<a href="http://geekswithblogs.net/TarunArora/archive/2011/06/06/unshelve-shelveset-created-from-one-branch-to-another.aspx">http://geekswithblogs.net/TarunArora/archive/2011/06/06/unshelve-shelveset-created-from-one-branch-to-another.aspx</a></li>
</ol>
<p>You can can now check in your changes to the new branch</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/create-branch-of-modified-working-copy-in-tfs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ToolBucket multi-line search plugin for Notepad++</title>
		<link>http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/</link>
		<comments>http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 22:17:24 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[notepad++]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=273</guid>
		<description><![CDATA[ToolBucket is a C# .NET Framework plugin for Notepad++ Features ToolBucket contains the following features: Multi-line search and replace dialog. Change indentation dialog. Generate GUID Generate Lorem Ipsum Compute MD5 Hash Compute SHA1 Hash Base 64 encode Base 64 decode Download The latest version is available here: https://github.com/phdesign/NppToolBucket/downloads Installation Copy the NppToolBucket.dll file to your [...]]]></description>
			<content:encoded><![CDATA[<p>ToolBucket is a C# .NET Framework plugin for Notepad++</p>
<h3>Features</h3>
<p>ToolBucket contains the following features:</p>
<ul>
<li>Multi-line search and replace dialog.</li>
<li>Change indentation dialog.</li>
<li>Generate GUID</li>
<li>Generate Lorem Ipsum</li>
<li>Compute MD5 Hash</li>
<li>Compute SHA1 Hash</li>
<li>Base 64 encode</li>
<li>Base 64 decode</li>
</ul>
<h3>Download</h3>
<p>The latest version is available here:<br />
<a href="https://github.com/phdesign/NppToolBucket/downloads">https://github.com/phdesign/NppToolBucket/downloads</a></p>
<h3>Installation</h3>
<p>Copy the NppToolBucket.dll file to your Notepad++\plugins directory.</p>
<h3>Dependencies</h3>
<p>Requires .NET Framework 2.0 or higher to be installed on the system.</p>
<h3>Screenshots</h3>

<a href='http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/attachment/toolbucket1/' title='ToolBucket: Menu Options'><img width="150" height="121" src="http://www.phdesign.com.au/wp-content/uploads/2012/01/ToolBucket1.png" class="attachment-thumbnail" alt="ToolBucket: Menu Options" title="ToolBucket: Menu Options" /></a>
<a href='http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/attachment/toolbucket2/' title='ToolBucket: Indentation Settings'><img width="150" height="80" src="http://www.phdesign.com.au/wp-content/uploads/2012/01/ToolBucket2.png" class="attachment-thumbnail" alt="ToolBucket: Indentation Settings" title="ToolBucket: Indentation Settings" /></a>
<a href='http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/attachment/toolbucket3/' title='ToolBucket: Multi-line Search and Replace'><img width="150" height="71" src="http://www.phdesign.com.au/wp-content/uploads/2012/01/ToolBucket3.png" class="attachment-thumbnail" alt="ToolBucket: Multi-line Search and Replace" title="ToolBucket: Multi-line Search and Replace" /></a>

]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/toolbucket-multi-line-search-plugin-for-notepad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>Unindent in Expression Blend</title>
		<link>http://www.phdesign.com.au/programming/unindent-in-expression-blend/</link>
		<comments>http://www.phdesign.com.au/programming/unindent-in-expression-blend/#comments</comments>
		<pubDate>Mon, 14 Feb 2011 00:29:43 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[blend]]></category>
		<category><![CDATA[wpf]]></category>
		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=236</guid>
		<description><![CDATA[Unindenting in Expression Blend drove me mad, I just couldn&#8217;t get it to work. Today I figured out why. The code I am copying from Visual Studio uses spaces for indentation, in Blend I was using tabs, this means when I paste code from VS, Blend doesn&#8217;t see any tabs to &#8216;unindent&#8217;. Simple solution &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>Unindenting in Expression Blend drove me mad, I just couldn&#8217;t get it to work. Today I figured out why.</p>
<p>The code I am copying from Visual Studio uses spaces for indentation, in Blend I was using tabs, this means when I paste code from VS, Blend doesn&#8217;t see any tabs to &#8216;unindent&#8217;.</p>
<p>Simple solution &#8211; make sure your Visual Studio indentation settings match your Blend settings.<span id="more-236"></span></p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2011/02/blend-indent-settings.png"><img class="alignnone size-medium wp-image-237" title="blend-indent-settings" src="http://www.phdesign.com.au/wp-content/uploads/2011/02/blend-indent-settings-300x281.png" alt="Expression Blend indent settings" width="300" height="281" /></a></p>
<p><a href="http://www.phdesign.com.au/wp-content/uploads/2011/02/blend-indent-settings.png"></a><a href="http://www.phdesign.com.au/wp-content/uploads/2011/02/vs-indent-settings.png"><img class="alignnone size-medium wp-image-238" title="vs-indent-settings" src="http://www.phdesign.com.au/wp-content/uploads/2011/02/vs-indent-settings-300x177.png" alt="Visual Studio indent settings" width="300" height="177" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/unindent-in-expression-blend/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>Logging Messages in Dot Net</title>
		<link>http://www.phdesign.com.au/programming/logging-messages-in-dot-net/</link>
		<comments>http://www.phdesign.com.au/programming/logging-messages-in-dot-net/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:39:15 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=215</guid>
		<description><![CDATA[The .Net Framework provides an easy way to log messages using the System.Diagnostics.Trace class. By using Trace the user can configure where and what to log in the config file. Below are two simple ways to log a message to a text file. 1. The simplest way if you don&#8217;t care about the format of [...]]]></description>
			<content:encoded><![CDATA[<p>The .Net Framework provides an easy way to log messages using the System.Diagnostics.Trace class. By using Trace the user can configure where and what to log in the config file.</p>
<p>Below are two simple ways to log a message to a text file.<span id="more-215"></span></p>
<p>1. The simplest way if you don&#8217;t care about the format of the message is to use a filter on the trace listener in app.config to determine which events to log.</p>
<pre><code>&lt;system.diagnostics&gt;
  &lt;trace autoflush="true"&gt;
    &lt;listeners&gt;
      &lt;add name="LogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log" traceOutputOptions="DateTime"&gt;
        &lt;!--
        EventTypes:
        Critical: Fatal error or application crash.
        Error: Recoverable error.
        Warning: Noncritical problem.
        Information: Informational message.
        Verbose: Debugging trace.
        Start: Starting of a logical operation.
        Stop: Stopping of a logical operation.
        Suspend: Suspension of a logical operation.
        Resume: Resumption of a logical operation.
        Transfer: Changing of correlation identity.
        --&gt;
        &lt;filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"/&gt;
      &lt;/add&gt;
    &lt;/listeners&gt;
  &lt;/trace&gt;
&lt;/system.diagnostics&gt;</code></pre>
<p>Then you only need to call one of the following methods to log a message with a specific EventType.</p>
<pre><code>System.Diagnostics.Trace.TraceInformation("Information messge");
System.Diagnostics.Trace.TraceError("Error messge");</code></pre>
<p>2. If you want more control over the format of the message you can use a TraceSwitch in app.config:</p>
<pre><code>&lt;system.diagnostics&gt;
  &lt;switches&gt;
    &lt;clear/&gt;
    &lt;!--
    Trace Levels:
    Off: 0: None
    Error: 1: Only error messages
    Warning: 2: Warning messages and error messages
    Info: 3: Informational messages, warning messages, and error messages
    Verbose: 4: Verbose messages, informational messages, warning messages, and error messages
    --&gt;
    &lt;add name="LogLevel" value="Info"/&gt;
  &lt;/switches&gt;
  &lt;trace autoflush="true"&gt;
    &lt;listeners&gt;
      &lt;add name="LogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/&gt;
    &lt;/listeners&gt;
  &lt;/trace&gt;
&lt;/system.diagnostics&gt;</code></pre>
<p>Then retrieve the TraceSwitch in code as follows:</p>
<pre><code>TraceSwitch logLevel = new TraceSwitch("LogLevel", "The logging level");
Trace.WriteLineIf(logLevel.Level &gt;= level, string.Format("[{0}] [{1}]: {2}", DateTime.Now, level, message));</code></pre>
<p>The examples are for a desktop application, but they would work equally well in a web application by configuring web.config. Note that web applications aren&#8217;t compiled with Trace enabled, so you need to enable them in web.config by using the following after the &lt;system.diagnostics&gt; node:</p>
<pre><code>&lt;system.codedom&gt;
  &lt;compilers&gt;
    &lt;compiler language="c#;cs;csharp"
      extension=".cs"
      compilerOptions="/d:TRACE"
      type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="1" /&gt;
    &lt;/compilers&gt;
&lt;/system.codedom&gt;</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/programming/logging-messages-in-dot-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>phreplace Goes Open Source</title>
		<link>http://www.phdesign.com.au/general/phreplace-goes-open-source/</link>
		<comments>http://www.phdesign.com.au/general/phreplace-goes-open-source/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 08:09:48 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[phreplace]]></category>

		<guid isPermaLink="false">http://www.phdesign.com.au/?p=193</guid>
		<description><![CDATA[I&#8217;ve decided to release phreplace as open source software in order to continue it&#8217;s development, I no longer have the time to give it the attention it deserves. The VB6 source code will be released under the GNU Lesser General Public License (LGPL), in my understanding this means that anyone can use phreplace and even [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve decided to release phreplace as open source software in order to continue it&#8217;s development, I no longer have the time to give it the attention it deserves.</p>
<p>The VB6 source code will be released under the GNU Lesser General Public License (LGPL), in my understanding this means that anyone can use phreplace and even include the library in a greater works (e.g. PSPad), however if they modify the code it must be released under a similar open source library, in order that everyone will benefit from the changes.</p>
<p>The source code is available at <a title="phreplace source code available at Assembla" href="https://www.assembla.com/spaces/phreplace/documents">Assembla</a>, feel free to send any code changes to me to be included in the project.<span id="more-193"></span></p>
<h3>Architecture</h3>
<p>I rewrote phreplace in early 2009 when I was studying design patterns and as such the VB6 source code is heavily object-oriented and pattern focused. VB6 is not strictly an oo language but it does support inheritance through the &#8216;Implements&#8217; keyword.</p>
<p>phreplace uses the iterator, observer and factory methods. I found some of the sample chapters of <em>Visual Basic design patterns: VB 6.0 and VB.NET</em> By James William Cooper on <a title="Visual Basic design patterns: VB 6.0 and VB.NET By James William Cooper" href="http://books.google.com.au/books?id=TLhvRJTKDssC&amp;lpg=PP1&amp;pg=PP1#v=onepage&amp;q&amp;f=false">Google Books</a> a very useful resource.</p>
<p>This early <a href="http://www.phdesign.com.au/wp-content/uploads/2010/06/phreplace-architecture.pdf">class architecture diagram (PDF)</a> may help decipher some of the code design.</p>
<h3>Future Direction</h3>
<p>phreplace was designed to be application agnostic, it currently works only with PSPad but I hoped that by implementing only a few interfaces (IHostAdapter, IDocument and IDocumentCollection) it could work with any other editor that supported the basic operations required. My next intended editor to support was SciTE.</p>
<p>The first major change that I would like to see is support for Vista / Windows 7. At present the phreplace.vbs script intialises the application by checking to see if the phreplace.dll library is registered, if it isn&#8217;t it tries to register it with regsvr32. This works for Windows XP but standard users aren&#8217;t able to register libraries in Vista / Windows 7. So far I have come up with 3 solutions.</p>
<ol>
<li>Override DllRegisterServer using <a title="Classic VB Tools: vbAdvance" href="http://vb.mvps.org/tools/vbAdvance/">vbAdvance</a>. I can&#8217;t get this library to work. See <a href="http://www.phdesign.com.au/programming/registering-phreplace-dll-in-windows-vista/" title="Registering phreplace DLL in Windows Vista">Registering phreplace DLL in Windows Vista</a>.</li>
<li>Create a separate utility similar to regsvr32 and include this with phreplace. I think this is messy. Again see <a href="http://www.phdesign.com.au/programming/registering-phreplace-dll-in-windows-vista/" title="Registering phreplace DLL in Windows Vista">Registering phreplace DLL in Windows Vista</a>.</li>
<li>Use the <a title="Registration-Free COM" href="http://msdn.microsoft.com/en-us/library/ms973913.aspx">Registration-Free COM</a> solution of adding a manifest file for PSPad which references the phreplace.dll library so that we don&#8217;t have to register it in the registry at all. This solution works for XP, see the <a title="reg-free-com branch of phreplace source code." href="https://www.assembla.com/code/phreplace/subversion/nodes/branches/reg-free-com?rev=5">reg-free-com branch of the source code</a>, but doesn&#8217;t seem to work for Vista. My theory is that perhaps Vista handles vbscript differently, so it doesn&#8217;t inherit the PSPad manifest. If someone could get this working I think this is the most elegant solution.</li>
</ol>
<p>I look forward to seeing user contributions to this project.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phdesign.com.au/general/phreplace-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

