Skip to content

MikeBevers.be

Putting it out there…

Archive

Archive for May, 2009

The Solution

It’s very useful for generating safe file or folder names from text that a user inputs.

public static string CleanStringForFileSystem(string dirtyFileName)
{
	// first trim the raw string
	string safe = dirtyFileName.Trim();

	// replace spaces with hyphens
	safe = safe.Replace(" ", "-").ToLower();

	// replace any 'double spaces' with singles
	if (safe.IndexOf("--") > -1)
		while (safe.IndexOf("--") > -1)
			safe = safe.Replace("--", "-");

	// trim out illegal characters
	safe = Regex.Replace(safe, "[^a-z0-9\\-]", "");

	// trim the length
	if (safe.Length > 50)
		safe = safe.Substring(0, 49);

	// clean the beginning and end of the filename
	char[] replace = { '-', '.' };
	safe = safe.TrimStart(replace);
	safe = safe.TrimEnd(replace);

	return safe;
}

Auto Generated Properties

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects.

When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property’s get and set accessors.

continue reading…

Reading a file into a Byte[] in .NET 1.1

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(filePath).Length;
byte[] buff = br.ReadBytes((int)numBytes);
br.Close();
fs.Close();

Don’t forget to put the code in a try/catch/finally block. In finally block, call the Close() methods.

continue reading…

The Problem

In version 1 of Entity Framework, there is no “Undo changes” method you can call. So in order to rollback the changes we made, we have to be creative.

In my opinion, we have three ways to archieve this.

continue reading…