Sunday, June 5, 2011

A simple way to remove HTML tags from a text.

Code:
string RemoveHTML(string text)
{
string cleanString = text;
//Iterate through the whole text as long as it have '<' and '>'
while (cleanString.Contains('<') && cleanString.Contains('>'))
{
//Getting the indices of '<' and '>'.
int openIndx = cleanString.IndexOf('<');

int closeIndx = cleanString.IndexOf('>');
//Surrounding the '<' and '>' with '^' and '~' respectively.
cleanString = cleanString.Insert(openIndx, "^");
cleanString = cleanString.Insert(closeIndx + 2, "~");
//Getting the indices of '^' and '~'.
openIndx = cleanString.IndexOf('^');
closeIndx = cleanString.IndexOf('~');
/*Clean all the text between '^' and '~'. This is meant in order to make a place holder in the text that will be replaced with a space.*/
cleanString = cleanString.Remove(openIndx , closeIndx - openIndx + 1);
//Replacing the resulting "^~" placeholder with a space.
cleanString = cleanString.Replace("^~", " ");
}
//Cleaning the text from "\n".
cleanString = cleanString.Replace("\n", " ");
//Cleaning the text from heading and trailing spaces.
cleanString = cleanString.TrimStart().TrimEnd();

return cleanString; //Return the all clean text.
}


Usage:
string cleanText = RemoveHTML("Your Text with html goes here");
I hope this helps, Silver Geeks. Let me know if you have any comments. :)

Monday, May 30, 2011

Highlight a specific word in a TexlBlock control - Silverlight.

Here's a very simple method to highlight a certain word across a tex block's text:
void HighlightInnerText(TextBlock control, string HighlightingKey)
{
//Looping through words after splitting them with an empty character.
string[] strArr = control.Text.Split(' ');
//Clearing the Inlines list of the textBlock.
control.Inlines.Clear();
for (int i = 0; i < strArr.Length; i++)
{
Run run = new Run();
if (strArr[i].ToLower() == HighlightingKey.ToLower())
{
//Define a Run to wrap the keyword and add it to the textBlock.
run.Text = HighlightingKey + " ";
run.FontWeight = FontWeights.Bold;
run.Foreground = new SolidColorBrush(Colors.Red);
}
else
{
//Define an Inline and add the text to it directly.
if (i == strArr.Length)
{
run.Text = strArr[i];
}
else
run.Text = strArr[i] + " ";
}
control.Inlines.Add(run);
}
}


Now we use it in a very simple and a clear way:
HighlightInnerText(_yourTextBlock, "Keyword");

I hope that helps, silver geeks :) ... Let me know if it helped.