Enum Extension Methods

July 17, 2020 c#, enum, extension

Did you know you can create extension methods for enums?

Read More

Disable C# null checks for a field or property

January 02, 2020 c#, nrt, nullable

The new nullable reference types in C# are great but sometimes you might need to disable it for a single field or property. You can do that by assigning the value to null and using the ! operator.

Read More

Use nameof() to set a string variable to its name

December 17, 2019 c#, nameof()

This is one of those things that should have just been obvious to me but once I saw it I wondered why I had never thought to use it myself. nameof() can be used when declaring a variable to set the value of the variable to the name of the variable:

public const string MyVariable1 = nameof(MyVariable1); public static void Main() { Console.WriteLine(MyVariable1); }
Read More

Dynamically loaded DLL thows AccessViolationException on first function call

October 22, 2019 c#, LoadLibrary, GetProcAddress

In my library GLESDotNet I load the libegl.dll and libglesv2.dll DLLs dynamically via the Win32 functions LoadLibrary and GetProcAddress. I already had everything working via DLLImport but I wanted to be able to load the DLLs from different subdirectories depending on the architecture.

For the first test I only loaded the libegl.dll DLL before moving on to the libglesv2.dll. I made the classic programmer mistake of changing too much at one time. The first call to any function in libegl.dll resulted in an AccessViolationException. I couldn't figure out what was going wrong so I decided to revert my changes and try again.

I noticed that when the DLLs were in the same directory the AccessViolationException went away. Changing the working directory to the directory of the DLLs also solved the problem once the DLLs were placed in subdirectories again. This led me to believe that loading libegl.dll must be implicitly loading libglesv2.dll. Loading libglesv2.dll via LoadLibrary along with libegl.dll solved the problem.

Abusing IDisposable

August 27, 2019 c#, IDisposable

In C# the interface IDisposable is usually used to indicate that an object needs to dispose of unmanaged resources. C# provides the using syntax to ensure that the Dispose method is called once the instance of the object is no longer needed.

Dispose is just like any other method though and the using syntax can be used quite nicely for other use cases as well. Let's create a class we can use to collect some actions to be "deferred" until a later time.

Read More

Generating string permutations for unit testing

February 11, 2019 c#, nunit, math

I needed to parse a string containing 6 characters. Each character should only be one of 3 possibilities: '?' for null, '0' for false or '1' for true. The problem sounded easy enough to generate a whole bunch of unit tests for.

Read More

Functional Card Deck in C#

October 11, 2018 c#, fp

I've been inspired lately by Mark Seemann's series of posts about Applicative Functors. One of the latest posts is an example about creating a full deck of cards. Most of posts up to this point have contained a C# example but for some reason this one didn't. This inspired me to take a shot at it.

Read More

Enabling the latest version of C#

June 21, 2018 c#, msbuild

As of this writing when creating a new console project via dotnet new console the version of C# used in the project is version 7.0. This means you're missing out cool features like Default Literal Expressions. The language version can be changed via Visual Studio though I prefer to enable it via MSBuild. This can be done in the csproj file or globally via a Build.Directory.props file. Changing the C# language version is done via a property known as LangVersion.

<PropertyGroup>
    <LangVersion>latest</LangVersion>
</PropertyGroup>

This property can set to any of the values listed here. As of this writing VS Code doesn't seem to like it when you use 7.3 instead of latest. VS Code will show errors in your code although the code will compile without any problems.

A neat way to curry in C#

May 25, 2018 c#, fp

I was reading an older blogpost from Mike Hadlow about Partial Application in C# in which he discusses how Partial Application can be implemented in C# via Currying. Although I appreciate his example of implementing currying via extsion methods, the syntax is hideous. There is a suggestion in the comments though that I found to be a much better solution.

// Define a local function Add. int Add(int a, int b) => a + b; // Here we do the currying. Func<int, int> add3 = (b) => Add(3, b); // This will print 5. Console.WriteLine(add3(2)); // Curry one more time so that we have // a function that simply produces 5. Func<int> five = () => add3(2); // This will also print 5. Console.WriteLine(five());

Lambda Collection Wrappers

April 26, 2018 c#, lambda, fp

I've been reading a lot as of late about functional programming and I try to incorperate as much as possible into my everyday programming. One trick that I've definitely started using is wrapping collections in lambda functions.

Read More

string.Join Extension Method

April 19, 2018 c#, linq

Normally if want to do a string.Join on the result of a Linq query you end up with somthing looking like this:

Console.WriteLine(string.Join(", ", numbers.Where(x => x % 2 == 0)));

The call to string.Join has to come first and then the Linq query. I've always felt this breaks the flow of the code and would be easier to read if the string.Join was at the end of the Linq query:

Console.WriteLine(numbers.Where(x => x % 2 == 0).JoinString(", "));

This can be implemented with the following extension methods:

public static class JoinStringExtensions { public static string JoinString<T>(this IEnumerable<T> source, string seperator) => string.Join(seperator, source.Select(x => x.ToString())); public static string JoinString(this IEnumerable<string> source, string seperator) => string.Join(seperator, source); }

The specialization for IEnumerable<string> is just mirroring the implementation from string.Join.

Poor Man's Template Engine in C# Part 3

Include

March 22, 2018 c#, template, template-engine

In our last episode we implemeted the first two helper funcitons HtmlEncode and If. Today we want to implement Include.

Read More

Poor Man's Template Engine in C# Part 2

HtmlEncode and If

March 14, 2018 c#, template, template-engine

In our last episode we laid the groundwork for our simple template engine. In this episode we'll introduce our first 2 helper functions.

Read More

Poor Man's Template Engine in C# Part 1

Groundwork

March 06, 2018 c#, template, template-engine

If you're looking for a poor man's solution to a templating engine for .net and don't really need the overhead a complete template engine brings with it, I've come up with the following solution.

Read More

Snowball V2.0

February 23, 2018 Snowball, c#

I haven't written anything new here in a very long time and a lot has happened since then. I started a new job at BeumerGroup this year and now work mostly in TypeScript writing an html5 spa app.

In my spare time I've decided to working on version 2.0 of my Snowball, my 2D game framework. I've been playing around with the idea for a while now. This version will be developed directly for .net core and will be developed with cross platform capability in mind. The api will look similar but will have some changes.

The old repo is still available on my github at https://github.com/smack0007/Snowball_v1.

Using Component Glue to build your object graphs automatically

July 26, 2013 Open Source, Dependency Injection, IoC, C#, .NET

Component Glue is an IoC container and you use it of course to wire up your object graphs for you. Component Glue can also build your object graphs for you automatically if there are no interfaces involved. Take this example:

In After.cs, you can see that Component Glue is able to build the entire object graph for us. This will include all future dependencies as well so long as interfaces don't come into play. Should an interface be needed, you can just bind that single component.

This is a very powerful thing. If one component needs to take on a dependency, just ask for it in the constructor and Component Glue will handle it for you.

Component Glue v1.0

June 11, 2013 .NET, C#, ComponentGlue, Dependency Injection, Github, IoC, NuGet

I finally brought Component Glue up to a state where I felt like the product was finished. You can get it via NuGet:

`PM> Install-Package ComponentGlue`

or you can get the source from GitHub. The documentation is definitely sparse I know but I recommend taking a look at the unit tests to get a feel for what you can do with Component Glue.

Credit for the NuGet CSS here.

GLDotNet Version 0.6.0

February 19, 2013 C#, OpenGL, .NET

I just released GLDotNet Version 0.6.0.

Changelog:

  • **GLDotNet.Toolkit**: Assembly containing simple app framework.
  • **GLDotNet.Objects**: Assembly containing higher level objects such as Texture2D and VertexBuffer.
  • More overloads added to GLContext class.
  • byte and sbyte are now mapped correctly in generated code.
  • Fixed the naming of some functions so as not to include type notation, i.e. Color4u.
  • Decreased the number of enum values output.

Introducing GLDotNet

January 02, 2013 C#, OpenGL, .NET, Open Source

Today I released a project I've been playing around with for a year or so on Codeplex. It's called GLDotNet. From the project description:

C# wrapper for OpenGL. Partially generated from the OpenGL spec and partially written by hand, the aim is to have a flexible and native feeling C# binding.

I have generated functions from the OpenGL spec excluding 1 or 2 but unfortunately of the generated code is untested. There is a demo project included in the source code. The Github repository is located here: https://github.com/smack0007/GLDotNet

Getting Started with Snowball

March 04, 2012 C#, .NET, Game Programming

My game framework Snowball is far enough along that small games can be developed with it by now. The basic overall design is now laid out and not too much is likely to change as I'm now developing my own small games with it.

In order to create some kind of documentation on how to use Snowball, I created a Samples folder in the source. In the Samples folder is a WalkingWizard sample. I'm posting this source code here but it can also be viewed on GitHub here.

What is Snowball and what do I want to do with it?

October 16, 2011 2d, C#, CodePlex, Open Source, SlimDX, Xna

I originally got the idea for Snowball after working with the Xna Framework. The Xna Framework is a good piece of software for what it is but there are some things about which I just do not agree with:

  • The content pipeline only works with content in the serialized .xnb format.
  • There are certain content types which can only be loaded via the content pipeline.
  • Certain features don't exist on the PC because they don't exist on the XBox or Windows Phone 7.

Xna was designed as an abstraction layer for all the 3 platforms mentioned in the last point, so that one is somewhat understandable. I don't want to write games for my XBox right now though, so why should things like drawing lines not be available to me?

With these points in mind I started working on Snowball. It's designed to be an Xna like framework for making 2D games. It uses SlimDX on the backend, but that is completely abstracted away from consumers of the framework. What I want to do is design the API so that the backend can be swapped out somewhat painlessly.

I still have a ways to go before I will consider it a version 1.0 release. As of this writing, I'm transitioning to more of a ContentLoader class style for loading your game's content. Any resource type from within the framework can be loaded by hand if you want, the ContentLoader class will just make it easier. After that I have a few other features like GamePad and Music which I would like to implement before saying I have a Beta type release.

The future after that is up in the air. I would love to try and have different implementations of the API for Xna and/or OpenTK.

I recommend for anyone who is interested as to why an API designer choose to implement the API in the way they did to try it for themselves. I have learned many things from this project including why certain design decisions were made by the Xna Framework team.

Component Glue

November 02, 2010 C#, CodePlex, IoC, Open Source

The other day I started an open source project for an IoC Container I call Component Glue. It's in a toy / learning tool status right now and I don't know how far I actually want to take the project. More to come though.

Component Glue on Codeplex

Implementing basic Dependency Injection using a Service Container

June 21, 2010 .NET, C#, Dependency Injection, Design Patterns, Service Continer

By extending your Service Container class, a very basic version of dependency injection can be implemented. We'll implement two forms of dependency injection: constructor and property injection.

Read More

Progress Bar in Windows 7 Taskbars

June 01, 2010 .NET, C#, Windows 7

I decided to add progress bar to the Windows 7 Taskbar in my Timer app.

I started by downloading and compiling the Windows API Code Pack in Release mode. I then added a reference to the Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll files to the project. After that add the lines:

using Microsoft.WindowsAPICodePack.Taskbar;

to your using statements. When the clock starts running I create the progress bar in the taskbar with:

// Initialize progress bar if(TaskbarManager.IsPlatformSupported) { TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal); TaskbarManager.Instance.SetProgressValue(0, (int)this.totalTime.TotalSeconds, this.Handle); }

to stop the progress bar:

// Stop progress bar if(TaskbarManager.IsPlatformSupported) TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);

and finally to update the progress bar on each tick:

// Update progress bar if(TaskbarManager.IsPlatformSupported) TaskbarManager.Instance.SetProgressValue((int)this.totalTime.TotalSeconds - (int)this.time.TotalSeconds, (int)this.totalTime.TotalSeconds, this.Handle);

Drawing Rectangles with SpriteBatch

March 29, 2010 C#, Code Snippets, Xna

Just a quick code snippet which adds an extension method for drawing Rectangles to SpriteBatch:

public static class SpriteBatchHelper { static Texture2D pixel; private static void LoadPixel(GraphicsDevice graphicsDevice) { if(pixel == null) { pixel = new Texture2D(graphicsDevice, 1, 1); pixel.SetData&lt;Color&gt;(new Color[] { Color.White }); } } public static void DrawRectangle(this SpriteBatch spriteBatch, Rectangle rectangle, Color color) { LoadPixel(spriteBatch.GraphicsDevice); spriteBatch.Draw(pixel, rectangle, color); } }

C# Extension Methods in your own Library

March 08, 2010 C#, Extension Methods

Normally I use extension methods in C# to extend a library that I did not write and therefore I have no control over. There are situations where it makes sense to use extension methods for a library that you yourself are writing.

For example, when you have interfaces in your library. You want to keep the number of methods in that interface as low as possible so that classes implementing the interface don't have to do a lot of heavy lifting. This means cutting out methods in an interface that are for the most part just syntactic sugar for another method in the interface.

public interface IServiceContainer { void AddService(Type type, Object provider); object GetService(Type type); } public static class IServiceContainerExtensions { public static void AddService&lt;T&gt;(this IServiceContainer services, object provider) { services.AddService(typeof(T), provider); } public static T GetService&lt;T&gt;(this IServiceContainer services) where T : class { return services.GetService(typeof(T)) as T; } public static T GetRequiredService&lt;T&gt;(this IServiceContainer services) where T : class { T service = services.GetService(typeof(T)) as T; if(service == null) throw new ServiceNotFoundException(typeof(T)); return service; } }

All of the methods in IServiceContainerExtensions are just helper methods for method in IServiceContainer. By making them extension methods in our own library though, we've made the barrier to entry lower. Other people can implement the interface and in a sense "inherit" the helper methods as well.