Rick van den Bosch - Blog

... on .NET, software architecture, software development and whatnot

Recent Posts

Tags

News

  • Live space

    Photo blog

    Follow me at twitter

    Rick  van den Bosch

    LinkedIn profile

    Add to Technorati Favorites

    Disclaimer
    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Community

Email Notifications

Blogs I read

Interesting links

Archives

May 2005 - Posts

HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

The following method returns the MD5 hash for any given string. For instance for a password. It might be of some assistance when you're trying to validate user credentials but you don't want to store the password readable in the database.

For this method, you'll need the following using statements:

using System;
using
System.Text;
using
System.Security.Cryptography;

...

public
string EncodePassword(string originalPassword)
{
  //Declarations
  Byte[] originalBytes;
  Byte[] encodedBytes;
  MD5 md5;

  //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  md5 = new
MD5CryptoServiceProvider();
  originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  encodedBytes = md5.ComputeHash(originalBytes);

  //Convert encoded bytes back to a 'readable' string
  return
BitConverter.ToString(encodedBytes);
}

Hmmm... I seem to write comments when I'm trying to explain something ;)

Commenting your code - The sequel

As Ernst put it in the comments: we opened a can of worms here!
In my previous post about Commenting your code, I stated you should not comment your code. Of course, this is nonsense. The reason I stated that, however, isn't. And I didn’t only say that because I would get some attention ;)

Too many times, I see complete useless naming of variables, classes, methods and so on. Because of this incomprehensible naming the developer who wrote the code then has to place enormous amounts of comments between his code to keep it even remotely understandable, even to himself. This way it becomes a completely unreadable mess. So I started out by saying: don’t comment. This is because I think it’s the first thing you have to keep in mind: write your code so it will be completely readable without any comments.

My next statement about commenting would be: pick comment-spots carefully. Sometimes you can’t choose method names, or that what you are trying to do is not easily readable from your code, whatever name you give to the diverse participants. Then and only then are you allowed to place comments in your code. This way, you minimize the amount of (useless) comments someone has to wrestle to, because in 80 percent of the time, your code will do the talking. The last 20 percent can be taken care of by comments, which you carefully added…

Commenting your code

There are several ways to comment your code. There’s the style where you place comments on the same line as the code. This might get less readable, because there’s some horizontal scrolling involved when your statements get longer. An example:

string s;               //Declare string

s = e.Message;          //Assign exception message to string s


Another way to place comments in your code is to place every comment on its own line. This is less readable when you get long methods, because your methods will get twice as long because of the comments! An example:

//Declare string

string s;

//Assign exception message to string s

s = e.Message;

 

My thoughts about commenting are: don’t. I think naming should be so readable that every line of code makes sense. Use the C# ‘three-slashes-comment-block’ to explain what a method does which parameters it takes and, if necessary, what it returns. The above given code example would look like this:

string exceptionMessage;

exceptionMessage = exception.Message;


This piece of code doesn’t really move mountains, so it’s kind of hard to find a good descriptive piece of text for it. I’ll leave that up to your own imagination ;).

 

You see that, by naming the Exception ‘exception’ in stead of ‘e’, it is instantly much clearer what it contains. The string is now called ‘exceptionMessage’ which leaves very little place for argument as to what this variable would contain. Therefore the line where the exception message is assigned to the string doesn’t need any comments. This eliminates all comment within your code, except for maybe the occasional exotic function you call, where you need to specify why or how you’re calling it…

HOWTO: Draw your own string (URL, copyright) on each displayed picture in an ASP.Net website

The AdRotator .Net provides can be used to show a different image each time a page is visited. You could write a webpage which does this for you, but it’s probably not very useful. Although you need to change the XML file when changing the images to be showed when you use an AdRotator, but that's not the issue here.
Something .Net doesn’t deliver is a control to add your own text to an image when it is displayed on a webpage. And that’s exactly what we will be doing in this HowTo.

Below is the code I placed inside the page load of a webpage called showimg.aspx. To display images with the text I want to print on them, you don’t use <IMG src=”test.jpg”/>, but instead you use <IMG src=”showimg.aspx?image=test.jpg”/>.

Please note: this code is illustrative. Normally you would perform a number of checks. For instance check if the querystring is filled, if the image exists, if the text will fit the image, and so on…

  //Const declarations
  const string outtext = "bloggingabout.net/rick";
  //Variable declarations
  string img;
  Image image;
  Graphics graphics;
  Font font;
  SizeF textSize;
  SolidBrush brush;

  //Set font & brush and get image from QueryString
  img = Request.QueryString["image"];
  font = new Font("Verdana", 9);
  brush = new SolidBrush(Color.Black);

  //Opening the specified image from the images folder
  image = Image.FromFile(Server.MapPath("images/" + img));
  //Create graphics object for painting
  graphics = Graphics.FromImage(image);
  //Get the size the text will be with the defined font
  textSize = graphics.MeasureString(outtext, font);
  //Set SmoothingMode to AntiAlias
  graphics.SmoothingMode = SmoothingMode.AntiAlias;
  //Draw the string in the lower right corner of the image
  graphics.DrawString(outtext, font, brush, 
                      image.Width - textSize.Width,
                      image.Height - textSize.Height);
  //Dispose used objects
  graphics.Dispose();
  font.Dispose();
  brush.Dispose();

//Writing the image to the browser as the response:
  //Set contenttype to image
  Response.ContentType = "image/jpeg";
  //Save the changed image to response
  image.Save(Response.OutputStream, ImageFormat.Jpeg);
  //End repsone: it's done ;)
  Response.End();
  //Dispose the image object
  image.Dispose();

HOWTO: create an animated GIF using .Net (C#)

.Net (at least 1.1, they might incorporate it in 2.0) does not give you possibilities to create animated GIFs through GDI+. But there are ways to make them! This solution is one I used myself, and I'm very pleased!

//Variable declaration
StringCollection stringCollection;
MemoryStream memoryStream;
BinaryWriter binaryWriter;
Image image;
Byte[] buf1;
Byte[] buf2;
Byte[] buf3;
//Variable declaration

stringCollection = a_StringCollection_containing_images;

Response.ContentType = "Image/gif";
memoryStream = new MemoryStream();
buf2 = new Byte[19];
buf3 = new Byte[8];
buf2[0] = 33;  //extension introducer
buf2[1] = 255; //application extension
buf2[2] = 11;  //size of block
buf2[3] = 78;  //N
buf2[4] = 69;  //E
buf2[5] = 84;  //T
buf2[6] = 83;  //S
buf2[7] = 67;  //C
buf2[8] = 65;  //A
buf2[9] = 80;  //P
buf2[10] = 69; //E
buf2[11] = 50; //2
buf2[12] = 46; //.
buf2[13] = 48; //0
buf2[14] = 3;  //Size of block
buf2[15] = 1;  //
buf2[16] = 0;  //
buf2[17] = 0;  //
buf2[18] = 0;  //Block terminator
buf3[0] = 33;  //Extension introducer
buf3[1] = 249; //Graphic control extension
buf3[2] = 4;   //Size of block
buf3[3] = 9;   //Flags: reserved, disposal method, user input, transparent color
buf3[4] = 10;  //Delay time low byte
buf3[5] = 3;   //Delay time high byte
buf3[6] = 255; //Transparent color index
buf3[7] = 0;   //Block terminator
binaryWriter = new BinaryWriter(Response.OutputStream);
for (int picCount = 0; picCount < stringCollection.Count; picCount++)
{
  
image = Bitmap.FromFile(stringCollection[picCount]);
  
image.Save(memoryStream, ImageFormat.Gif);
  
buf1 = memoryStream.ToArray();

  
if (picCount == 0)
  
{
      //only write these the first time....
     
binaryWriter.Write(buf1, 0, 781); //Header & global color table
      binaryWriter.Write(buf2, 0, 19); //Application extension
  
}

   binaryWriter.Write(buf3, 0, 8); //Graphic extension
   binaryWriter.Write(buf1, 789, buf1.Length - 790); //Image data

   if (picCount == stringCollection.Count - 1)
   {
      //only write this one the last time....
     
binaryWriter.Write(";"); //Image terminator
   }

   memoryStream.SetLength(0);
}
binaryWriter.Close();
Response.End();



Edit
To illustratie te poor quality I'm talking about, I've added an animated gif created dynamically using the code above, based on a directory containing some source images. Look at the 'raster' in the darker images... (the source images were solid filled 200 x 200 GIF's, created using Paint.Net, where they look fine)





Edit2
Damn Paint.Net! I make a test-image: looks great. I save it as a GIF: still looks great. Use it in my anigif-code: no more greatness. I reopen the file in Paint.Net: then it's fubar! Creating the testfiles in oldskool Paint solves this (because you only have GIF-supported colors in your toolbar)...

When you are converting a file to a GIF, old Paint warns you because you might be losing color information, Paint.Net does not. Paint reloads the file the way you saved it so you see what remains. Paint.Net does not. These are two wannahaves on Paint.Net for me!



Edit3
Thanks to Dennis for pointing out a small glitch in my type-work.
It should have been 'picCount == stringCollection.Count - 1'.