You can’t fix stupid…

Posts Tagged ‘Code’

Removing Odd Characters from Strings.

Okay, so I ran into an issue while working on a project at work where an internal web service was returning a large string of text as driving directions that apparently was copied and pasted out of a word document.  The problem was that unicode characters (tiny rectangle representing a list item bullet for example) were strung all throughout the text.  Just imagine a blurb of text that is about 2000 characters but there isn't a single bit of formatting in it.  So I set out to find some code since I knew that someone had to have had this problem at some point or another.  I ran into the following, which ended up being exactly what I was looking for:

The blog post entitled "A .NET Unicode Puzzle (Revised)" had the answers I sought.  Below is an example of the method that I ended up using in my solution.


public static string RemoveUnicode(string s)
{
    try
    {
	string normalized = s.Normalize(NormalizationForm.FormKD);
	Encoding ascii = Encoding.GetEncoding(
	      "us-ascii",
	      new EncoderReplacementFallback(string.Empty),
	      new DecoderReplacementFallback(string.Empty));
	byte[] encodedBytes = new byte[ascii.GetByteCount(normalized)];
	int numberOfEncodedBytes = ascii.GetBytes(normalized, 0,
        normalized.Length, encodedBytes, 0);
	string newString = ascii.GetString(encodedBytes);
	return newString;
    }
    catch
    {
	return s;
    }
}

Dynamic order by with ASC / DESC

Well, today I ran into some old code where I needed to add a dynamic sort to an ASP page. Here was the solution, which required an adaptation to the stored procedure pulling the data... after the initial select and where clause this is placed after the ORDER BY:

        .... create procedure
	....
	@orderby VARCHAR (20) = NULL
	...
	SELECT column1, column2
	FROM table
	ORDER BY
	CASE WHEN @orderby='column1 ASC' THEN column1 END ASC, 
        CASE WHEN @orderby='column1 DESC' THEN column1 END DESC,
        CASE WHEN @orderby='column2 ASC' THEN column2 END ASC, 
        CASE WHEN @orderby='column2 DESC' THEN column2  END DESC,
        CASE WHEN @orderby='' THEN column1 END ASC

I'm passing a potential null parameter into the stored procedure containing a string from the application. So the parameter has "column1 ASC" if I want to sort by column1 in ascending order. Pretty easy... just wanting to make a quick note it.