ASP.Net | Learn the basics of developing your first website using VB.Net or C#

March 8, 2015

You are here, seeking some information and we are more than happy to re-direct you to http://webproject.scottgu.com, a right place to start learning how to develop a website using Visual Studio IDE. Though the posts with scottgu.com mostly deal with VS 2005, almost everything they mentioned with their lessons are still applicable to the latest VS releases.
So give it a try, and you will be more than glad to visit one of the best beginners place.

regards,

rajesh


Teaser | Visual Studio | VB.Net & Oracle Database

March 2, 2015

t1

Okay, my last few posts were all about VB.Net & utilities for Windows domain administrators. Doesn’t mean that I stopped being a Oracle bouy ;) I still earn my salary for the Oracle job I do everyday at work and once after managing to purchase a legal copy of Visual Studio 2013 Professional Edition, I am committed to develop few sample applications using VB.Net & Oracle database.

So, stay tuned

regards,

rajesh


VB.Net | Appending an existing XML file

February 23, 2015

VB.Net | Appending an existing XML file

XML is widely used by .net oriented programming. It is vast and learning XML could be requiring loads of dedication. I needed to add a XML file to hold certain configuration details that could be read with one of the VB.Net projects currently I am busy with. This project deals with running Oracle VirtualBox VM(Virtual Machines) headless using a Windows Service as Local System so that multiple administrators could log in and log off from the Windows Server that hosts Virtual machines without closing down the machines abrupt (This project is ongoing, half cooked)

Without wasting more time, let us see how to append an “existing” XML file using VB.Net

Create a Windows Form Project
Create a XML file (MyVMS.xml) using your favorite text editing tool and copy the below

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<VM>
<MACHINE>
    <MACHINE_ID>1</MACHINE_ID>
    <VM_NAME>MyVM</VM_NAME>
    <VM_SHUTDOWNMODE>poweroff</VM_SHUTDOWNMODE>
  </MACHINE>
</VM>

and copy the XML file to the project root folder

Add the namespaces to your new project

Imports System.Xml
Imports System.Data

As I said in the beginning, we will be adding data to an “existing” XML file, hence the XML files must have a root element, for example

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<VM>
</VM>

Drag a button to your forms1.vb design view
Drag another button to your forms1.vb design view
Drag a DataGridView to your forms1.vb design view

Now we will try to add one more “MACHINE” node into the existing XML file using VB.Net code block

Public Class Form1
 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xmldoc As New XMLDocument()
        Try
            xmldoc.Load("MyVMS.xml")
            Dim e1 As XmlElement = xmldoc.CreateElement("MACHINE")
            Dim e2 As XmlElement = xmldoc.CreateElement("MACHINE_ID")
            e2.InnerText = "2"
            Dim e3 As XmlElement = xmldoc.CreateElement("VM_NAME")
            e3.InnerText = "Linux"
            Dim e4 As XmlElement = xmldoc.CreateElement("VM_SHUTDOWNMODE")
            e4.InnerText = "savestate"
 
            e1.AppendChild(e2)
            e1.AppendChild(e3)
            e1.AppendChild(e4)
 
            xmldoc.DocumentElement.AppendChild(e1)
            xmldoc.Save("MyVMS.xml")
 
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
 
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim xmlFile As XmlReader
        xmlFile = XmlReader.Create("MyVMS.xml", New XmlReaderSettings())
        Dim ds As New DataSet
        ds.ReadXml(xmlFile)
        DataGridView1.DataSource = ds.Tables(0)
        DataGridView1.Columns(0).HeaderText = "Id"
        DataGridView1.Columns(1).HeaderText = "VM Name"
        DataGridView1.Columns(2).HeaderText = "Shutoff Mode"
 
    End Sub
End Class

Now, as you click on the first button, a new node for “MACHINE” will be inserted using the static information attached & by activating the second button, your data grid view should populate the MACHINE information already stored within the XML file.

Pretty simple & easy, right? You may rush ahead and say thanks to my dearest friend and ONE of the best .Net programmers Aziz Marafi / @azizane , who had coded majority of the block above for the “FileMyster” project.

Please post your comments and queries and I may learn few more things with you!

regards,

rajesh


VB.Net | Get IP address of a computer against hostname | Fun projects

February 11, 2015

Credits: http://stackoverflow.com/questions/19713868/returning-ipv6-instead-of-ipv4-in-vb

How to?

Open Visual Studio IDE (We are using VS 2012 Express and the .Net framework is 4.5 by default, hence if few things do not work at your setups, please cross check the specs we specified) and create a Windows form application. We’ll be mostly doing our samples using forms, a better mechanism to test stuffs against console applications (Minimum from our experiences)

drag a button to the form

drag a listbox to the form

& do not change any property for any of the above items

right click on the form and select view code, once the code page opens
Ctrl+A (Select all and delete)

copy and paste the below code block (replacing the original content of the code page)

Imports System.Net

Public Class Form1
    Public Function getip(ByVal lst As ListBox) As ListBox
        Dim hostEntry = Dns.GetHostEntry("hostname")
        Dim addressList As New List(Of IPAddress)

        For Each address In hostEntry.AddressList
            If address.AddressFamily = Sockets.AddressFamily.InterNetwork Then
                lst.Items.Add(address)
            End If
        Next
        Return lst

    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        getip(ListBox1)
    End Sub
End Class

Now replace the “hostname” with some actual hostnames and execute the application by pressing F5. Click the button over the form you are done! Please note, this sample is restricted to fetch IPV4 addresses.


VB.Net | Active Directory | Windows Form Application for listing users & details in a grid view

January 15, 2015

Have you read our previous post about finding last logon date time value for a domain member computer or user yet? If not, please read about it here

Now, we are going to provide you a decent (Warning: Amateurish code blocks possible) Windows forms based application that could list all your domain users and few of their details including last logon date time values.

run

Above image demonstrates the run time interface of the application. Application has a search textbox, that could accept values before and after the user details are populated.

Before the population, the users will be limited to matching string, after population, the list could be refined against the combination of keystrokes

Mandatory References as seen with the below image

ref

You can download the solution from here

regards,

rajesh


VB.net | Active Directory | Get last logon for computer/user account

January 15, 2015

Ever wondered how to fetch the last logon details for a domain member computer or user? Using .Net Microsoft has made it pretty easier for the developers to populate the active directory attributes to desired data repositories, however getting the last logon date time value still remains a complex stuff (for beginners like us), especially when your domain consist of multiple domain controllers and they are spread across different geographical areas and subnets :)

After dwelling for long a while, I came across a C# code snippet @ http://www.codeproject.com/Articles/19181/Find-LastLogon-Across-All-Windows-Domain-Controlle that was mostly built against http://www.rlmueller.net/Last%20Logon.htm

I had to copy the codes those were split into multiple blocks for proper explanations, re-arrange and then using the online C# to VB.Net converters, convert to readable VB.Net coding. Again, there were few mismatches and I was able to figure them out through stackoverflow & tech forums posts.

Without going on with what and how I did it, here comes the complete coding. Please note, this is a console application solution, and you should add the references as seen with the below image in order to successfully call the methods and types

Ref

Imports System.DirectoryServices
Imports ActiveDs


Module Module1

    ''' &lt;summary&gt;
    ''' You should able to easily convert this console application to windows form application
    ''' with least efforts
    ''' Original code was posted with http://www.codeproject.com/Articles/19181/Find-LastLogon-Across-All-Windows-Domain-Controlle
    ''' using C#, I converted most of the C# Codes using online converter(s)
    ''' and ammended at few places, as the code block provided with the project were not fetching decent results
    ''' Rajesh Thampi / 15-Jan-2015 | w7bugs at gmail dot com | windows7bugs.wordpress.com
    ''' &lt;/summary&gt;
    ''' &lt;remarks&gt;&lt;/remarks&gt;
    Sub Main()
        'Get the root of the directory data tree on a directory server.
        Dim rootDse As New DirectoryEntry(&quot;LDAP://rootDSE&quot;)
        'Dictionary object to hold the records retrived by the search
        Dim lastLogons As Dictionary(Of String, Int64) = New Dictionary(Of String, Int64)
        'Local variable for holding formatted last logon values in datetime format
        Dim llogon As DateTime = Nothing


        'for User last logon
        'Dim TargetUsername As String = &quot;george&quot; ' -&gt; Pass sAMAccountName 
        'Dim objType As Integer = 805306368 '-&gt; 805306368  User | 805306369 Computer

        'for Computer
        Dim TargetUsername As String = &quot;JOSE-KSP$&quot; ' -&gt; Pass sAMAccountName 
        Dim objType As Integer = 805306369 '-&gt; 805306368  User | 805306369 Computer


        'Loop through all available domain controllers
        For Each dsDC As DirectoryServices.ActiveDirectory.DomainController In _
         DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.DomainControllers
            'Print the individual domain controller name
            'Debug.Write(dsDC.Name &amp; vbCrLf) ' Uncomment for print
            'Get the Entry details for domain controller
            Dim dirEntry As DirectoryEntry = New DirectoryEntry(&quot;LDAP://&quot; + dsDC.Name + &quot;/&quot; + DirectCast(rootDse.Properties(&quot;defaultNamingContext&quot;).Value, String))
            'Define searcher for the objects of interest
            Dim dirObjects As DirectorySearcher = New DirectorySearcher(dirEntry)
            'Define a large integer to hold the COM object translated value
            'ActiveDS COM object is a MUST reference, yet to find another way to deal with highpart, lowpart values obtained from &quot;lastlogon&quot;
            Dim lastLogonThisServer As Int64 = New Int64()
            'Set up the filter for object to be returned through findall method
            dirObjects.Filter = &quot;(&amp;(sAMAccountType=&quot; &amp; objType &amp; &quot;)(sAMAccountName=&quot; &amp; TargetUsername &amp; &quot;))&quot;
            ' Loop through the records found
            For Each objRecords In dirObjects.FindAll()
                'Get the directory entry, this will return all the attributes associated with the object (Computer/User)
                Dim dirObj As DirectoryEntry = objRecords.GetDirectoryEntry()
                If Not dirObj Is Nothing Then
                    ' Get the distinguishedName and lastLogon for each user


                    Dim distinguishedName As String = dirObj.Properties(&quot;distinguishedName&quot;).Value.ToString()

                    Try

                        If Not dirObj.Properties(&quot;lastLogon&quot;).Value Is Nothing Then
                            Dim lgIntas As ActiveDs.LargeInteger = dirObj.Properties(&quot;lastLogon&quot;).Value
                            Dim lngHigh As Long = lgIntas.HighPart
                            Dim lngLow As Long = lgIntas.LowPart
                            lastLogonThisServer = (lngHigh * (2 ^ 32) - lngLow)


                        End If

                    Catch ex As Exception
                        Debug.Write(ex.Message)
                    End Try
                    'Different date time formats you can play around with
                    'Dim format As String = &quot;MMM ddd d HH:mm yyyy&quot;  -&gt; Jan Thu 15 08:11 2015
                    'Dim format As String = &quot;dd/MMM/yyyy HH:mm tt&quot; -&gt; 15/Jan/2015 08:36 AM
                    'Debug.Write(distinguishedName &amp; &quot;;&quot; _
                    '&amp; DateTime.FromFileTime(lastLogonThisServer).ToString(format, Globalization.CultureInfo.InvariantCulture) &amp; vbCrLf)

                    'Save the most recent logon for each user in a Dictionary object
                    'How it works
                    'lastLogons dictionary object has two parts, key and corresponding value
                    'Prior adding a new record, using ContainsKey call we can check the array for existing keys
                    'With this example, the key is &quot;distinguishedName&quot;
                    'If the distinguishedName as key found

                    If lastLogons.ContainsKey(distinguishedName) Then
                        'We compare the latest fetched logon date integer value against the key value of the dictionary object
                        If lastLogons(distinguishedName) &lt; lastLogonThisServer Then
                            'If the existing value is smaller than the new value &quot;lastLogonThisServer&quot; holds
                            lastLogons(distinguishedName) = lastLogonThisServer
                            'We will update the existing key value with recent lastLogonThisServer value
                        End If
                    Else
                        'We will add a new entry to the dictionary object
                        lastLogons.Add(distinguishedName, lastLogonThisServer)
                    End If
                End If
            Next
        Next
        'Now we will loop through the dictionary object and fetch the details
        'For a single user/computer the dictionary object will not have more than one entry
        For Each kvp As KeyValuePair(Of String, Int64) In lastLogons
            Dim v1 As String = kvp.Key
            Dim v2 As DateTime = DateTime.FromFileTime(kvp.Value).ToString()
            ' llogon = v2
            Dim format As String = &quot;dd/MMM/yyyy HH:mm tt&quot;
            Debug.Write(&quot;Distinguished Name :&quot; &amp; v1 &amp; &quot;;   Last logged :&quot; &amp; v2.ToString(format) &amp; vbCrLf)

        Next


    End Sub

End Module

You may download the solution from https://drive.google.com/file/d/0B-3iVeOMTCbWWFliTGN1NmNxMjQ/view?usp=sharing

regards,

rajesh


VB.net console application for Deleting old files from a particular folder

January 13, 2013

How are you guys? Happy New Year! We were quite busy and quiet during last few weeks. Here we are once again, coming up with a simple, yet powerful utility which could make a system administrator’s life bit easier.

We have a 12 years old Oracle database server with oracle data folder residing in D:\ drive with less than 20GB total free space where we do a full export everyday by late night.

Each full export (.dmp) file is almost 5GB, thus occupying the entire 20GB by every forth day. We were painfully following up the schedules and deleting the files to preserve much valued disk space.

Well, finally we decided to write a small console application to handle this task through a scheduled task. You can download the entire solution from following link

https://skydrive.live.com/redir?resid=68080371B15625F8!126&authkey=!AHiWHLBzE1x1YdU

The executable could be downloaded from following link

https://skydrive.live.com/redir?resid=68080371B15625F8!127&authkey=!AKmvC5fF61iSkiA

 

 

We developed this solution using Visual Studio Express for Desktop, ie, akka free version of VS 2012. You may need to download the same, so that you can open the solution.

However, to make stuff easier, we are copying the module1.vb code over here

Imports System.Console
Imports System.IO
Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Text
Imports System.Environment




Module Module1


    Sub Main()
        Dim strStartupArguments() As String, intCount As Integer
        Dim fldrName As String, fileType As String, nDays As Integer

        strStartupArguments = System.Environment.GetCommandLineArgs
        For intCount = 0 To UBound(strStartupArguments)
            ' Console.WriteLine(strStartupArguments(intCount).ToLower)
            ' Console.WriteLine(strStartupArguments(intCount))
            Select Case strStartupArguments(intCount).ToLower
                Case &quot;-dfolder&quot;
                    ' fldrName = strStartupArguments(intCount).ToLower
                    fldrName = strStartupArguments(intCount + 1)
                    'Console.WriteLine(fldrName)
                Case &quot;-ftype&quot;
                    fileType = strStartupArguments(intCount + 1)
                    'Console.WriteLine(fileType)
                Case &quot;-ndays&quot;
                    nDays = strStartupArguments(intCount + 1)
            End Select
        Next intCount

        If ((fldrName Is Nothing) Or (fileType Is Nothing) Or (nDays = 0)) Then
            Console.WriteLine(&quot;No or not all arguments given, USAGE DeleteOldFiles.exe -dFolder &lt;folder name&gt; -fType &lt;*.extention&gt; -nDays &lt;N&gt; &quot;)
            Console.WriteLine(&quot;Example: DeleteOldFiles.exe -dFolder C:\myfolder -fType *.txt -nDays 100&quot;)
            Console.WriteLine(&quot;         C:\myfolder --is the target folder from files will be deleted&quot;)
            Console.WriteLine(&quot;         *.txt --tells the system what kind of files should be deleted &quot;)
            Console.WriteLine(&quot;         100 --defines file age in number of days&quot;)
            End
        End If

        Dim fileName = Date.Now.ToString(&quot;ddMMyyyy&quot;) &amp; &quot;.log&quot;
        Dim filePath = IO.Path.Combine(fldrName, fileName)
        Using sw As StreamWriter = New StreamWriter(filePath)
            sw.WriteLine(&quot;File Name&quot; + &quot;;&quot; + &quot;Creation Date&quot; + &quot;;&quot; + &quot;Deletion Time&quot;)
            Try
                ' For Each file As IO.FileInfo In New IO.DirectoryInfo(&quot;D:\Documents&quot;).GetFiles(&quot;*.pdf&quot;)
                For Each file As IO.FileInfo In New IO.DirectoryInfo(fldrName).GetFiles(fileType)
                    '     Console.WriteLine((Now - file.CreationTime))
                    If file.IsReadOnly = False Then
                        If (Now - file.CreationTime).Days &gt;= nDays Then
                            sw.WriteLine(file.Name + &quot;;&quot; + file.CreationTime + &quot;;&quot; + Now)
                            file.Delete()
                        End If
                    End If


                Next
            Catch ex As Exception
                Console.WriteLine(ex.ToString)
            End Try
        End Using


    End Sub
End Module

The default solution name is “DeleteOldFiles” hence when you open and build the solution, the .exe file name would be DeleteOldFiles.exe

Usage syntax

DeleteOldFiles.exe –dFolder <driverletter:\foldername> –fType *.extension –nDays <number of days>

eg: DeleteOldFiles.exe –dFolder C:\temp –fType *.tmp –nDays 3

Now you can schedule a job, and let this small piece of application doing the cleanup job for you

Yes, it does a logging for you :), so that you can always check which files were deleted from the folder (for eg: C\temp). The log file location will be the same folder from which the files were permanently deleted.

 

Tested on Windows Server 2003, Windows 8 64Bit, Windows 2008 Server

regards,

admin