Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European VB.NET Hosting - HostForLIFE :: Namespace Aliases In Visual Basic .NET

clock December 17, 2021 08:28 by author Peter

In Visual Basic .NET, it is possible to declare aliases for namespaces, giving the possibility of using more concise declarations, if the developer desires to do so.

Let's see an example: Typically, the use of StringBuilder class could follow the following three declarative ways:

Without Imports statement

    Dim s As New System.Text.StringBuilder("test")  
    s.Append("123")  

This kind of implementation requires the developer to declare the "s" variable writing down the path to the desired class, in our case StringBuilder, contained into System.Text namespace.

With Imports statement
    Imports System.Text  
    ' ...  
    Dim s As New StringBuilder("test")  
    s.Append("123")  


Using an Imports statement, the programmer can simply use the classes names, for the namespace(s) to be used will be declared at the beginning of the code.

Using Aliases
    Imports sb = System.Text.StringBuilder  
    '...  
    Dim s As New sb("test")  
    s.Append("123")  


The Imports statement could be implemented with customized names. In the example above, I have stated that in the rest of the code, the class System.Text.StringBuilder will be redefined as "sb". So, we can declare a new StringBuilder with the function "New sb()", accessing the same constructors possessed by System.Text.StringBuilder, being sb a simple alias of the real thing.



European VB.NET Hosting - HostForLIFE :: Invoke Method To Update UI From Secondary Threads In VB.NET

clock November 17, 2021 07:36 by author Peter

As many developers well knows it's not possible -- using .NET Framework -- to realize a direct interaction between processes which run on threads different from the one on which the UI resides (typically, the main thread of the program). We are in a situation from which we can exploit the many advantages of multi-threading programming to execute parallel operations, but if those tasks must return an immediate graphical result, we won't be able to access the user controls from those processes.

In this brief article, we'll see how it can be possible, through the Invoke method, which is available to all controls through the System.Windows.Form namespace, to realize such functionality in order to execute a graphic refresh and update through delegates.

Delegates
The MSDN documentation states delegates are constructs which could be compared to the pointer of functions in languages like C or C++. Delegates incapsulate a method inside an object. The delegate object could then be passed to code which will execute the referenced method, or method that could be unknown during the compilation phase of the program itself. Delegates could be EventHandler instances, MethodInvoker-type objects, or any other form of object which ask for a void list of parameters.

Here follows a pretty trivial, though effective, example of their use.

Basic example

Let's consider a WinForm on which will reside a Label, Label2. That label must be use to show an increasing numeric counter. Since we desire to execute the value increase on a separated thread, we will incur into the named problem. Let's see why. First of all, we will write the code that will execute the increment of our numerical value on a secondary task from the main one, trying to update Label2, to observe the result of the operation.
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
      Dim n As Integer = 0  
       
      Dim t As New Task(New Action(Sub()  
                                  n += 1  
                    Label2.Text = n.ToString  
         End Sub))  
     t.Start()  
    End Sub


At runtime, the raised exception will attest what we saw up to here: it's not possible to modify an object properties (in reality, some of them), if the object itself is managed from a different thread other than the main one.

Yet, the Label control has - like any other control - a method named Invoke, through which we can call delegates toward the main thread. We can rewrite our method like the following. This time, for the sake of completeness, inserting our increment in a loop, to show how Invoke can work inside loops too.
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
      Dim n As Integer = 0  
       
      Dim t As New Task(New Action(Sub()  
      For n = 1 To 60000  
       
      Label2.Invoke(Sub()  
               Label2.Text = n.ToString  
               End Sub)  
      Next  
     End Sub))  
      t.Start()  
    End Sub


Running the program we can see how the graphical data update will be correctly executed, simultaneously with the development of the numerical variable.

That's -- as aforementioned -- a very basic and trivial example, but in a delegate context it's possible to execute an arbitrary number of operations of different complexity, making it possible to realize any feature in regarding of cross-threading operations.

Update UI from different tasks
To explore the subject further, we'll see now a more demanding example, in terms of resources needed. In this case, we'll make a program that will process simultaneously many text files, to update the UI to show what a single thread is doing in a given moment.

Example definition
We have 26 different text files, each of which contains a variable number of words, mainly italian but not exclusively. Those words begin with a particular letter: for example, the file "dizionario_a.txt" will contain only words which stars with "a", "dizionario_b.txt" only those which starts with "b", and so on. We want to write a program which possesses 26 labels and, starting a task for each letter, will proceed in inserting every read word in a variable of type List(Of String). Each task must show the processed word, so that every thread will execute -- through the Invoke() method -- the refreshing of the content of the Label on which it works.

Let's take a look to the code, to make some considerations after it.
    imports System.IO  
       
    public class Form1  
       
        Dim wordList As New List(Of String)  
       
        Public Sub AddWords(letter As Char, lbl As Label)  
            Using sR As New StreamReader(Application.StartupPath & "\text\dizionario_" & letter & ".txt")  
                While Not sR.EndOfStream  
                    Dim word As String = sR.ReadLine  
       
                    wordList.Add(word)  
       
                    lbl.Invoke(Sub()  
                          lbl.Text = word  
                          counter.Text = wordList.Count.ToString  
                          Me.Refresh()  
                        End Sub)  
                End While  
            End Using  
       
            lbl.ForeColor = Color.Green  
        End Sub  
       
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
            Me.DoubleBuffered = True  
       
            Dim _x As Integer = 8  
            Dim _y As Integer = 40  
       
            For ii As Integer = Asc("a") To Asc("z")  
       
                Dim c As New Label  
                c.Name = "Label" & ii.ToString("000")  
                c.Text = "---"  
                c.Top = _y  
                c.Left = _x  
                Me.Controls.Add(c)  
       
                _y += 20  
                If _y > 180 Then  
                    _y = 40  
                    _x += 120  
                End If  
       
                Dim j As Integer = ii  
                Dim t As New Task(Sub()  
                      AddWords(Chr(j), CType(Me.Controls("Label" & j.ToString("000")), Label))  
                     End Sub)  
       
                t.Start()  
            Next  
       
        End Sub  
       
    End Class


The project is a simple WinForms program. During Load() event, we'll create all the Labels we need, starting the tasks that will use, each of them on a different word, the AddWords() subroutine, to process a single dictionary (dictionary files will be found in the downloadable project, at the end of the article). We will see, taking a look at the loop in the Load() event, that each created task is launched immediately, letting the OS the worries of queueing those processes which aren't immediately manageable.

Each task, calling the AddWords() subroutine, will provide in: 1) opening the file having a given letter, 2) read each line, 3) save that value in the List wordList. We will also note a calling to the method Invoke() on the Label passed as argument to the subroutine. An interesting particular is that inside a single Invoke() a developer can manage more than a single UI update. In our specific case, we can see how the Label is updated, updating also the one named "counter", which we will use to show the global number of words read to a given moment. Moreover, to help the graphical rendering of our controls, we will call upon the Refresh() method of the Form itself, though - doing so - we will impair the overall performances, since the program will dedicate part of its cycles to refresh the Form and all its children, at every iteration.

As we can see running the code, or through the following video, the update of the content of our controls will happen in a concerted way, allowing each task to modify the value of controls which constitutes the UI of our program.



European VB.NET Hosting - HostForLIFE :: Getting an External IP Address Locally using VB.Net

clock August 27, 2021 07:33 by author Peter

This short article shall address the easiest way possible to get your external IP address (and local/internal IP address). There is no particular magic to getting your external IP address; the easiest way I have found is to use the automation service provided by http://whatismyip.com/automation/n09230945.asp, the good folks at whatismyip.com are nice enough to provide a free service to return the external IP address. All that the ask in return is that you do not beat them up with too many requests; they suggest about one every five minutes as being within their comfort zone; however, they also offer to provide additional services upon request so if you need something more than that, give them a call and talk to them about it.

 
Now, if you have a public site and are interested in getting the user's IP address that is really not an issue. You can still just request the REMOTE_ADDR or HTTP_X_FORWARDED_FOR server variable to get that.
 
Code
There is not much code to address in this one. There are three examples to show: the local IP address, the external IP address (for when you might need to see that locally), and the remote IP address.
 
The first example shows how to collect the local IP address; here we use an instance of the IPHostEntry container class to capture the host entry and then we display the first item in the host entry's address list as the local IP address.

    ' Local IP Address (returns your internal IP address)  
    Dim hostName As String = System.Net.Dns.GetHostName()  
    Dim myIPs As IPHostEntry = Dns.GetHostEntry(hostName)  
    Response.Write("<em>Your Local IP Address is:  " & myIPs.AddressList(0).ToString() & "</em><br />")  
 

The next example uses the whatismyip.com automation service to capture the external IP address locally. This value is displayed as the external IP address. If you just need to find out your external IP address, you can use a browser to navigate to the whatismyip.com website and you will see your external IP address displayed on the page; alternatively, you can use another service such as IPChicken.com to perform the same function. If you want to pro-grammatically capture the external IP address locally, this code will do the job.

    ' External IP Address (get your external IP locally)  
    Dim utf8 As New UTF8Encoding()  
    Dim webClient As New WebClient()  
    Dim externalIp As String = _     utf8.GetString(webClient.DownloadData("http://whatismyip.com/automation/n09230945.asp"))  
    Response.Write("<h2>Your External IP Address is: " & externalIp & _  
    "</h2><br />")  

If you are working from a public website and you want to capture the user's IP address; the following code will do the job.
    ' Remote IP Address (useful for getting user's IP from public site; run locally it just returns localhost)  
    Dim remoteIpAddress As String = Request.ServerVariables("HTTP_X_FORWARDED_FOR")  
    If (String.IsNullOrEmpty(remoteIpAddress)) Then  
    remoteIpAddress = Request.ServerVariables("REMOTE_ADDR")  
    End If  
    Response.Write("<em>Your Remote IP Address is:  " + remoteIpAddress + "</em><br />")  

 
This article was intended to show some simple ways to capture IP address information under different circumstances. The three examples show demonstrate how to capture the local IP address, how to capture the external IP address locally, and how to capture the user's IP address from a public website.



European VB.NET Hosting - HostForLIFE.eu :: Drawing rubber-band lines and shapes in VB.NET

clock June 21, 2019 11:13 by author Peter

The lack of XOR Drawing feature in GDI+ was not certainly welcome in the programmer's community. I guess it will be hard to survive with this handicap.

In spite of this, I would like to show how we can draw rubber-band lines and shapes in GDI+ with just a few lines of code.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
Dim size As Size = SystemInformation.PrimaryMonitorMaximizedWindowSize 
bitmap = New Bitmap(size.Width, size.Height) 
gB = Graphics.FromImage(bitmap) 
Dim bckColor As Color = Me.BackColor 
gB.Clear(bckColor) 
End Sub 
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
Dim p As Point = New Point(e.X, e.Y) 
x0 = p.X 
y0 = p.Y 
drag = True 
End Sub 
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
Dim p As Point = New Point(e.X, e.Y) 
x= p.X 
y = p.Y 
Dim cx As Integer = x - x0 
Dim cy As Integer = y - y0 
If drag Then 
Dim gx As Graphics = CreateGraphics() 
gx.DrawImage(bitmap, 0, 0) 
gx.Dispose() 
Dim g As Graphics = CreateGraphics() 
Dim pen As Pen = New Pen(Color.Blue) 
Select Case DrawMode
Case 1 
g.DrawLine(pen, x0, y0, x, y) 
Exit Select 
Case 2 
g.DrawEllipse(pen, x0, y0, cx, cy) 
Exit Select 
Case 3 
g.DrawRectangle(pen, x0, y0, cx, cy) 
Exit Select 
End Select 
g.Dispose() 
pen.Dispose() 
End If 
End Sub 
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) 
Dim cx As Integer = x - x0 
Dim cy As Integer = y - y0 
Dim pen As Pen = New Pen(Color.Blue) 
Select Case DrawMode 
Case 1 
gB.DrawLine(pen, x0, y0, x, y) 
Exit Select 
Case 2 
gB.DrawEllipse(pen, x0, y0, cx, cy) 
Exit Select 
Case 3 
gB.DrawRectangle(pen, x0, y0, cx, cy) 
Exit Select 
End Select 
drag = False 
pen.Dispose() 
End Sub 
Private Sub Form1_Paint(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.PaintEventArgs) 
Dim gx As Graphics = CreateGraphics() 
gx.DrawImage(bitmap, 0, 0) 
gx.Dispose() 
End Sub 
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)button1.ForeColor = Color.Red 
button2.ForeColor = Color.Black 
button3.ForeColor = Color.Black 
DrawMode = 1 
End Sub 
Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
button2.ForeColor = Color.Red 
button1.ForeColor = Color.Black 
button3.ForeColor = Color.Black 
DrawMode = 2 
End Sub 
Private Sub button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
button3.ForeColor = Color.Red 
button1.ForeColor = Color.Black 
button2.ForeColor = Color.Black 
DrawMode = 3 
End Sub 
Private Sub panel1_Paint(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.PaintEventArgs) 
button1.ForeColor = Color.Red 
button1.Focus() 
End Sub



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in