Thursday, January 29, 2009

How to: Define Value Equality for a Type (C# Programming)

When you define a class or struct, you
decide whether it makes sense to create a custom definition of value
equality (or equivalence) for the type. Typically, you implement value
equality when objects of the type are expected to be added to a
collection of some sort, or when their primary purpose is to store a
set of fields or properties. You can base your definition of value
equality on a comparison of all the fields and properties in the type,
or you can base the definition on a subset. But in either case, and in
both classes and structs, your implementation should follow the five
guarantees of equivalence:


  1. x.Equals(x) returns true. This is called the reflexive property.


  2. x.Equals(y) returns the same value as y.Equals(x). This is called the symmetric property.


  3. if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true. This is called the transitive property.


  4. Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.


  5. x.Equals(null) returns false. However, null.Equals(null) throws an exception; it does not obey rule number two above.


Any struct that you define already has a default implementation of value equality that it inherits from the System..::.ValueType override of the Object..::.Equals(Object)
method. This implementation uses reflection to examine all the public
and non-public fields and properties in the type. Although this
implementation produces correct results, it is relatively slow compared
to a custom implementation that you write specifically for the type.

The implementation details for value equality
are different for classes and structs. However, both classes and
structs require the same basic steps for implementing equality:


  1. Override the virtual Object..::.Equals(Object) method. In most cases, your implementation of bool Equals( object obj ) should just call into the type-specific Equals method that is the implementation of the System..::.IEquatable<(Of <(T>)>) interface. (See step 2.)


  2. Implement the System..::.IEquatable<(Of <(T>)>) interface by providing a type-specific Equals
    method. This is where the actual equivalence comparison is performed.
    For example, you might decide to define equality by comparing only one
    or two fields in your type. Do not throw exceptions from Equals. For classes only: This method should examine only fields that are declared in the class. It should call base.Equals to examine fields that are in the base class. (Do not do this if the type inherits directly from Object, because the Object implementation of Object..::.Equals(Object) performs a reference equality check.)


  3. Optional but recommended: Overload the == and != operators.


  4. Override Object..::.GetHashCode so that two objects that have value equality produce the same hash code.


  5. Optional: To support definitions for "greater than" or "less than," implement the IComparable<(Of <(T>)>) interface for your type, and also overload the <= and >= operators.


The first example that follows shows a class implementation. The second
example shows a struct implementation.




The following example shows how to implement value equality in a class (reference type).

<span style="color: blue;">namespace</span> ValueEquality<br />{<br />    <span style="color: blue;">using</span> System;<br />    <span style="color: blue;">class</span> TwoDPoint : IEquatable<TwoDPoint><br />    {<br />        <span style="color: green;">// Readonly auto-implemented properties.</span><br />        <span style="color: blue;">public</span> <span style="color: blue;">int</span> X { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br />        <span style="color: blue;">public</span> <span style="color: blue;">int</span> Y { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br /><br />        <span style="color: green;">// Set the properties in the constructor.</span><br />        <span style="color: blue;">public</span> TwoDPoint(<span style="color: blue;">int</span> x, <span style="color: blue;">int</span> y)<br />        {<br />            <span style="color: blue;">if</span> ((x < 1) || (x > 2000) || (y < 1) || (y > 2000))<br />                throw <span style="color: blue;">new</span> System.ArgumentException(<span style="color: maroon;"><span style="color: maroon;">"Point must be in range 1 - 2000"</span></span>);<br />            <span style="color: blue;">this</span>.X = x;<br />            <span style="color: blue;">this</span>.Y = y;<br />        }<br /><br />        <span style="color: blue;">public</span> override <span style="color: blue;">bool</span> Equals(object obj)<br />        {<br />            <span style="color: blue;">return</span> <span style="color: blue;">this</span>.Equals(obj as TwoDPoint);<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">bool</span> Equals(TwoDPoint p)<br />        {<br />            <span style="color: green;">// If parameter is null, return false.</span><br />            <span style="color: blue;">if</span> (Object.ReferenceEquals(p, <span style="color: blue;">null</span>))<br />            {<br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br />            }<br /><br />            <span style="color: green;">// Optimization for a common success case.</span><br />            <span style="color: blue;">if</span> (Object.ReferenceEquals(<span style="color: blue;">this</span>, p))<br />            {<br />                <span style="color: blue;">return</span> <span style="color: blue;">true</span>;<br />            }<br /><br />            <span style="color: green;">// If run-time types are not exactly the same, return false.</span><br />            <span style="color: blue;">if</span> (<span style="color: blue;">this</span>.GetType() != p.GetType())<br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br /><br />            <span style="color: green;">// Return true if the fields match.</span><br />            <span style="color: green;">// Note that the base class is not invoked because it is</span><br />            <span style="color: green;">// System.Object, which defines Equals as reference equality.</span><br />            <span style="color: blue;">return</span> (X == p.X) && (Y == p.Y);<br />        }<br /><br />        <span style="color: blue;">public</span> override <span style="color: blue;">int</span> GetHashCode()<br />        {<br />            <span style="color: blue;">return</span> X * 0x00010000 + Y;<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator ==(TwoDPoint lhs, TwoDPoint rhs)<br />        {<br />            <span style="color: green;">// Check for null on left side.</span><br />            <span style="color: blue;">if</span> (Object.ReferenceEquals(lhs, <span style="color: blue;">null</span>))<br />            {<br />                <span style="color: blue;">if</span> (Object.ReferenceEquals(rhs, <span style="color: blue;">null</span>))<br />                {<br />                    <span style="color: green;">// null == null = true.</span><br />                    <span style="color: blue;">return</span> <span style="color: blue;">true</span>;<br />                }<br /><br />                <span style="color: green;">// Only the left side is null.</span><br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br />            }<br />            <span style="color: green;">// Equals handles case of null on right side.</span><br />            <span style="color: blue;">return</span> lhs.Equals(rhs);<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator !=(TwoDPoint lhs, TwoDPoint rhs)<br />        {<br />            <span style="color: blue;">return</span> !(lhs == rhs);<br />        }<br />    }<br /><br />    <span style="color: green;">// For the sake of simplicity, assume a ThreeDPoint IS a TwoDPoint.</span><br />    <span style="color: blue;">class</span> ThreeDPoint : TwoDPoint, IEquatable<ThreeDPoint><br />    {<br />        <span style="color: blue;">public</span> <span style="color: blue;">int</span> Z { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br /><br />        <span style="color: blue;">public</span> ThreeDPoint(<span style="color: blue;">int</span> x, <span style="color: blue;">int</span> y, <span style="color: blue;">int</span> z)<br />            : <span style="color: blue;">base</span>(x, y)<br />        {<br />            <span style="color: blue;">if</span> ((z < 1) || (z > 2000))<br />                throw <span style="color: blue;">new</span> System.ArgumentException(<span style="color: maroon;"><span style="color: maroon;">"Point must be in range 1 - 2000"</span></span>);<br />            <span style="color: blue;">this</span>.Z = z;<br />        }<br /><br />        <span style="color: blue;">public</span> override <span style="color: blue;">bool</span> Equals(object obj)<br />        {<br />            <span style="color: blue;">return</span> <span style="color: blue;">this</span>.Equals(obj as ThreeDPoint);<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">bool</span> Equals(ThreeDPoint p)<br />        {<br />            <span style="color: green;">// If parameter is null, return false.</span><br />            <span style="color: blue;">if</span> (Object.ReferenceEquals(p, <span style="color: blue;">null</span>))<br />            {<br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br />            }<br /><br />            <span style="color: green;">// Optimization for a common success case.</span><br />            <span style="color: blue;">if</span>(Object.ReferenceEquals(<span style="color: blue;">this</span>, p))<br />            {<br />                <span style="color: blue;">return</span> <span style="color: blue;">true</span>;<br />            }<br /><br />            <span style="color: green;">// Check properties that this class declares.</span><br />            <span style="color: blue;">if</span> (Z == p.Z)<br />            {<br />                <span style="color: green;">// Let base class check its own fields </span><br />                <span style="color: green;">// and do the run-time type comparison.</span><br />                <span style="color: blue;">return</span> <span style="color: blue;">base</span>.Equals((TwoDPoint)p);<br />            }<br />            <span style="color: blue;">else</span><br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br />        }<br /><br />        <span style="color: blue;">public</span> override <span style="color: blue;">int</span> GetHashCode()<br />        {<br />            <span style="color: blue;">return</span> (X * 0x100000) + (Y * 0x1000) + Z;<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator ==(ThreeDPoint lhs, ThreeDPoint rhs)<br />        {<br />            <span style="color: green;">// Check for null.</span><br />            <span style="color: blue;">if</span> (Object.ReferenceEquals(lhs, <span style="color: blue;">null</span>))<br />            {<br />                <span style="color: blue;">if</span> (Object.ReferenceEquals(lhs, <span style="color: blue;">null</span>))<br />                {<br />                    <span style="color: green;">// null == null = true.</span><br />                    <span style="color: blue;">return</span> <span style="color: blue;">true</span>;<br />                }<br /><br />                <span style="color: green;">// Only the left side is null.</span><br />                <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br />            }<br />            <span style="color: green;">// Equals handles the case of null on right side.</span><br />            <span style="color: blue;">return</span> lhs.Equals(rhs);<br />        }<br /><br />        <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator !=(ThreeDPoint lhs, ThreeDPoint rhs)<br />        {<br />            <span style="color: blue;">return</span> !(lhs == rhs);<br />        }<br />    }<br /><br />    <span style="color: blue;">class</span> Program<br />    {<br />        <span style="color: blue;">static</span> <span style="color: blue;">void</span> Main(<span style="color: blue;">string</span>[] args)<br />        {<br />            ThreeDPoint pointA = <span style="color: blue;">new</span> ThreeDPoint(3, 4, 5);<br />            ThreeDPoint pointB = <span style="color: blue;">new</span> ThreeDPoint(3, 4, 5);<br />            ThreeDPoint pointC = <span style="color: blue;">null</span>;<br />            <span style="color: blue;">int</span> i = 5;<br /><br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA.Equals(pointB) = {0}"</span></span>, pointA.Equals(pointB));<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA == pointB = {0}"</span></span>, pointA == pointB);<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"null comparison = {0}"</span></span>, pointA.Equals(pointC));<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"Compare to some other type = {0}"</span></span>, pointA.Equals(i));<br /><br />            TwoDPoint pointD = <span style="color: blue;">null</span>;<br />            TwoDPoint pointE = <span style="color: blue;">null</span>;<br /><br /><br /><br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"Two null TwoDPoints are equal: {0}"</span></span>, pointD == pointE);<br /><br />            pointE = <span style="color: blue;">new</span> TwoDPoint(3, 4);<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"(pointE == pointA) = {0}"</span></span>, pointE == pointA);<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"(pointA == pointE) = {0}"</span></span>, pointA == pointE);<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"(pointA != pointE) = {0}"</span></span>, pointA != pointE);<br /><br />            System.Collections.ArrayList list = <span style="color: blue;">new</span> System.Collections.ArrayList();<br />            list.Add(<span style="color: blue;">new</span> ThreeDPoint(3, 4, 5));<br />            Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointE.Equals(list[0]): {0}"</span></span>, pointE.Equals(list[0]));<br /><br />            <span style="color: green;">// Keep the console window open in debug mode.</span><br />            System.Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"Press any key to exit."</span></span>);<br />            System.Console.ReadKey();<br />        }<br />    }<br /><br />    <span style="color: green;">/* Output:<br />        pointA.Equals(pointB) = True<br />        pointA == pointB = True<br />        <span style="color: blue;">null</span> comparison = False<br />        Compare to some other type = False<br />        Two <span style="color: blue;">null</span> TwoDPoints are equal: True<br />        (pointE == pointA) = False<br />        (pointA == pointE) = False<br />        (pointA != pointE) = True<br />        pointE.Equals(list[0]): False<br />    */</span><br />}<br /><br /><br /></pre></div></div></div><p>
On classes (reference types), the default implementation of both <span><a id="ctl00_rs1_mainContentContainer_ctl42" onclick="javascript:Track('ctl00_rs1_mainContentContainer_cpe198786_c|ctl00_rs1_mainContentContainer_ctl42',this);" href="http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx">Object<span class="cs">.</span><span class="vb">.</span><span class="cpp">::</span><span class="nu">.</span>Equals(Object)</a></span>
methods performs a reference equality comparison, not a value equality
check. When an implementer overrides the virtual method, the purpose is
to give it value equality semantics. </p><p>
The <span><span class="input">==</span></span> and <span><span class="input">!=</span></span>
operators can be used with classes even if the class does not overload
them. However, the default behavior is to perform a reference equality
check. In a class, if you overload the <span><span class="input">Equals</span></span> method, you should overload the <span><span class="input">==</span></span> and <span><span class="input">!=</span></span> operators, but it is not required.
</p><p>
The following example shows how to implement value equality in a struct (value type):
</p><div id="snippetGroup1"><div class="libCScode" id="ctl00_rs1_mainContentContainer_ctl44_CSharp"><div class="CodeSnippetTitleBar"><div class="CodeDisplayLanguage">C#</div><div class="CopyCodeButton"><a class="copyCode" title="Copy Code" href="javascript:CopyCode('ctl00_rs1_mainContentContainer_ctl44CSharp');"><img class="LibC_copy_off" src="http://i.msdn.microsoft.com/Global/Images/clear.gif" align="middle" border="0" height="9" /> Copy Code</a></div></div><div dir="ltr"><pre class="libCScode" style="white-space: pre-wrap;" id="ctl00_rs1_mainContentContainer_ctl44CSharp" space="preserve"> struct TwoDPoint : IEquatable<TwoDPoint><br /> {<br /> <span style="color: green;">// Read/write auto-implemented properties.</span><br /> <span style="color: blue;">public</span> <span style="color: blue;">int</span> X { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br /> <span style="color: blue;">public</span> <span style="color: blue;">int</span> Y { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }<br /><br /> <span style="color: blue;">public</span> TwoDPoint(<span style="color: blue;">int</span> x, <span style="color: blue;">int</span> y) : <span style="color: blue;">this</span>()<br /> {<br /> X = x;<br /> Y = x;<br /> }<br /><br /> <span style="color: blue;">public</span> override <span style="color: blue;">bool</span> Equals(object obj)<br /> {<br /> <span style="color: blue;">if</span> (obj is TwoDPoint)<br /> {<br /> <span style="color: blue;">return</span> <span style="color: blue;">this</span>.Equals((TwoDPoint)obj);<br /> }<br /> <span style="color: blue;">return</span> <span style="color: blue;">false</span>;<br /> }<br /><br /> <span style="color: blue;">public</span> <span style="color: blue;">bool</span> Equals(TwoDPoint p)<br /> {<br /> <span style="color: blue;">return</span> (X == p.X) && (Y == p.Y);<br /> }<br /><br /> <span style="color: blue;">public</span> override <span style="color: blue;">int</span> GetHashCode()<br /> {<br /> <span style="color: blue;">return</span> X ^ Y;<br /> }<br /><br /> <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator ==(TwoDPoint lhs, TwoDPoint rhs)<br /> {<br /> <span style="color: blue;">return</span> lhs.Equals(rhs);<br /> }<br /><br /> <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">bool</span> operator !=(TwoDPoint lhs, TwoDPoint rhs)<br /> {<br /> <span style="color: blue;">return</span> !(lhs.Equals(rhs));<br /> }<br /> }<br /><br /><br /> <span style="color: blue;">class</span> Program<br /> {<br /> <span style="color: blue;">static</span> <span style="color: blue;">void</span> Main(<span style="color: blue;">string</span>[] args)<br /> {<br /> TwoDPoint pointA = <span style="color: blue;">new</span> TwoDPoint(3,4);<br /> TwoDPoint pointB = <span style="color: blue;">new</span> TwoDPoint(3,4);<br /> <span style="color: blue;">int</span> i = 5;<br /><br /> <span style="color: green;">// Compare using virtual Equals, static Equals, and == and != operators.</span><br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA.Equals(pointB) = {0}"</span></span>, pointA.Equals(pointB));<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA == pointB = {0}"</span></span>, pointA == pointB);<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"Object.Equals(pointA, pointB) = {0}"</span></span>, Object.Equals(pointA, pointB)); <br /> <span style="color: green;">// False:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA.Equals(null) = {0}"</span></span>, pointA.Equals(<span style="color: blue;">null</span>));<br /> <span style="color: green;">// False:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"(pointA == null) = {0}"</span></span>, pointA == <span style="color: blue;">null</span>);<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"(pointA != null) = {0}"</span></span>, pointA != <span style="color: blue;">null</span>);<br /> <span style="color: green;">// False:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA.Equals(i) = {0}"</span></span>, pointA.Equals(i)); <br /> <span style="color: green;">// CS0019:</span><br /> <span style="color: green;">// Console.WriteLine("pointA == i = {0}", pointA == i); </span><br /><br /> <span style="color: green;">// Compare unboxed to boxed.</span><br /> System.Collections.ArrayList list = <span style="color: blue;">new</span> System.Collections.ArrayList();<br /> list.Add(<span style="color: blue;">new</span> TwoDPoint(3,4));<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointE.Equals(list[0]): {0}"</span></span>, pointA.Equals(list[0])); <br /><br /><br /> <span style="color: green;">// Compare nullable to nullable and to non-nullable.</span><br /> TwoDPoint? pointC = <span style="color: blue;">null</span>;<br /> TwoDPoint? pointD = <span style="color: blue;">null</span>;<br /> <span style="color: green;">// False:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA == (pointC = null) = {0}"</span></span>, pointA == pointC);<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointC == pointD = {0}"</span></span>, pointC == pointD); <br /><br /> TwoDPoint temp = <span style="color: blue;">new</span> TwoDPoint(3,4);<br /> pointC = temp;<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointA == (pointC = 3,4) = {0}"</span></span>, pointA == pointC); <br /><br /> pointD = temp;<br /> <span style="color: green;">// True:</span><br /> Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"pointD == (pointC = 3,4) = {0}"</span></span>, pointD == pointC); <br /><br /> <span style="color: green;">// Keep the console window open in debug mode.</span><br /> System.Console.WriteLine(<span style="color: maroon;"><span style="color: maroon;">"Press any key to exit."</span></span>);<br /> System.Console.ReadKey();<br /> }<br /> }<br /><br /> <span style="color: green;">/* Output:<br /> pointA.Equals(pointB) = True<br /> pointA == pointB = True<br /> Object.Equals(pointA, pointB) = True<br /> pointA.Equals(<span style="color: blue;">null</span>) = False<br /> (pointA == <span style="color: blue;">null</span>) = False<br /> (pointA != <span style="color: blue;">null</span>) = True<br /> pointA.Equals(i) = False<br /> pointE.Equals(list[0]): True<br /> pointA == (pointC = <span style="color: blue;">null</span>) = False<br /> pointC == pointD = True<br /> pointA == (pointC = 3,4) = True<br /> pointD == (pointC = 3,4) = True<br /> */</span><br />}<br /><br />


For structs, the default implementation of Object..::.Equals(Object) (which is the overridden version in System..::.ValueType)
performs a value equality check by using reflection to compare the
values of every field in the type. When an implementer overrides the
virtual Equals method in a
stuct, the purpose is to provide a more efficient means of performing
the value equality check and optionally to base the comparison on some
subset of the struct's field or properties.


The == and != operators cannot operate on a struct unless the struct explicitly overloads them.



Wednesday, January 21, 2009

Restart Firefox - A Great extension to use while developing Firefox Extensions

While developing Firefox extensions you need to restart Firefox endlessly. Use this cool extension to do it from the File menu or Toolbar.

Get Quick Restart.

Long Description


This simple extension adds a "Restart
Firefox" item to the "File" menu. You can also use the Ctrl+Alt+R
keyboard shortcut, or the included toolbar button.



To use the toolbar button: right click on toolbar -> Customize... then drag the Restart button to the toolbar.

Yes, very long...

Reviews






  • A necessary tool for developers testing a bunch of pages that may draw infinite looping errors.








    by Angie Schottmuller on January 16, 2009





  • It
    would've received 5 stars from me if not for the ugly icon that totally
    messes up the file menu. No other options on the file menu has icons,
    so it doesn't look right, especially with such an ugly icon.








    by Oddish on January 2, 2009





  • This
    is a great extension. FF has many options and settings, when
    configuring your setup, it is necessary to constantly restart the
    browser to test the changes. This extension performs the session
    restore and puts you right back where you were. Awesome!








    by wittmeba on December 18, 2008


Tell me if it works for you.

Thursday, January 15, 2009

Digg removed links to upcoming pages. Bug or Feature?

I believe it was the last version that rolled out on December that first had this bug/feature. The upcoming pages of the specific categories does not have the once-were-links to "Most dugg" and "Most comments" pages of the specific category. Instead, if you click those buttons you get the "most" and "commented" pages of the "All topics" category.

I would consider that a (poor) feature, unless the URLs of those links look like there is something broken. They are as they were, except that the category name is missing from them.



The "Programming" category link to upcoming stories with most diggs was once http://digg.com/all/programming/upcoming/most and is now http://digg.com/all//upcoming/most , like someone dropped the pen in the middle of the sentence. The first link still works, and shows the most dugg stories in programming, but it's not linked from the site anymore.

Does anyone knows if this is a bug or a feature? Did you hear or read anything about it? Is this meant to reduce the power of power users? Is another programmer about to lose his job?

How to resize the Firefox window with a bookmarklet

Many developers work on large screens, but want to Preview web design in a 1024×768 browser screen.
To resize the Firefox browser window to 1024 x 768 create a resizing bookmarklet.

Creating a Resizing Bookmarklet


Step 1


Right click on Bookmark Toolbar -> New Bookmark to launch the Bookmark dialog box.



Step 2


Insert the following into the box:


  • Name: Give a descriptive name if you are planning to add several bookmarklet.
  • Location: Place javascript:window.resizeTo(1024,768) into the textfield. Alter 1024 & 768 to create bookmarklet of another size.

Both Keywords and Description can be left blank.



Step 3


Test your bookmarklet, click and it should resize to it’s specific size.

Saturday, January 10, 2009

Using Custom Fields to create a dynamic sidebar

WordPress has the ability to allow post authors to assign custom fields to a post. This arbitrary extra information is known as meta-data. This meta-data can include bits of information such as:

  • Mood: Happy
  • Currently Reading: Cinderella
  • Listening To: Rock Around the Clock
  • Weather: Hot and humid

With some extra coding, it is possible to achieve more complex actions, such as using the metadata to store an expiration date for a post.

Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the information that will appear in the meta-data list on each individual post that the information is associated with.

Getting Custom Fields

To fetch meta values use the get_post_meta() function:

 get_post_meta($post_id, $key, $single);<br />
  • $post_id is the ID of the post you want the meta values for. Use $post->ID to get a post's ID.
  • $key is a string containing the name of the meta value you want.
  • $single can either be true or false. If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields.

Highly Customized Sidebar using Custom Fields and Categories Per-Post


I've used WordPress for a few years now, but currently I am in need of help of building custom sidebars on a per-post basis using information stored in custom fields and categories. I'm a web designer by trade, not a programmer, and have some experience with PHP but not enough to do what I need.

Setup
I'm currently designing a website that uses WordPress as a CMS and will be used by location scouts for potential movie and commercial shooting locations. Posts act in two ways: 1. as News (much like a blog) and 2. as an individual location.

Each individual location is categorized using the WordPress category system, however there are over 75 categories including children. Some locations may have up to 3 different categories. On top of that, each location also has a series of custom fields.

Intention
When an individual location is being viewed, the purpose of the sidebar is to feature two sets of 3+ locations: 1. via a category based on the posts categories and 2. locations nearby using a custom field stored in the post.

Since some posts may have up to 3 categories in all, I don't know how to narrow down the category to just one. For instance, the post may have the main category of House with children of Historic & Period 1950s. All I would want is to pull the House category when someone is viewing a home location and list other locations categorized under Houses in the sidebar.

The same is for the Custom Fields application. Here the intention is to pull the zoning area for the location and list other locations in the same zone.

So if I'm looking at a post for a particular location that is categorized under Gas Station and is located in Zone 1, I should see in the sidebar at least 3 other gas stations and 3 different locations in the zone 1.

Since each post is unique concerning a location, the sidebar must spit out specific information. I've tried to figure out the code, but can't make anything work correctly.

Try something like:

<?php $thumb = get_post_meta($post->ID, "post_thumb", true); if (!empty($thumb)) { ?><img class="alignright size-thumbnail" src="<? echo $thumb;?>" width="120" alt="Thumbnail image for '<?php the_title();?>'" /><? } ?>

Another way to handle this issue

I recently finished the redesign of my blog, The Humanaught, and as these things tend to - it came with a few forehead slapping mind scratchers.

The key one being that the design utilized the post’s footer to store comments. On many posts you wouldn’t even know there was a problem, however when I - on occasion - veer from my usual rambling and only write a tiny little blurb, the issue is evident.

Take, for example, a standard page layout. On one side (in my case, the left) you have your content, on the other you have your sidebar, and hanging out at the bottom you’ve your footer (fig. 1). If your content and your sidebar have a roughly equal amount of doodats in them, you’re golden - but when you short change your comment box, your sidebar extends its full length and makes everything look goofy

Digging into my WordPress template, I needed a dynamic way of determining the size of the content box. For this I threw the following code just above The Loop of my single.php and page.php pages.

<?php
$post = get_post(the_ID(), ARRAY_A);
$contlen = strlen($post[‘post_content’]);
?>

I come out of that with a variable ($contlen) that gives me the character count of my content. Now all I needed to do was pass that variable to my sidebar and use some conditionals (IF bla bla bla) to decide what should be displayed and what should be cut.

The problem with the standard WordPress template is that the <?php get_sidebar(); ?> that WordPress uses by default to load all the goodies in sidebar.php doesn’t pass variables defined in other areas of the template.

To fix this we change:

<?php get_sidebar(); ?>

to

<?php include (TEMPLATEPATH . ‘/sidebar.php’); ?>

Now any variables you set in single.php/page.php will carry over to sidebar.php.

Next up, we need to attribute some values to that prioritized list we made a bit earlier. We need to decide after what character count certain sidebar elements will be displayed. As this is all very much a “give or take” solution, figures will vary depending on things like font-size, the size of elements in the sidebar, etc. However, let’s use my numbers for the sake of … well… just because.

  • All - Search Box, Recent Posts
  • >1,000 - Badges
  • >3,500 - Recent Comments
  • >5,000 - Blogroll

To implement this, we just wrap the sidebar elements in IF statements:

<?php if (is_home() || $contlen > 3500) { ?>
<h2>Recent Comments</h2>
<ul>
<?php get_recent_comments(); ?>
</ul>
<?php } ?>

The IF statement simply says if it is the home/index.php (is_home()) or (||) our content’s length ($contlen) is greater than 3500, display this crap - otherwise, move along.

That about does it, but for the sake of re-illustration, here’s the conditional to display the blogroll:

<?php if (is_home() || $contlen > 5000) { ?>
<h2>Blogroll</h2>
<ul>
<?php wp_list_bookmarks(); ?>
</ul>
<?php } ?>

What this doesn’t take into account are pages that display things like search results, particularly if those results are few to none. But with some simple modifications, I’m sure you can adjust this method to suit your blog’s particular needs.

Technorati Tags: , , , , ,

Thursday, January 8, 2009

How to Unlock a File in Team Foundation Server

We've all been in the
situation before when a developer goes away for a long weekend (usually
leaving on Thursday) and they forget to check in a file and ensure the
solution builds. Here is how to deal with that in TFS. Unlock the
file according to the instructions found here:


http://blogs.msdn.com/rimuri/archive/2006/03/06/544686.aspx


The gist is that running this command will unlock the file:


tf undo /workspace:TheirWorkspace;DOMAIN\TheirUserAccount $/path/to/file


To get a list of workspaces run this:


tf workspaces /owner:DOMAIN\TheirUserAccount /computer:*

Another way to do this:

One of the rare but critical tasks of Configuration Management is
the unlocking of items locked or checked out by someone else, like an
ex-employee or a developer in the Bahamas while an emergency patch
needs to be pushed out.


Unfortunately, the unlock action is not available in the
context-menu or a GUI but needs to be executed from a command line. I
wonder why it’s not in the GUI, granted deleted files and pending
changes will not necessarily be visible in the GUI but at least the
Undo should be available for visible items while the command line still
provides the all-encompassing functionality.


The help was not very clear, so I’ll simplify the command for you.


There are 2 possible options for unlocking, viz. unlock or undo (if checked out for Edit).

The respective command to use is tf lock /lock:none or tf undo


The parameters in both cases are the same:


filename (in the help topic, this is the itemspec parameter)

This is the file you want to unlock


/workspace: [user's workspace]:[user name]

The user’s workspace needs to be figured out…by right-clicking the locked item and selecting Properties… and then the Status tab

The user name is the fully qualified user name, in the form: domain/user


/s:[server path]

This is the TFS server in question. Typically it’s http://servername:8080/


So, a sample command would be something like:

tf undo $/Applications/Dev/Branch1/file1.aspx /workspace:”Ra Dev Notebook”;corp1\ra /s:http://altair:8080


(You run this is on a VS client, at the Visual Studio command prompt)


PS: Hope the color coding helped


Another command I found useful during the process was tf status /user:Joe /s:server path, which essentially lists all files locked by Joe. I piped it to a text file (with >> C:\joe.locked.txt) to get a report.


A User-Friendly C# Descriptive Statistic Class

Today I found and used this class, I highly recommend it for simple statistics calculations required for many reporting systems.

http://www.codeproject.com/KB/recipes/DescriptiveStatisticClass.aspx


The author says:

"The 80-20 rules applies: even with the advances of statistics, most of our work requires only univariate descriptive statistics – those involve the calculations of mean, standard deviation, range, skewness, kurtosis, percentile, quartiles, etc. This article describes a simple way to construct a set of classes to implement descriptive statistics in C#. The emphasis is on the ease of use at the users' end."

It has great reviews and ratings.