Friday, October 10, 2008

Get the Product Code of the Installed Product

[Not Sure but can be useful]
Private Function getInstalledProductCode(ByVal InstalledProductNameStr As String) As String
Dim retStr As String = "-1"
Try
Dim installer As Object
installer = CreateObject("WindowsInstaller.Installer")
Dim products As Object = installer.Products
For Each strProductCode As String In products
Dim strProductName As String = installer.ProductInfo(strProductCode, "InstalledProductName")
If strProductName.Contains(InstalledProductNameStr) = True Then
retStr = strProductCode
End If
Next
Catch ex As Exception

End Try
Return retStr
End Function

Generate Globally Unique Identifier (GUID)

Private Function GUID() As String

Return (System.GUID.NewGuid().ToString())

End Function

Monday, October 6, 2008

Attributes with VB.NET

1. Creating and Using Custom Attributes with VB.NET

The common language runtime allows programmers to add descriptive declarations to programming elements called Attributes. Attributes are like annotations that can be applied to assemblies, types, methods, or properties. Attributes are emitted into the assembly metadata and they can be extracted by using Reflection services of the .NET framework.

2. Attributes Programming in VB.NET

An attribute is a new code level language construct in all major .NET languages. It provides integration of declarative information to assemblies, classes, interfaces, members, etc. at the code level. The information can then be used to change the runtime behavior or collect organizational information. . . . . . .

Method Synchronization [MethodImplAttribute]

Code attributes in the Dot Net Framework can sometimes make programming easier. The MethodImplAttribute is one example of the hundreds of different attributes that you can use. It is in the System.Runtime.CompilerServices namespace. This attribute is particularly interesting to synchronization because it can synchronize an entire method with one simple command.

If you place the attribute before a function and supply the MethodImplOptions. Synchronized enumeration in the constructor, the entire method will be synchronized when called. The compiler will create output that wraps the whole function, SynchronizedMethodName, in a Monitor. Enter and Monitor. Exit block. When a thread starts to enter the method it will acquire a lock. Upon exiting the method, it will release the lock. Here is an example of using the attribute.

"<" METHODIMPLATTRIBUTE(METHODIMPLOPTIONS.SYNCHRONIZED) ">"

Private Sub SynchronizedMethodName()

End Sub

This attribute should only be used when an entire function needs to be synchronized, so it is rarely used. If you can exit the synchronized block of code before the end of the method or wait to enter it to the middle of the method, Monitor should be used, as the attribute would waste processing cycles by locking the whole method and not just what needs to be synchronized.


Note: There are two SynchronizationAttribute classes. One is in
System.EnterpriseServices and the other is in
System.Runtime.Remoting.Contexts. The first can only be used on
classes derived from ServicedComponent. The second can only be used on
classes derived from ContextBoundObject.

Syntax for a class

Class Statement [ Public | Private | Protected |
Friend | Protected Friend ]
[ Shadows ][ MustInherit | NotInheritable ] _
Class name [ Inherits classname ][ Implements interfacenames ]
[ statements ]
End Class

Modifiers Brief explanation

Public
There are no restrictions on the use of a class declared as Public.

Private
A Private class is accessible only within its "declaration context" including any nested entities. A nested procedure is an example of a nested entity. A Public variable in a Private class is accessible from inside the class, but not from outside that class.

Protected
Protected means that elements are accessible only from within their own class or from a derived class. Protected can also be used with the Friend keyword. When they're used together, elements are accessible from the same assembly, from their own class, and from any derived classes.

Protected, Friend and Protected Friend

[These Definitions may not be exact definitions but can give a brief
idea]
Protected --> Accessible ONLY by 1.Derived classes 2.Within
the same class
Or
1. Code within the class
2. Code in derived classes within the same assemblies
3. Code in derived classes in other assemblies

A Protected procedure may only be declared within a class.
Procedures declared within the same class can call it, as
can other methods in inherited classes.[From MSDN]

methods in inherited classes.
Protected variables can be used within the class as well as
the classes that inherites this class.

Friend --> Accessible ONLY by 1.Derived classes 2.Classes
in the same assembly 3.Within the same class
Or
1. Code within the class
2. Code in derived classes within the same assembly
3. Other code in the same assembly

Friends can be accessed by all classes within assembely but
not from outside the assembely.

A variable declared with the Friend access specifier can only
be seen by other classes within the same program. This means
that if a class has a Friend variable and that class resides
in a DLL, then only other classes within the same DLL can see
that Friend variable. Any other program that uses that DLL
cannot see that variable.[From MSDN]


Protected Friend --> Accessible ONLY by 1.Derived classes
2.Classes in the same assembly 3.Within the same class
Or
1. Code within the class
2. Code in derived classes within the same assembly
3. Other code in the same assembly
4. Code in derived classes in other assemblies

The Protected Friend can be accessed by Members of the
Assembely (Friend) or the inheriting Assembely class
(Protected).

Friday, September 26, 2008

Move/Rename File

 Dim fi As New FileInfo("myOldName.txt")
fi.MoveTo("myNewName.txt")

Calculate File Size

Imports System.IO

Private Function GetFileSize(ByVal MyFilePath As String) As Long
Dim MyFile As New FileInfo(MyFilePath)
Dim FileSize As Long = MyFile.Length
Return FileSize
End Function

DateTime Formats

d - Numeric day of the month without a leading zero.
dd - Numeric day of the month with a leading zero.
ddd - Abbreviated name of the day of the week.
dddd - Full name of the day of the week.

f,ff,fff,ffff,fffff,ffffff,fffffff - Fraction of a second. The more F's the higher the presision.

h - 12 Hour clock, no leading zero.
hh - 12 Hour clock with leading zero.
H - 24 Hour clock, no leading zero.
HH - 24 Hour clock with leading zero.

m - Minutes with no leading zero.
mm - Minutes with leading zero.

M - Numeric month with no leading zero.
MM - Numeric month with a leading zero.
MMM - Abbreviated name of month.
MMMM - Full month name.

s - Seconds with no leading zero.
ss - Seconds with leading zero.

t - AM/PM but only the first letter.
tt - AM/PM

y - Year with out century and leading zero.
yy - Year with out century, with leading zero.
yyyy - Year with century.

zz - Time zone off set with +/-.

String to DateTime conversion and Vice Versa

'String to DateTime

VB.Net
Dim dateString As String
dateString = "1999-09-01 21:34 PM"
Dim datetimeStamp As New DateTime
datetimeStamp = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm tt", Nothing)

C#
//
String to DateTime
String
MyString;
MyString = "1999-09-01 21:34 PM";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

VB.Net
'DateTime to String
datetimeStamp = New DateTime(1999, 9, 1, 21, 34, 0)
dateString = datetimeStamp.ToString("yyyy-MM-dd HH:mm tt")

C#
//
DateTime to String
MyDateTime = new DateTime(1999, 09, 01, 21, 34, 00);
String
MyString;
MyString = MyDateTime.ToString("yyyy-MM-dd HH:mm tt");

Thursday, August 21, 2008

VB.Net Usefull Code Snippets

From: http://www.dreamincode.net/code/snippet870.htm

Change bitmaps certain color transparency


  1. 'Written by Margus Martsepp AKA m2s87
  2. Private Function v2bista(ByRef OnPict As System.Drawing.Bitmap, _
  3. ByVal xColor As System.Drawing.Color, _
  4. ByVal How_Tr As Integer) As Boolean
  5. Dim x%, y%, R%, G%, B%
  6. v2bista = True
  7. With OnPict
  8. For x = 1 To .Width - 1
  9. For y = 1 To .Height - 1
  10. R = .GetPixel(x, y).R
  11. G = .GetPixel(x, y).G
  12. B = .GetPixel(x, y).B
  13. If xColor.R = R And xColor.G = G And xColor.B = B Then
  14. .SetPixel(x, y, System.Drawing.Color.FromArgb(How_Tr, R, G, B))
  15. End If
  16. Next
  17. Next
  18. End With
  19. End Function

Tuesday, July 1, 2008

Early vs. Late Binding

Early vs. Late Binding

One of the strengths of VB has long been that we had access to both early and late binding when interacting with objects.

Early binding means that our code directly interacts with the object – knowing its data type ahead of time and thus being able to very efficiently interact with the object. Early binding allows the IDE to use IntelliSense to aid our development efforts and it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.

Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn’t care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn’t known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible – but in exchange we get unprecedented flexibility.

VB.NET continues this tradition, providing support for both early and late binding as we work with
our objects.

By default, all objects are early bound. The IDE and compiler enforce this as long as Option Strict On is set, and this is the default. However, if we set Option Strict Off at the top of a source file (as discussed in Chapter 3), we open the door for late binding throughout the code in that file.

Use of the Object Type

Late binding occurs when the compiler can’t determine the type of object we’ll be calling. This level of ambiguity is achieved through the use of the Object data type. A variable of data type Object can hold virtually any value – including a reference to any type of object. Thus, code such as the following could be run against any object that implements a MyMethod method that accepts no parameters:

Option Strict Off
Module LateBind
Public Sub DoSomething(obj As Object)
obj.MyMethod()
End Sub
End Module

If the object passed into this routine doesn’t have a MyMethod method that accepts no parameters, then a run-time error will result. Thus, it is recommended that any code that uses late binding you should always provide error trapping:

Option Strict Off
Module LateBind
Public Sub DoSomething(obj As Object)
Try
obj.MyMethod()
Catch
‘ do something appropriate given failure to call the method
End Try
End Sub
End Module

While late binding is flexible, it can be error prone and it is slower than early bound code. To make a late bound method call, the .NET runtime must dynamically determine if the target object actually has a method that matches the one we’re calling, and then it must invoke that method on our behalf. This takes more time and effort than an early bound call where the compiler knows ahead of time that the method exists and can compile our code to make the call directly.

Late Binding and Reflection

The .NET Framework supports a concept known as reflection. This is the ability to write code that examines other .NET code to determine its composition. Reflection is supported by the System.Reflection namespace.

Reflection allows us to write code that discovers the classes within an assembly and the methods, properties and events exposed by those classes. We can then use reflection to create instances of those classes and call those methods. This entire process can be very dynamic – much like late binding.

In fact, VB.NET uses reflection to implement late binding on our behalf. Rather than forcing us to write the code that uses reflection to find and invoke a method, VB.NET handles this for us when we use late binding coding techniques.

We could implement a limited form of reflection within VB6 by using the typelib DLL. The functions in this DLL allowed us to dynamically discover the classes and methods in a COM DLL, and then invoke them. Of course COM components were described with IDL – a rather inaccurate description of the component. In .NET, assemblies are described by metadata that accurately describes each assembly, making reflection a much more robust solution.

Wednesday, June 25, 2008

OOPs in VB.Net

0. VB.Net don't support : Operator Overloading, Multiple Inheritance

1. Private interfaces can not be implemented (Ans)
Explanation: Interfaces must always be declared as public so that they can be
implemented or inherited
2. a subclass created
With the help of Inherits.
3. encapsulation :Hiding the implementation and exposing the interface and is The
separation of interface and implementation
4. interface implementation requires Implements keyword for to be implemented.
5. Static Methods can't be overridable
6. significance of Shadowing :It replaces all the implementation from high in the
inheritance chain.
7. In VB.Net Abstract class is specified with MustInherit keyword.
8. Polymorphism is implemented using Method Overloading,Method Overriding
9. overloading operators requires Overloads keyword.
10. encapsulation : The separation of interface and implementation.
11. Late Binding, Multiple Interfaces and . NET Reflection can be used to achieve
polymorphic behavior of an object.

Sunday, June 22, 2008

Tips

You can access the Application information easily as can be seen in the following lines of code

My.Application.AssemblyInfo.DirectoryPath
My.Application.AssemblyInfo.ProductName
My.Application.Log.WriteEntry(“Application Starting”, EventLogEntryType.Information, Nothing)

The above lines of code will retrieve this information from the assembly which can used by the application on run time.


properties and methods of the My.Application Object

ApplicationContext Gives access to the context associated with the current thread.

AssmblyInfo Allows easy access to data from the AssemblyInfo.vb file, including CompanyName, ProductName, Title and Version.

ChangeCurrentCulture Allows Change the culture in which the current thread is running, which affects such things as string manipulation and formatting

ChangeCurrentUICulture Allows changing the culture that the current thread uses for retrieving culture-specific resources

CommandLineArgs Return a collection of command-line arguments

CurrentCulture Returns a collection of command-line arguments

CurrentDirectory Returns the folder where the application resides

CurrentUICulture Returns the culture that the current thread is using for retrieving culture-specific resources

DoEvents Causes all messages in the message queue to be processed

GetEnvironmentVariable Returns a specific environment variable on the local maching\e

IsNetWorkDeployed Returns True if the application was network-deployed else returns False.

Log Allows writing to application log on the local machine

MainForm A read-write property that allows setting or getting the form that the application will use as its main form

Run Sets up and starts the VB Startup/Shutdown Application model

SplashScreen Lets setting or getting the application's splash screen

Visual Basic has a public function MsgBox. It displays a message in a dialog box, waits for the user to click a button, and then returns an integer indicating which button the user clicked.

Public Function MsgBox( _
ByVal Prompt As Object, _
Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly, _
Optional ByVal Title As Object = Nothing _
) As MsgBoxResult

The MsgBoxStyle enumeration values are listed in the following table.

Enumeration

Value

Description

OKOnly

0

Displays OK button only.

OKCancel

1

Displays OK and Cancel buttons.

AbortRetryIgnore

2

Displays Abort, Retry, and Ignore buttons.

YesNoCancel

3

Displays Yes, No, and Cancel buttons.

YesNo

4

Displays Yes and No buttons.

RetryCancel

5

Displays Retry and Cancel buttons.

Critical

16

Displays Critical Message icon.

Question

32

Displays Warning Query icon.

Exclamation

48

Displays Warning Message icon.

Information

64

Displays Information Message icon.

DefaultButton1

0

First button is default.

DefaultButton2

256

Second button is default.

DefaultButton3

512

Third button is default.

ApplicationModal

0

Application is modal. The user must respond to the message box before continuing work in the current application.

SystemModal

4096

system is modal. All applications are suspended until the user responds to the message box.

MsgBoxSetForeground

65536

Specifies the message box window as the foreground window.

MsgBoxRight

524288

Text is right-aligned.

MsgBoxRtlReading

1048576

Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.



The VB.Net framework graphically can be viewed as below:


The brief description of the various features of the dot net framework is can be considered as below:


  • An object oriented programming model (inheritance, polymorphism, exception handling etc);
  • A common standardised type system;
  • Metadata support for all types at run-time;
  • A comprehensive set of .NET Framework classes that encapsulate most of the Win32 API and several other technologies, such as data access and XML parsing;
  • Advanced debugging and profiling support;
  • 'Virtualised' code execution and memory management;
  • A system-wide garbage collector handling the object lifetime of all managed memory;
  • Intermediate Language to native code translators;
  • A declarative security model.