Welcome Guest!
 VB Helper
 Previous Message All Messages Next Message 
VB Helper Newsletter  Rod Stephens
 Oct 12, 2011 12:03 PDT 

Visual Basic 24-Hour Trainer
http://www.vb-helper.com/24hourvb.htm

Unique book-and-DVD package for novice Visual Basic programmers

Start from scratch, and even if you don't know a thing about Visual
Basic, you soon will with this thorough introduction to Visual Basic
programming. Using easy-to-follow lessons and step-by-step instruction,
this practical book teaches you concepts and hands-on techniques, then
reinforces your learning with video screencasts and supplemental
materials. Follow the exercises, then access the Try It section on the
DVD, and watch as well-known VB authority and author Rod Stephens works
through programming problems.
-----
Have a great week and thanks for subscribing!

Rod
RodSte-@vb-helper.com

Twitter feeds:
    VBHelper
    CSharpHelper
==========
==========

    VB.NET Contents:
1. New HowTo: Use regular expressions and LINQ to list the unique words
contained in a text file in Visual Basic .NET
2. New HowTo: Use a setting that contains a string collection in Visual
Basic .NET
3. New HowTo: Make a series of TextBoxes and corresponding Labels at
runtime in Visual Basic .NET
4. New HowTo: Show samples of EXIF image orientations in Visual Basic
.NET
5. New HowTo: Read an image file's EXIF orientation data in Visual Basic
.NET
==========
++++++++++
      <VB.NET>
++++++++++
==========
1. New HowTo: Use regular expressions and LINQ to list the unique words
contained in a text file in Visual Basic .NET
http://www.vb-helper.com/howto_net_list_file_words_linq.html
http://www.vb-helper.com/HowTo/howto_net_list_file_words_linq.zip

When you enter the name of a file and click List Words, the following
code executes.

' List the words in the file.
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnGo.Click
    ' Get the file's text.
    Dim txt As String = File.ReadAllText(txtFile.Text)

    ' Use regular expressions to replace characters
    ' that are not letters or numbers with spaces.
    Dim reg_exp As New Regex("[^a-zA-Z0-9]")
    txt = reg_exp.Replace(txt, " ")

    ' Split the text into words.
    Dim words() As String = txt.Split( _
        New Char() {" "c}, _
        StringSplitOptions.RemoveEmptyEntries)

    ' Use LINQ to get the unique words.
    Dim word_query = _
        (From word As String In words _
         Order By word _
         Select word).Distinct()

    ' Display the result.
    lstWords.DataSource = word_query.ToArray()
    lblSummary.Text = lstWords.Items.Count & " words"
End Sub

The code first uses File.ReadAllText to copy the file's text into a
string.

Next the code uses regular expressions to replace non-letter and
non-number characters with spaces. It uses the pattern [^a-zA-Z0-9]. The
^ means "not the following characters." The a-zA-Z0-9 part means any
lowercase or uppercase letter or a digit. The code uses the Regex
object's Replace method to replace characters that match the pattern
with a space.

The code then uses Split to break the text into an array of words,
removing any adjacent duplicates.

The code uses LINQ to select all of the words from the array and sort
them. It uses the Distinct method to remove duplicates.

Finally the code displays the words in a ListBox and displays the number
of words in a Label.
==========
2. New HowTo: Use a setting that contains a string collection in Visual
Basic .NET
http://www.vb-helper.com/howto_net_list_setting.html
http://www.vb-helper.com/HowTo/howto_net_list_setting.zip

A program's settings can have many data types such as int, char,
DateTime, and Color. If you want to be able to hold a list of strings,
you can make a setting that has type StringCollection.

To create such a setting, open the Project menu and select Properties at
the bottom to see the following Properties page, and click the Settings
tab.

(Picture at http://www.vb-helper.com/howto_net_list_setting2.png.)

Enter the name you want to give the property in the left text box.
Select the data type System.Collections.Specialized.StringCollection in
the left dropdown. Use the right dropdown to set the setting's scope to
User (not shared) or Application (shared by all users).

If you run the program at this point, the setting isn't actually created
so if you try to add or remove an item from the collection you'll get
the error "Object reference not set to an instance of an object."

There are a couple of ways you can fix this. First, you can create the
setting object at run time if it is null, but this is a bit of a hassle.

A better solution is to click the Value text box on the Settings page.
Then click the ellipsis to the right to open a String Collection Editor.
If you close this without adding any strings, the Settings window
<b>still</b> doesn't actually create the setting object. To prevent
that, add a string to the String Collection Editor and click OK. Then
open the editor again, remove the string, and click OK. This keeps the
setting object but it's empty. If you look closely at the value shown in
the Settings page, you'll see:

    <?xml version="1.0" encoding="utf-16"?>
    <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

This defines an empty array of strings and that makes the program create
the setting object with no entries in it.

After going through all this to create the object, using is is fairly
easy. The following code shows how the program lists the strings in the
Items setting object.

' List the current items.
Private Sub ListItems()
    lstItems.DataSource = My.Settings.Items.Cast(Of String)().ToArray()
    lstItems.SelectedIndex = -1
End Sub

This code takes the Items object, invokes its Cast method to convert the
items into an IEnumerable of string, turns that into an array, and
assigns the result to the lstItems ListBox's DataSource property to
display the items. The code then makes sure no item is selected in the
list.

If the user clicks on an item in the ListBox, the following code
displays it in the program's text box.

' Display the selected item.
Private Sub lstItems_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles lstItems.SelectedIndexChanged
    If (lstItems.SelectedItem Is Nothing) Then
        txtValue.Clear()
    Else
        txtValue.Text = lstItems.SelectedItem.ToString()
    End If
End Sub

The following code shows how the program adds and removes items from the
Items collection.

' Add an item value.
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
    My.Settings.Items.Add(txtValue.Text)
    txtValue.Clear()
    txtValue.Focus()
    ListItems()
End Sub

' Remove an item value.
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnRemove.Click
    My.Settings.Items.Remove(txtValue.Text)
    txtValue.Clear()
    txtValue.Focus()
    ListItems()
End Sub

The program automatically saves changes to the settings when the form
closes.
==========
3. New HowTo: Make a series of TextBoxes and corresponding Labels at
runtime in Visual Basic .NET
http://www.vb-helper.com/howto_net_make_textboxes.html
http://www.vb-helper.com/HowTo/howto_net_make_textboxes.zip

When the program starts, it uses the following code to create a series
of TextBoxes with corresponding Labels.

' Make some Labels and TextBoxes.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
    ' Coordinates for the controls.
    Dim y As Integer = 8

    ' The labels to display.
    Dim captions() As String = {"Name:", "Street:", "City:", "State:",
"ZIP:"}
    For Each caption As String In captions
        ' Make the Label.
        Dim new_label As New Label()
        new_label.Parent = Me
        new_label.Text = caption
        new_label.Location = New Point(8, y)
        new_label.AutoSize = True

        ' Make the TextBox.
        Dim new_textbox As New TextBox()
        new_textbox.Parent = Me
        new_textbox.Location = New Point(50, y)
        new_textbox.Name = "txt" & caption.Replace(":", "")

        ' Move down.
        y += new_textbox.Height + 4
    Next caption
End Sub

The code defines the captions that the Labels should display. It then
loops through the captions creating Labels and TextBoxes. About the only
non-obvious thing to remember here is that you must set the controls'
Parent property to the form.
==========
4. New HowTo: Show samples of EXIF image orientations in Visual Basic
.NET
http://www.vb-helper.com/howto_net_show_exif_orientations.html
http://www.vb-helper.com/HowTo/howto_net_show_exif_orientations.zip

(Picture at
http://www.vb-helper.com/howto_net_show_exif_orientations.png.)

This example includes an ExifStuff module that holds routines for
working with EXIF data. The following code shows how the module defines
the ExifOrientations enumeration.

' Orientations.
Public Enum ExifOrientations As Byte
    Unknown = 0
    TopLeft = 1
    TopRight = 2
    BottomRight = 3
    BottomLeft = 4
    LeftTop = 5
    RightTop = 6
    RightBottom = 7
    LeftBottom = 8
End Enum

The following code shows the OrientationImage method, which returns a
sample image for each EXIF orientation.

' Make an image to demonstrate orientations.
Public Function OrientationImage(ByVal orientation As ExifOrientations)
As Image
    Const size As Integer = 64
    Dim bm As New Bitmap(size, size)
    Using gr As Graphics = Graphics.FromImage(bm)
        gr.Clear(Color.White)
        gr.TextRenderingHint =
System.Drawing.Text.TextRenderingHint.AntiAliasGridFit

        ' Orient the result.
        Select Case (orientation)
            Case ExifOrientations.TopLeft
            Case ExifOrientations.TopRight
                gr.ScaleTransform(-1, 1)
            Case ExifOrientations.BottomRight
                gr.RotateTransform(180)
            Case ExifOrientations.BottomLeft
                gr.ScaleTransform(1, -1)
            Case ExifOrientations.LeftTop
                gr.RotateTransform(90)
                gr.ScaleTransform(-1, 1, MatrixOrder.Append)
            Case ExifOrientations.RightTop
                gr.RotateTransform(-90)
            Case ExifOrientations.RightBottom
                gr.RotateTransform(90)
                gr.ScaleTransform(1, -1, MatrixOrder.Append)
            Case ExifOrientations.LeftBottom
                gr.RotateTransform(90)
        End Select

        ' Translate the result to the center of the bitmap.
        gr.TranslateTransform(size / 2, size / 2, MatrixOrder.Append)
        Using string_format As New StringFormat()
            string_format.LineAlignment = StringAlignment.Center
            string_format.Alignment = StringAlignment.Center
            Using the_font As New Font("Times New Roman", 40,
GraphicsUnit.Point)
                If (orientation = ExifOrientations.Unknown) Then
                    gr.DrawString("?", the_font, Brushes.Black, 0, 0,
string_format)
                Else
                    gr.DrawString("F", the_font, Brushes.Black, 0, 0,
string_format)
                End If
            End Using
        End Using
    End Using

    Return bm
End Function

This code simply uses scale and translation transformations to orient
its drawing output. It then draws the letter F to produce an image that
shows the letter with the correct EXIF orientation.

The main program contains 8 PictureBoxes. When it starts, the program
uses the following code to make each PictureBox display one of the EXIF
orientation images.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
    pic1.Image = OrientationImage(ExifOrientations.TopLeft)
    pic2.Image = OrientationImage(ExifOrientations.TopRight)
    pic3.Image = OrientationImage(ExifOrientations.BottomRight)
    pic4.Image = OrientationImage(ExifOrientations.BottomLeft)
    pic5.Image = OrientationImage(ExifOrientations.LeftTop)
    pic6.Image = OrientationImage(ExifOrientations.RightTop)
    pic7.Image = OrientationImage(ExifOrientations.RightBottom)
    pic8.Image = OrientationImage(ExifOrientations.LeftBottom)
End Sub
==========
5. New HowTo: Read an image file's EXIF orientation data in Visual Basic
.NET
http://www.vb-helper.com/howto_net_read_exif_orientation.html
http://www.vb-helper.com/HowTo/howto_net_read_exif_orientation.zip

(Picture at
http://www.vb-helper.com/howto_net_read_exif_orientation.png.)

The EXchangeable Image File (EXIF) standard defines all sorts of
information that a camera can add to a jpg file. For example, the camera
may record latitude, longitude, altitude, date and time, focal length,
shutter speed, and resolution. This example shows how to get an image's
orientation information.

Note that not all cameras can set EXIF information and some that can may
not unless you set the proper settings. The two pictures included with
this example do contain EXIF orientation information so you can test the
program.

The Image class (from which Bitmap inherits) provides two useful items
for working with EXIF data: the PropertyIdList property, and the
GetPropertyItem and SetPropertyItem methods.

The PropertyIdList property
dn.microsoft.com/en-us/library/system.drawing.image.propertyidlist.aspx)
returns an array of integers giving the IDs of the properties stored in
the image. You can use Array.IndexOf to try to find the index of a
particular property's ID in this array. (If the image doesn't contain
information for that property, Array.IndexOf returns -1.)

The GetPropertyItem method
://msdn.microsoft.com/library/system.drawing.image.getpropertyitem.aspx)
returns a PropertyItem object
dn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.aspx)
containing information about a property. You need to pass
GetPropertyItem the ID of the item you want to retrieve.

The PropertyItem class has the properties Id (the property's ID), Len
(the length in bytes of the property's value), Type (defines the type of
data in the Value property), and Value (the value).

The SetPropertyItem method
n.microsoft.com/en-us/library/system.drawing.image.setpropertyitem.aspx)
sets a property's value. Unfortunately there is no constructor for the
PropertyItem class so you cannot create one from scratch. You can,
however, get a PropertyItem from an image and modify it.

The orientation property's ID is 0x0112. The PropertyItem for the
orientation property holds an array of bytes in its Value property, with
the first byte giving the orientation. The following picture shows the
meanings of the orientations demonstrated by the letter F.

(Picture at
http://www.vb-helper.com/howto_net_show_exif_orientations.png.)

The example program places EXIF methods in an ExifStuff module. Here's
how it defines the orientation ID and the orientation values.

' Orientations.
Private Const OrientationId As Integer = &H112
Public Enum ExifOrientations As Byte
    Unknown = 0
    TopLeft = 1
    TopRight = 2
    BottomRight = 3
    BottomLeft = 4
    LeftTop = 5
    RightTop = 6
    RightBottom = 7
    LeftBottom = 8
End Enum

The following code shows how the program gets the image's orientation.

' Return the image's orientation.
Public Function ImageOrientation(ByVal img As Image) As ExifOrientations
    ' Get the index of the orientation property.
    Dim orientation_index As Integer = Array.IndexOf(img.PropertyIdList,
OrientationId)

    ' If there is no such property, return Unknown.
    If (orientation_index < 0) Then Return ExifOrientations.Unknown

    ' Return the orientation value.
    Return DirectCast(img.GetPropertyItem(OrientationId).Value(0),
ExifOrientations)
End Function

This code uses Array.IndexOf to see if the image's property ID list
includes orientation. If the orientation ID is found, the method uses
GetPropertyItem to get the corresponding PropertyItem object, gets its
first Value entry, converts it into an ExifOrientations value, and
returns the result.

The ExifStuff class also contains the following OrientationImage method,
which returns an image showing the letter F in a particular orientation.
You can download the example program that generated the orientation
images shown earlier <a
href="HowTo/howto_net_show_exif_orientations.zip">here</a>. (Look at
that example's code to see how it works.)

' Make an image to demonstrate orientations.
Public Function OrientationImage(ByVal orientation As ExifOrientations)
As Image
    Const size As Integer = 64
    Dim bm As New Bitmap(size, size)
    Using gr As Graphics = Graphics.FromImage(bm)
        gr.Clear(Color.White)
        gr.TextRenderingHint =
System.Drawing.Text.TextRenderingHint.AntiAliasGridFit

        ' Orient the result.
        Select Case (orientation)
            Case ExifOrientations.TopLeft
            Case ExifOrientations.TopRight
                gr.ScaleTransform(-1, 1)
            Case ExifOrientations.BottomRight
                gr.RotateTransform(180)
            Case ExifOrientations.BottomLeft
                gr.ScaleTransform(1, -1)
            Case ExifOrientations.LeftTop
                gr.RotateTransform(90)
                gr.ScaleTransform(-1, 1, MatrixOrder.Append)
            Case ExifOrientations.RightTop
                gr.RotateTransform(-90)
            Case ExifOrientations.RightBottom
                gr.RotateTransform(90)
                gr.ScaleTransform(1, -1, MatrixOrder.Append)
            Case ExifOrientations.LeftBottom
                gr.RotateTransform(90)
        End Select

        ' Translate the result to the center of the bitmap.
        gr.TranslateTransform(size / 2, size / 2, MatrixOrder.Append)
        Using string_format As New StringFormat()
            string_format.LineAlignment = StringAlignment.Center
            string_format.Alignment = StringAlignment.Center
            Using the_font As New Font("Times New Roman", 40,
GraphicsUnit.Point)
                If (orientation = ExifOrientations.Unknown) Then
                    gr.DrawString("?", the_font, Brushes.Black, 0, 0,
string_format)
                Else
                    gr.DrawString("F", the_font, Brushes.Black, 0, 0,
string_format)
                End If
            End Using
        End Using
    End Using

    Return bm
End Function

This method demonstrates some interesting graphics transformations.
First it creates a Bitmap and an associated Graphics object. Then
depending on the desired orientation, it applies a transformation to the
Graphics object to rotate and flip the drawing that follows.

Next the code applies a translation to center the resulting image in the
Bitmap. Finally the method draws the letter F centered at the origin.
The transformations rotate and flip the result and then translate it to
center it in the Bitmap.

The main example program uses the ExifStuff methods in the following
code to display an image, its orientation, and an oriented sample image
containing the letter F.

' Open the file and read its orientation information.
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnOpen.Click
    ' Open the file.
    Dim bm As New Bitmap(txtFile.Text)
    picOriginal.Image = bm

    ' Get the PropertyItems property from image.
    Dim Orientation As ExifOrientations = ImageOrientation(bm)
    lblOrientation.Text = Orientation.ToString()
    picOrientation.Image = OrientationImage(Orientation)
End Sub

The code opens a JPG file and displays it. It then calls
ImageOrientation to get the image's orientation and displays it as a
string. It then calls OrientationImage to get the oriented sample image
and displays it.
==========
Archives:
    http://www.topica.com/lists/VBHelper
    http://www.topica.com/lists/VB6Helper
    http://www.topica.com/lists/VBNetHelper

Twitter feeds:
    VBHelper
    CSharpHelper

Post questions at:
    http://www.topica.com/lists/VBHelperQA
	
 Previous Message All Messages Next Message 
  Check It Out!

  Topica Channels
 Best of Topica
 Art & Design
 Books, Movies & TV
 Developers
 Food & Drink
 Health & Fitness
 Internet
 Music
 News & Information
 Personal Finance
 Personal Technology
 Small Business
 Software
 Sports
 Travel & Leisure
 Women & Family

  Start Your Own List!
Email lists are great for debating issues or publishing your views.
Start a List Today!

© 2001 Topica Inc. TFMB
Concerned about privacy? Topica is TrustE certified.
See our Privacy Policy.