Posts tagged with c - page 12

Equatable Weak References

In a previous post I described a [WeakReference](// class for providing strongly-typed [WeakReference]( objects.

GitHub has the latest version of EquatableWeakReference</a> </p> One problem with the previous WeakReference class is being able to use and find it within the various collection classes. This is because one WeakReference is not equal to another WeakReference class. Overriding the Equals method fixes this problem at first glance however also reveals another issue. If you override Equals you should also override the GetHashCode method so that two objects that equal each other return the same hash code. This is because some of the collection classes use hash codes to efficiently lookup items within their collection. Normally a hash code would be calculated from the various data items that comprise the class but in our case we really only have one to go on – the Target object itself. This raises two more issues: 1. The hash code should not change over the objects lifetime – difficult when your Target object can be changed. 2. The hash code should be stored because the Target object might well be collected by the GC – after all that’s what this class is all about. This doesn’t leave us with many choices at all. We must grab the hash code from the Target object within our constructor and store it for subsequent retrieval. Here is EquatableWeakReference with the usual disclaimers as to it’s suitability for any purpose. ```csharp using System; using System.Runtime.InteropServices; public class EquatableWeakReference : IEquatable<EquatableWeakReference>, IDisposable where T : class { protected GCHandle handle; protected int hashCode; public EquatableWeakReference(T target) { if (target == null) throw new ArgumentNullException("target"); hashCode = target.GetHashCode(); InitializeHandle(target); } protected virtual void InitializeHandle(T target) { handle = GCHandle.Alloc(target, GCHandleType.Weak); } ~EquatableWeakReference() { Dispose(); } public void Dispose() { handle.Free(); GC.SuppressFinalize(this); } public virtual bool IsAlive { get { return (handle.Target != null); } } public virtual T Target { get { object o = handle.Target; if ((o == null) || (!(o is T))) return null; else return (T)o; } } public override bool Equals(object other) { if (other is EquatableWeakReference) return Equals((EquatableWeakReference)other); else return false; } public override int GetHashCode() { return hashCode; } public bool Equals(EquatableWeakReference other) { return ReferenceEquals(other.Target, this.Target); } } ``` _[)amien_

Microsoft announces XNA for homebrew, score 1 for my prediction skills

Over the last few months I’ve pieced together various snippets and hints from the web to come to the conclusion that Microsoft’s forthcoming XNA platform, specifically the XNA Framework version, would be available to home-brew developers and let them develop on the Xbox 360 – the first official home-brew since the PlayStation 1’s Net Yaroze!

Indeed I’ve been telling people in IRC and on forums that I believe this to be true. One friend, after messing with Managed DirectX2, told me if I was wrong about this I was in trouble. I went as so far to claim that it’s already tested and GarageGames Marble Blast Ultra was an XNA Framework title.

Today Microsoft announced at their Gamefest conference the XNA Game Studio Express – a free download due this “holiday season” (a beta is out 30th August) – that lets anyone create XNA Framework based games on their PC which other people can run, on their PC.

The real icing on the cake however is that for $99 USD a year you can join the “creators club” and run home-brew XNA titles on your 360 – your own or other peoples.

Check out Microsoft’s XNA Developer Center and their XNA FAQ for the low-down.

Phew, seems my reputation is in tact.


Calculating CRC-32 in C# and .NET

Just a few days ago I found myself needing to calculate a CRC-32 in .NET. With so many facilities available I was a little shocked that there was nothing built-in to do it so knocked up something myself.

GitHub has the latest version of Crc32

Because unsigned ints aren’t CLS compliant it won’t play well with VB.NET and implementing the HashAlgorithm might lead people to believe it’s suitable for signing – it isn’t. CRC-32’s are only any good for check-sums along the lines of WinZIP, RAR etc. and certainly shouldn’t come near a password and instead consider SHA-512 or similar.

As well as using it as a HashAlgorithm with block processing you can also access the static method Compute although there is an overhead with every call building the table with that. If neither option suits you needs cut ‘n splice it to something that does.

If using the Compute methods multiple times for the same hash you must XOR (~) the current hash when passing it in to the next subsequent call’s seed parameter.

To compute the hash for a file simply:

var crc32 = new Crc32();
var hash = String.Empty;

using (var fs = File.Open("c:\\myfile.txt", FileMode.Open))
  foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();

Console.WriteLine("CRC-32 is {0}", hash);


Implementing a generic WeakReference in C#

Check out the replacement EquatableWeakReference class</a> </p> A [weak reference]( lets you hold a reference to an object that will not prevent it from being garbage collected. There are a few scenarios where this might be important – such as listening for events, caching, various [MVC patterns]( .NET and Java supports weak references with the aptly named [WeakReference]( class. In .NET it exposes a .Target property of type object that weakly points to whatever you like. Java also sports a generic WeakReference to give you a strongly typed version so it’s somewhat puzzling why .NET doesn’t. Here is my attempt at a WeakReference for .NET. It works fine in the scenarios I’ve used and performance is close to the non-generic version but a quick glance at the SSCLI code for WeakReference reveals that the standard version is a little more complicated and it’s possible there is a reason for that – most likely due to finalizer issues. ```csharp using System; using System.Runtime.InteropServices; public class WeakReference : IDisposable { private GCHandle handle; private bool trackResurrection; public WeakReference(T target) : this(target, false) { } public WeakReference(T target, bool trackResurrection) { this.trackResurrection = trackResurrection; this.Target = target; } ~WeakReference() { Dispose(); } public void Dispose() { handle.Free(); GC.SuppressFinalize(this); } public virtual bool IsAlive { get { return (handle.Target != null); } } public virtual bool TrackResurrection { get { return this.trackResurrection; } } public virtual T Target { get { object o = handle.Target; if ((o == null) || (!(o is T))) return default(T); else return (T)o; } set { handle = GCHandle.Alloc(value, this.trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak); } } } ```

I’ve allowed Target to be settable against my better judgment to bring it more in like with WeakReference. It’s still not serializable though unlike WeakReference.