Strings are immutable - meaning the space allocated in memory is fixed. If two strings are concatenated, .net internally creates another string. The string builder is muatble, meaning the space allocated in memory is dynamic.
If two stringbuilders are concatenated, no new object is created. However, if the capacity is reached, then the stringBuilder automatically doubles its capacity (huge).
Example:
Dim szText As System.Text.StringBuilder = New _
System.Text.StringBuilder("First String")
MessageBox.Show("Default Capacity : " & szText.Capacity) ''Returns 16
MessageBox.Show("Max Capacity : " & szText.MaxCapacity)
‘'Returns 2147348647
MessageBox.Show("Default Length : " & szText.Length) ''Returns 12
szText.Append("Second String")
MessageBox.Show("Default Capacity : " & szText.Capacity) ''Returns 32
MessageBox.Show("Max Capacity : " & szText.MaxCapacity)
‘'Returns 2147348647
MessageBox.Show("Default Length : " & szText.Length) ''Returns 25
We can check the capacity
If szText.Capacity < 1024 then
szText.Capacity = 1024
End If
Or
szText.EnsureCapacity (1024)
We can do string manipulation
szText.Insert ( 5, "Middle" ) ''Will insert at the position 5
szText.Replace ( "First", "Begin")
-
Constructs: Is a method that runs when a new instance at class is created. It is called Sub New. Sub New may have arguments. Constructs may be overloaded.
Events: Different from VB6.
Class ClassName
Event EventName ( .. )
RaiseEvent EventName ( .. )
End Class
Trapping Events with WithEvents:
Module MainMode
Dim WithEvents EventName As New EventType
:
Sub SubName
EventName ( .. )
End Sub
End Module.
Constructors and Destructors
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim oClass As ThisClass = New ThisClass()
oClass.Dispose()
oClass = Nothing
End Sub
End Class
Public Class ThisClass
Public Sub New()
MessageBox.Show("NEW")
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
MessageBox.Show("Finalize")
End Sub
Protected Sub Dispose()
MessageBox.Show("Dispose")
End Sub
End Class
The Finalize is not called right away, it is called when ever the garbage collector needs to clean up the memory (or when the app is closed). So to get around the problem programmers create a function called dispose and call it explicitly.
System.GC: Lets you access the garbage collection programmatically. However, this may slow down the application.
0Add a comment
-
AddHandler & RemoveHandler:
AddHandler: Allows at run time to decide which runtime should serve a given event. AddHandler routine should serve a given event. AddHandler routine takes two arguments (i) the event we want to handle and (ii) the address of the routine that handles the routine.
Example: Dim Log1 As Logger //Logger is a class
AddHandler Log1.LogAction, AddressOf LogActionEvent
The counterpart of AddHandler is RemoveHandler. Both AddHandler & RemoveHandler are key words of VB.
RemoveHandler: Log1.LogAction, AddressOf LogActionEvent.
If an event has been added using AddHandler than make sure that RemoveHandler is also used, else there might be unforeseeable consequences. For Example, if AddressHndler is used of FormA to trap events raised by FormB, the AddHandler would create a hidden reference inside FormB that points to FormA. If RemoveHandler is not explicitly called, then that reference remains alive. WithEvent keyword ties an EventHandler to a specific variable, whereas the AddHandler command ties an event handler to a specific object.
0Add a comment
-
Threading*:
Imports System.IO
Imports System.Thread
Fundamentals: Premptive multitasking means that thread can be suspended at alsmot any time and another one can be give CPU time. In older versions of windows, we had cooperative multitasking, where each thread had to ask to be suspended explicitily.
When to use Threads: Each thread maintains a private set of structures that the OS uses to save information (thread contentent). When the thread isn’t running, icluding the values of CPU reisters at the time when the thread was suspended and the process was allowed to create another thread. It also maintains it’s exception handler and the priority values. OS scheduler taken CPU and memory to manage threads, so running too many threads drains the resources. Threads can compete for shared resources. We must synchronize access to resources or run into trouble. SyncLock is thus provide to deal with this issue.
Creating Threads: System.Threading.Thread offers all methods and properties needed to create and manage threads. To create a new thread, instientiate a new new thread object and invoke its start method. The thread object constructor requires one argument, a start delegate object that points to the routine that runs when the thread starts. Such a routine must have a sub without any arguments.
Sub TestThread()
Dim t As New Thread(New ThreadStart(AddressOf DoTheTask))
Dim szMsg As String = String.Empty
t.Start()
For i As Integer = 1 To 10
szMsg &= "First : " & i & vbCrLf
Thread.Sleep(100)
Next
MessageBox.Show(szMsg)
End Sub
Sub DoTheTask()
Dim szMsg As String = String.Empty
For i As Integer = 1 To 10
szMsg &= "Second : " & i & vbCrLf
Thread.Sleep(200)
Next
MessageBox.Show(szMsg)
End Sub
Working with threads: Thread.Current.Thread returns the current thread, once we have a reference to it, we can start, suspend, resume or abort it (using methods of thread class). Thread is automatically terminated when it reaches exit or end, but can be suspended or aborted. Start, suspending or aborting of thread doesn’t happen right away, unless done for current thread.
Sub TestThread()
Dim t As New Thread(New ThreadStart(AddressOf DoTheTask))
'These work only with current thread
t.Start()
t.Suspend()
t.Resume()
t.Abort()
End Sub
Also, Timeout.Infinite can suspend till infinity or another thread invokes it.
Sub TestThread()
Dim t As New Thread(New ThreadStart(AddressOf DoTheTask))
t.Start()
t.Join()
End Sub
Join can take optional timeout, returns true if the method is declared with the given timespan, false if nto
Sub TestThread()
Dim t As New Thread(New ThreadStart(AddressOf DoTheTask))
t.Start()
Do Until t.Join(1000)
..
Loop
End Sub
Thread properties: IsAlive can be used to see if the thread is alive. A bit wise property is used to check the state of any thread. All threads have a name property, usually null, but can be used.
Abort The thread has been aborted
AbortRequested The thread is responding to an abort request
Background The thread is running in the background. (Same as the IsBackground property).
Running The thread is running. (Another thread has called the start method)
Stopped The thread has been stopped. (A hread can never leave this state.)
StopRequested The thread is about to stop.
Suspended The thread has been suspended.
SuspendedRequested The thread has been created, but the start method hasn’t been call yet.
WaitSleepJoin The thread has called Monitor.Wait or Thread.Join on another thread.
Debugging Thrads:.NET UI allows us to watch threads. It allows us to watch
(i) number fo logical threads
(ii) number of current physical threads
(iii) number of current recognized threads
(iv) Contention rated/second (reate at which threads in the runtime fail to acquire a managed lock.
(v) Total number of contentions, the number of times thread in the common language runtime have failed to acquire a managed lock.
(vi) Current queue/sec.
______________________________________________
*Notes from Balena's book VB.NET
______________________________________________
0Add a comment
-
Serialization
Serialization is the act of saving an object onto a storage medium – a file, a data base field, a buffer in memory and later de-serialization it from the medium to re-create an object instance that can be considered identical to the original one. Serialization is also known as Persistence, however, MSDN documentation defines persistence as saved to a durable medium.
Basic Serialization: .Net framework knows how to serialize all basic data types (numbers, string, arrays etc). A formatter is an object that implements the IFormattter interface (defined in System.Runtime.Serailization). User can create his own formatter by defining a class that implements this interface.
Predefined formatters:
Binary: (System.Runtime.Serialization.Formatter.Binary) persists an object as compact binary formatter.
Example
Dim arr() As Interger = {1,2,3}
Dim fs As FileStream = New FileStream (filename, FileMode.Create)
Dim bf As New BinaryFormatter()
bf.Serialize ( fs, arr)
fs.close ()
Open
Dim fs as FileStream = New FileStream (FileName, FileMode.Open)
Dim Arr () As Integer = CType (bf.Deserialize (fs), Integer ())
For each n As Integer in Arr
Console.Write (n.ToString & “ “ )
Next
Soap: (System.Runtime.Serialize.Formatter.Soap) in human readable XML file format using SOAP specs.
Dim sf As New SoapFormatter (Nohing, ..)
Serialized and non-serialized attributes: A class can be made serializable by setting a flag with serializable attributes._
Class ClassName
…
End Class
For this to work base class must be serializable. Similarly non serializable can be used to make a class nonserializable (Non-Serializable flag). Item that can and should be calculated at runtime, should be non-serializable.
Object Graphs: Object graph is a set of multiple object with reference to one another. Serialization mechanism is smart enough to understand the underlying connections.
Deep Object Cloning:
Custom Serialization: iDeserializationCallBack and ISerializable interfaces allows developers to implement custom serialization.
Formatter Services Helper Class: Expresses a few shared methods that help you build code that serializes and des-serializes an object_
Class SuperClass
Implements ISerialziable
Public Sub …
…
…
0Add a comment
-
Reflection:
Reflection is a set of classes that allow you to access and manipulate assemblies and modules and the types and the metadata that they contain. For example, you can use reflection to enumerate loaded assemblies, modules, and classes and the methods, properties, fields, and events that each type exposes. Reflection plays a fundamental role in the Microsoft .NET Framework and works as a building block for other important portions of the runtime. The runtime uses reflection in many circumstances, such as to enumerate fields when a type is being serialized or is being marshaled to another process or another machine. Microsoft Visual Basic transparently uses reflection whenever you access an object’s method through late binding.
Example
Imports System.Reflection
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MethodObj As System.Reflection.MethodInfo
Dim MessageDemo As New Demo()
For Each MethodObj In MessageDemo.GetType.GetMethods()
Dim Attr As Attribute
Dim szMessage As String = String.Empty
For Each Attr In MethodObj.GetCustomAttributes(False)
szMessage += MethodObj.Name & vbCrLf
'Console.WriteLine(Attr)
szMessage += Attr.ToString & vbCrLf
szMessage += CType(Attr, UserName).Name & vbCrLf
Next
MessageBox.Show(szMessage)
Next
End Sub
End Class
Class UserName
Inherits Attribute
Public Name As String
Public Sub New(ByVal Name As String)
MyBase.New()
Me.Name = Name
End Sub
End Class
Class Demo
Sub DemoMsg()
Console.WriteLine("Message")
End Sub
Sub Greet()
Console.WriteLine("Hello")
End Sub
End Class
Get Class Member and Property Information from base and inherited Class
Imports System.Reflection
Public Class MainClass
Public Shared Sub Main()
Dim Book = New Derived()
Dim Member As MemberInfo
Console.WriteLine("Members:")
For Each Member In Book.GetType.GetMembers()
Console.WriteLine(Member.Name & " " & Member.MemberType)
Next
Dim PropertyObj As PropertyInfo
Console.WriteLine("Properties:")
For Each PropertyObj In Book.GetType.GetProperties()
Console.WriteLine(PropertyObj.Name & " " & PropertyObj.PropertyType.ToString())
Next
Dim MethodObj As MethodInfo
Console.WriteLine("Methods:")
For Each MethodObj In Book.GetType.GetMethods()
Console.WriteLine(MethodObj.Name & " " & MethodObj.ReturnType.ToString())
Next
Dim EventObj As EventInfo
Console.WriteLine("Events:")
For Each EventObj In Book.GetType.GetEvents()
Console.WriteLine(EventObj.Name & " " & EventObj.IsMulticast)
Next
Dim InterfaceObj As Type
Console.WriteLine("Events:")
For Each InterfaceObj In Book.GetType.GetInterfaces()
Console.WriteLine(InterfaceObj.Name)
Next
End Sub
End Class
Class Base
Public ProductID As String
Public Weight As Double
Private ProductPrice As Double
Public Sub New()
End Sub
Public ReadOnly Property Price() As Double
Get
Return 0
End Get
End Property
End Class
Class Derived
Inherits Base
Implements IFormattable
Public Title As String
Public Author As String
Public Publisher As String
Public Overridable Overloads Function ToString(ByVal _
Format As String, ByVal Provider As IFormatProvider) _
As String Implements IFormattable.ToString
ToString = Title
End Function
Public Sub New()
MyBase.New()
End Sub
End Class
Get Method Information
Imports System.Reflection
Public Class MainClass
Public Shared Sub Main()
Dim SomeObj = New Demo()
Dim MethodObj As System.Reflection.MethodInfo
Console.WriteLine()
Console.WriteLine("Methods:")
For Each MethodObj In SomeObj.GetType.GetMethods()
Console.WriteLine(MethodObj.Name & " " & MethodObj.ReturnType.ToString())
Dim Param As ParameterInfo
For Each Param In MethodObj.GetParameters()
Console.WriteLine(Param.Name & " " & Param.ParameterType.ToString())
Next
Console.WriteLine()
Next
End Sub
End Class
Class Demo
Public Sub A()
End Sub
Public Sub B(ByVal Msg As String)
End Sub
Public Function C(ByVal A As Integer, ByVal B As Integer) As Integer
End Function
Public Sub D(ByVal A As Double, ByVal B As Double, ByVal C As Double)
End Sub
End Class
0Add a comment
-
Interfaces
Can have no code, un-creatable – just defines the sub names & variable names etc.
Interface Basics:
1) Define only the property and method signatures, NOT the actual implementation.
2) require that classes which implement the given Interface must adhere to these property and method signatures.
3) ARE LIKE CONTRACTS ... classes which implement an interface guarantee that they can be trusted to be used polymorphic-ly. If you need to change the way ‘’ a class works (i.e., change its property or method signatures) then you must MUST keep the old ones AND implement new properties and methods. One way to do this is to implement additional Interfaces.
4) Notice: No scope identifiers ... by default, it is scoped as 'Friend'. If we add a 'Public' in front of Interface IProduct', then we could scope the individual properties and methods as 'Public'.
5) Have other scoping rules ... when inside classes, etc. See help about Interfaces.
Example
Public Interface IProduct
Property SKU() As String
Property Name() As String
Property ListPrice() As Double
Function CalculateTax(ByVal country As String) As
Double
Function InStock() As Integer
End Interface
' Classes that implement Interfaces ...
'
1) Are agreeing to a contract ... this contract must not be broken. The ramifications of breaking a contract (i.e., changing the property and method signatures) might break older programs which rely on the old Interface.
2) Classes that implement a given Interface can extend the properties and methods, if desired ... and can implement additional Interfaces.
3) Classes can expose Interfaces (this too is a topic for another day.)
Public Class Book
Implements IProduct
Private m_SKU As String
Private m_Name As String
Private m_ListPrice As Double
Property SKU() As String Implements IProduct.SKU
Get
Return m_SKU
End Get
Set(ByVal Value As String)
m_SKU = Value
End Set
End Property
Property Name() As String Implements IProduct.Name
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property
Property ListPrice() As Double Implements
IProduct.ListPrice
Get
Return m_ListPrice
End Get
Set(ByVal Value As Double)
m_ListPrice = Value
End Set
End Property
Function CalculateTax(ByVal country As String) As Double Implements IProduct.CalculateTax
Return 5
End Function
Function InStock() As Integer Implements IProduct.InStock
Return 8
End Function
End Class
A class can implement multiple interfaces.
Implements IClassA, IClassB
We will also need to use the implements on each property and method. For example
Function CalculateTax(ByVal country As String) As Double Implements IProduct.CalculateTax0Add a comment
-
Interfaces
Can have no code, un-creatable – just defines the sub names & variable names etc.
Interface Basics:
1) Define only the property and method signatures, NOT the actual implementation.
2) require that classes which implement the given Interface must adhere to these property and method signatures.
3) ARE LIKE CONTRACTS ... classes which implement an interface guarantee that they can be trusted to be used polymorphic-ly. If you need to change the way ‘’ a class works (i.e., change its property or method signatures) then you must MUST keep the old ones AND implement new properties and methods. One way to do this is to implement additional Interfaces.
4) Notice: No scope identifiers ... by default, it is scoped as 'Friend'. If we add a 'Public' in front of Interface IProduct', then we could scope the individual properties and methods as 'Public'.
5) Have other scoping rules ... when inside classes, etc. See help about Interfaces.
Example
Public Interface IProduct
Property SKU() As String
Property Name() As String
Property ListPrice() As Double
Function CalculateTax(ByVal country As String) As
Double
Function InStock() As Integer
End Interface
' Classes that implement Interfaces ...
'
1) Are agreeing to a contract ... this contract must not be broken. The ramifications of breaking a contract (i.e., changing the property and method signatures) might break older programs which rely on the old Interface.
2) Classes that implement a given Interface can extend the properties and methods, if desired ... and can implement additional Interfaces.
3) Classes can expose Interfaces (this too is a topic for another day.)
Public Class Book
Implements IProduct
Private m_SKU As String
Private m_Name As String
Private m_ListPrice As Double
Property SKU() As String Implements IProduct.SKU
Get
Return m_SKU
End Get
Set(ByVal Value As String)
m_SKU = Value
End Set
End Property
Property Name() As String Implements IProduct.Name
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property
Property ListPrice() As Double Implements
IProduct.ListPrice
Get
Return m_ListPrice
End Get
Set(ByVal Value As Double)
m_ListPrice = Value
End Set
End Property
Function CalculateTax(ByVal country As String) As Double Implements IProduct.CalculateTax
Return 5
End Function
Function InStock() As Integer Implements IProduct.InStock
Return 8
End Function
End Class
A class can implement multiple interfaces.
Implements IClassA, IClassB
We will also need to use the implements on each property and method. For example
Function CalculateTax(ByVal country As String) As Double Implements IProduct.CalculateTax0Add a comment
-
Inheritance
In VB.Net you can inherit from any object, including objects fro which you don’t have the source code, because all the plumbing code is provided by the .net framework. The only exception to this rule occurs when the another of the class you want to derive from has marked the class sealed, which means that not other class can inherit from it.
The derived class inherits all the Public and Friends fields, properties, methods and events of the base class. Inheriting a field can be a problem, though, because a derived class becomes dependent on that field and the another of the base class can’t change the implementation of that field. For example, to make it a calculated value without breaking the derived class. For this reason, it’s usually preferable that classes meant to work at base classes should include only PrivateFields. You should always use a Property instead of a field to make piece of data visible outside the class because you can always change the internal implementation of a property without any impact on derived classes.
Using Derived Classes: Inheritance rule states that you can always assign a derived object to a base class variable
OverRides Members in the base class: To override a method it must be prefixed with word “Overridable” in the base class.
Example
Base Class
Overridable Function FuncName ( .. ) As String
End Function
Derived Class:
Overrides Function FuncName ( .. ) As String
:
End Function
VB.Net also supports “NotOverridable” key word, which explicitly states that a method can’t be overridden.
Constructors In Derived Classes: If the base class has “New” and this “New” function has no arguments, then we don’t need to call it explicitly. However, if the New function in base class has one or more argunments then we need to call the New Function explicitly from the derived (child) class.
MyClass: Can be used to make sure that the methods and properties are used from the base class and not from the derived class.
Members Shadowing: A member in the derived class method with shadows keyword hides all the members in the base class with the same name.
For Eample,
Class AAA
Function Func1 ( .. )
:
End Function
End Class
Class BBB
Inherits AAA
Shadows Func1 ( .. )
:
End Function
End Class
More on inheritance: In OO term the parent class is called the base class. The child class is called the inherited class or the derived class. Inheritance can be declared two ways.
(C# Style)
Public Class className : Inherits BaseClassName
..
End Class
Or
Public Class className
Inherits BaseClassName
..
End Class
To make a function vertual in baseclass (meaning overridable) we must declare it as OVERIRDABLE
Public OVerridable Function FunctionName (..) As ..
..
ENd Function
In the derived class we declare it as Overides.
Public Overrides Function FunctionName (..) As ..
..
ENd Function
Casting - We can cast a an objects baseclass to a derived class. For Example:
Dim oMyObject As BaseClass = DerivedClass
But this is not allowed
Dim oMyObject As DerivedClass = BaseClass
Because the Option Explicit ON does not allow casting of base type to a derived type.
To do that we need to cast the object.
Dim oMyObject As DerivedClass = DirectCast ( BaseClass, DerivedClass )
Or
Dim oMyObject As DerivedClass = CType ( BaseClass, DerivedClass )
This kind of relationship is called as IsA relationship. So the DerivedClass IsA BaseClass - for example if the base class is called Product and derived class is books then we
can say Books isa Product.0Add a comment
-
Generics - (New in VB2005)
Example
System.Collections.Generics. This allows us to use Dictionary, List, Queue, SortedDictionary and Stack classes.
Dim employees As New Dictionary(Of String, Employee)
Dim emp As Employee emp = New Employee
emp.SSN = “111-11-1111"
emp.FirstName = “Scott"
emp.LastName = “Swigart"
emp.Salary = 50000
employees.Add(emp.SSN, emp)
txtOutput.Text = “Consuming generics” & vbCrLf & vbCrLf
Dim emp2 As Employee
emp2 = employees.Item(“111-11-1111”)
Dim s As String
s = employees.Item(“111-11-1111”) ‘ This is now a syntax error
employees.Item(“111-11-1111”).LastName = “SomeoneElse"
txtOutput.Text &= “Employee last name:” & vbCrLf & _
employees.Item(“111-11-1111”).LastName
So the generic types are instantiated as
Dim employees As New Dictionary (Of String, Employee)
Here the use of word OF specifies the desired data type of the keys. Any attempt to save any value other than Employee will result in the compile time error. With generics using incorrect data type will result in compiler error.
One of the reasons of using Generics in the .NET framework is performance. Simply put, they are faster than the previous collection classes because the compiler optimizes them specifically for the types they store.0Add a comment
Add a comment