Tuesday, May 28, 2013

Example to connect to a WAN using VB.NET

Example to connect to a WAN using VB.NET


Small example using VB.NET to connect to a remote server


Choosing a programming language to make your program is only one part of a programming project. You also need to choose the network protocol to use.
The most popular network protocol use is IPv4 use in the 3rd network layer from the OSI model. Why?  I don’t know. Maybe ordinary people starting earing keywords such as IP address and thing like that. Maybe the World Wide Web (WWW) is made of email address and http address. Who knows?
Anyway, most people don’t master or even know all the protocol available in the world. Hopefully, Microsoft made a .NET framework with a lot of network protocol all in a single Enumeration: AddressFamily

Here a few sample inside AddressFamily:
  • InterNetwork
  • InterNetworkV6
  • NetBios
  • AppleTalk
  • HyperChannel
  • Unknown
  • Unspecified


If don’t specifiy an AddressFamily, your program will not be able to resolve an address. For example, if you set your program to InterNetwork (IPv4), you socket will expect an IPv4 address when it connect to the endpoint.

Here is an example with the minimum requirement to connect to a server from a client program using: “AddressFamily. InterNetwork”


Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
''' <summary>
''' This is a sample on how to conenct to a server using the
''' minimum stuff in IPv4.
''' Base from an example from MSDN.
''' </summary>
''' <remarks></remarks>
Module Module1

    Sub Main()
        Dim aString As String
        Dim s As Socket = Nothing
        Dim hostEndPoint As IPEndPoint
        Dim hostAddress As IPAddress = Nothing
        Dim conPort As Integer = 80


        ' Get DNS host information.
        Dim hostInfo As IPHostEntry ' = Dns.Resolve(server)
        ' Get the DNS IP addresses associated with the host.
        Dim IPaddresses As IPAddress() '= hostInfo.AddressList
        Try
            Do
                Console.Write("host to test (exemple : www.yahoo.com) ?  ")
                aString = Console.ReadLine()
                hostInfo = Dns.Resolve(aString)

                Console.Write("port to test (exemple : 80) ? ")
                aString = Console.ReadLine()
                conPort = aString


                IPaddresses = hostInfo.AddressList

                For index = 0 To IPaddresses.Length - 1
                    hostAddress = IPaddresses(index)
                    hostEndPoint = New IPEndPoint(hostAddress, conPort)


                    ' Creates the Socket to send data over a TCP connection.
                    s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

                    ' Connect to the host using its IPEndPoint.
                    s.Connect(hostEndPoint)

                    If Not s.Connected Then
                        ' Connection failed, try next IPaddress.
                        Console.Write("Unable to connect to host")
                        s = Nothing

                    Else
                        Console.Write("connected to host !  ")
                    End If

                Next index  ' End of the for loop.



                Console.Write("Quit or Retry? (Q/R)")
                aString = Console.ReadLine()

            Loop Until aString = "Q" Or aString = "q"
        Catch ex As Exception

        End Try

    End Sub


End Module




I use Microsoft Visual Studio 2010 to do all my projects. I suggest you to buy and get the best IDE in the world and the newest one: Microsoft Visual Studio 2012 on Amazon
or
Download the sample code here: SampleConsoleIPv4.zip

Others related post:

Thursday, May 23, 2013

Example of thread synchronization in VB.NET

Example of thread synchronization


Refers of the idea of using multiples thread in a process



When you stats using thread, you will notice that the speed of each thread is not very important. You will notice that synchronization is more important because sometimes, you want a thread to be completed before starting and other one. You could try to use or check for the Thread status using the IsAlive and IsBackground properties, but you will find it mostly hard to get reliable things.
That is why synchronization between asynchronous tasks is the key for success. If you master the basic of timing between functions, nothing will stop you from doing more complex application or games.

MMORPG (stands for Massive Multi Online Role Player Game) is the perfect example of challenge for a programmer or a team where each player has different computer speed and network performance.

HereVB a code sample I made in less than 15 minutes. Yes, it is very simple. The concept is also simple. I made a WinForm using 4 ProgressBar. The last ProgressBar will only start if the 3 previous have completed. In other words, the last ProgressBar must wait for the 3 others.

This sample could be use in any situation in the modern world.

By pressing the button START, 4 independent threads will start. Each Thread has their speed.

The last Thread is blocked by 3 ManualResetEvent. If the 3 ManualResetEvent are set, then the last task could start.






''' <summary>
''' Author : Check-Kay Wong
''' Description:
''' This is a sample of synchronasation between multiples task
''' using a Simple WaitOne and a Set from a ManualResetEvent
'''
''' Comment : this is an exemple
''' </summary>
''' <remarks></remarks>
Public Class Form1

    Private tTask1 As System.Threading.Thread
    Private tTask2 As System.Threading.Thread
    Private tTask3 As System.Threading.Thread
    Private tTask4 As System.Threading.Thread

    Private mreTask1 As System.Threading.ManualResetEvent
    Private mreTask2 As System.Threading.ManualResetEvent
    Private mreTask3 As System.Threading.ManualResetEvent
    Private mreTask4 As System.Threading.ManualResetEvent

    Private Delegate Sub dTask1()
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        StartAllTasks()
    End Sub
    ''' <summary>
    ''' all working stuff inside the thread are simulated by progressbar
    ''' </summary>
    ''' <remarks></remarks>
#Region "Working Thread 1, 2 and 3"
    Private Sub Task1()
        Do
            Me.BeginInvoke(New dTask1(AddressOf sTask1))
            System.Threading.Thread.Sleep(100)
        Loop Until ProgressBar1.Value >= ProgressBar1.Maximum
        mreTask1.Set()
    End Sub
    Private Sub sTask1()
        Me.ProgressBar1.PerformStep()
    End Sub

    Private Sub Task2()
        Do
            Me.BeginInvoke(New dTask1(AddressOf sTask2))
            System.Threading.Thread.Sleep(100)
        Loop Until ProgressBar2.Value >= ProgressBar2.Maximum
        mreTask2.Set()
    End Sub
    Private Sub sTask2()
        Me.ProgressBar2.PerformStep()
    End Sub

    Private Sub Task3()
        Do
            Me.BeginInvoke(New dTask1(AddressOf sTask3))
            System.Threading.Thread.Sleep(100)
        Loop Until ProgressBar3.Value >= ProgressBar3.Maximum
        mreTask3.Set()
    End Sub
    Private Sub sTask3()
        Me.ProgressBar3.PerformStep()
    End Sub
#End Region
#Region "Finale Task Thread"
    Private Sub Task4()
        mreTask1.WaitOne()
        mreTask2.WaitOne()
        mreTask3.WaitOne()
        Do

            Me.BeginInvoke(New dTask1(AddressOf sTask4))
            System.Threading.Thread.Sleep(100)
        Loop Until ProgressBar4.Value >= ProgressBar4.Maximum
        mreTask4.Set()
        My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep) 'a little bell
    End Sub
    Private Sub sTask4()
        Me.ProgressBar4.PerformStep()
    End Sub
#End Region

    ''' <summary>
    ''' Init stuff
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Me.Text = My.Application.Info.ProductName & " from " & My.Application.Info.CompanyName
        ProgressBar1.Maximum = 200
        ProgressBar2.Maximum = 100
        ProgressBar3.Maximum = 140
        ProgressBar4.Maximum = 240

        'create the ManualResetEvent
        mreTask1 = New System.Threading.ManualResetEvent(False)
        mreTask2 = New System.Threading.ManualResetEvent(False)
        mreTask3 = New System.Threading.ManualResetEvent(False)
        mreTask4 = New System.Threading.ManualResetEvent(False)
    End Sub

    ''' <summary>
    ''' Start All Task at the same time
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StartAllTasks()
        If tTask1 IsNot Nothing Then tTask1 = Nothing
        tTask1 = New System.Threading.Thread(AddressOf Task1)
        tTask1.IsBackground = True
        tTask1.Start()

        If tTask2 IsNot Nothing Then tTask2 = Nothing
        tTask2 = New System.Threading.Thread(AddressOf Task2)
        tTask2.IsBackground = True
        tTask2.Start()

        If tTask3 IsNot Nothing Then tTask3 = Nothing
        tTask3 = New System.Threading.Thread(AddressOf Task3)
        tTask3.IsBackground = True
        tTask3.Start()

        If tTask4 IsNot Nothing Then tTask4 = Nothing
        tTask4 = New System.Threading.Thread(AddressOf Task4)
        tTask4.IsBackground = True
        tTask4.Start()
    End Sub

End Class


I use Microsoft Visual Studio 2010 to do all my projects. I suggest you to buy and get the best IDE in the world and the newest one: Microsoft Visual Studio 2012 on Amazon
or
Download the sample code here: ManualResetEventExample.zip

Others related post:

Thursday, May 16, 2013

Public Enum inside Module in VB.NET

Public Enum inside Module in VB.NET


'choice' cannot expose type 'Module1.Enum_choice' outside the project through class 'Class1'



You have this error but you don’t know why. You have an Enumeration inside a Module and you want to use it inside a class. Why this isn’t working?

I have a sample project at the end of this post if you want to experiment the case.
First of all, if you have this problem, it is probably that you haven’t told the program that your module is public. You could easily correct the problem by adding the keyword PUBLIC at the beginning of your Module.

Assuming the module and the class are in the same project.

In yellow, the error you might have:


Public Class Class1
    Private _Choice As Enum_Choice
    Public Sub New()
        _Choice = Enum_choice.none
    End Sub

    Public Sub New(choice As Enum_choice)
        _Choice = choice
    End Sub
End Class



Here is the error I copy from Microsoft Visual Studio 2010:

Error      1             'choice' cannot expose type 'Module1.Enum_choice' outside the project through class 'Class1'.                C:\Users\checkkay\Documents\Visual Studio 2010\Projects\GlobalEnumSample\GlobalEnumSample\Class1.vb                7             30           GlobalEnumSample


The solution for you problem is in Yellow. You have to tell your program that the Enumeration is accessible.

Public Module Module1
    Public Enum Enum_choice
        none = 0
        first = 1
        twice = 2
    End Enum
End Module



Download sample Project:  GlobalEnumSample.zip

I work with Microsoft Visual Studio 2010 for most of my projects. You could get or download it from this link: Download Visual Studio or Express Edition

You could also buy the same version I am using from Amazon here: Visual Studio 2010 Professional (Old Version)
Microsoft Visual Studio 2012 Professional is now cheaper than the older version. If you want to buy it, I advise you to buy the newer version. If you want to compare both versions, I made a little post on the subject here: VS2010 vs VS2012



Others interesting post on Modules:


Wednesday, May 8, 2013

How to fill ComboBox with Text File

How to fill ComboBox with Text File

Fill a ComboBox quickly by importing data from a Text File


ComboBox SampleText files are the simplest way to store data. It requires minimum knowledge to use them. Knowing how to read them make it possible to help you fill data in a control like in a ComboBox. Here is a very simple example. It uses an OpenFileDialog to get a Text File the user is requesting. The program validates the file and if everything is fair, it loads each line and put them in the ComboBox1. When the cursor reaches the end of the file, the property EndOfStream will be true. This will make your program quit the loop and safely close the function. Remember to close the Stream File after you finish.
Download the project sample here: ComboBoxSample.zip

ComboBox Sample

ComboBox Sample

SQL Server Developer Edition 2012 and Microsoft Visual Studio Pro 2012 are very cheap on Amazon ! Free Delivery. Check here:
 






    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        Dim oStream As IO.StreamReader
        Dim oOpenFileDialog As OpenFileDialog


        oOpenFileDialog = New OpenFileDialog
        oOpenFileDialog.SupportMultiDottedExtensions = False

        If oOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            If IO.File.Exists(oOpenFileDialog.FileName) Then
                oStream = New IO.StreamReader(oOpenFileDialog.FileName)

                'Read all lines and add them into the ComboBox1
                Do Until oStream.EndOfStream = True
                    ComboBox1.Items.Add(oStream.ReadLine)
                Loop
                oStream.Close() 'very important to close the file
            End If
        End If


    End Sub




Tuesday, May 7, 2013

ComboBox Control for VB.NET

ComboBox Control for VB.NET

 
Here is some example of ComboBox in visual basic VB.NET. We show you how to add and delete items with some basic tips. Most codes are self-explanatory.

A project sample is available to download at the end of this post. Free to download.




Using a TextBox: Add Item in ComboBox


From the project example available at the end of this post, I made a simple Button1 that adds a String from a TextBox1. The method checks the TextBox1 value before adding it the ComboBox1. The TextBox clears at the end.

If the ComboBox1 contains the value, then the TextBox1 is highlighted.  This way, we tell the user to change the entry.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'Add values in ComboxBox1
        'will not add if value exist in ComboBox
        If TextBox1.Text IsNot Nothing Then
            If TextBox1.Text.Length > 0 Then
                If Not ComboBox1.Items.Contains(ComboBox1.Text) Then
                    ComboBox1.Items.Add(TextBox1.Text)
                    TextBox1.Text = ""
                Else
                    TextBox1.SelectionStart = 0
                    TextBox1.SelectionLength = TextBox1.Text.Length
                End If

            End If
        End If

    End Sub


Using a Button: Delete item in ComboBox


SelectedIndex could be minus one if nothing is selected. So we always have to make sure the SelectedIndex for a ComboBox is valid. If you are using the ComboBox with the default specifications, try to no use SelectedValue, SelectedText or SelectedItem. Be advare that ComboBox1 Dot Text is the visible text inside the ComboBox1. That text is not inside the ComboBox1 collection.
In the sample, I use the RemoveAt to delete the current Selected Index. Deleting the ComboBox1 dot text is a nice to have.



    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        'Delete a value in ComboBox1

        If ComboBox1.SelectedIndex >= 0 Then
            ComboBox1.Items.RemoveAt(ComboBox1.SelectedIndex)
        End If

        If ComboBox1.Items.Count = 0 Then
            ComboBox1.Text = ""
        End If
    End Sub



Add item in ComboBox using Keyboard


You need to use the KeyEventArgs. I choose the KeyUp event because I think is better than the KeyDown.
The KeyUp work the same way than my previous example with my Button1. Again, I do basic checking before adding the String value.

Private Sub ComboBox1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp
        'pressing Enter will add the text in the ComboBox1 Collection
        'will not put duplicate values (case true)
        If e.KeyCode = Keys.Enter Then
            If ComboBox1.Text.Length > 0 Then
                If Not ComboBox1.Items.Contains(ComboBox1.Text) Then
                    ComboBox1.Items.Add(ComboBox1.Text)
                    ComboBox1.Text = ""
                Else
                    ComboBox1.SelectionStart = 0
                    ComboBox1.SelectionLength = ComboBox1.Text.Length
                End If

            End If

        End If
    End Sub



Download the little project sample is you want: ComboBoxSample.zip



SQL Server Developer Edition 2012 and Microsoft Visual Studio Pro 2012 are very cheap on Amazon ! Free Delivery. Check here: