.

Saturday, October 11, 2008

Show message box in ASP.NET

Show message box in ASP.NET

I've written a simple function which uses JavaScript.

private void ShowMessageBox(string Message)
{

Label lblMessageBox = new Label();

lblMessageBox.Text =

"";

Page.Controls.Add(lblMessageBox);

}

To call out the message box, just write this:

ShowMessageBox("Hello world!");

The problem with this is that I can't customize the message box. I can only pass in the message as parameter, but not changing the title, the button text or image.
Message box

Wednesday, October 8, 2008

C# - Create a thread to run an process or operation in the background.

C# - Create a thread to run an process or operation in the background.

Using threads is an easy way to stop your user interface from freezing up. In C# .Net creating a thread is as easy as draging and dropping. The component to be used is the "BackgroundWorker" that is located in the Components section of your toolbar.
Steps for using threads.

  • Create a new Windows Form Project.
  • Add 2 buttons to your form. One to start the thread and one to stop it.(btnStartThread, btnEndThread).
  • Add a BackgroundWorker component to your form.
Image

  • Create “Click” event handlers for both the buttons. (Go to the properties window, click on the event icon and then dbl-click on the event handlers you want created. ).
Image

  • Create a “DoWork” and “RunWorkerCompleted” event handler for the BackgroundWorker.
Image

  • Change the BackgroundWorker’s WorkerSupportCancellation property to true. This will enable the cancellation of a running thread.
  • Add “using System.Threading;” To the using part of your program. This will be used to create sleep event.
Next add the following example code to the event handlers you just created.


Code for the "Start Thread" button.

private void btnStartThread_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}


Code for the "End Thread" button.

private void btnEndThread_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}


Code for the Process you want to run.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Make the thread result false by default.
e.Result = false;

// listen for when the cancel button is pressed...
while (!backgroundWorker1.CancellationPending)
{
//-- Background Code Begin -----------------------------------
// This is the process that you want to run. My Example will
// wait for 3 seconds.
//------------------------------------------------------------

for (int k = 1; k < 3000; k++)
{
Thread.Sleep(1);
// Test if the thread was canceled.
if (backgroundWorker1.CancellationPending) break;
}

//-- Background Code Ends- -----------------------------------

// This is a result indicator that shows the background
// process has finished successful.
e.Result = true;

// Run the loop once and exit
break;
}


if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
// Do a roll back if you need to.
}
}


Result of the process that was run.

private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("The operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else if ((bool)e.Result)
{
// The operation completed normally.
string msg = String.Format("Process was completed successful ");
MessageBox.Show(msg);
}

}

Tuesday, October 7, 2008

30 Common String Operations in C# and VB.NET

30 Common String Operations in C# and VB.NET – Part II
All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
VB.NET
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
16. Count Words and Characters In a String – You can use Regular Expression to do so as shown below:
C#
// Count words
System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
MessageBox.Show(wordColl.Count.ToString());
// Count characters. White space is treated as a character
System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charColl.Count.ToString());
VB.NET
' Count words
Dim wordColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, "[\S]+")
MessageBox.Show(wordColl.Count.ToString())
' Count characters. White space is treated as a character
Dim charColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, ".")
MessageBox.Show(charColl.Count.ToString())
17. Remove characters in a String - The String.Remove() deletes a specified number of characters beginning at a given location within a string
C#
// Removes everything beginning at index 25
strModified = strOriginal.Remove(25);
MessageBox.Show(strModified);
or
// Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5);
MessageBox.Show(strModified);
VB.NET
' Removes everything beginning at index 25
strModified = strOriginal.Remove(25)
MessageBox.Show(strModified)
Or
' Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5)
MessageBox.Show(strModified)
18. Create Date and Time from String – Use the DateTime.Parse() to convert a string representing datetime to its DateTime equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in various formats.
C#
strOriginal = "8/20/2008";
DateTime dt = DateTime.Parse(strOriginal);
VB.NET
strOriginal = "8/20/2008"
Dim dt As DateTime = DateTime.Parse(strOriginal)
19. Convert String to Base64 - You will have to use the methods in System.Text.Encoding to convert string to Base64. The conversion involves two processes:
a. Convert string to a byte array
b. Use the Convert.ToBase64String() method to convert the byte array to a Base64 string
C#
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);
VB.NET
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)
20. Convert Base64 string to Original String - In the previous example, we converted a string ‘strOriginal’ to Base64 string ‘strModified’. In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:
a. The FromBase64String() converts the string to a byte array
b. Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();
C#
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
VB.NET
Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)
21. How to Copy a String – A simple way to copy a string to another is to use the String.Copy(). It works similar to assigning a string to another using the ‘=’ operator.
C#
strModified = String.Copy(strOriginal);
VB.NET
strModified = String.Copy(strOriginal)
22. Trimming a String – The String.Trim() provides two overloads to remove leading and trailing spaces as well as to remove any unwanted character. Here’s a sample demonstrating the two overloads. Apart from trimming the string, it also removes the "#" character.
C#
strOriginal = " Some new string we test ##";
strModified = strOriginal.Trim().Trim(char.Parse("#"));
VB.NET
strOriginal = " Some new string we test ##"
strModified = strOriginal.Trim().Trim(Char.Parse("#"))
23. Padding a String – The String.PadLeft() or PadRight() pads the string with a character for a given length. The following sample pads the string on the left with 3 *(stars). If nothing is specified, it adds spaces.
C#
strModified = strOriginal.PadLeft(34,'*');
VB.NET
strModified = strOriginal.PadLeft(34,"*"c)
24. Create a Delimited String – To create a delimited string out of a string array, use the String.Join()
C#
string[] strArr = new string[3] { "str1", "str2", "str3"};
string strModified = string.Join(";", strArr);
VB.NET
Dim strArr As String() = New String(2) { "str1", "str2", "str3"}
Dim strModified As String = String.Join(";", strArr)
25. Convert String To Integer - In order to convert string to integer, use the Int32.Parse(). The Parse method converts the string representation of a number to its 32-bit signed integer equivalent. If the string contains non-numeric values, it throws an error.
Similarly, you can also convert string to other types using Boolean.Parse(), Double.Parse(), char.Parse() and so on.
C#
strOriginal = "12345";
int temp = Int32.Parse(strOriginal);
VB.NET
strOriginal = "12345"
Dim temp As Integer = Int32.Parse(strOriginal)
26. Search a String – You can use IndexOf, LastIndexOf, StartsWith, and EndsWith to search a string.
27. Concatenate multiple Strings – To concatenate string variables, you can use the ‘+’ or ‘+=’ operators. You can also use the String.Concat() or String.Format().
C#
strModified = strOriginal + "12345";
strModified = String.Concat(strOriginal, "abcd");
strModified = String.Format("{0}{1}", strOriginal, "xyz");
VB.NET
strModified = strOriginal & "12345"
strModified = String.Concat(strOriginal, "abcd")
strModified = String.Format("{0}{1}", strOriginal, "xyz")
However, when performance is important, you should always use the StringBuilder class to concatenate strings.
28. Format a String – The String.Format() enables the string’s content to be determined dynamically at runtime. It accepts placeholders in braces {} whose content is replaced dynamically at runtime as shown below:
C#
strModified = String.Format("{0} - is the original string",strOriginal);
VB.NET
strModified = String.Format("{0} - is the original string",strOriginal)
The String.Format() contains 5 overloads which can be studied over here
29. Determine If String Contains Numeric value – To determine if a String contains numeric value, use the Int32.TryParse() method. If the operation is successful, true is returned, else the operation returns a false.
C#
int i = 0;
strOriginal = "234abc";
bool b = Int32.TryParse(strOriginal, out i);
VB.NET
Dim i As Integer = 0
strOriginal = "234abc"
Dim b As Boolean = Int32.TryParse(strOriginal, i)
Note: TryParse also returns false if the numeric value is too large for the type that’s receiving the result.
30. Determine if a String instance starts with a specific string – Use the StartsWith() to determine whether the beginning of a string matches some specified string. The method contains 3 overloads which also contains options to ignore case while checking the string.
C#
if (strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase))
MessageBox.Show("true");
VB.NET
If strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase) Then
MessageBox.Show("true")
End If
So those were some 30 common string operations that we saw in these two articles. Since these articles contained only a short introduction of each method, I would suggest you to explore each method in detail using the MSDN documentation. Mastering string operations can save us a lot of time in projects and improve application performance too. I hope this article was useful and I thank you for viewing it.

.