Windows Phone Developers

Friday, July 13, 2007

StackTrace in Visual Basic .Net

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:

Stack Trace Picture

StackTrace in VB.Net, Exception Handling in VB.Net, Environment.StackTrace



Technorati Profile
Add to Technorati Favorites


Academics blogs
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, June 30, 2007

Opening & Closing Notepad using .Net

Opening & Closing of Application using .Net / Create New process in .Net / Shell Function in .Net

A program is not Userinterface and database connections alone, it also needs to interact with other applications. Many a times, this interaction happens internally, like updating Word Template, Printing out a document etc, but there are times where one needs to open an document through the Application.

Let us have a sample app that opens a Notepad on click of a command button. We have a sample form with a button (see below).



Now add the process control from the Components Control (see below)





This control has no design features and will be used in run-time and it straightway gets docked in the tray (see below)




Change the following properties of the control.



This can also be changed during run time.



Now in the Button Click event write the following code:

Private Sub ButtonNotepad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadNotepadButton.Click
' http://dotnetdud.blogspot.com/
ProcessNotepad.EnableRaisingEvents = True
ProcessNotepad.Start()

End Sub


The EnableRaisingEvents property indicates whether the component should be notified when the operating system has shut down a process. The EnableRaisingEvents property is used in asynchronous processing to notify your application that a process has exited. To force your application to synchronously wait for an exit event (which interrupts processing of the application until the exit event has occurred), use the WaitForExit method.

This will start the Notepad Application. If you want receive the closure of application use the following event

Private Sub ProcessNotepad_Exited(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessNotepad.Exited
' Coded for http://dotnetdud.blogspot.com/
MessageBox.Show("Notepad has been closed ", "Dot Net Tips & Tricks", MessageBoxButtons.OK)
End Sub

If you want to close the application use the kill method.

Private Sub ButtonClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeNotepadButton.Click
If ProcessNotepad.HasExited = False Then
ProcessNotepad.Kill()
End If
End Sub


We have used Notepad, as it is simple and easy. Try it with other stuff!!

See Also:

Show All Processes using VBA

Run a VB6.0 Executable from Excel/Word Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, June 23, 2007

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.


For CommonDialog implementation in VB6.0 refer http://vbadud.blogspot.com/2007/06/visual-basic-common-dialog.html

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility). Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Selecting a Folder in VB.Net

Directory Selection in Windows Forms using VB.Net

The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in Visual Basic 2005. If you want to select a directory FolderBrowser Dialog will be the one you need to use

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 BtnFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFolder.Click

Dim MyFolderBrowser As New System.Windows.Forms.FolderBrowserDialog

' Descriptive text displayed above the tree view control in the dialog box
MyFolderBrowser.Description = "Select the Folder"

' Sets the root folder where the browsing starts from
'MyFolderBrowser.RootFolder = Environment.SpecialFolder.MyDocuments

' Do not show the button for new folder
MyFolderBrowser.ShowNewFolderButton = False

Dim dlgResult As DialogResult = MyFolderBrowser.ShowDialog()

If dlgResult = Windows.Forms.DialogResult.OK Then
txt_watchpath.Text = MyFolderBrowser.SelectedPath
End If

End Sub


The FolderBrowserDialog component is displayed at run time using the ShowDialog method. Set the RootFolder property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. Once the dialog box has been shown, you can use the SelectedPath property to get the path of the folder that was selected


For similar functionality in VB6.0 refer http://vbadud.blogspot.com/2007/04/browse-folder-select-folder-thru-shell.html

When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility). Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, June 15, 2007

Directory Size using VB.Net

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

'--------------------------------------------------------
' Coded by Shasur for http://dotnetdud.blogspot.com/
'--------------------------------------------------------


'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"

'--------------------------------------------------------
' Coded by Shasur for http://dotnetdud.blogspot.com/
'--------------------------------------------------------

oBuffer = New System.IO.StreamWriter(sOPFile)
oBuffer.WriteLine(Now())

Get_Directory_Size("c:\")

oBuffer.Close()
End Sub Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, June 8, 2007

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



For setting the same in VBA/VB refer : http://vbadud.blogspot.com/2007/06/setting-default-cancel-buttons-in.html Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

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


RSS Feeds Submission Directory



alt="Webfeed (RSS/ATOM/RDF) registered at http://www.feeds4all.com" border="0">
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon