Windows Phone Developers

Thursday, July 31, 2008

Validate Windows Form Controls in Vb.Net

Validation Controls for Windows Forms (VB.NET)

The Windows Forms ErrorProvider component is used to validate user input on a form or control. It is typically used in conjunction with validating user input on a form, or displaying errors within a dataset. An error provider is a better alternative than displaying an error message in a message box, because once a message box is dismissed, the error message is no longer visible. The ErrorProvider component displays an error icon ( ) next to the relevant control, such as a text box; when the user positions the mouse pointer over the error icon, a ToolTip appears, showing the error message string.


ErrorProvider Component

Drag the component to the Windows Forms Designer

ErrorProvider Component Attached to Designer


The ErrorProvider component's key properties are DataSource, ContainerControl, and Icon. When using ErrorProvider component with data-bound controls, the ContainerControl property must be set to the appropriate container (usually the Windows Form) in order for the component to display an error icon on the form. When the component is added in the designer, the ContainerControl property is set to the containing form; if you add the control in code, you must set it yourself.

The Icon property can be set to a custom error icon instead








The key method of the ErrorProvider component is the SetError method, which specifies the error message string and where the error icon should appear.

The code below uses ErrorProvider1.SetError instead of the usual msgbox for displaying errors.

Private Sub MaskedTextBox1_MaskInputRejected(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected

If MaskedTextBox1.MaskFull Then

ErrorProvider1.SetError(MaskedTextBox1, "Please do not attempt to type extra data")

ElseIf e.Position = MaskedTextBox1.Mask.Length Then

ErrorProvider1.SetError(MaskedTextBox1, "End of Input: If necessary modify appropriate data by typeover")

Else

ErrorProvider1.SetError(MaskedTextBox1, "Only numerals are accepted")

End If

End Sub

The icon will appear next to the component that has error. This can be customized for your application. When you hover mouse over the icon, the error message will be displayed as a tooltip

Windows Forms ErrorProvider component in VB.NET, SetError Method in VB.NET, VB.NET Windows form Validation, Display error messages in tooltips using Vb.NET, VB.NET Windows Form Controls

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

Visual Studio 2008 Image Library

The Visual Studio 2008 Image Library is a collection of application images that appear in Microsoft Windows, Microsoft Office, Microsoft Visual Studio, and other Microsoft software. You can use this set of over 1,000 images to create applications that look visually consistent with Microsoft software.

The image library includes three main categories of images: animations, bitmaps, and icons. A readme file, *readme.htm, is included for each major area. These readme files include information about the appropriate use of these images in your applications.
During Visual Studio setup, the image library is copied to your computer as the file VS2008ImageLibrary.zip. The default directory for this file is \...\Program Files\Microsoft Visual Studio 8\Common7\VS2005ImageLibrary\ (for VS 2005) or C:\Program Files\Microsoft Visual Studio 9.0\Common7\.


VS2008ImageLibrary.zip


To Install VS 2008 Image library, right click the compressed file and select extract all and follow the process

Install Visual Studio 2008 Image Library

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

Calculating Time taken for an operation using VB.NET (in Milliseconds)

Calculate Processing Time for a Vb.NET Subroutine (accuracy to millisecond)

Not every project will have the luxury of having rational analyzer to check the process time for every subroutine/function. In those cases we can use the StopWatch to determine the time taken for a program

Imports System.Diagnostics

Sub Get_Accurate_ProcessTime()

Dim oWatch As New Stopwatch

oWatch.Start()

Process_database()

oWatch.Stop()

MsgBox("Total Time Taken for Database Operation := " & oWatch.ElapsedMilliseconds.ToString)


End Sub

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.

By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter. 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

Tuesday, July 29, 2008

Create Custom Task Panes for Word using VSTO

How to Create a Word Addin using Visual Studio

Creating VSTO Word Addins in using Visual Studio is a simple process

Select Project - -> New Project - -> Office - ->Select the Version of Office (Office 2007, Office 2003) - ->Word 2007/2003 Addin


VSTO Word Addin

This will create a solution as shown below. A new class will be added with Startup and Shutdown methods



VSTO Startup & Shutdown Methods

To add a custom taskpane, insert an user control and add required controls on it and use the following code


VB.NET User Control
VSTO CustomTaskPane Designer

Imports Word = Microsoft.Office.Interop.Word

Public Class ThisAddIn

Private oUC As New UserControl1

Private oTaskPane As Microsoft.Office.Tools.CustomTaskPane

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup

For i1 = 1 To Me.CustomTaskPanes.Count

Me.CustomTaskPanes.Remove(Me.CustomTaskPanes(i1))

Next i1

Add_Task_Pane()

End Sub

Private Sub ThisAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown

End Sub

Public ReadOnly Property MyTaskPane() As Microsoft.Office.Tools.CustomTaskPane

Get

Return oTaskPane

End Get

End Property

Private Sub Add_Task_Pane()

oUC = New UserControl1 ' New Object of TaskPane (UserControl)

oTaskPane = Me.CustomTaskPanes.Add(oUC, "VBADUD Sample TaskPane", Me.Application.ActiveWindow)

oTaskPane.Visible = True

End Sub

Public ReadOnly Property WordDoc() As Word.Document

Get

Return Me.Application.ActiveDocument

End Get

End Property

End Class

To get the document information on the Label use the following code

Public Class UserControl1

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

End Sub

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

Label1.Text = Globals.ThisAddIn.WordDoc.FullName

Label1.Update()

End Sub

End Class

WordDoc is retrieved from the property exposed by the Addin class


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

Validate Phone Numbers, Zipcode TextBox entry in Vb.NET Used Masked Text Boxes.

MaskedTextBox Control in VB.NET

MaskedTextBoxes can be thought as the extension of MaskedEdit Control of VB6.0. It can be used to validate TextBox input based on ‘Mask’

The MaskedTextBox class is an enhanced TextBox control that supports a declarative syntax for accepting or rejecting user input. Using the Mask property, you can specify the following input without writing any custom validation logic in your application:

· Required input characters.

· Optional input characters.

· The type of input expected at a given position in the mask; for example, a digit, or an alphabetic or alphanumeric character.

· Mask literals, or characters that should appear directly in the MaskedTextBox; for example, the hyphens (-) in a phone number, or the currency symbol in a price.

· Special processing for input characters; for example, to convert alphabetic characters to uppercase.




When a MaskedTextBox control is displayed at run time, it represents the mask as a series of prompt characters and optional literal characters. Each editable mask position, representing a required or optional input, is shown with a single prompt character. For example, the number sign (#) is often used as a placeholder for a numeric character input. You can use the PromptChar property to specify a custom prompt character. The HidePromptOnLeave property determines if the user sees the prompt characters when the control loses input focus.




As the user types input into the masked text box, valid input characters replace their respective prompt characters in a sequential fashion. If the user types an invalid input character, no replacement occurs, but instead a beep is issued if the BeepOnError property is set to true, and the MaskInputRejected event is raised. You can provide your own custom error logic by handing this event.

Private Sub MaskedTextBox1_MaskInputRejected(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected

If MaskedTextBox1.MaskFull Then

MsgBox("Please do not attempt to type extra data")

ElseIf e.Position = MaskedTextBox1.Mask.Length Then

MsgBox("End of Input: If necessary modify appropriate data by typeover")

Else

MsgBox("Only numerals are accepted")

End If

End Sub

When the current insertion point is at a literal character, the user has a number of options:

· If a character other than the prompt character is typed, the literal will automatically be skipped and the input character will be applied to the next editable position, represented by the next prompt character.

· If the prompt character is typed and the AllowPromptAsInput property is true, the input will overtype the prompt character and insertion point will be moved to the next position in the mask.

· As is always the case, the arrow keys can be used to navigate to a previous or subsequent position.

You can use the MaskFull property to verify whether or not the user has entered all of the required input. The Text property will always retrieve the user's input formatted according to the mask and the TextMaskFormat property.

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

Dim sBoardingCity As String

Dim sDestnCity As String

sBoardingCity = DomainUpDownSource.Text

sDestnCity = DomainUpDownDestn.Text

If MaskedTextBox1.MaskFull = False Then

MsgBox("Please complete the form")

MaskedTextBox1.Focus()

End If

End Sub





The MaskedTextBox control actually defers all mask processing to the System.ComponentModel..::.MaskedTextProvider class specified by the MaskedTextProvider property. This standard provider supports all Unicode characters except for surrogates and vertically combined characters; however, the AsciiOnly property can be used to restrict input to the characters sets a-z, A-Z, and 0-9.

Masks do not necessarily guarantee that a user's input will represent a valid value for a given type; for example, -9 could be entered for an age in years. You can verify that a user's input represents a valid value by assigning an instance of that value's type to the ValidatingType property. You can detect whether the user removes focus from MaskedTextBox when it contains an invalid value by monitoring for the TypeValidationCompleted event. If type validation succeeds, the object representing the value will be available through the ReturnValue property of the TypeValidationEventArgs parameter.

As with the TextBox control, several common keyboard shortcuts do not work with MaskedTextBox. In particular, CTRL-R (right justify text), CTRL-L (left justify text), and CTRL-L (center text) have no effect.


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

VB.NET Controls - DomainUpDown Example

DomainUpDown Control in VB.NET


The Windows Forms DomainUpDown control looks like a combination of a text box and a pair of buttons for moving up or down through a list. The control displays and sets a text string from a list of choices. The user can select the string by clicking up and down buttons to move through a list, by pressing the UP and DOWN ARROW keys, or by typing a string that matches an item in the list. One possible use for this control is for selecting items from an alphabetically sorted list of names. (To sort the list, set the Sorted property to
true.) The function of this control is very similar to the list box or combo box, but it takes up very little space.

The key properties of the control are Items, ReadOnly, and Wrap. The Items property contains the list of objects whose text values are displayed in the control. If ReadOnly is set to false, the control automatically completes text that the user types and matches it to a value in the list. If Wrap is set to true, scrolling past the last item will take you to the first item in the list and vice versa. The key methods of the control are UpButton and DownButton.

This control displays only text strings. If you want a control that displays numeric values, use the NumericUpDown control.

Here is the way to add items in the control

Sub Add_Cities_To_DropDown()

DomainUpDownSource.Items.Add("Tokyo")

DomainUpDownSource.Items.Add("Moscow")

DomainUpDownSource.Items.Add("Chennai")

DomainUpDownSource.Items.Add("New York")

DomainUpDownSource.Items.Add("London")

DomainUpDownSource.Items.Add("Paris")

DomainUpDownSource.Sorted = True

DomainUpDownSource.ReadOnly = True

End Sub

Selected Items can be retrieved through Text property:

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

Dim sBoardingCity As String

Dim sDestnCity As String

sBoardingCity = DomainUpDownSource.Text

sDestnCity = DomainUpDownDestn.Text

End Sub






SelectedItemChanged event can be trapped to dynamically generate output based on selected text

Private Sub DomainUpDownSource_SelectedItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DomainUpDownSource.SelectedItemChanged

GetDestination(DomainUpDownSource.Text)

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

Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'

Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'

If a property is not declared as ReadOnly or WriteOnly, it must supply procedures for reading and writing its value.

Error ID: BC30124




The error comes in the following example as ‘Set’ procedure is not available

Public Property MyTaskPane() As Microsoft.Office.Tools.CustomTaskPane

Get

Return oTaskPane

End Get

End Property

To correct

1. Make sure you include both a Get procedure and a Set procedure between the Property statement and the End Property statement.

2. Verify that other procedures within the Property declaration are correctly terminated.

In the above example, the TaskPane is not set and hence it can be a read-only property

Public ReadOnly Property MyTaskPane() As Microsoft.Office.Tools.CustomTaskPane

Get

Return oTaskPane

End Get

End Property


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

Reference to a non-shared member requires an object reference


How to Reference Word/Excel application in a UserControl/TaskPane



After creating taskpane (through user control, you will have necessity to process the Word document/ Excel workbook based on events)

Imports Word = Microsoft.Office.Interop.Word

Public Class UserControl1

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

Word.Selection.Text = ""

End Sub

End Class

The above code would cause Reference to a non-shared member required an object reference error. Instead declare a Shared Variable in the Addin class and use the same from usercontrol

Public Class ThisAddIn

Public Shared oWA As Word.Application

..

End Class

And in the UserControl reference it with the object name

Public Class UserControl1

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

ThisAddIn.oWA.ActiveDocument.Range.Text = "Sample"

End Sub

End Class

You have referenced a non-shared member within your code and failed to supply an object reference. You cannot use the class name itself to qualify a member that is not shared. The instance must first be declared as an object variable and then referenced by the variable name.

Error ID: BC30469

To correct this error

1. Declare the instance as an object variable.

2. Reference the instance by the variable name.

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, July 21, 2008

Preventing Office Addin from loading Everytime when Application Opens

When add-in is created its LoadBehavior registry value is 3 in the Setup project. This results in every Office session add-in load. Change the value of 3 to 1 for not loading the add-in by default

Registry key is available HKEY_CLASSES_USER\Software\Microsoft\Office\\Addins\\LoadBehavior

(Registry Value for LoadBehavior)





(Office Addin when Automatic Loaded)




Preventing Excel Addin from loading Everytime when Application Opens, Preventing Word Addin from loading Everytime when Application Opens, Preventing Powerpoint Addin from loading Everytime when Application Opens, Preventing Outlook Addin from loading Everytime when Application Opens
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, July 20, 2008

Creating a Serialized Class using VB.NET

Storing objects in a flat file using VB.NET

Serialization/ Retrieving object data from file using Vb.NET Deserialization

In the following example, let us look at a way by which we can make user-defined classes Serializable. The first step is to have attribute added to the class as

Public Class CVideoLibraryOrder

Now the objects that are derived from the classes can be serialized

Imports System

Imports System.IO

Imports System.Collections

Imports System.Runtime.Serialization.Formatters.Binary

Imports System.Runtime.Serialization

Public Class CVideoLibraryOrder

Implements IDeserializationCallback

Public VID As Integer

Public VName As String

Public VQty As Integer

Public VPrice As Decimal

Public VTotal As Integer

Public Sub New(ByVal _VID As Integer, ByVal _VName As String, ByVal _Vqty As Integer, ByVal _vPrice As Decimal)

MyBase.New()

VID = _VID

VName = _VName

VQty = _Vqty

VPrice = _vPrice

VTotal = VPrice * VQty

End Sub

Sub IDeserializationCallback_Deserialize(ByVal sender As Object) Implements IDeserializationCallback.OnDeserialization

' Calculate the total after Deserialization

VTotal = VPrice * VQty

End Sub

End Class

makes the objects of the class serializable. The above example has an Variable ‘VTotal’ which can be generated dynamically. Hence we need not serialize this object; can be calculated during deserialization (Disable Serialization of Class Members - VTotal). This can be done by using IDeserializationCallback interface

Public Class CVideoLibraryOrder

Implements IDeserializationCallback

And implement IDeserializationCallback.OnDeserialization

Sub IDeserializationCallback_Deserialize(ByVal sender As Object) Implements IDeserializationCallback.OnDeserialization

' Calculate the total after Deserialization

VTotal = VPrice * VQty

End Sub

This will calculate VTotal when deserialized as shown in the following example:

Sub Rent_A_DVD()

' Example of using a custom class which is serializable

' --------------------------------------------

' Hold Operation

' Store the data Temporarily in Text File

' --------------------------------------------

Dim FS As FileStream = New FileStream("c:\VBADUD\VCDExmpleSerialized.txt", FileMode.Create)

Dim oItem As CVideoLibraryOrder

Dim BFmt As New BinaryFormatter

oItem = New CVideoLibraryOrder(132, "Day of Jackal", 2, 4.5)

BFmt.Serialize(FS, oItem)

FS.Flush()

FS.Close()

' Some Other Operations - Different Bill etc

Dim oRestoredItem As CVideoLibraryOrder

FS = New FileStream("c:\VBADUD\VCDExmpleSerialized.txt", FileMode.Open)

oRestoredItem = CType(BFmt.Deserialize(FS), CVideoLibraryOrder)

FS = Nothing

oRestoredItem = Nothing

BFmt = Nothing

End Sub

End Class

Keywords : Writing Object to a Flat File using .NET, Writing Object to a Text File using .NET, Writing Object to a ASCII File using .NET, Retrieving objects from Flat Files, Retrieving objects from Text Files, Storing Object to a Flat File using .NET, Storing Object to a Text File using .NET, Storing Object to a ASCII File using .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