Monday, October 25, 2010

Finding Controls in ASP.NET Web Page

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

ASP.NET State Management Overview

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.
To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:
  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state
  • Profile Properties
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.
Client-Based State Management Options

The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.

View State

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
You can store values in view state as well. For more information on using View State, see ASP.NET View State Overview. For recommendations about when you should use view state, see ASP.NET State Management Recommendations.

Control State

Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields

ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.
Security noteSecurity Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly. For more information, see ASP.NET State Management Recommendations.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. For more information, see HiddenField Web Server Control Overview.
In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available. For usage recommendations, see ASP.NET State Management Recommendations.

Cookies

A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Security noteSecurity Note
The browser can only send the data back to the server that originally created the cookie. However, malicious users have ways to access cookies and read their contents. It is recommended that you do not store sensitive information, such as a user name or password, in a cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look up the sensitive information on the server.
For more information about using cookies, see Cookies and ASP.NET State Management Recommendations.

Query Strings

A query string is information that is appended to the end of a page URL. A typical query string might look like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
Security noteSecurity Note
Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or send the URL to other users, thereby passing that information along with it. For more information, see ASP.NET State Management Recommendations and How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.
In order for query string values to be available during page processing, you must submit the page using an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST command. For usage recommendations, see ASP.NET State Management Recommendations.
Server-Based State Management Options

ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state management features: application state, session state, and profile properties.

Application State

ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. For more information, see ASP.NET Application State Overview.
Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Once you add your application-specific information to application state, the server manages it. For usage recommendations, see ASP.NET State Management Recommendations.

Session State

ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session. For an overview, see ASP.NET Session State Overview.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages. For more information, see ASP.NET Session State Overview.
You can use session state to accomplish the following tasks:
  • Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  • Store session-specific data on the server for use across multiple browser or client-device requests within the same session.
  • Raise appropriate session management events. In addition, you can write application code leveraging these events.
Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running Microsoft SQL Server. For usage recommendations, see ASP.NET State Management Recommendations.

Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web garden. For more information, see ASP.NET Profile Properties Overview.

Tuesday, October 19, 2010

Common String Operations .NET

Common String Operations in C# and VB.NET 
 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
1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.
C#
    for (int i = 0; i < strOriginal.Length; i++)
    {
        MessageBox.Show(strOriginal[i].ToString());
    }
or
    foreach (char c in strOriginal)
    {
        MessageBox.Show(c.ToString());
    }
VB.NET
For i As Integer = 0 To strOriginal.Length - 1
            MessageBox.Show(strOriginal(i).ToString())
      Next i
Or
For Each c As Char In strOriginal
            MessageBox.Show(c.ToString())
Next c
2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.
C#
    char[] delim = {' '};
    string[] strArr = strOriginal.Split(delim);
    foreach (string s in strArr)
    {
        MessageBox.Show(s);
    }
VB.NET
      Dim delim As Char() = {" "c}
      Dim strArr As String() = strOriginal.Split(delim)
      For Each s As String In strArr
            MessageBox.Show(s)
      Next s
3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.
C#
    // only starting position specified
    strModified = strOriginal.Substring(25);
    MessageBox.Show(strModified);
    // starting position and length of string to be extracted specified
    strModified = strOriginal.Substring(20, 3);
    MessageBox.Show(strModified);
VB.NET
      ' only starting position specified
      strModified = strOriginal.Substring(25)
      MessageBox.Show(strModified)
      ' starting position and length of string to be extracted specified
      strModified = strOriginal.Substring(20, 3)
      MessageBox.Show(strModified)
4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:
C#
    // Single Dimensional String Array
    string[] strArr = new string[3] { "string 1", "string 2", "string 3"};
    // Omit Size of Array
    string[] strArr1 = new string[] { "string 1", "string 2", "string 3" };
    // Omit new keyword
    string[] strArr2 = {"string 1", "string 2", "string 3"};
    // Multi Dimensional String Array
    string[,] strArr3 = new string[2, 2] { { "string 1", "string 2" }, { "string 3", "string 4" } };
    // Omit Size of Array
    string[,] strArr4 = new string[,] { { "string 1", "string 2" }, { "string 3", "string 4" } };
    // Omit new keyword
    string[,] strArr5 = { { "string 1", "string 2" }, { "string 3", "string 4" } };
VB.NET
     ' Single Dimensional String Array
      Dim strArr As String() = New String(2) { "string 1", "string 2", "string 3"}
      ' Omit Size of Array
      Dim strArr1 As String() = New String() { "string 1", "string 2", "string 3" }
      ' Omit new keyword
      Dim strArr2 As String() = {"string 1", "string 2", "string 3"}
      ' Multi Dimensional String Array
      Dim strArr3 As String(,) = New String(1, 1) { { "string 1", "string 2" }, { "string 3", "string 4" } }
      ' Omit Size of Array
      Dim strArr4 As String(,) = New String(, ) { { "string 1", "string 2" }, { "string 3", "string 4" } }
      ' Omit new keyword
      Dim strArr5 As String(,) = { { "string 1", "string 2" }, { "string 3", "string 4" } }
5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function. To use it in C#, you need to add a reference to the Microsoft.VisualBasic dll.
C#
    string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
    MessageBox.Show(strModified); 
VB.NET
    Dim strModified As String = StrReverse(strOriginal)
      MsgBox(strModified)
6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).
C#
    if ((string.Compare(strOriginal, strModified, false)) < 0)
    {
        MessageBox.Show("strOriginal is less than strOriginal1");
    }
    else if ((string.Compare(strOriginal, strModified, false)) > 0)
    {
        MessageBox.Show("strOriginal is more than strOriginal1");
    }
    else if ((string.Compare(strOriginal, strModified, false)) == 0)
    {
        MessageBox.Show("Both strings are equal");
    }
VB.NET
      If (String.Compare(strOriginal, strModified, False)) < 0 Then
            MessageBox.Show("strOriginal is less than strOriginal1")
      ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then
            MessageBox.Show("strOriginal is more than strOriginal1")
      ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then
            MessageBox.Show("Both strings are equal")
      End If
7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).
C#
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
VB.NET
Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)
Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
C#
    // Assuming you have a Byte Array byte[] b
    strModified = Encoding.Unicode.GetString(b);
VB.NET
      ' Assuming you have a Byte Array byte[] b
      strModified = Encoding.Unicode.GetString(b)
9. Convert a String to Char[](Char Array) – To convert a String to Char Array, use the String.ToCharArray() which copies the characters in the string to a Unicode character array.
C#
    char[] chArr = strOriginal.ToCharArray();
VB.NET
      Dim chArr As Char() = strOriginal.ToCharArray()
10. Convert a Char[] to String – A convenient way to convert a character array to string is to use the String constructor which accepts a character array
C#
    strModified = new String(chArr);
VB.NET
      strModified = New String(chArr)
11. Test if String is null or Zero Length – A simple way to test if a string is null or empty is to use the String.IsNullOrEmpty(string) which returns a Boolean value.
C#
     bool check = String.IsNullOrEmpty(strOriginal);
VB.NET
       Dim check As Boolean = String.IsNullOrEmpty(strOriginal)
Create a String of characters accepted from user -
12. Convert the Case of a String – The String class contains methods to convert a string to lower and upper cases. However, it lacks a method to convert a string to Proper Case/Title Case. Hence we will use the ‘TextInfo’ class to do the same.
C#
    System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
    // Lower Case
    MessageBox.Show(textInfo.ToLower(strOriginal));
    // Upper Case
    MessageBox.Show(textInfo.ToUpper(strOriginal));
    // Proper Case
    MessageBox.Show(textInfo.ToTitleCase(strOriginal));
VB.NET
      Dim cultureInfo As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
      Dim textInfo As System.Globalization.TextInfo = cultureInfo.TextInfo
      ' Lower Case
      MessageBox.Show(textInfo.ToLower(strOriginal))
      ' Upper Case
      MessageBox.Show(textInfo.ToUpper(strOriginal))
      ' Proper Case
      MessageBox.Show(textInfo.ToTitleCase(strOriginal))
13. Count the occurrences of words in a String – You can adopt multiple ways to find the occurrence of a word in a string. One of them is to use the String.IndexOf() which is one of the ways of finding the occurrence of the word. In VB.NET, use String.InStr().
Another simple way is to use ‘Count’ property of the Regex.Matches() collection. However this method is slow. We will explore both these methods in the sample.
C#
    // Using IndexOf
     int strt = 0;
     int cnt = -1;
     int idx = -1;
     strOriginal = "She sells sea shells on the sea shore";
     string srchString = "sea";
     while (strt != -1)
     {
         strt = strOriginal.IndexOf(srchString, idx + 1);
         cnt += 1;
         idx = strt;
     }
     MessageBox.Show(srchString + " occurs " + cnt + " times");
    // Using Regular Expression
     System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srchString);
    int count = rex.Matches(strOriginal).Count;
    MessageBox.Show(srchString + " occurs " + count + " times");
VB.NET
      ' Using IndexOf
       Dim strt As Integer = 0
       Dim cnt As Integer = -1
       Dim idx As Integer = -1
       strOriginal = "She sells sea shells on the sea shore"
       Dim srchString As String = "sea"
       Do While strt <> -1
             strt = strOriginal.IndexOf(srchString, idx + 1)
             cnt += 1
             idx = strt
       Loop
       MessageBox.Show(srchString & " occurs " & cnt & " times")
      ' Using Regular Expression
       Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)
      Dim count As Integer = rex.Matches(strOriginal).Count
      MessageBox.Show(srchString & " occurs " & count & " times")
14. Insert Characters inside a String – The String.Insert() inserts text at a specified index location of a string. You can insert either a character or a string at a given index location. For eg: We will insert a string “very” at index 26 in string strOriginal.
C#
    strModified = strOriginal.Insert(26, "very ");
    MessageBox.Show(strModified);
VB.NET
strModified = strOriginal.Insert(26, "very ")
MessageBox.Show(strModified)
15. Replace characters in a String – The String.Replace() removes characters from a string and replaces them with a new character or string.
C#
    strModified = strOriginal.Replace("come handy", "be useful");
    MessageBox.Show(strModified);
VB.NET
      strModified = strOriginal.Replace("come handy", "be useful")
      MessageBox.Show(strModified)
 
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