Using the KeyedCollection object in C# .NET

The abstract generic KeyedCollection object can be used to declare which field of your custom object to use as a key in a Dictionary. It provides sort of a short-cut where you’d want to organise your objects in a Dictionary by an attribute of that object.

Let’s take the following object as an example:

public class CloudServer
{
	public string CloudProvider { get; set; }
	public string ImageId { get; set; }
	public string Size { get; set; }
}

The Image IDs are always unique so the ImageId property seems to be a good candidate for a dictionary key.

Here’s an example:

Read more of this post

HTTPS and X509 certificates in .NET Part 2: creating self-signed certificates

Introduction

In the previous post we looked at TLS and certificates in general. We saw what makes up an SSL certificate and how browsers use it to verify the identity of the server and to decrypt/encrypt the communication.

In this post we’ll look at a tool called makecert.exe.

Before we actually continue there are some other important terms that we need to investigate.

Read more of this post

Getting notified when collection changes with ObservableCollection in C# .NET

Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.

If you don’t know what events, event handlers and delegates mean then start here.

Let’s see a simple example with a collection of strings:

ObservableCollection<string> names = new ObservableCollection<string>();
names.Add("Adam");
names.Add("Eve");
names.Add("Clive");
names.Add("Anne");
names.Add("John");
names.Add("Peter");
names.Add("Hannah");

Nothing special so far I guess. This looks exactly like a “normal” collection.

The following example demonstrates the CollectionChanged event:

private static void RunObservableCollectionCode()
{
	ObservableCollection<string> names = new ObservableCollection<string>();
	names.CollectionChanged += names_CollectionChanged;
	names.Add("Adam");
	names.Add("Eve");
	names.Remove("Adam");
	names.Add("John");
	names.Add("Peter");
	names.Clear();
}

static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
	Debug.WriteLine("Change type: " + e.Action);
	if (e.NewItems != null)
	{
		Debug.WriteLine("Items added: ");
		foreach (var item in e.NewItems)
		{
			Debug.WriteLine(item);
		}
	}

	if (e.OldItems != null)
	{
		Debug.WriteLine("Items removed: ");
		foreach (var item in e.OldItems)
		{
			Debug.WriteLine(item);
		}
	}
}

The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.

If I run the RunObservableCollectionCode method I get the following output:

Change type: Add
Items added:
Adam
Change type: Add
Items added:
Eve
Change type: Remove
Items removed:
Adam
Change type: Add
Items added:
John
Change type: Add
Items added:
Peter
Change type: Reset

You can then decide how to handle additions and deletions in the event handler.

View all various C# language feature related posts here.

Customise your list by overriding Collection of T with C# .NET

Imagine that you’d like to build a list type of collection where you want to restrict the insertion and/or deletion of items in some way. Let’s say we need an integer list with the following rules:

  • The allowed range of integers is between 0 and 10 inclusive
  • A user should not be able to remove an item at index 0
  • A user should not be able to remove all items at once

One possible solution is to derive from the Collection of T class. The generic Collection of T class in the System.Collections.ObjectModel namespace provides virtual methods that you can override in your custom collection.

The virtual InsertItem and SetItem methods are necessary to control the behaviour of the Collection.Add and the way items can be modified through an indexer:

Read more of this post

Using the HashSet of T object in C# .NET to store unique elements

The generic HashSet of T is at first sight a not very “sexy” collection. It simply stores objects with no order, index or key to look up individual elements.

Here’s a simple HashSet with integers:

HashSet<int> intHashSet = new HashSet<int>();
intHashSet.Add(1);
intHashSet.Add(3);
intHashSet.Add(5);
intHashSet.Add(2);
intHashSet.Add(10);

HashSets can be handy when you want to guarantee uniqueness. The following example will only put the unique integers in the set:

Read more of this post

SOLID principles in .NET revisited part 10: concentrating on enumerations resolved

Introduction

In the previous post we built some bad code. We built it like that deliberately to make you aware of how easy it is to misuse enumerations. We ended up with classes that are coupled in a way that if you extend one then you’ll need to extend at least one other.

In this post we’ll refactor the code to make it better.

Objects instead of enumerations

The main point I want to make in this exercise is that building “proper” objects instead of enumerations can make your code base much more flexible. It’s important to note that there are multiple ways to improve the code. I’m only going to present a solution that I think is good. You might come up with a different solution and it may well be just as good or even superior. The main thing is that the components of your code base should be as loosely coupled as possible.

The PerformanceMetricType enumeration and its members will be transformed into an abstract base class and two implementations. The abstract class will have a single “description” parameter so that the Metric type can be described. It will also have an abstract method where the implementing type will have to extract the correct value from the PerformanceSummary object:

public abstract class Metric
{
	private string _description;

	public Metric(String description)
	{
		if (string.IsNullOrEmpty(description)) throw new ArgumentNullException("Metric description");
		_description = description;
	}

	public string Description
	{
		get
		{
			return _description;
		}
	}

	public abstract double ExtractActualValueFrom(PerformanceSummary performanceSummary);
}

Here come the implementations as well. First AverageResponseTimeMetric:

public class AverageResponseTimeMetric : Metric
{
	public AverageResponseTimeMetric() : base("Average response time per page")
	{}

	public override double ExtractActualValueFrom(PerformanceSummary performanceSummary)
	{
		return performanceSummary.AverageResponseTimePerPage;
	}
}

…and second the UrlCallsPassedPerMinuteMetric:

public class UrlCallsPassedPerMinuteMetric : Metric
{
	public UrlCallsPassedPerMinuteMetric() : base("Url calls passed per minute")
	{}

	public override double ExtractActualValueFrom(PerformanceSummary performanceSummary)
	{
		return performanceSummary.TotalPassedCallsPerMinute;
	}
}

We’ll do the same with the EvaluationOperator enumeration. The abstract base class EvaluationOperation also has a description field and a single abstract method. The implementing class will have to determine whether the actual value breaks a certain limit:

public abstract class EvaluationOperation
{		
	private string _description;

	public EvaluationOperation(String description)
	{
		if (string.IsNullOrEmpty(description)) throw new ArgumentNullException("Description");
		_description = description;
	}

	public string Description
	{
		get
		{
			return _description;
		}
	}

	public abstract bool LimitBroken(double limit, double actual);
}

Here’s the GreaterThan implementation of EvaluationOperation:

public class GreaterThan : EvaluationOperation
{
	public GreaterThan() : base ("Greater than")
	{}

	public override bool LimitBroken(double limit, double actual)
	{
		return actual > threshold;
	}
}

…and here comes LessThan:

public class LessThan : EvaluationOperation
{
	public LessThan() : base("Less than")
	{ }

	public override bool LimitBroken(double limit, double actual)
	{
		return actual < threshold;
	}
}

ThresholdEvaluationResult is the same as before:

public class ThresholdEvaluationResult
{
	public bool ThresholdBroken { get; set; }
}

The updated Threshold class looks quite different from what we had before. The enumeration parameters are gone from the constructor and have been replaced by abstract classes. Also, the logic of evaluating whether a threshold is broken has been placed within the Threshold class instead of some specialised “service”:

public class Threshold
{
	private Metric _metric;
	private EvaluationOperation _operation;
	private double _thresholdValue;

	public Threshold(Metric metric, EvaluationOperation operation, double thresholdValue)
	{
		if (metric == null) throw new ArgumentNullException("Metric");
		if (operation == null) throw new ArgumentNullException("Operation");
		_metric = metric;
		_operation = operation;
		_thresholdValue = thresholdValue;
	}

	public ThresholdEvaluationResult Evaluate(PerformanceSummary performanceSummary)
	{
		ThresholdEvaluationResult res = new ThresholdEvaluationResult();
		double actualValue = _metric.ExtractActualValueFrom(performanceSummary);
		bool broken = _operation.LimitBroken(_thresholdValue, actualValue);
		res.ThresholdBroken = broken;
		return res;
	}
}

As you see the Evaluate method calls upon the injected abstract classes in order to determine whether some limit has been broken. The Threshold class knows nothing about the actual implementations. Also, if you need to extend your domain with other Operation types, such as EqualTo, LessThanOrEqualTo or implement new metric types, like CpuUsageMetric, then you can do that in isolation. Other classes in the model won’t need to be updated at all. The Threshold class will happily accept the new implementations without any complaints.

This post concludes our discussion of SOLID in .NET for the time being.

View the list of posts on Architecture and Patterns here.

Determine if two arrays are structurally equal in C# .NET

Two arrays are said to be structurally equal if they contain the same elements in the same order. Whether or not two elements are the same depends on how you define equality for your custom types. Equality for primitive types, like integers, is more or less straightforward but you’ll need to declare in code what is meant by equality for reference types.

We’ve looked at a couple of strategies to do so on this blog and here we’ll re-use the topic of implementing the IEqualityComparer of T interface.

The non-generic IStructuralEquatable interface has an equals method that accepts an object to compare with and another object which implements the non-generic IEqualityComparer interface. This is an important distinction as implementing the generic IEqualityComparer interface won’t be enough for structural equality. We’ll need to derive from the EqualityComparer base class which implements both the generic and non-generic version of IEqualityComparer. If you try to run the below example with a generic IEqualityComparer of T instance then you’ll get a compiler error.

Note that structural equality is not available for all collection types. Currently only arrays and tuples support it, i.e. they can be cast to type IStructuralEquatable. However, as List objects can be easily converted into arrays that’s not really an obstacle.

Read more of this post

SOLID principles in .NET revisited part 9: concentrating on enumerations

Introduction

In the previous post we streamlined our demo code so that it adheres to the SOLID principles. You may still spot bits and pieces that violate some design principle. It’s important to remark that in a large enterprise project it’s very difficult to attain 100% SOLID, if that state exists at all. You might be able to spot “deviations” even in the most well-maintained code bases.

In this post we’ll concentrate on enumerations. We saw before in this series how false usage of enums can easily lead to maintainability problems. Enumerations seem to be very popular due to their simplicity and how easily they can be used to create a list of valid values in a certain category.

We’ll first build up a short case study with all types of mistakes with special emphasis on enumerations. We’ll then improve the code in the next post.

Read more of this post

Implementing equality of derived reference types by overriding the == operator with C# .NET

In this post we saw one solution to override the == operator for a reference type to implement equality checking. Here’s a reminder of the Person class:

public class Person
{
	public int Id { get; set; }
	public string Name { get; set; }
	public int Age { get; set; }

	public static bool operator ==(Person personOne, Person personTwo)
	{
		return personOne.Id == personTwo.Id;
	}

	public static bool operator !=(Person personOne, Person personTwo)
	{
		return personOne.Id != personTwo.Id;
	}

        public override int GetHashCode()
	{
		return Id;
	}
}

Read more of this post

Implementing the IEquatable of T interface for object equality in a derived class with C# .NET

In this post we saw how to implement the IEquatable of T interface for a simple Person class. We based our equality logic on the Id property of the object. We implemented the IEquatable.Equals method and also overrode the Object.Equals and GetHashCode methods.

In this post we’ll see how you might go about extending that logic in derived classes. For that purpose we’ll go with another object:

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.