Friday, July 27, 2007

Formatting Number, Currency, Dates, and Time in VB.NET

Here is a great link with lots of formatting examples:

http://msconline.maconstate.edu/tutorials/VBNET/VBNET01/vbnet01-08.aspx

Friday, July 20, 2007

Path and Filename Decomposition function in VB.NET and C#

I had already written Path and Filename Decomposition functions in VB.NET and C# before I found the simple way to do it with the Path class:

filename = Path.GetFileName(Path)
extension = Path.GetExtension(Path)
fullPath = Path.GetFullPath(Path)
directoryName = Path.GetDirectoryName(Path)
FilenameWithoutExt = Path.GetFileNameWithoutExtension(Path)



However, I have need to use these function for similar things that the Path class cannot handle, so I am including them in this posting.

Here are 4 functions in VB.NET and C# that do path and filename decomposition:


1) GetFileNameFromPath will return a filename and its extension from a full directory path.

GetFileNameFromPath("c:\temp\test.txt") returns "test.txt"

GetFileNameFromPath("test.txt") returns "test.txt"

2) GetFileNameWithoutExtFromPath will return a filename without its extension from a full directory path.

GetFileNameWithoutExtFromPath("c:\temp\test.txt") returns "test"

GetFileNameWithoutExtFromPath("test.txt") returns "test"

3) GetDirFromPath will get the directory from a full path.

GetDirFromPath("c:\temp\test.txt") returns "C:\temp"

GetDirFromPath("test.txt") returns ""

4) GetExtensionFromPath will return only the file extension from either a filename or a full path.

GetExtensionFromPath("c:\temp\test.txt") returns ".txt"

GetExtensionFromPath("test.txt") returns ".txt"



VB.NET Code:


Public Function GetDirFromPath(ByVal path As String) _
As String

Try
Return path.Substring(0, path.LastIndexOf("\") + 1)

Catch ex As Exception
' error
Return ""
End Try

End Function
'
Public Function GetFileNameFromPath(ByVal path _
As String) As String

Try
Return path.Substring(path.LastIndexOf("\") + 1)
Catch ex As Exception
' error
Return ""
End Try

End Function
'
Public Function GetFileNameWithoutExtFromPath(ByVal path _
As String) As String

Try
Dim filename As String = _
path.Substring(path.LastIndexOf("\") + 1)
Dim pos As Integer = filename.LastIndexOf(".")

If pos <> -1 Then
Return filename.Substring(0, pos)
Else
Return filename
End If

Catch ex As Exception
' error
Return ""
End Try

End Function
'
Public Function GetExtensionFromPath(ByVal path _
As String) As String

Try
Dim pos As Integer = _
path.LastIndexOf(".")
If pos <> -1 Then
Return path.Substring(pos)
Else
Return ""
End If

Catch ex As Exception
' error
Return ""
End Try
End Function



C# Code:


public String GetDirFromPath(String path)
{
try
{
return path.Substring(0, path.LastIndexOf("\\") + 1);
}
catch (Exception ex)
{
// error
return "";
}
}


public String GetFileNameFromPath(String path)
{
try
{
return path.Substring(
path.LastIndexOf("\\") + 1);
}
catch (Exception ex)
{
// error
return "";
}

}

public String GetFileNameWithoutExtFromPath(String path)
{
try
{
String filename = path.Substring(
path.LastIndexOf("\\") + 1);
int pos = filename.LastIndexOf(".");

if (pos != -1)
return filename.Substring(0, pos);
else
return filename;
}

catch (Exception ex)
{
// error
return "";
}

}

public String GetExtensionFromPath(String path)
{
try
{
int pos = path.LastIndexOf(".");
if (pos != -1)
return path.Substring(pos);
else
return "";
}

catch (Exception ex)
{
// error
return "";
}

}

Thursday, July 19, 2007

Sharing a file between Multiple Projects in VB.NET or C#

It was difficult for me to figure this problem out without some help. If you want a .vb or .cs file (or any other file) shared between multiple projects in Visual Studio, the normal thing to do is to right click on the project in the Solution Explorer, select Add, then select Existing Item, and pick the file from project 1 that you want to share with project 2. This unfortunately makes a copy of the file and you now have two different versions of the file to maintain. However, the Add button on the Exiting Item's dialog has a innocuous drop down arrow. If you drop down the menu, you can choose Add as Link, which does not copy the file.




Here is a rambling discussion on this topic, but the is solution they come to is described above:




Generating a GUID in Windows Mobile using VB.NET or C#

It is puzzling to me why Windows Mobile can't natively generate its own GUIDs, but Microsoft does provide VB.NET and C# source code for creating a GUID:

http://msdn2.microsoft.com/en-us/library/aa446557.aspx

Finding the My Documents Directory in Windows Mobile (or the Desktop)

You can find the \My Documents directory on a Windows Mobile device by saying:

path = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)


GetFolderPath also works on the desktop.


For More Info:

http://msdn2.microsoft.com/en-us/library/system.environment.getfolderpath.aspx

http://blogs.msdn.com/windowsmobile/archive/2006/07/26/678742.aspx

Camera API for Windows Mobile

While is it sometimes a little difficult to find information on the Windows Mobile Camera API, there are several references. The CameraCaptureDialog is probably the key thing to look for, and also the CameraPresent attribute:

http://blogs.msdn.com/vsdteam/archive/2005/06/29/433961.aspx

http://msdn2.microsoft.com/en-us/library/microsoft.windowsmobile.forms.cameracapturedialog_members.aspx

http://www.google.com/search?q=camerapresent&sourceid=ie7&rls=com.microsoft:en-US&ie=utf8&oe=utf8

http://channel9.msdn.com/ShowPost.aspx?PostID=209787

Wednesday, July 18, 2007

File Handles are automatically closed for Files on a Storage Card when a Windows Mobile Device goes to Sleep

A difficult problem to track down in Windows Mobile development is the annoying problem caused when a Windows Mobile or Pocket PC devices goes to Sleep (when it inactive for a specfied amount of time). If you have a file on the storage card open and the devices goes to sleep, then when the device wakes back up, the file handle to your open file is invalid, but your application does not know this.

Here is some more information as to why:

http://blogs.msdn.com/windowsmobile/archive/2007/01/12/everything-you-want-to-know-about-sd.aspx

SetLength in VC++ will Throw Exception in Windows Mobile 6 emulator when file is in Shared Directory

While this posting is not really a .NET related issue, I am posting it anyway because the information is difficult to find on the web.

If you have a Windows Mobile 6 Emulator running (and appearently this error is also true for a few versions back), and you are sharing a directory between the desktop file system and the emulator (Shared Folder under the Emulator's Configure dialog will make a desktop directory show up as a \Storage Card directory on the emulator), then if you try to use CFile::SetLength on a file in the shared directory, the application will throw an exception for no apparent reason. I am also found other saying that FlushFileBuffers also has the same problem.

Here is the only other reference I have found to this problem:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=796830&SiteID=1

Friday, July 13, 2007

Optional Parameters and parameters with default values in VB.NET

It is possible to use an optional parameter in VB.NET that uses a default value as shown below:

Public Function SplitAttrValue(ByVal str As String, ByRef attr As String, ByRef value As String, Optional ByVal delimiter As String = "=") As Boolean

However, here is an article that describes why you should not do this:

http://www.knowdotnet.com/articles/optionalparams.html

Main reason is that C# doesn't support them (you must use overloading).

Using Reflection in VB.NET

Here is a link that has lots of good examples of using Reflection in VB.NET to get a list of members in a class, calling members in a class, etc.

http://www.java2s.com/Code/VB/Development/UseReflectiontocreateClassinstanceandcallmethod.htm

Tuesday, July 10, 2007

Passing a Function by Reference in VB.NET

If you are creating Test code, it is often very useful to be able to pass a function by reference. In my example below, my test modules all have one parameter which is a pointer to a TestResult object. I pass my Test modules to the RunTest function which creates a TestResult object, populates certain fields, and passes the object to the test module (which was passed in as a reference). This allows all of the work done for each call to a test module to be consolidated into one nice and neat function.

The key to making this work is to define a delegate with the right parameter signature, then use the delegate's name (TestDelegate in my example) when defining the type for the function you are passing.

Example:

Public Class TestResult

Public name As String = ""
Public pass As Boolean = False
Public startTime As DateTime
Public endTime As DateTime
Public comments As String = ""

End Class

Public Delegate Sub TestDelegate(ByVal result As TestResult)



Private Sub RunTest(ByVal testFunction As TestDelegate)

Dim result As New TestResult
result.startTime = DateTime.Now
testFunction(result)
result.endTime = DateTime.Now

End Sub

Private Sub MenuItemStartTests_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MenuItemStartTests.Click

Debug.WriteLine("Starting Tests...")
Debug.WriteLine("")
'==================================

' Add Calls to Test Modules Here

RunTest(AddressOf Test1)
RunTest(AddressOf Test2)

'==================================


Debug.WriteLine("")
Debug.WriteLine("Tests Completed")

End Sub


Private Sub Test1(ByVal result As TestResult)

result.name = "Test #1"
.
.
.
result.pass = True

End Sub

Private Sub Test2(ByVal result As TestResult)

result.name = "Test #2"
.
.
.
result.pass = True

End Sub

Thursday, July 5, 2007

Gridlines in a Listview with .NET Compact Framework

The .NET Compact Framework does not support the Gridline property on a listbox, but there is a way to get Gridlines to appears in a SmartDevice appliation.

Look at the Grid in Listview (C# and VB.NET) item on this page:

http://www.businessanyplace.net/?p=code#listviewgrid