Introduction
Hello, and welcome to today’s article. Today, I’d like to talk about ten of the basic .NET Framework functions (or methods) that every VB developer should know; but, before I can do that, I need to talk about Namespaces first.
.NET Framework
According to Microsoft, the .NET Framework is a computing platform that simplifies application development. This tells me nothing, honestly. Basically, the .NET Framework has come into existence to provide the following objectives:
- To provide a consistent, object-oriented programming environment, whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.
- To provide a code-execution environment that minimizes software deployment and versioning conflicts.
- To provide a code-execution environment that guarantees safe execution of code, including code created by an unknown or semi-trusted third party.
- To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.
- To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications.
- To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.
Namespaces
A namespace contains types that you can use in your program. These types are: classes, structures, enumerations, delegates, and interfaces. Here is a list of most of the namespaces found in .NET Framework 4.5.
Now that you have an understanding of both the .NET Framework and what namespaces are, I can start showing you some of the most important (according to me) functions and namespaces that you should know about if you want to be a great VB programmer.
1. Asynchrony
Asynchrony is crucial to any app that depends on certain tasks that may cause bottlenecks or block the rest of your program, better yet, freezing. So, in fact, it makes the application respond quicker while running several tasks in the background.
Async and Await, as quoted from MSDN: “If you specify that a method is an async method by using an Async or async modifier, you enable the following two capabilities:
- “The marked async method can use Await or await to designate suspension points. The await operator tells the compiler that the async method can’t continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.
- “The suspension of an async method at an await expression doesn’t constitute an exit from the method, and finally blocks don’t run.
“The marked async method can itself be awaited by methods that call it.
“An async method typically contains one or more occurrences of an await operator, but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods.”
For more information regarding Async and Await, have a read through an earlier article of mine: Async Programming.
2. String.Split
You can use Split to break a string apart and make many other little strings from it. How does this happen? Well, all you need to have is a delimiter. If you look at normal written language: We use a space as a separator between words so that we know which word starts where. In this case, a space is a delimiter. A delimiter can be any character, such as a comma, a period, a colon, or even a hyphen. It depends on your needs, ultimately. Here is a small example:
Dim SplitString As String = "Milk,Toast,Honey" Dim SplitArr(2) As String Dim i As Integer 'Split at Each Comma SplitArr = SplitString.Split(","c) For i = 0 To SplitArr.Length - 1 MessageBox.Show(SplitArr(i)) Next
If you look at the very first line of the preceding code segment, you will see that an object called SplitString is created. It contains the phrase: “Milk,Toast,Honey”. Now, notice the commas. Those commas are your delimiters. The next line creates an array with three elements (from 0 to 2). This will be used to store each phrase from the original string. An object named i is created; it will be used as a loop counter, a bit later. The next line is where the Splitting process actually happens. I employed the Split method to split at each comma character. Inside the loop, I simply displayed the contents of each array object. It should read:
Milk Toast Honey
The key to working with strings is to know what functions are available. There are actually many string functions available to Visual Basic developers. A detailed list of all of the string functions can be found at: http://msdn.microsoft.com/en-us/library/system.string_methods%28v=vs.110%29.aspx.
3. DateTime.AddDays
You can add any time or date onto an existing date or time. That sounds confusing, almost as the title of the Back to the Future movies! This simply means that if you have an existing date, you can add on to that date to get a future date or time. Now, why would we ever want to do this? It is simple: Any program should be able to compensate for future events. In a sense, your program should be able to see he future and make decisions based on that. Let me use a small example now: Let us say that you have a fruit market. Let us presume further that each of the fruits have expiry dates on them. You should be able to know when those fruit expire so that you can take them off of the shelves and not sell potentially almost rotten fruit to the public. Make sense now? Sure it does!
Our first Adding method is Add Days:
'Add Days Dim dtToday As DateTime 'For Today's Date Dim dtTomorrow As DateTime 'For Tomorrow's Date dtToday = System.DateTime.Now 'Get Today's Date dtTomorrow = dtToday.AddDays(1) 'Add A Day To A Date 'Show Nicely Formatted Date MessageBox.Show("Today is : " & _ dtToday.ToString("mmm-dd-yyyy")) 'Show Tomorrow's Date Formatted The Same Way MessageBox.Show("Tomorrow is : " & _ dtTomorrow.ToString("mmm-dd-yyyy"))
I created two DateTime objects. One is aptly named dtToday for today’s date and the next is named dtTomorrow, for tomorrow’s date. Although tomorrow’s date may be obvious to you, it is not for your program. I stored System.DateTime.Now inside dtToday. This gives me the precise date and time—more on this later—and I used the AddDays method to add one day to today’s date. This gives me tomorrow’s date. I show today’s date in a MessageBox as well as tomorrow’s date.
You will notice that I have made use of the ToString method to format the date like this: “mmm-dd-yyy”. This simply gives me: “25/01/2014”.
As with any class in the .NET Framework, the DateTime class has several properties and methods. Properties are simple settings that you can use to store and retrieve for an object, whereas methods are what that particular object can do. Here is a complete list of all the DateTime Properties and methods:
4. Database Command.ExecuteReader(CommandBehavior.Default)
Extracting data from databases is not complicated at all. Any developer needs to know how to do this because this is essentially what will make your app tick. Here is a small example of extracting information from a database table:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) _ Handles btnSearch.Click Try 'Create A Command To Host Our Query Dim oSelCmd As OleDbCommand = New OleDbCommand 'The Command Only Uses Text oSelCmd.CommandType = CommandType.Text 'Set The Command's Connection oSelCmd.Connection = _ Me.StudentInfoTableAdapter.Connection 'Specify The Command oSelCmd.CommandText = strSearch & strSearchField _ & strSearchValue 'Open Connection Me.StudentInfoTableAdapter.Connection.Open() 'Excute Command Via DataReader Object Dim oDr As OleDbDataReader = _ oSelCmd.ExecuteReader(CommandBehavior.Default) 'Construct A DataTable To Host Returned Values Dim dt As New DataTable 'Declare Counter For Columns Dim i As Integer 'How Many Fields Are There? Dim count As Integer = oDr.FieldCount - 1 'Add Returned Columns To DataTable For i = 0 To count dt.Columns.Add(oDr.GetName(i), _ oDr.GetFieldType(i)) Next 'Add Returned Rows To DataTable Do While oDr.Read() 'Create A New Row Dim r As DataRow = dt.NewRow 'Add All Records Returned For i = 0 To count r(i) = oDr.Item(i) Next 'Add Rows dt.Rows.Add(r) Loop 'Set DataGridView's DataSource To Show 'Found Records Me.dgvStudents.DataSource = dt 'General Exception, Can Narrow It Down Later Catch ex As Exception MessageBox.Show(ex.Message.ToString()) 'Show Error Finally 'Close Connection Me.StudentInfoTableAdapter.Connection.Close() End Try End Sub
This is where all the database communication takes place. I did the following inside the Search button’s click event:
- Created a new command to execute on the database.
- Created a connection to the database, which is stored inside the Table Adapter’s connection.
- Specified my command which is the query I continuously built.
- Opened the connection.
- Executed the command, which is now my query.
- Created a Data Reader object to return the results found, if found at all.
- Created a new Data Table to store the results into. With this, I specified the columns I wanted, and looped through each found result.
- Set the DataGridView’s Data Source property to the new DataTable.
- Closed the connection.
Whatever gets returned is now placed inside the DataGridView, for example.
5. RegistryKey.OpenSubKey
Many people do not know what the Rregistry is, or how to use it. I used to be scared of the Registry. Why? Well, because the Registry is the place where all the settings are saved. It’s like an inventory where all the info about the programs, and the controls are stored. With the following code segment, I explore the HKEY_CLASSES_ROOTExcel.ApplicationCurVer key to determine what version of Microsoft Office is installed. This is where the information about Excel is stored. CurVer means Current Version. Now, we have to get the information out of there and use it to determine our actual comprehensible version. The information is stored like this:
Excel.Application.12
Very few people will know that this actually means Office 2007 because it is the 12th Office to be created. With some string manipulation, we extract the “12” and then do the test to see what version is present on the system. Not too difficult now, is it?
Private Sub Determine_OfficeVersion_2() '/HKEY_CLASSES_ROOT/Excel.Application/Curver Dim strEVersionSubKey As String = _ "Excel.ApplicationCurVer" Dim strValue As String 'Value Present In Above Key Dim strVersion As String 'Determines Excel Version 'Registry Key To Determine Excel Version Dim rkVersion As RegistryKey = Nothing 'Open Registry Key rkVersion = Registry.ClassesRoot.OpenSubKey(name:=strEVersionSubKey, _ writable:=False) If Not rkVersion Is Nothing Then 'If Key Exists strValue = rkVersion.GetValue(String.Empty) 'get Value 'Store Value strValue = strValue.Substring(strValue.LastIndexOf(".") + 1) Select Case strValue 'Determine Version Case "7" strVersion = "95" Case "8" strVersion = "97" Case "9" strVersion = "2000" Case "10" strVersion = "2002" Case "11" strVersion = "2003" Case "12" strVersion = "2007" Case "14" strVersion = "2010" End Select 'Display Result MessageBox.Show("Excel " & strVersion & _ " Installed!") End If End Sub
6. Clipboard.SetText(SelectedText)
Through the years, access to the Clipboard object has become easier and easier. Here is a small example on using the Clipboard to copy, cut, and paste information to and from textboxes:
Private Sub btnClipCopy_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClipCopy.Click If txtSource.Text <> "" Then If txtSource.SelectionLength > 0 Then strSelectedText = txtSource.SelectedText 'put selection on Clipboard Clipboard.SetText(strSelectedText) Else txtSource.SelectAll() 'put all text on Clipboard Clipboard.SetText(txtSource.Text) End If End If End Sub Private Sub btnClipCut_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClipCut.Click If txtSource.Text <> "" Then If txtSource.SelectionLength > 0 Then strSelectedText = txtSource.SelectedText Clipboard.SetText(strSelectedText) 'clear text, for cutting; otherwise, it's same as copy txtSource.SelectedText = "" Else txtSource.SelectAll() Clipboard.SetText(txtSource.Text) txtSource.Text = "" End If End If End Sub Private Sub btnClipPaste_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClipPaste.Click Dim ClipText As String 'store text from clipboard Dim OldText As String 'previous text in textbox OldText = txtDest.Text 'store previous text ClipText = Clipboard.GetText 'get the clipboard contents 'to paste at back of text. 'Otherwise, just say textbox2.text = cliptext txtDest.Text = OldText & ClipText End Sub
7. CultureInfo.GetCultures(CultureTypes.AllCultures)
Globalization is basically the process of making your application culture-friendly. You have to realize that the users of your application may speak a different language than you, and therefore their language adheres to different rules, apart from being a different language. For example, some languages are displayed left to right, while others should be displayed right to left. Now, you have to not only think about the different language, but different currencies, date and time settings, as well as different colours being used with different cultures.
With Globalization, you can make your application useable with any culture irrespective of their language. Here are some more articles on Globalization:
- http://msdn.microsoft.com/en-us/library/vstudio/system.globalization.cultureinfo
- http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx
- http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28vs.71%29.aspx
- http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Globalization/types/CultureInfo.html
Private Sub Form1_Load(sender As Object, e As EventArgs) _ Handles MyBase.Load ' Get & Enumerate All Cultures. ciAllCultures = _ CultureInfo.GetCultures(CultureTypes.AllCultures) Dim ciCurrentCulture As CultureInfo For Each ciCurrentCulture In ciAllCultures ' Display Name Of Each Culture And English Name ComboBox1.Items.Add(ciCurrentCulture.Name & " [ " _ & ciCurrentCulture.EnglishName & " ]") Next End Sub
The first line of code obtains all the cultures and stores them inside the ciAllCultures array. Then, I looped through each of the cultures and loaded them inside the Combobox. Inside the Combobox, I display both the Culture’s native name as well as its English name. The user is now able to select any culture from this list.
8. Generic Lists
According to MSDN, “a Generic List represents a strongly typed list of objects that can be accessed by an index. Provides methods to search, sort, and manipulate lists.” This is very vague and does not tell anyone about a Generic List’s use and advantages. Let me try to explain it better: A Generic List is simply a list that you can make yourself. This list can be anything! An example of a generic List will be a student list. Do not think of the Student list as containing only the student’s names; it can contain all methods and properties associated with a student object.
This means that you can create a Student class, supply some properties to it, and then make a list of Students that will contain all the Student object’s properties and methods.
An example follows:
Public Class Students Private strStudentSurname As String Private strStudentName As String 'Student Name Property Public Property StudentName() As String Get Return strStudentName End Get Set strStudentName = Value End Set End Property 'StudentSurname Property Public Property StudentSurname() As String Get Return strStudentSurname End Get Set strStudentSurname = Value End Set End Property 'ToString Method Public Overrides Function ToString() As String Return "Name: " & StudentName & _ " Surname: " & StudentSurname End Function 'Equals Method Public Overrides Function Equals(objTemp As Object) _ As Boolean If objTemp Is Nothing Then Return False Dim objAsStudent As Students = _ TryCast(objTemp, Students) If objAsStudent Is Nothing Then Return False Else eturn Equals(objAsStudent) End If End Function End Class
I added Properties for the Student Class. This gives us a way to get and set the Student name and Surname. Next, I added some methods. These methods enable us to check an object’s existence inside the list, as well as to return the appropriate object when referenced.
Now, let’s use this list of Students inside our form!
Import the Generic Lists namespace:
Imports System.Collections.Generic
Create the physical list:
'Create List Of Students Private lstStudents As List(Of Students) = _ New List(Of Students)
This creates a list of students, with all its associated properties and methods.
Adding items to a Generic List
Add the next code segment to a button:
Private Sub btnAdd_Click( sender As Object, e As EventArgs) _ Handles btnAdd.Click 'Add Supplied Student Details To List lstStudents.Add(New Students() With { _ .StudentName = txtStudentName.Text, _ .StudentSurname = txtStudentSurname.Text _ }) txtStudentName.Text = "" txtStudentSurname.Text = "" End Sub
This adds whatever was entered in the txtStudentName and txtStudentSurname textboxes and adds it to the generic List.
9. System.IO
System.IO allows us access to a PC’s filesystem. Here is a small example:
Private Sub AddAllFolders(ByVal TNode As TreeNode, _ ByVal FolderPath As String) Try 'Load All Sub Folders For Each FolderNode As String In Directory.GetDirectories(FolderPath) 'Add Each Sub Folder Name Dim SubFolderNode As TreeNode = TNode.Nodes.Add(FolderNode.Substring _ (FolderNode.LastIndexOf(""c) + 1)) SubFolderNode.Tag = FolderNode 'Set Tag For Each Sub Folder SubFolderNode.Nodes.Add("Loading...") Next Catch ex As Exception MessageBox.Show(ex.Message) ' Something Went Wrong End Try
This example uses System.IO to get all the directories (folders) inside another folder and adds them to a Treeview.
10. Color.FromArgb
I just had to add something form the System.Drawing namespace; the temptation was a bit too much to resist. Obviously, this is not one of the most commonly used functions from the System.Drawing namespace, but it has its uses. The Color.FromArgb method returns an RGB color value plus a transparancy value. RGB means Red Green Blue.
Conclusion
I hope you have enjoyed today’s article. Until next time, cheers!