Creating sorted sets with C# .NET

The SortedSet of T object is the sorted version of the HashSet object. We’ve already seen what a HashSet can do for you in the referenced post. A SortedSet keeps the elements in increasing order.

Consider the following integer set:

SortedSet<int> sortedInts = new SortedSet<int>();
sortedInts.Add(1);
sortedInts.Add(4);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(3);
sortedInts.Add(10);
sortedInts.Add(8);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(4);
foreach (int i in sortedInts)
{
	Debug.WriteLine(i);
}

This will print…

1
3
4
8
10

Notice that duplicates were rejected to ensure uniqueness just like in the case of HashSets.

That is straightforward for primitive types like integers since .NET “knows” how to compare them. It can decide whether 10 is greater than 5, we don’t need to provide any help.

However what about reference types like your own objects, such as this one?

public class Band
{
	public string Name { get; set; }
	public int YearFormed { get; set; }
	public int NumberOfMembers { get; set; }
	public int NumberOfRecords { get; set; }
}

How can .NET decide on the ordering of your objects? We’ll need to give it a hint by providing an object which implements the generic IComparer of T interface like we saw in this post. We’ll let the Band objects be sorted by their names:

public class BandNameComparer : IComparer<Band>
{
	public int Compare(Band x, Band y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

Let’s see this in action:

SortedSet<Band> bands = new SortedSet<Band>(new BandNameComparer());
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Well known band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });

foreach (Band band in bands)
{
	Debug.WriteLine(band.Name);
}

This will print…

Best band
Famous band
Great band
Well known band

…so not only were the items sorted by their names but the non-unique values were rejected as well. The IComparer argument also provided a way to declare equality.

View all various C# language feature related posts here.

Various topics from software architecture part 5: aggregate roots

Introduction

In the previous post we looked at the second installment of the unit of work pattern. We designed a mock implementation of the unit of work and unit of work repository interfaces.

In this post we’ll look at a key concept from Domain Driven Design, the aggregate root. This topic was discussed in detail as part of the DDD series but it deserves a dedicated post.

Read more of this post

Basics of working with pipes in C# .NET part 6: message compression

In the previous part we looked at a possible solution to transmit objects through a pipe from the client to a server. We saw that it was not much different compared to transmitting a string message as the object had to be serialised first.

In this post we’ll consider a way to reduce the message size by compressing it. In messaging you should always aim for short and concise messages for good speed and scaling. However, sometimes the messages are simply large and you cannot do much about it. E.g. consider a service that scans the contents of a web page and returns the HTML as a string along with some measurements for every element on the page, such as CSS and JS files etc: time to first byte, header receive time, header size etc. That can be a large piece of string.

We’ll reuse a technique outlined in this post dedicated to BZip2 string compression. If you don’t know how that works then read through that article, it’s very short.

You’ll need to import the following NuGet package to use BZip2 in the pipe server in client console applications:

sharpziplib nuget

Here’s the pipe client code to send a BZip2 compressed message to the pipe server:

private static void SendCompressedMessageToServer()
{
	using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test"))
	{
		string longMessage = "This is a large piece of text";
		string compressed = string.Empty;
		using (MemoryStream source = new MemoryStream(Encoding.UTF8.GetBytes(longMessage)))
		{
			using (MemoryStream target = new MemoryStream())
			{
				BZip2.Compress(source, target, true, 4096);
				byte[] targetByteArray = target.ToArray();
				compressed = Convert.ToBase64String(targetByteArray);
			}
		}
		namedPipeClient.Connect();
		byte[] messageBytes = Encoding.UTF8.GetBytes(compressed);
		namedPipeClient.Write(messageBytes, 0, messageBytes.Length);
	}
}

…and here’s how the server can handle the message:

private static void ReceiveCompressedMessageFromClient()
{
	using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("test", PipeDirection.InOut,
		1, PipeTransmissionMode.Message))
	{
		namedPipeServer.WaitForConnection();
		StringBuilder messageBuilder = new StringBuilder();
		string messageChunk = string.Empty;
		byte[] messageBuffer = new byte[5];
		do
		{
			namedPipeServer.Read(messageBuffer, 0, messageBuffer.Length);
			messageChunk = Encoding.UTF8.GetString(messageBuffer);
			messageBuilder.Append(messageChunk);
			messageBuffer = new byte[messageBuffer.Length];
		}
		while (!namedPipeServer.IsMessageComplete);
		string fullMessage = messageBuilder.ToString().Trim('\0');
		byte[] largeCompressedTextAsBytes = Convert.FromBase64String(fullMessage);
		using (MemoryStream source = new MemoryStream(largeCompressedTextAsBytes))
		{
			using (MemoryStream target = new MemoryStream())
			{
				BZip2.Decompress(source, target, true);
				string uncompressedString = Encoding.UTF8.GetString(target.ToArray());
				Console.WriteLine(uncompressedString);
			}
		}
	}
}

We compress the string using the BZip2 algorithm and then convert that to a base 64 string in the client. The server performs the exact opposite. You may be wondering about this bit:

string fullMessage = messageBuilder.ToString().Trim('\0');

The character described in the Trim argument is the string termination or null-termination character that marks the end of the message. That’s how the pipe server and client can determine whether there’s anything remaining of an incoming message.

View the list of posts on Messaging here.

Various topics from software architecture part 4: the unit of work continued

Introduction

In the previous post we looked at the basic goals and the abstractions associated with the unit of work pattern. We came to the conclusion that it might not be necessary to introduce an abstraction for the unit of work to begin with as modern ORMs like EntityFramework already have a well-tested unit of work object inside. There may still be cases though where you can make use of the pattern and the associated unit of work repository.

In this post we’ll see some possible mock implementations of these abstractions and how they can be wired up in the repository layer.

Implementation stubs

We’ll briefly look at some implementation skeletons for the IUnitOfWork and IUnitOfWorkRepository interfaces and how they can be used in a concrete repository.

Read more of this post

Basics of working with pipes in C# .NET part 5: transmitting objects

In the previous part we saw a very basic chat application between a client and a server through a pipe. In this post we’ll see a way of how to transmit objects from the client to the server.

You’ll see that it really is not much different from transmitting a message. We cannot simply transmit an object using e.g. a WriteObject method. Instead the object must be serialised at the client side and deserialised at the server side. We’ll serialise our object using JSON and transmit the object properties using the message transmission technique we’ve seen earlier. The server will then deserialise the JSON string into the object.

We’ll pretend that the client wants to transmit an order:

public class Order
{
	public string ProductName { get; set; }
	public int Quantity { get; set; }
	public string CustomerName { get; set; }
	public string Address { get; set; }
}

Read more of this post

Basics of working with pipes in C# .NET part 4: basic conversation with messages

In this post we saw how a pipe stream client and server can send each other single bytes. In this post we managed to send a single message from the client to the server. It’s time to marry the two concepts. We’ll let the client and server start a conversation.

The server side code has nothing new compared to the posts referred to above:

Read more of this post

Various topics from software architecture part 3: the unit of work

Introduction

In the previous post we looked at a basic implementation of the Repository pattern. We said that this pattern is often used in large layered projects where persistence ignorance of the domain layer is a requirement. It is also very useful in unit testing where you want to avoid calling a real data store and instead create mocks or stubs for the repository.

In this post we’ll look at another concept that comes up in conjunction with data access: the unit of work. We’ll also refer back to the previous post on the Repository pattern here and there as the Unit of Work pattern is often used in conjunction with repositories.

This post will be more concerned with abstractions. The next post will continue with some implementation stubs.

Some of the explanations are taken directly from the series on domain driven design so they might look familiar if you’ve seen that.

Read more of this post

Basics of working with pipes in C# .NET part 3: message transmission

So far in the posts on pipe streams in .NET we’ve been considering the transmission of single bytes. That’s not really enough for a real-world messaging application. In this post we’ll extend our discussion to complete messages.

We have to explicitly indicate that we want to process messages in the NamedPipeServerStream constructor. Also, we’ll need to read the messages in chunks. A message is represented by a byte array and we don’t know in advance how long the message will be. Fortunately the NamedPipeServerStream object has an IsMessageComplete property which we’ll be able to use in the do-while loop:

Read more of this post

Various topics from software architecture part 2: the Repository pattern

Introduction

In the previous post we looked at the RequestResponse messaging pattern. This pattern is often used in Service Oriented Architecture projects to simplify the communication between the service and its client.

In this post we’ll look at something very different. The Repository pattern is frequently employed in layered architectures where the domains in the Domain layer expose data access related operations through abstract interfaces. The actual repository layer, e.g. EntityFramework or MongoDb then implement those interfaces.

The primary goal of the Repository pattern is to decouple the domain objects from the physical repository layer. The domain objects and the domain layer are not supposed to know about the actual data access operations such as opening a database connection and querying a database. This is a common approach in Domain Driven Design (DDD).

We’ll go through the basic concepts of the pattern in this post. If you’d like to see a more complex design then you can go through the series on DDD. Also, there are multiple ways to implement the pattern but the main objective is to keep the technology-specific data access operations out of the domain layer.

A simple domain

Read more of this post

Basics of working with pipes in C# .NET part 2: continuous byte communication

In this post we briefly introduced how interprocess communication pipes are represented in .NET. The server sent a single byte to the client and the client sent a single byte in response. We’ll add some more flesh to the code but still keep it very simple. We’ll let the client and server send each other individual bytes as messages. Obviously that is still very childish but it will do for demo purposes. We’ll continue with proper messages in the next post.

Here’s the extended server code with a lot more output. We read a line of input from the console but only transmit the very first byte. We wait for the client’s response. The byte value of ‘x’, i.e. 120 will indicate that the client wants to end the communication:

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.