Tutorials & Guides

May 07 2012

A guide to creating class libraries in c#: The Caesar Cipher part four


So we can use our dll file in another project? Indeed. Start up a new console project (I loaded up another instance of visual studio) and call it CaesarTest. Now the important bit is to reference your newly created library. To do this, complete the following steps: Right click on references in the solution explorer and choose “Add reference” Click on browse Locate your dll file (Should be located in CaesarLib\bin\Debug\) and click ok So we can use it now? Yup, using our library is as simple as importing the namespace. Have a look at this simple program I put together to test the library This code produces the output: Is this secure? NO. The caesar cipher shown here is only used to demonstrate a very simple use case for creating a class library. It is easily broken and should NOT be used for any security purpose whatsoever. Summary So what did we learn about? We learnt what a class library is and why it is useful We learnt about the basic caesar cipher We learnt how to implement the caesar cipher as a class library And finally, we learnt how to bring an external library into a new project Thank you for following this tutorial, I hope it helped you in some way If anybody has any questions/feedback, please do not hesitate to contact me (You can use the contact buttons at the top of this page). Download The project files are available to download. Just use the button below.

Read more

May 07 2012

A guide to creating class libraries in c#: The Caesar Cipher part three


Finally it is code time The idea with a class library is that you define a bunch of public types, which are then available for use from any program that references the dll. We will call our class the “CaesarCipher” and it will have two simple methods, Encrypt(string plaintext) and Decrypt(string ciphertext). Have a look at the codelisting: Lets break it down…first the constructor Its pretty simple going. We initialise the _shiftValue variable, but we modulus by 26 to give us a number in the range of 0..25 so that we can easily apply it to the alphabet (If you didn’t know, the English alphabet has 26 letters ) Then we use String.Substring() to get the first part of our alphabet by grabbing the last bunch of characters (i.e. for a shift of 4, we would get WXYZ). Then we use Substring again to chop off these last few letters (with a shift of 4, we would end up with ABCDEFGHIJKLMNOPQRSTUV). The encrypt and decrypt methods are very similar. One thing to note is that we are converting all letters to upper case (so they are compatible with our alphabets) and ignoring all characters that are not letters. (indexOf returns -1 if the character is not found). The only difference between the two methods is that we swap the arrays around in the indexOf and Append calls. Just “swap the alphabets” to convert it to a decryption. So thats it? Yup. Build it and go to the output folder and you should find your DLL! As for how to use it? Well… that can only come in part 4

Read more

May 07 2012

A guide to creating class libraries in c#: The Caesar Cipher part two


So what`s this caesar cipher thing? No. It is not a kind of salad. It is a very very simple encryption technique from ancient times. More specifically it is a kind of substitution cipher, and all that means is that it works by replacing each letter of the plaintext with something else, thus making the text unreadable (ciphertext). What do you mean plaintext and ciphertext? The time has come to define some simple cryptography lingo: plaintext : Some kind of message that you want to obscure and make unreadable using encryption. ciphertext : The message after it has been encrypted. This should be unreadable to anybody who does not possess the decryption key. key : A secret phrase or other information that is used to encrypt/decrypt plaintext/ciphertext. Ok, so show me how it works Its very simple. The algorithm works by swapping each character with another character. It chooses based on a simple table produced by shifting the alphabet by a certain amount. Check out the following example:SHIFT = 4 ABCDEFGHIJKLMNOPQRSTUVWXYZ WXYZABCDEFGHIJKLMNOPQRSTUV The idea is very simple. We have used the shift 4, which means we shift the bottom alphabet by 4 characters. So now it begins with WXYZ and ends with V. All we have done is move the last 4 characters to the start. Using these two alphabets to encrypt a plaintext is very simple. You match each character with the top row, and the corresponding character on the bottom row becomes part of the cipher text. Lets look at the following example.PLAINTEXT = SEGFAULT SHIFT = 4 ABCDEFGHIJKLMNOPQRSTUVWXYZ WXYZABCDEFGHIJKLMNOPQRSTUV S = O E = A G = C F = B A = W U = Q L = H T = P CIPHERTEXT = OACBWQHP Totally mixed up heh. To decrypt the plain text you just flip the alphabets and go through the process again, like this:CIPHERTEXT = OACBWQHP SHIFT = 4 WXYZABCDEFGHIJKLMNOPQRSTUV ABCDEFGHIJKLMNOPQRSTUVWXYZ O = S A = E C = G B = F W = A Q = U H = L P = T PLAINTEXT = SEGFAULT Thats simple enough. Where can I find more information? Wikipedia has a rather good article on this stuff. Have a look at the caesar ciphers more complex cousin, the Vigenére cipher too. This is all very well, but where is the code? In part 3 I will show you how to make this into a class library!

Read more

May 07 2012

A guide to creating class libraries in c#: The Caesar Cipher part one


So what are these class library things? A class library is a way to bundle up all of the types in a project into a single file called a class library. The idea is that you can then give this DLL file (DLL stands for dynamic linked library) to other developers who can reference it in their own applications and make use of your types. But what use is that? So, suppose that I had made some kind of awesome library (such as a really bad cryptography library) and I wanted anybody who was daft enough to be able to use it, but I didn’t really want to distribute my source code and project files. Well in that case, I could just offer a download of my DLL file and other people would be able to use it! Sounds good, tell me more In this example I am going to show you how to build a simple class library with just one class in it, which implements the caesar cipher (More on that in part 2!) How do I get started? First of all, please note that I am using Microsoft Visual Studio 2010 Professional for this tutorial. I believe other IDEs will behave in a similar manner, but you may have to do a little bit of research to figure out how to start a class library project if you aren’t using MSVS 2010. With that said, when you start a project, you will want to select the right template. It can be found under “Visual C# >> Windows” and you need to click “Class Library” and enter a name for your project (I called mine “CaesarLib” and I suggest you do the same if you are following along) Here is a picture to help you find the correct template : When the project loads up, you will have a single Class1.cs file in your project explorer. I deleted that file to give myself a blank slate. I will later create one source file for each type I create. Show us some code man! In the next part I will talk about the caesar cipher and show you how to implement it.

Read more

Apr 30 2012

“One program, Four ways” – A beginner’s guide to abstraction and interfaces in C# (Part three)


So what’s next? So, in part two we refactored our program and de-cluttered our main method, and made our code a bit better and easier to read, but there were still a few problems. Our program class was still full of stuff which should be put elsewhere. Lets have a look at our objectives for the next version: De-clutter the whole program class. Lets get it as clean as we can Make classes for each of the string processing methods that we have now Make a class to handle the displaying of coloured strings to the screen Let us begin..:D This time around I have put each class into a file of its own. One class per file is how myself and most people usually work in C#. I have kept them all in the same namespace for simplicities sake. Moving the functionality from the methods to classes was a very simple job. The body of the methods didn’t need to change at all. Have a look at the following classes: And there we have it. Three instance classes which separate the functionality out and away from the Program class. It may seem a bit extreme to put them in their own class with only a single method, but it isn’t really, and it doesn’t take much extra work to do it, but the extra functionality afforded to you by doing it is immense. Now you are able to give your string processors their own sets of data to work with, and they are fully independant now. They are only dependant on themselves, but we haven’t lost any functionality. This can only be a good thing. I have thought about this, and I have extracted the two display methods from the program class and put them into their own class. Take a look: Now you may notice that this class contains BOTH of the display methods and you may be wondering why I didn’t make two classes for this? Well, if you think about the single responsibility principle, I think this class is okay, because the class as a whole still only has one responsibility if you think about it. Its responsibility is to display strings to the user and it uses two methods to fulfill this responsibility. Yup! And its all because we have taken all extraneous information out of it and put it somewhere else. Have a look: Much cleaner now, and because of that, it is actually easier to tell at a glance what it does. We are making good progress, but there are still some problems First of all, let us not forget the program that we started with back in part one, it consisted of just a main method with all of this stuff written inside of it. Sure it did the same thing, but if you needed to continue working on the code, would you prefer to improve this new version, or the original version? Which do you think would be easier to work with? I hope you picked this one. One of the problems with this version is that the StringDisplayer class has to rely on the Program class to feed it strings to display, but it shouldn’t have to really since the other classes all provide strings. It is like we have a middle-man that can be got rid of. Of course we could have each of the string generating classes inside of StringDisplayer, but that isn’t really a good idea either. For one thing it violates the single responsibility principle, because StringDisplayer should be concerned only with displaying strings and nothing more. Also it would be difficult to maintain as you added more string generating classes. Every time you added a new string generating class you would have to update the StringDisplayer class, and this is bad and it makes your code harder to manage. In the next part I will demonstrate how to use interfaces to take this to the next level.

Read more

Apr 30 2012

“One program, Four ways” – A beginner’s guide to abstraction and interfaces in C# (Part two)


Shall we continue? In part one we set up a simple program and we illustrated some issues with the code. In this part I will introduce you to a slightly better version of the same program. Let us talk about what we are going to do. We have a couple of objectives: Get rid of all the clutter from main Seperate the string processing procedures into their own methods, to make them easier to combine Setup an easier way to display strings in different colours Lets make some methods Did you notice a pattern in the first program? We were dealing with a single string, and with each different type of output, all we were doing was outputting a single string. This is a good candidate for a method. We can write a bunch of methods that each take in a string and each return a string. For example: This is the simplest example of extracting it to a method. Sure it might seem a bit daft to extract a single line and put it in a method, but what you are doing is taking that responsibility away from main. Putting it in its own method allows you to update the method with new code, without breaking everything else that uses it, and also without cluttering anything that uses it. The idea here is to move the responsibility away from main, and be able to re-use this bit of code as much as possible. Lets have a look at another example: This is a better example, now we have a whole bunch of code which has been removed from the main method and put in its own little box. It has nearly the same signature as before, but it has a different name. The idea with methods is that somebody should be able to tell exactly what a method is for, and how to use it just by looking at the signature and not looking at the actual implementation, and we can see that our signature does this. If we look at just the signature we are able to work out exactly what the method does AND how to use it. Its self explanatory, and all methods should be like this. And finally the reverse string method! It does the same thing as before, but again it is factored out into its own method, and the signature of the method tells us exactly what it does and exactly how to use it! But what about the pretty colors! Don’t worry! This can be factored out too, but we have to do it slightly differently, as changing the colour doesn’t take in a string and it doesn’t need to return anything. What would be great is if we had a way of telling the console to display a string in a certain color, and then to reset the color back afterwards. It will be something that we can re-use over and over again. This method, if you look at its signature, takes an input and a colour and displays the input in the specified colour. It makes use of the ConsoleColor enum which is part of the BCL. Once it has displayed the string it then resets the colour to what it was before. As a way of demonstrating a good candidate for method overloading, we can create new version of this method, which defaults the colour to white: All it does is call the other version using the provided input, but with white as the parameter for the colour. Simple enough But wait! What happened to main!? Don’t worry, I saved the best bit until last. Using the code above we can effectively clean up the main method See how much cleaner that is now. It is now easier to follow the logic of what main is actually doing. It is more of an overview of logic rather than an explicit list of each and every step. It is also self documenting to a degree, and that is down to how the signatures for each method had been written. If the small parts are named well, then the whole will be much easier to read. Since we are now dealing with strings and black boxes (the methods), it is now easier to combine functionality. Now if the boss comes in and says “OMG WE NEED IT TO BE IN RED AND UPPERCASE”, we know we can easily do it with the following line: Simples! Full source code listing So there are still problems? You bet! The big problem we have here is how the Program class has so much clutter in it. It has 5 extra methods on it. A good tip to try and remember is to try and keep your classes as clean as possible and to try and give them only one responsibility. This is known as the SINGLE RESPONSIBILITY PRINCIPLE which is often referred to as SRP for short. In general, you will want to try and keep your Program class as simple as possible since its only responsibility is to start the application. Its responsibility isn’t really to display anything or perform any program logic. What would be great is if we were able to separate all of our logic into a set of classes. We will do this in part 3!

Read more

Apr 29 2012

“One program, Four ways” – A beginner’s guide to abstraction and interfaces in C# (Part one)


Introduction A few of the people I know who are currently learning C# and object oriented programming and design have been sharing with me their problems in getting their heads around object oriented design. I have decided to try and help by working up an example which shows a program written 4 ways; Starting out with bad design and illustrating the problems with the design, each iteration will be a more advanced version until I feel I am happy with the overall design. So lets begin! For myself, the process of learning how to write better code was an iterative one. When you are just starting out it is easy to code yourself into a corner with object oriented programming. You find yourself against a wall of problems. Over time you work out how to solve the problems and eventually you start avoiding the problems before they become a problem altogether. The example I am going to show has some problems. In this part of the tutorial I will show you the code for a simple program and illustrate some problems that it has. By problem, I mean some kind of problem in the design, and this is important to realise. Each of the four editions of the program will produce the same output, but they will work differently under the hood. The difference will be how easy it is to alter / expand / remove functionality in them, so when I say code has a problem, it means that it is difficult to change or expand the program, and changing the code it to a better design will make it easier to modify and expand it. This is the whole point of object oriented design. The process of changing the code in such a way to improve the design without changing the output is called refactoring. The program! I decided to keep the program in question very simple. All it does is take some input from the user, and then displays the input back to the user in a number of different ways. Check out the source code below:- When you run it, you get the following output: As you can see it is very simple, but it does have a couple of issues. Problem one: Adding functionality is tricky If we wanted to add more functionality to this program in order to show the input in another way (For example in a different colour or by swapping words around) then our only way would be to add additional code, like this: Of course, it isn’t too difficult to do it in this example, but this is just filling up our main method with lots of stuff that isn’t really relevant. Imagine that these bits of functionality are only small parts of a much larger program (A large program with lots of more important parts) and it becomes clear that adding functionality in this way is going to make things less manageable down the line. Problem two: Combining functionality Suppose that we wanted to have an extra line of output, but this time it displays the input text in reverse AND in capitals AND in green. Of course we can do this easily by adding extra lines to our program as follows: Ok so that works fine right? NO! Whilst the program displays the expected message, this way of coding is not a good idea. There is an important rule of programming that it is a good idea to live by, and it is DON’T REPEAT YOURSELF often abbreviated to DRY. Here we have repeated ourselves by writing three bits of functionality twice, and this is never a good idea, because we want both versions of the functionality to behave the same way, which means if we change one version we have to go back and change the other version too, and this is more difficult to manage. But the program works… Yep, but now suppose your boss comes in and says “Ok, so we need it to show in green, in lowercase, but not in reverse” or “we need it in reverse and uppercase, but not in green”. For each of these problems you have to write a big chunk of code and it can very easily become unmanageable. So what`s the solution then? The solution is to refactor the code and improve its design. We will look at that in part two.

Read more