Wednesday, June 4, 2008

Why StringBuilder and not String concatenation?

Reasons:

1. A string is immutable meaning you can't actually change the string.

2. StringBuilder is easy to implement. Using built-in functions such as Append and Insert makes my life easier!


Here's my sample code that uses StringBuilder

by the way, do not forget to include this namespace: System.Text

/*
* must be in this format: 999-999-9999
*/
public string formatPhone(string phone)
{
StringBuilder retVal = new StringBuilder();

char[] charArrayPhone = phone.Trim().ToCharArray();
foreach(char cap in charArrayPhone)
{
if (isCharacterNumeric(cap))
retVal.Append(cap);
}

//must only use the last 10 characters (numbers)
if (retVal.Length>10)
retVal.Remove(0,retVal.Length - 10);

//insert dashes
if (retVal.Length>4)
retVal.Insert(retVal.Length - 4, "-");

//area code is not supplied
if(retVal.Length>8)
retVal.Insert(retVal.Length - 8, "-");

return retVal.ToString();
}

/*
* must be in this format: 99999 or 99999-9999
*/
public string formatZipcode(string zipcode)
{
StringBuilder retVal = new StringBuilder();
char[] charArrayZip = zipcode.Trim().ToCharArray();
foreach (char caz in charArrayZip)
{
if (isCharacterNumeric(caz))
retVal.Append(caz);
}

//must only use the first 9 characters (numbers)
if (retVal.Length > 9)
retVal.Remove(9, retVal.Length - 9);

//insert dash
if (retVal.Length > 5)
retVal.Insert(5, "-");


return retVal.ToString();
}

private bool isCharacterNumeric(char Character)
{
char[] charArrayNumbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
foreach (char can in charArrayNumbers)
{
if (Character == can)
return true;
}
return false;
}

Tuesday, June 3, 2008

Guidelines between CLR and T-SQL

• Use declarative T-SQL SELECT, INSERT, UPDATE, and DELETE statements whenever possible. Procedural and row-based processing should be used only when the logic is not expressible using the declarative language.
• If the procedure is simply a wrapper for declarative T-SQL commands it should be written in T-SQL.
• If the procedure primarily involves forward-only, read-only row navigation through a result set with some processing of each row, using the CLR is likely more efficient.
• If the procedure involves both significant data access and computation, consider separating the procedural code into a CLR portion that calls into a T-SQL procedure to perform data access, or a T-SQL procedure that calls into the CLR to perform computation. Another alternative is to use a single T-SQL batch that includes a set of queries that are executed once from managed code to reduce the number of round trips of submitting T-SQL statements from managed.