Thursday 22 December 2011

Change the Default Project Values in .NET

You can change the default values of Option Explicit and Option Strict on a per project type basis. For example, when you create a new Visual Basic .NET or Visual Basic 2005 application, the value for Option Explicit is set to On. You can change this default value to Off.

To change the default values of Option Explicit and Option Strict, follow these steps:
  1. Locate the following project template files on your system:
    • EmptyProjectIPF.vbproj
    • EmptyWebProjectIPF.vbproj
    • WebApplication.vbproj
    • WebControl.vbproj
    • WebService.vbproj
    • WindowsApplication.vbproj
    • WindowsControl.vbproj
    • WindowsService.vbproj
  2. Open a project template in Notepad.
  3. Add (or edit if they are already present) the OptionStrict and OptionExplicit lines in the section of the template.

    For example, the following code demonstrates how to set OptionExplicit to Off and OptionStrict to On:
OutputType = "Exe"
StartupObject = ""
OptionExplicit = "Off"
OptionStrict = "On"
>
Repeat steps 2 and 3 for each project template that you want to change the default behavior for.

Wednesday 14 December 2011

Conversions in Dot Net (.Net) - Strict , Widening and Narrowing



Impact of Option Strict in Conversions (.NET)
Option Strict restricts implicit data type conversions to only widening conversions. Widening conversions explicitly do not permit any data type conversions in which data loss may occur and any conversion between numeric types and strings. For more information about widening conversions, see the Widening Conversions section.

When you use the Option Strict statement, the statement must appear before any other code. In Visual Basic .NET, you can typically convert any data type to any other data type implicitly. Data loss can occur when the value of one data type is converted to a data type with less precision or with a smaller capacity. However, you receive a run-time error message if data will be lost in such a conversion. Option Strict notifies you of these types of conversions at compile time so that you can avoid them.

Option Strict also generates an error message in the following scenarios:
  • For any undeclared variable. This is because Option Strict also implies Option Explicit. (Option Strict On requires all variable declarations to have an 'As' clause - Error ID: BC30209 )
To correct this error
1. Check to see if the As keyword is misspelled.
2. Supply an As clause for the declared variable, or turn Option Strict Off.
  • Late binding.
You will get the following error, if you attempt to execute the code below “Option Strict On disallows implicit conversions from 'Double' to 'Integer'”
Sub Convert_Double_To_int()
Dim DoubleVar As Double
Dim IntVar As Integer
DoubleVar = 123.456
IntVar = 2 + DoubleVar
End Sub



An important consideration with a type conversion is whether the result of the conversion is within the range of the destination data type. A widening conversion changes a value to a data type that can accommodate any possible value of the original data. A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. The above conversion is an example of narrowing conversion
Widening Conversions
The following table lists the standard widening conversions.
Data Type
Widens to Data Types
Byte
Byte, Short, Integer, Long, Decimal, Single, Double
Short
Short, Integer, Long, Decimal, Single, Double
Integer
Integer, Long, Decimal, Single, Double
Long
Long, Decimal, Single, Double
Decimal
Decimal, Single, Double
Single
Single, Double
Double
Double
Any enumerated type
Its underlying integer type and any type to which it will widen
Char
Char, String
Any type
Object, any interface that it implements
Any derived type
Any base type from which it is derived
Nothing
Any data type or object type

The following conversions may lose precision:
  • Integer to Single
  • Long to Single or Double
  • Decimal to Single or Double
However, these conversions do not lose information or magnitude.

Widening conversions always succeed, and you can always perform widening conversions implicitly.
Explicit Conversion with Casting
An explicit conversion uses a type conversion keyword. Visual Basic .NET or Visual Basic 2005 provides several such keywords, which coerce an expression in parentheses to the data type that you want. These keywords behave as functions, but the compiler generates the code inline. Therefore, execution is a little faster with explicit conversion than with a function call.

The following table lists the available conversion keywords.
Type Conversion Keyword
Converts Expression
to Data Type
Permitted Data Types of Expression to Be Converted
CBool
Boolean
Any numeric type (including Byte and enumerated types), String, Object
CByte
Byte
Any numeric type, any enumerated type, Boolean, String, Object
CChar
Char
String, Object
CDate
Date
String, Object
CDbl
Double
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CDec
Decimal
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CInt
Integer
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CLng
Long
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CObj
Object
Any type
CShort
Short
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CSng
Single
Any numeric type (including Byte and enumerated types), Boolean, String, Object
CStr
String
Any numeric type (including Byte), Boolean, Char, Char array, Date, Object
CType
Type specified following the comma (,)
When you convert to an elementary type (including an array of an elementary type), the same types as are permitted for the corresponding conversion keyword.

When you convert to a composite type, the interfaces it implements and the classes from which it inherits.

Monday 12 December 2011

Extract Interface from Custom Class (C#)

How to Extract Class Members to Interface in C#

You can extract one or more public members from a type into a new interface.
To extract members to a new interface
1. In Class Designer, right-click the type that contains the member or members you want to extract, point to Refactor, and click Extract Interface.
The Extract Interface dialog box displays default values for the name of the interface and the name of the code file in which it will be declared. Either accept the default values or change them.
2. In the Select public members to form interface pane, select or clear the check box next to the members you want to extract into the new interface, and click OK.
A new interface is created, and the file that houses it is added to the project.

Friday 9 December 2011

Visual Studio Add-ins vs. Shared Add-ins

Types of Add-Ins in Visual Studio

There are two different Add-in project types: Visual Studio and Shared.

A Visual Studio add-in can be loaded into both Visual Studio and the Visual Studio Macros IDE. Conversely, a Shared add-in can be loaded only into Microsoft Office applications such as Microsoft Word, Microsoft Publisher, Microsoft Visio, and Microsoft Excel. Also, each type offers a different set of options.

For example, the Visual Studio Add-in Wizard allows you to:

• Create a command bar user interface (UI) for your add-in,
• Define when the add-in loads, and
• Insert information into the Visual Studio Help About box.

The Shared Add-in Wizard only allows you to:

• Specify whether the add-in loads when the host application (that is, the Office application) loads, and
• Specify whether the add-in is available to all users of the computer or only the person who installed it.

In short, create Shared add-ins for use in Office applications, and create Visual Studio add-ins for use in Visual Studio.

Wednesday 7 December 2011

What is a static class?

Static classes are classes that do not contain instance members other than those inherited from Object, and do not have a callable constructor.
 
The members of a static class are accessed directly 
without an instance of the class.

Example
Console.WriteLine ("I Do not need any instances")

Tuesday 6 December 2011

Preventing multiple instances of .Net Application

Single instance application in VB.Net
If you were creating a Windows application, most often you would be doing some database initialization or some network validation before you show up the form to the user.
The patient user might wait few seconds to let the form show, others might launch the application again. To avoid user launch multiple instances of the application, select the Make single instance application check box to prevent users from running multiple instances of your application. The default setting for this check box is cleared, allowing multiple instances of the application to be run.
You can do this from ProjectàPropertiesàApplication tab

Friday 2 December 2011

Download Visual Studio 2008 and the .NET Framework 3.5

Microsoft announced that Visual Studio 2008 and the .NET Framework 3.5 were released to manufacturing (RTM). With more than 250 new features,Visual Studio 2008 includes significant enhancements in every edition, including Visual Studio Express and Visual Studio Team System. Developers of all levels – from hobbyists to enterprise development teams – now have a consistent, secure and reliable solution for developing applications for the latest platforms: the Web, Windows Vista, Windows Server 2008, the 2007 Office system, and beyond. Learn more about Visual Studio 2008. All of the above happening @ http://msdn2.microsoft.com/en-us/vstudio/default.aspx

Wednesday 30 November 2011

StackTrace in VB.Net


Stack Trace is a string that describes the contents of the call stack, with the most recent method call appearing first.
This is most commontly used to know the place of code that generated an exception
Sub Stack_Trace_Exception_Example()

Try
Dim iVar As Long
iVar = "Assign String"
Catch ex As Exception
MsgBox(ex.StackTrace)
End Try
End Sub

The above example shows the stacktrace in message box when the type mismatch exception is thrown
The execution stack keeps track of all the methods that are in execution at a given instant. A trace of the method calls is called a stack trace. The stack trace listing provides a means to follow the call sequence to the line number in the method where the exception occurs.
StackTrace may not report as many method calls as expected, due to code transformations, such as inlining, that occur during optimization.
The StackTrace property is overridden in classes that require control over the stack trace content or format. By default, the stack trace is captured immediately before an exception object is thrown. Use Environment.StackTrace to get stack trace information when no exception is being thrown as shown below:

Sub Stack_Trace_Environ_Example_Level1()
Console.WriteLine(System.Environment.StackTrace.ToString)
Stack_Trace_Environ_Example_Level2()
End Sub

Sub Stack_Trace_Environ_Example_Level2()
MsgBox(System.Environment.StackTrace)
End Sub

The trace output is shown below:

Sunday 27 November 2011

Get Folder Size using .Net


For getting the size of each directory in Vb.Net, you need to add up the size of each file in the directory.

This function gets the size of each directory including sub-directories and writes to a text file

Imports System.IO

Dim oBuffer As System.IO.TextWriter


Function Get_Directory_Size(ByVal sDirPath As String)

Dim lDirSize As Long
Dim oDir As DirectoryInfo
Dim sDir As DirectoryInfo
Dim sFiles As FileInfo
Dim iFN As Short '* File Number
Dim sPath As String '* Saving Path

'Dim oFSW As System.IO.FileSystemWatcher

oDir = New DirectoryInfo(sDirPath)

Dim oDirs As DirectoryInfo() = oDir.GetDirectories()

For Each sDir In oDirs

lDirSize = 0

For Each sFiles In sDir.GetFiles("*.*")
lDirSize += sFiles.Length
Next


'MsgBox("Size of Directory " & sDir.Name & " is " & lDirSize)
oBuffer.WriteLine(sDir.FullName & vbTab & lDirSize)

Get_Directory_Size(sDirPath & sDir.Name & "\")

Next


End Function

The procedure below uses WriteLine function of the StreamWriter class


Sub Store_Size_Of_Directory

Dim sOPFile As String

sOPFile = c:\SystemDirSize.log"
oBuffer = New System.IO.StreamWriter(sOPFile)
oBuffer.WriteLine(Now())

Get_Directory_Size("c:\")

oBuffer.Close()
End Sub

Thursday 24 November 2011

VB.Net Setting Default & Cancel Buttons

Setting Default & Cancel Buttons in Visual Basic.Net Form

Default button is in VB.NEt with a different name - AcceptButton. However, cancel button retains its name:

Here is a way you can set them

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

'Sets cmdOK as the button control that is clicked when the user presses the Enter key.
Me.AcceptButton = cmdOK

'Sets cmdCancel as the button control that is clicked when the user presses the ESC key.
Me.CancelButton = cmdCancel

End Sub

Wednesday 23 November 2011

VB.Net Form Close vs Form Dispose

Two methods doing some identical jobs always create some confusion. What to use to 'unload' the form Form.Close or Form.Dispose

Form.Close should be the answer as going by Microsoft Form.Close disposes the form as well if the form Modeless .

One more advantage you get from this method is from the events that are associated with the form

You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show("Form is closing", "Form Close", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) = Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub

The above prevents the form being closed

When the form is opened as Modal form (using Showdialog) you can dispose the form explicitly

Tuesday 22 November 2011

Opening & Closing Forms in .Net

Opening & Closing the forms have changed from Visual Basic 6.0 to VB.Net

The Form object in Visual Basic 6.0 is replaced by the Form class in Visual Basic 2005. The names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior


Form1.Show Modal=True in VB 6.0 is replaced with the ShowDialog


Sub Show_Form_Modal()

Form1.ShowDialog() ' Modal

End Sub


Sub Show_Form_Modeless()

Form1.Show() ' Modeless

End Sub

Closing which was done by Unload(Me)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.Close()

End Sub

Monday 21 November 2011

Get Computer Name in .Net

Use the My object to get the name of the computer

' Returns Name of the Computer

Function Get_Comp_Name() As String

Return My.Computer.Name.ToString

End Function

Sunday 20 November 2011

Get Day of the Week

A simplest function to get the day of the week

Sub DisplayTime()
MessageBox.Show(GetTime)
End Sub

Function GetTime() As String
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or _
My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then
Return "Happy Weekend!"
Else
Return "Happy Weekday! Don't work too hard!"
End If
End Function

Friday 18 November 2011

OpenFileDialog in Visual Basic .Net

List Files in Visual Basic .Net / Visual Basic 2005

The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in Visual Basic 2005.

Conceptual Differences
The Visual Basic 6.0 DirListBox control was typically used to display directories and paths in a File Open or Save dialog box.

In Visual Basic 2005, the Windows Forms OpenFileDialog and SaveFileDialog components provide the ability to create standard Windows dialog boxes for working with files, in most cases eliminating the need for the DirListBox control.


For this example, Let us have a form with a TextBox and a command button. When the command buton is pressed, the folderdialog is shown and then the selected folder is displayed in the textbox

Sample Form:




Add the FolderBrowser Dialog to the form from the Dialogs Collection (see below).




This control will not be placed on the form but on a separate tray at the bottom of the Windows Forms Designer. (see below)




Now in the click event for the Button have the following code:


Private Sub BtnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFile.Click

Dim MyFileOpen As New System.Windows.Forms.OpenFileDialog
Dim bExOccured As Boolean
Dim retVal As DialogResult
Dim sMyFile As String
Try
' does not add an extension to a file name if the user omits the extension
MyFileOpen.AddExtension = True

'dialog box does not allow multiple files to be selected
MyFileOpen.Multiselect = False

MyFileOpen.Filter = "ASCII files (*.txt;*.log)|*.txt;*.log"

retVal = MyFileOpen.ShowDialog()
If retVal = Windows.Forms.DialogResult.OK Then

If MyFileOpen.CheckFileExists = True And MyFileOpen.CheckPathExists = True Then

sMyFile = MyFileOpen.FileName

End If
End If
Catch ex1 As AccessViolationException
MsgBox(ex1.StackTrace.ToString)
bExOccured = True
Catch ex As Exception
MsgBox(ex.StackTrace.ToString)
bExOccured = True
Finally
If bExOccured = True Then
MsgBox("Program executed with some errors!!!")
End If
End Try
End Sub

You can use filters to restrict the type of files that can be opened. A sample of common filters is given below

'MyFileOpen.Filter = "Microsoft Word Documents (*.doc)|*.doc|Microsoft Word Documents (*.rtf)|*.rtf"
'MyFileOpen.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF"
'MyFileOpen.Filter = "Microsoft Word Documents (*.doc;*.rtf)|*.doc;*.rtf"

'MyFileOpen.Filter = "Microsoft Excel Workbooks (*.xls)|*.xls"
'MyFileOpen.Filter = "Microsoft Excel Addins (*.xla;*.xll)|*.xla;*.xll"
'MyFileOpen.Filter = "All files (*.*)|*.*"
'MyFileOpen.Filter = "Text files (*.txt)|*.txt"


This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only check box is checked.

Most of the functionality for this class is found in the FileDialog class.

Microsoft recommends that you use the OpenFileDialog and SaveFileDialog components to provide a consistent and familiar user experience. If you find it necessary to create your own file dialog boxes, Visual Basic 2005 does provide a DirListBox control as part of the Microsoft Visual Basic Compatibility Runtime library.

Thursday 17 November 2011

How to get Temporary Folder using .NET (C#)

How to get path of the current system's temporary folder using .NET (C#)

Temporary folders are useful to store simple logs during execution of the program. It is also used for storing the decompressed files before any operation. The folder location varies from OS to OS. The following C# snippet would help in retrieving the Temporary folder path
string sPath;
sPath = Path.GetTempPath();
Console.WriteLine("Temporary Path := " + sPath );

Wednesday 16 November 2011

C# Console Application – Pause for User Input / Pause Command in C# Console Application

In some cases you may require to pause for the user input or display a message to the user and prompt him to continue by pressing the key.

ReadKey does the trick. It obtains the next character or function key pressed by the user.
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
If you want the key to be displayed on user window, you can set the parameter to be false. You can also get the pressed key using as ConsoleKeyInfo shown below
Console.WriteLine("Press any key to continue...");
System.ConsoleKeyInfo KInfo = Console.ReadKey(true);
Console.WriteLine("You have pressed :" + KInfo.Key.ToString());
Press any key to continue in C#, C# Console Application Wait, Wait for user input in C# Console Application, C# Console Application, C# ConsoleKeyInfo, C# KeyPress in Console Application
Press any key to continue in .NET, .NET Console Application Wait, Wait for user input in .NET Console Application, .NET Console Application


Convert String to Long using C#


Int64.Parse Method converts the string representation of a number to its 64-bit signed integer equivalent. This can be used to convert the string to long as shown below
public long Convert2Long(String Str1)
{
try
{
long LngString = Int64.Parse(Str1);
return LngString;
}
catch (System.FormatException)
{
Console.WriteLine("Parameter is not in required format");
return -1;
}
}