Windows Phone Developers

Wednesday, April 30, 2008

Get Free Disk Space in all drives using VB.Net

Get Available Disk Space using VB.Net


Sub GetSpaceInDrives()

'Dim oDinfo As DriveInfo

Dim oDrvs() As DriveInfo = DriveInfo.GetDrives

For Each Drv In oDrvs

If Drv.IsReady Then

MsgBox(Drv.Name & " " & Drv.AvailableFreeSpace.ToString)

End If

Next

End Sub

The statement

Dim oDrvs() As DriveInfo = DriveInfo.GetDrives

retrieves the drive names of all logical drives on a computer.

The IsReady property returns true if the drive is ready; false if the drive is not ready. If this check is not done then you will get System.IO.IOException was unhandled Message="The device is not ready. " exception.

AvailableFreeSpace property indicates the amount of free space available on the drive. Note that this number may be different from the TotalFreeSpace number because this property takes into account disk quotas

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

Copying Files using .Net Functions

CopyFile Function in VB.Net


Imports System.IO

Function CopyFile(ByVal sSourceFile As String, ByVal sDestnFile As String)

Dim oFile As New FileInfo(sSourceFile)

If oFile.Exists Then

oFile.CopyTo(sDestnFile)

Else

MsgBox("File Does not exist")

End If

End Function

Use the FileInfo class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.

Many of the FileInfo methods return other I/O types when you create or open files. You can use these other types to further manipulate a file. For more information, see specific FileInfo members such as Open, OpenRead, OpenText, CreateText, or Create.

If you are going to reuse an object several times, consider using the instance method of FileInfo instead of the corresponding static methods of the File class, because a security check will not always be necessary.

By default, full read/write access to new files is granted to all users.

The following table describes the enumerations that are used to customize the behavior of various FileInfo methods.

Enumeration

Description

FileAccess

Specifies read and write access to a file.

FileShare

Specifies the level of access permitted for a file that is already in use.

FileMode

Specifies whether the contents of an existing file are preserved or overwritten, and whether requests to create an existing file cause an exception.

NoteNote:

In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, "c:\temp c:\windows" also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string.





In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all the following are acceptable paths:

· "c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

· "c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

· "MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

· "\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

It is always a good practice to check the existence of the file with Exists property before performing operations

If oFile.Exists Then

oFile.CopyTo(sDestnFile)

Exists will return true if the file exists; false if the file does not exist or if the file is a directory.


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

Monday, April 28, 2008

.NET 3.5 Enhancements Training Kit Available for Download

Download .NET 3.5 Enhancements Training Kit


The .NET Framework 3.5 Enhancements Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the .NET 3.5 Enhancement features including: ASP.NET MVC, ASP.NET Dynamic Data, ASP.NET AJAX History, ASP.NET Silverlight controls, ADO.NET Data Services and ADO.NET Entity Framework.

System Requirements

  • Supported Operating Systems: Windows Vista; Windows XP
Microsoft Windows Vista
Microsoft Visual Studio 2008
Microsoft SQL Server 2005 (Express recommended)
Microsoft Office Powerpoint 2007 or the PowerPoint Viewer 2007 - Required to view the presentations
Windows PowerShell 1.0 RTM

Top of page

Instructions

Download and execute the kit. The kit will uncompress to the selected folder and launch a HTML browser for the content.

Top of page

Additional Information

This kit was developed by the Developer and Platform Evangelism Group.

Download the Kit http://www.microsoft.com/downloads/details.aspx?FamilyID=355c80e9-fde0-4812-98b5-8a03f5874e96&displaylang=en#AdditionalInfo

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

Sunday, April 27, 2008

Check Type of Variable in VB.Net

Identify Variable Type in VB.NET

Sub Check_Variable_Types()

Dim varByte As SByte

Dim varInt As Integer

Dim varString As String

Dim varExp As Exception

varString = "Temp"

varExp = New System.Exception("Sample Exception")

Dim varArr As Object() = {varByte, varInt, varString, varExp}

'The Object data type can point to data of any data type, including any object instance your application recognizes. Use Object when you do not know at compile time what data type the variable might point to.

'The default value of Object is Nothing (a null reference).

MsgBox(varArr.GetType.ToString())

For Each obj As Object In varArr

MsgBox(obj.GetType.IsValueType) 'Gets a value indicating whether the Type is a value type.

MsgBox(obj.GetType().ToString)

Next

End Sub

' Value types are those that are represented as sequences of bits; value types are not classes or interfaces. These are referred to as "structs" in some programming languages. Enums are a special case of value types.

'This property returns false for the ValueType class.

'This property returns true for enumerations, but not for the Enum type itself. For an example that demonstrates this behavior, see IsEnum.

'This property is read-only.


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

Nullable Type in Visual Basic.Net

Storing Null Values in VB.Net Variables

Most of times we use variables to store the response from the user; might be a simple message box. In that case, we would be using a boolean variable - one that can store True or False. What if the User didn't answer the question? It would be taken as False by default. To overcome this you can use the variable as Nullable. Now the var can have three states - True , False and Null

Sub Nullable_Example()

' Nullable type will be used to check if the value is assigned

Dim Answer As Nullable(Of Boolean)

Dim RetVal ' As MsgBoxResult

RetVal = MsgBox("Have you booked the ticket for olympics", vbYesNoCancel, "DotNetDud Examples")

If RetVal = vbYes Then

Answer = True

ElseIf RetVal = vbNo Then

Answer = False

End If

'Gets a value indicating whether the current Nullable<(Of <(T>)>) object has a value.

If Answer.HasValue Then

MsgBox("Question answered")

Else

MsgBox("Question not answered")

End If

' The above checks if the question is answered or not. Here the boolean variable answer can store True, False and Other


End Sub

You will get Error 'HasValue' is not a member of 'Boolean', if the variable is not declared as nullable (i.e., Dim Answer As Boolean)

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

Using Timer in VB.Net


Building an Electronic Clock in VB.Net using timer class

(VB.NET ProgressBar using Timer)

Public Class Form1

Dim t As New Timer

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

t.Interval = 1000

AddHandler t.Tick, AddressOf Me.t_ShowProgress

AddHandler t.Tick, AddressOf Me.t_ShowTime

t.Start()

End Sub

Private Sub t_ShowProgress()

ProgressBar1.Value += 10

If ProgressBar1.Value = 100 Then

ProgressBar1.Value = 0

End If

End Sub

Private Sub t_ShowTime()

Label1.Text = Now

End Sub

End Class

Add Handler - Associates an event with an event handler at run time. The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles keyword when defining a procedure to specify that it handles a particular event.

The Tick event (this is similar to Visual Basic Timer1_Timer event) occurs when the specified timer interval has elapsed and the timer is enabled. This is based on the interval set for the Timer (1000 ms or 1 sec here)

The progress bar will be reset after it reaches 100. The timer will run till the form is closed. Since the process is synchronous only the timer event will be executed or the label will be updated. The same can also be achieved async

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

Regular Expressions in Dot Net (.NET)

Finding Duplicate Words in a String using .NET Regular Expressions

Regular Expressions (REGEX) does wonders in programming. Here is a simple Regex code that identifies duplicate words like 'the the', 'something something' etc. Probably copyeditors can use this code to do the work that Microsoft Spell check does


Sub Regex_Checker_Duplicate_Words()

Dim oRegex As Regex

Dim sPattern As String

Dim oMatches As Match

Dim sText As String

sText = " the the category catastropic cat cat and rat b b "

sPattern = "\b([a-zA-Z]+)\s+\1"

oRegex = New Regex(sPattern)

oMatches = oRegex.Match(sText, sPattern)

While oMatches.Success

MsgBox(oMatches.Groups(0).Value.ToString)

oMatches = oMatches.NextMatch

End While

End Sub

Returns a new Match with the results for the next match, starting at the position at which the last match ended (at the character beyond the last matched character).

See Also
Extract Ref Links From WebPage using VB.Net Regular Expressions
Remove HTML Tags from String using .NET Regular Expressions
VB.NET Regular Expression to Check URL
VB.NET Regular Expression to Check Email Addresses
VB.NET Regular Expression to Check MAC Address
Regular Expression to Check Zip Code
Validate eMail Addresses using VB.NET Function
Regular Expressions in Dot Net (.NET)

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

Function '' doesn't return a value on all code paths


Function '' doesn't return a value on all code paths


The error Function '' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used occurs when a Function procedure has at least one possible path through its code that does not return a value.

You can return a value from a Function procedure in any of the following ways:

· Assign the value to the Function procedure name and then perform an Exit Function statement.

· Assign the value to the Function procedure name and then perform the End Function statement.

· Include the value in a Return Statement (Visual Basic).

If control passes to Exit Function or End Function and you have not assigned any value to the procedure name, the procedure returns the default value of the return data type.

Error ID: BC42105

To correct this error

· Check your control flow logic and make sure you assign a value before every statement that causes a return.

It is easier to guarantee that every return from the procedure returns a value if you always use the Return statement. If you do this, the last statement before End Function should be a Return statement.

Most often this kind of error happens when the return is missed in the Catch block. It would be advisable to return a value for the error too as shown below

Function ReturnSomeVal() As String

Try

Dim Svalue As String

' Processing

Return sValue

Catch ex As Exception

Return vbNullString

Finally

End Try

End Function

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

Access of shared member through an instance; qualifying expression will not be evaluated

Access of shared member through an instance; qualifying expression will not be evaluated

This error occurs when an instance variable of a class or structure is used to access a Shared variable, property, procedure, or event defined in that class or structure. This warning can also occur if an instance variable is used to access an implicitly shared member of a class or structure, such as a constant or enumeration, or a nested class or structure.

· Use the name of the class or structure that defines the Shared member to access it.

· Ensure that two variables do not have the same name in a particular scope

The purpose of sharing a member is to create only a single copy of that member and make that single copy available to every instance of the class or structure in which it is declared. It is consistent with this purpose to access a Shared member through the name of its class or structure, rather than through a variable that holds an individual instance of that class or structure.

Accessing a Shared member through an instance variable can make your code more difficult to understand by obscuring the fact that the member is Shared. Furthermore, if such access is part of an expression that performs other actions, such as a Function procedure that returns an instance of the shared member, Visual Basic bypasses the expression and any other actions it would otherwise perform.




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

Late bound resolution in .NET

Late bound resolution; runtime errors could occur

This error (Error ID: BC42017) occurs because an object is assigned to a variable declared to be of the Object Data Type.

When you declare a variable as Object, the compiler must perform late binding, which causes extra operations at run time. It also exposes your application to potential run-time errors. For example, if you assign a Form to the Object variable and then try to access the XmlDocument..::.NameTable property, the runtime throws a MemberAccessException because the Form class does not expose a NameTable property.

If you declare the variable to be of a specific type, the compiler can perform early binding at compile time. This results in improved performance, controlled access to the members of the specific type, and better readability of your code.

To avoid this error it is better to declare the data type of the variable

Private app As Excel.Application

Instead of

Private app As Object


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

Implicit conversion from '' to ''

An expression or an assignment statement takes a value of one data type and converts it to another type. Because no conversion keyword is used, the conversion is implicit.


Implicit conversion from 'Object' to 'Microsoft.Office.Core.CommandBars' can be rectified using

CType(app.CommandBars, Microsoft.Office.Core.CommandBars)

Ctype returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.

expression

Any valid expression. If the value of expression is outside the range allowed by typename, Visual Basic throws an exception.

typename

Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface.

CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some cases there is no call to a procedure to accomplish the conversion, which makes execution faster.

If no conversion is defined from expression to typename, for example from Integer to Date, Visual Basic displays a compile-time error message.

If a conversion fails at run time, the appropriate exception occurs. If a narrowing conversion fails, an OverflowException is the most common result. If the conversion is undefined, an InvalidCastException occurs. This can happen, for example, if expression is of type Object and its run-time type has no conversion to typename.

If the data type of expression or typename is a class or structure you have defined, you can define CType on that class or structure as a conversion operator. This makes CType act as an overloaded operator. If you do this, you can control the behavior of conversions to and from your class or structure, including what exceptions can be thrown.

Overloading

The CType operator can also be overloaded on a class or structure defined outside your code. If your code converts to or from such a class or structure, be sure you understand the behavior of its CType operator.

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

Use of aliases in .NET (Imports Statement)

Imports Statement (.NET Namespace and Type) – Use of aliases

Use of aliases can save your precious time.

Imports Microsoft.Office.Interop.Excel

Public Class Form1

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

Dim oXL As Microsoft.Office.Interop.Excel.Application

oXL = New Microsoft.Office.Interop.Excel.Application

can be changed to

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

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

Dim oXL As Excel.Application

oXL = New Excel.Application

Saves a lot of typing and more concise.

Import aliases are useful when you need to use items with the same name that are declared in one or more namespaces. 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

Change the default values of Option Explicit and Option Strict in .NET

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"

>

  1. Repeat steps 2 and 3 for each project template that you want to change the default behavior for.
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

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.

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