A Standard CRC-16 and CRC-16 Kermit implementation in C#
Been a while since I posted anything, but here’s an update to my original CRC-16 class that does CRC-16 with CRC-CCITT Kermit code that I posted over on Stack Overflow a while ago. Unlike the code over there this doesn’t have a static look-up table (feel free to get the code from over there if you wanted the static table, but I’m actually not too fond of static look-up tables on example source code though they are more efficient).
If you need for this code to be CLS compliant, you can change the method signature’s return type from ushort to int and it will operate the same (the ushort crc value will be implicitly converted from ushort to int)
I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package
A CRC8 implementation in C#
So I’ve tackled CRC32, CRC16, CRC16-CCITT (and now CRC16-CCITT Kermit) implementations, and found myself wanting a CRC8 class to create checksums for small data (1-2 bytes) sets. Not having ever used or seen CRC8 in use before, I did some reading, and as far as I can tell, I’ve implemented it correctly… It works anyway, so without further ado, here’s my implementation:
This one differs slightly (API wise) from my previous ones, mainly because I was using it for check-summing smaller bits of data, so I made the ComputeChecksum method a params argument instead of a first class array type.
Here’s a sample of how I was using it (and testing it):
bytecrc = Crc8.ComputeChecksum( 1, 2, 3 );bytecheck = Crc8.ComputeChecksum( 1, 2, 3, crc );// here check should equal 0 to show that the checksum is accurateif ( check != 0 ) {Console.WriteLine( "Error in the checksum" );}
I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package
Pre-increment vs post-increment operators
OK, so here’s a question for you that most people should have learned in school, but didn’t. You have to answer this without running to visual studio.
What is the difference between ++i and i++?
What is the output of the following piece of code:
for(inti = 0; i < 5; ++i) {Console.WriteLine(i);}
C#
Is it A)
1
2
3
4
or B)
0
1
2
3
4
I’m sure there are quite a few who would choose A, but this is in fact incorrect (go ahead and run it in visual studio now).
Most of us when we learned C style programming were taught that pre-increment increments the value before taking the value, and that post increment takes the value then increments. After being taught that, pretty much every professor, every code sample, and everybody under the sun used post increment for every single iterative example in existence.
Question is… WHY?
Inside a loop, I cannot see why anyone would use post increment. What is the order of operation? Declare, loop body, compare, increment, loop body, compare, increment, ….
Unlike C++ (where there are there are actually 2 distinct operators: a pre and a post increment operator) C#, has only one generic “increment” / “decrement” operator, so exactly how the operator works is left completely out of our hands (and is handled internally by the framework). As stated in the ECMA spec (page 176 of the 4th edition of the ECMA-334):
The run-time processing of a postfix increment or decrement operation of the form x++ or x– consists of the following steps:
If x is classified as a variable:
x is evaluated to produce the variable.
The value of x is saved.
The saved value of x is converted to the operand type of the selected operator and the operator is invoked with this value as its argument.
The value returned by the operator is converted to the type of x and stored in the location given by the evaluation of x.
The saved value of x becomes the result of the operation.
By comparison, here is what is stated for a pre-increment operation (page 196 of ECMA-334 4th edition):
The run-time processing of a prefix increment or decrement operation of the form ++x or –x consists of the following steps:
If x is classified as a variable:
x is evaluated to produce the variable.
The value of x is converted to the operand type of the selected operator and the operator is invoked with this value as its argument.
The value returned by the operator is converted to the type of x. The resulting value is stored in the location given by the evaluation of x and becomes the result of the operation.
So in the case of post increment, a copy has to be made, the op_Increment is invoked using the copy, the value is returned, and the copy overwrites the original value.
With pre-increment, the value is passed into the op_Increment method, and its value is returned.
In the case of a loop, we are not using the value returned pre-increment, and are therefore only using the increment operation to alter the original value, so using post increment is completely pointless. Why anyone uses it is beyond me. Maybe its a case of not actually understanding whats going on.
There are a few places where it actually makes sense to use a post increment operation, but even these probably have better solutions to them as well:
So the moral of the story is… post increment wisely (have a good reason to use it, otherwise pre-increment).
A C# Command Line Args processing class
The other day I was working on our video game’s content server app. The way its set up is fairly complicated. It basically has 3 modes that it can run in (as a windows service, as a fully blown console shell, or as a windows application).
Being tired of writing long ugly blocks of code for command line arg’s processing, I decided to build out an object (not at all like my last command line parser class) that would manage the command line args in an intuitive manner.
There are Three basic ways to use this class:
Sort of like a dictionary
With one big event handler
By registering specific event handlers
What I typically do is add the args that are passed into the main function into an arraylist or List<string> and simply ask if the list contains this switch or that switch:
As you can see, it still takes quite a bit of code. My first iteration of my CommandLineArgs class parsed out the command line switches and placed everything in a dictionary
staticclassProgram {staticvoidMain(string[] args) {CommandLineArgscmdArgs = newCommandLineArgs();cmdArgs.IgnoreCase = true; // this adds a switch prefix regular expression used to determine // what is a switch and what is not.whats passed in is a normal Regex pattern.cmdArgs.PrefixRegexPatternList.Add("/{1}"); // forward slash or cmdArgs.PrefixRegexPatternList.Add("-{1,2}"); // - / -- optionscmdArgs.ProcessCommandLineArgs(args);if(cmdArgs.ContainsSwitch("myswitch"))) { // ... whatever ... } }}
C#
But that was pretty much just like using the list like I had been doing.
The next iteration added a SwitchMatch event so that when ProcessCommandLineArgs was called, as switches were parsed, it would kick of an event for each match, providing the switch name (minus the switch prefix) and the value of that switch.
By the way, I’m using .NET 3.5 here (notice the nice lambda event handler there… yes, I am lazy and lambda’s lend themselves nicely to how I do things) if you couldn’t tell. If you’re using .NET 1.1 or 2.0 then you can just create an event handler like you normally would.
This worked nicely. Only problem now is that I have to have the huge switch statement in my main class. So in the next iteration I decided it would be nice to be able to register specific switch handlers (one for “/foo”, one for “–bar” and so on.
staticclassProgram {staticvoidMain(string[] args) {CommandLineArgscmdArgs = newCommandLineArgs();cmdArgs.IgnoreCase = true;cmdArgs.PrefixRegexPatternList.Add("/{1}");cmdArgs.PrefixRegexPatternList.Add("-{1,2}");cmdArgs.RegisterSpecificSwitchMatchHandler("foo", (sender, e) => { // handle the /foo -foo or --foo switch logic here. // this method will only be called for the foo switch. });cmdArgs.ProcessCommandLineArgs(args); }}
C#
One other item I should also note is that there is also an InvalidArgs array too. On the events, there is an IsValidSwitch property that will let you know whether or not the switch is valid or not (since the SwitchMatch event is triggered whether or not the switch is valid) so if your command line contains any values that are not directly tied to a switch. For instance if you don’t quote a string with spaces: /foo this is a string like this /foo “this is a string” then /foo’s value will be “this” and is, a, string will all be contained in the invalid args list. If you use a switch prefix not accounted for in your prefix regex list, it will also be added to your InvalidArgs list (ex: yourapp.exe ^switch “values” both ^switch and values will be placed in your InvalidArgs list.
This class accepts the following formats:
<switch prefix>switch=value
<switch prefix>switch value
So in the spirit of sharing, here is my CommandLineArgs class:
Today I wanted to refactor some code that prohibited my application from running multiple instances of itself.
Previously I had use System.Diagnostics.Process to search for an instance of my myapp.exe in the process list. While this works, it brings on a lot of overhead, and I wanted something cleaner.
Knowing that I could use a mutex for this (but never having done it before) I set out to cut down my code and simplify my life.
In the class of my application main I created a static named Mutex (the GUID is irrelevant, just a “globally unique name” that we can use for our application):
Having a named mutex allows us to stack synchronization across multiple threads and processes which is just the magic I’m looking for.
Mutex.WaitOne has an overload that specifies an amount of time for us to wait. Since we’re not actually wanting to synchronizing our code (more just check if it is currently in use) we use the overload with two parameters: Mutex.WaitOne(Timespan timeout, bool exitContext). Wait one returns true if it is able to enter, and false if it wasn’t. In this case, we don’t want to wait at all; If our mutex is being used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 milliseconds), and set the exitContext to true so we can exit the synchronization context before we try to acquire a lock on it. Using this, we wrap our Application.Run code inside something like this:
staticclassProgram {staticMutexmutex = newMutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread]staticvoidMain() {if(mutex.WaitOne(TimeSpan.Zero, true)) {Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(newForm1());mutex.ReleaseMutex(); } else {MessageBox.Show("only one instance at a time"); } }}
C#
So, if our app is running, WaitOne will return false, and we’ll get a message box.
Instead of showing a message box, I opted to utilize a little Win32 to notify my running instance that someone forgot that it was already running (by bringing itself to the top of all the other windows). To achieve this I used PostMessage to broadcast a custom message to every window (the custom message was registered with RegisterWindowMessage by my running application, which means only my application knows what it is) then my second instance exits. The running application instance would receive that notification and process it. In order to do that, I overrode WndProc in my main form and listened for my custom notification. When I received that notification I set the form’s TopMost property to true to bring it up on top.
Here is what I ended up with:
Program.cs
staticclassProgram {staticMutexmutex = newMutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread]staticvoidMain() {if(mutex.WaitOne(TimeSpan.Zero, true)) {Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(newForm1());mutex.ReleaseMutex(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windowsNativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST,NativeMethods.WM_SHOWME,IntPtr.Zero,IntPtr.Zero); } }}
C#
NativeMethods.cs
// this class just wraps some Win32 stuff that we're going to useinternalclassNativeMethods {publicconstintHWND_BROADCAST = 0xffff;publicstaticreadonlyintWM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")]publicstaticexternboolPostMessage(IntPtrhwnd, intmsg, IntPtrwparam, IntPtrlparam); [DllImport("user32")]publicstaticexternintRegisterWindowMessage(stringmessage);}
C#
and our Form1.cs (front side partial)
publicpartialclassForm1 : Form {publicForm1() {InitializeComponent(); }protectedoverridevoidWndProc(refMessagem) { // handle the WM_SHOWME message and bring // this window to the topif(m.Msg == NativeMethods.WM_SHOWME) {ShowMe(); }base.WndProc(refm); }privatevoidShowMe() {if(WindowState == FormWindowState.Minimized) {WindowState = FormWindowState.Normal; } // get our current "TopMost" value (ours will always be false though)booltop = TopMost; // make our form jump to the top of everythingTopMost = true; // set it back to whatever it wasTopMost = top; }}
C#
Creating Fake Enums
In .NET Enums are a strongly typed flag-like object. Flags would normally defined as a macro, or constant variable. The trouble with typical numeric flags is that a) the coder using the flag may or may not know all of the possible values, or b) might accidentally type the wrong constant or macro. Since the flag is just some magic number they may end up with a logic error that may be hard to find under certain circumstances. With Enums I can provide the same logic (some numeric flag) but create a type that I can use to enforce some subset of numbers that are checked at compile time, and can be verified at run time ( Enum.IsDefined ). As with everything, Enums have their faults. What if I want to extend some Enum object (polymorphic Enums?), or give it additional functionality or meta data. Yesterday at work we ran across a case where being able to extend an Enum was mandatory. All of our Enums have numeric and string values, and are typically written like:
the FriendlyName attribute enables you to have both a numeric flag value as well as some human readable value of the enum element other than “One” or “Two” or “SomeEnumValue”(ie: Foo.One.ToString())
Our company uses code generation like most fish use water. We use Enums quite a bit and each Enum type and all of their values are stored in a database which is used by the code generation tool to generate 99% of our business and data layer code. Since our code is generated, if we go in and manually add additional values that don’t need to be stored in the database, our generation tool will blow away any hand written changes on every build. We would have killed to have something like a partial Enum, but alas, no such thing exists.
I set out to try to create a “Fake Enum” class that acted and felt like an Enum but allowed us to extend it by way of the partial class or inheritance. Well after a little poking around, inheritance flew out the window (just over complex without resorting to some generics base type), but the ability to do a partial fake Enum was definitely doable.
Since we were generating these guys, we’d put the class implementation in one file, and our enum like declarations in another. It made it look a bit more “enum” like.
From there, you can use it just like a normal enum except that you now have a built in friendly name that you can access:
Since additional partial classes would be added, I didn’t want to have to provide some functionality of ToString or explicit conversion for each partial class, so I resolved the ability to get the numeric value, string member name value through reflection. Since I had full control over the type, I decided it would be nice to add the FriendlyNameAttribute functionality into my fake enum, so I did.
Its implementation uses .net reflection to iterate over its members and obtain the enum like member and its associated and values (since every member we use like an enum will be a static instance of itself) and additionally its friendly name. actually we could make our fake enum non-numeric based (this would kind of defeat the ability to do a flag like operation) but that wasn’t something needed at the time so we just stuck with int.
To be able to use these objects like a bit field (like enums are), one would need to add the | and & operators so that fields could be combined or extracted (perhaps if I’m bored I’ll add this to a future version).
C# 3.0 Lambda expressions
I’ve finally seen the light for these little buggers. As I wrote in my original post that I really didn’t glean much from the description of lambda expressions that are mentioned in the specification, but I ran across a great article on it on the code project that did a really good job at explaining it.
So my meta blog for the day is a link to that article:
I ran across an article on the code project about a PHP compiler / language extension for .NET.
PHP has an extension for .NET that allows you to use .NET resources in PHP code, but this allows you to use PHP from .NET, with support for native PHP API’s as well as managed compilation. This project may end up making my article on nusoap & C# obsolete, though it should make writing web services in PHP as easy as it is in C#.
» Phalanger Home (now peachpie, link updated to new project) » Code Project Article (long since abandoned)
.NET Reflection
What is reflection? Its the image we seen in a mirror. In .NET however its a system that lets you do at runtime what you would normally do in a text editor or visual studio.
Like most object oriented programming languages, .net has the concept of a “type.” a Type defines what an object is. Whether your using a primitive such as an integer, or a complex data type, each thing in .net has a type that corresponds to what it is.
publicclassFoo {}
C#
This class is of type Foo. Now this class is basically pointless… Why? Well because it has no members. Actually it does have members because everything inherits from System.Object, and System.Object has 12 member methods some have overloads, some are static, some are private some are protected others are public. For the sake of simplicity, we wont discuss System.Object, but will stick only to Foo.
publicclassFoo {privateinta;}
C#
Typically we’d never have a class that looked like this. After all, the compiler would never let us access Foo::a because it is a private member. What does this have to do with reflection you may ask yourself? The rules of the compiler do not apply to reflection.
To understand reflection, you need to understand what a class is, how encapsulation works (what access modifiers are), what a function is and what variables are. We could go a little further, but that’s a good starting point.
Lets take our previous class declaration and spice it up a bit.
publicclassFoo {privateinta;publicintA { get { returna; }set { a = value; } }publicboolBar(stringinput) {returninput == "Baz"; }protectedvoidBing() {Console.WriteLine("I'm not very creative"); } publicFoo() { }}
C#
I’ve given Foo a makeover. It now has a private variable, a public property, a public and a protected method and a constructor. I’ve given Foo a few “members.”
On the surface (which I wont scratch much) reflection allows you to access, modify or invoke members of an object.
In our editor we can do this very easily:
Foof = newFoo();boolb = f.Bar("Baz");
C#
So lets look at what we’re doing here.
Where does Foo come from?
At the top (or bottom, depending on your endianness) of the Reflection world is the Assembly (a dll or exe). .NET assemblies are files that (can) contain namespaces and classes. Each assembly contains a manifest (aka a list) of other assemblies that it references. It also contains info about what classes it contains.
When a .NET application starts up, the framework spiders out and loads each assembly in each referenced assembly’s manifest until everything referenced is loaded into the current AppDomain. If Foo happens to be in one of these dll’s then everything is fine, but what if it isn’t? Lets start there. The AppDomain object contains a list of all loaded “Assemblies” (if you cared to look at whats loaded).
if an assembly is not loaded, we can load it ourselves (unlike other technologies, once an assembly is loaded into the app domain, it cannot be unloaded until the app domain is unloaded).
The Assembly object represents the actual dll or exe file and all that is contained within it. From it, we can get a list of types that the assembly contains:
Type[] types = fooAsm.GetTypes();
C#
or request a particular type:
TypefooType = fooAsm.GetType("Foo");
C#
if fooAsm did not contain a class named “Foo” then GetType would return null.
So, now we’ve loaded the dll / assembly that contained our class, and we’ve gotten a Type object that contains information about the class Foo. From fooType, we can get a list of Foo‘s members:
MemberInfo[] memberInfo = fooType.GetMembers();
C#
MemberInfo is the base class for other member specific things like fields, methods, properties and constructors. MemberInfo has a property named Name which will match the name you give the member at the source code level (variable a, property A, method Bar, and constructor Foo). The System.Type object can also be used to get specific types of members like fields, methods, constructors and properties.
These objects contains more member specific info, such as method parameters, and return type, whether the property has a get and set or just a getter. Each of these Get…() methods also has an overload that takes a BindingFlags parameter. BindingFlags are things that must be considered when looking for a member. if we use the GetMember(field,property,method or constructor) that takes a string, it will look for a member who’s name matches that. Reflection uses more than just the name to find the member that you’re requesting, the binding flags give additional info as to the members access modifier (public / non-public), whether it’s an instance member or a static member, and so on.
In the above code, I get a FieldInfo object which represents the private int variable “a” and I can do the same with the method Bar, the parameterless constructor and the property.
Great right? Who the heck cares? What does this have to do with the price of tea? Lets see…
When we simply wrote the code:
Foo f = new Foo();
the compiler had to locate the assembly that contains foo, load the foo type and create an instance. so lets do the same, but using reflection.
Keep in mind that when we load the assembly at runtime, we cannot simply do:
Foof = (Foo)Activator.CreateInstance(fooType);
C#
unless we add a reference to foo.dll inside visual studio or in our command line compile statement. If we did that, then we don’t need to use reflection. We simply need an instance of foo. At the time we code it, we don’t care what its type actually is. We know we have an instance of it, and can invoke its methods, access its properties and set its members through reflection (using the MemberInfo, MethodInfo, PropertyInfo, FieldInfo‘s that we get from its Type object). With reflection, the boundaries of encapsulation no longer apply (but should still be respected). We can access internal objects, we can access and manipulate private class members, or invoke private methods. Back to the matter of creating the instance of foo… One thing to keep in mind about using Activator.CreateInstance is that it actually uses the objects constructor to create the instance that gets returned, so if you CreateInstance as I have above, make sure you have a parameter-less constructor in your class. Otherwise, you’ll also have to pass in the constructor args as the second set of parameters after the System.Type in CreateInstance.
now lets imagine something crazy that we want to do:
Foofoo = newFoo();foo.a = 32;
C#
we could never write code that would do this unless it was inside a member (method or property) of Foo (a is a private member and therefore isn’t accessible externally to Foo).
so in the above code, we loaded the foo.dll, got the type that we were looking for (Foo), created an instance of it (using Activator.CreateInstance), got the field that we wanted to set, and used the FieldInfo object to set that field in our instance. then for good measures, we got the value that we just set using that field info object.
Each of the derived objects of MemberInfo (MethodInfo, FieldInfo, PropertyInfo, ConstructorInfo, EventInfo) all use the same concepts. First, you obtain an instance of the object you wish to reflect upon, then you obtain the XXXXInfo object that represents the member you want to manipulate, then you use that object to get, set, invoke or handle whatever your trying to do. That necessitates having a valid instance (which you have) and that’s pretty much the basics of using reflection.
This has been an end to end application of the use of reflection. It is not meant as a style guide in how you use reflection. You may very well know everything about the type you’re reflecting upon. In that instance, you may just want to reflectively invoke a method, or set a property. You may actually want to modify the look and feel or a Windows control which provides no public means of achieving what you wish to achieve.
Here’s a little parting sample using the reflection to access an modify various parts of Foo.
AssemblyfooAsm = Assembly.LoadFile(@"C:\My Path\foo.dll");TypefooType = fooAsm.GetType("Foo");objectfoo = Activator.CreateInstance(fooType);MethodInfobarMethod = fooType.GetMethod("Bar", BindingFlags.Public | BindingFlags.Instance);// invoke ( instance, method parameters );boolisBar = barMethod.Invoke(foo, newobject[] { "Baz" });MethodInfobingMethod = fooType.GetMethod("Bing", BindingFlags.NonPublic | BindingFlags.Instance);bingMethod.Invoke(foo, null);PropertyInfopropertyA = fooType.GetProperty("A", BindingFlags.Public | BindingFlags.Instance);propertyA.SetValue(foo, 33);intaVal = propertyA.GetValue(foo, null); // second parameter is for if the property was in indexer
C#
All of which equates to the following lines of code:
I’ve been working on a service at work that will end up being this big cluster of servers that all talk with each other. One of the things I needed was a small CRC checksum for some of the more compact UDP messages that get sent around. I thought about just using the CRC16-CCITT library I already had, but decided on using the standard CRC16 algorithm. Since I posted the CRC32 and CRC16-CCITT implementations I thought I’d post this one too.
If you need for this code to be CLS compliant, you can change the method signature’s return type from ushort to int and it will operate the same (the ushort CRC value will be implicitly converted from ushort to int)
I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package