Wednesday, October 19, 2011

Get Domain, PC Name and IP Address of your local network using VB.Net

Import below namespace in your project:


Imports System.DirectoryServices

Imports System.Net 


Use this functions to get data and store in to Data table :


Private Sub GetIPS()
        Dim child As DirectoryEntry
        Dim Parent As New DirectoryEntry()
        Try
            Parent.Path = "WinNT:"
            For Each child In Parent.Children

                Select Case child.SchemaClassName

                    Case "Domain"

                        Dim ParentDomain As New TreeNode(child.Name)
                        Dim SubChild As DirectoryEntry
                        Dim SubParent As New DirectoryEntry()
                        SubParent.Path = "WinNT://" & child.Name

                        For Each SubChild In SubParent.Children

                            Select Case SubChild.SchemaClassName
                                Case "Computer"
                                    Dim ipadd As String = GetIPAddress(SubChild.Name)
                                    CreateDT(child.Name, SubChild.Name, ipadd)
                            End Select
                        Next
                End Select

            Next

        Catch Excep As Exception
            MsgBox("Error While Reading Directories")
        Finally
            Parent = Nothing
        End Try
    End Sub



    Private Sub CreateDT(ByVal Domain As String, ByVal PCName As String, ByVal IpAddress As String)
        If dt.Rows.Count = 0 Then
            dt.Columns.Add("domain")
            dt.Columns.Add("pcname")
            dt.Columns.Add("ipaddress")
        End If

        Dim dr As DataRow
        dr = dt.NewRow()
        dr("domain") = Domain
        dr("pcname") = PCName
        dr("ipaddress") = IpAddress
        dt.Rows.Add(dr)
    End Sub

  Function GetIPAddress(ByVal CompName As String) As String
        Dim oAddr As System.Net.IPAddress
        Dim sAddr As String
        Try
            With System.Net.Dns.GetHostByName(CompName)
                oAddr = New System.Net.IPAddress(.AddressList(0).Address)
                sAddr = oAddr.ToString
            End With

            GetIPAddress = sAddr
        Catch Excep As Exception
            MsgBox(Excep.Message, MsgBoxStyle.OkOnly, "GET IP ADDRESS")
        Finally

        End Try
    End Function 
Sample Code Download Link : http://www.adrive.com/public/406bd58f991bf0afb884cadc2b78da6a28417082c16938c0bedd505ac224afbd.html

Monday, October 17, 2011

Read from XML file in VB.Net

This is a Sample XML file which we want to read from code :
 

Write below function to read data from file :


Public Sub ReadFromXML()

        Dim _FilePath As String
        Dim _dir As New DirectoryInfo(Application.StartupPath + "\DownloadXML")

        For Each _file As FileInfo In _dir.GetFiles("*.*")
            _FilePath = Application.StartupPath + "\DownloadXML\" + _file.Name.ToString

            Dim m_xmld As XmlDocument
            Dim m_nodelist As XmlNodeList
  

            m_xmld = New XmlDocument()
            'Load the Xml file
            m_xmld.Load(_FilePath)
            'Get the list of name nodes
            m_nodelist = m_xmld.SelectNodes("/XMLInfo/Info")
            For Each m_node As XmlNode In m_nodelist
                Dim Name As String = m_node.Attributes.GetNamedItem("Name").Value
                Dim Address As String = m_node.Attributes.GetNamedItem("Address").Value
            Next
        Next

    End Sub

Upload and Download files from FTP in VB.Net

For Upload and download files from FTP Server you need FTP Detail such as 'FTP Server name', 'User Name' and 'Password'.

First import below namespace in your project

Imports Utilities.FTP

Declare Variables for FTP Detail :

    Dim _HostName As String = "ftp.yourwebsite.com"
    Dim _UserName As String = "yourftpusername"
    Dim _Password As String = "password"
 

Use below function for upload files to FTP :

  Public Sub UploadFileToFTP()
        Dim _FromPath As String
        Dim _ToPath As String
        Dim Dt As New DataTable
        Dim flag As Boolean = False      

        'Create a link to an FtpServer
        Dim ftp As New FTPclient(_HostName, _UserName, _Password)
        Dim _dir As New DirectoryInfo(Application.StartupPath + "\Upload")
      ' Upload multiple files
        For Each _file As FileInfo In _dir.GetFiles("*.*")
            _FromPath = Application.StartupPath + "\Upload\" + _file.Name
            _ToPath = "/UploadedData /" + _file.Name
            'upload a file
            flag = ftp.Upload(_FromPath, _ToPath)
            '' file uploaded then delete

            If flag Then
                _file.Delete()
            End If
        Next
    End Sub


Use below function for Download files from FTP :

Public Sub DownloadXML()
        Try         

            Dim _FromPath As String
            Dim _ToPath As String 
                _FromPath = "/UploadedData /" 

            'Create a link to an FtpServer
            Dim ftp As New FTPclient(_HostName, _UserName, _Password)
            'Get the detailed directory listing of /pub/
            Dim dirList As FTPdirectory = ftp.ListDirectoryDetail(_FromPath)
            'filter out only the files in the list
            Dim filesOnly As FTPdirectory = dirList.GetFiles()
            'download these files
            For Each file As FTPfileInfo In filesOnly
                _ToPath = Application.StartupPath + "\Download\" + file.Filename
                ftp.Download(file, _ToPath, True)
           'Delete file after download
                ftp.FtpDelete(_FromPath + file.Filename)
            Next

        Catch ex As Exception
        End Try

    End Sub


Create XML File from code behind in VB.Net

For generate XML File from code behind in vb.net follow the below steps :

First Import name space
Imports System.Xml 
then you can write this simple function
Public Sub CreateXML( )



        Dim _FilePath As String = Application.StartupPath + "\MainXML.xml"
        If Not File.Exists(_FilePath) Then
            '' Create new xml File
            Dim writer As New XmlTextWriter(_FilePath, Nothing)
            writer.WriteStartElement("XMLInfo")
            writer.WriteEndElement()
            writer.Close()
        End If

        '' If File Exist then appand data

        If File.Exists(_FilePath) Then
            Dim objXML As New XmlDocument
            Dim NewItem As String = " "
            objXML.Load(_FilePath)
            Dim docFrag As XmlDocumentFragment = objXML.CreateDocumentFragment()
            docFrag.InnerXml = NewItem
           Dim root As XmlNode = objXML.DocumentElement
            root.AppendChild(docFrag)
            objXML.Save(_FilePath)
        End If
    End Sub

Sunday, July 3, 2011

Simple Function to write in Text File for error log

First of all you have to import name space
Imports System.IO

then you can write this simple function
Dim FilePath As String = Application.StartupPath + "\Error.log"
Public Sub WriteLog(ByVal StrError As String)
Try
If File.Exists(FilePath) Then
Using Writer As New System.IO.StreamWriter(FilePath, True)
Writer.WriteLine(Now() + "  |  " + StrError)
End Using
Else
Dim fs As FileStream = Nothing
fs = File.Create(FilePath)
Using fs
End Using
Using Writer As New System.IO.StreamWriter(FilePath, True)
Writer.WriteLine(Now() + "  |  " + StrError)
End Using
End If
Catch ex As Exception
End Try
End Sub

Saturday, July 2, 2011

Dos Print from Datagridview in VB.Net

Private Sub DosPrint()
        Try

            Dim table As New DataTable
            Dim i As Integer
            Dim j As Integer
            Dim Collist(dgvreport.ColumnCount) As String
            Dim TotalLen As Integer = 0
            Dim LineCount As Integer = 0
            Dim PageCount As Integer = 1
            Dim StrSeprator As String = ""



            ''========== Check total len from Each Rows ===============
            For Each dc As DataGridViewColumn In dgvreport.Columns
                If dc.Visible = True Then
                    Dim temp As Integer = dc.HeaderText.Length
                    For Each dr As DataGridViewRow In dgvreport.Rows
                        Dim drlen As Integer = dr.Cells(dc.Name).Value.ToString.Length
                        If temp < drlen Then
                            temp = drlen
                        End If
                    Next
                    Collist(dc.Index) = temp
                    TotalLen = TotalLen + temp
                End If

            Next

            Using Writer As New System.IO.StreamWriter("C:\Testfile.txt")

                ''=================== Write Reprot Header ================
                Writer.WriteLine("")
                Writer.WriteLine(Space(20) + Chr(27) + Chr(71) + Chr(14) + _
                                    Chr(27) + Chr(45) + Chr(1) + "Company Name" + _
                                    Chr(27) + Chr(72) + Chr(20) + _
                                    Chr(27) + Chr(45) + Chr(0))     '' For Bold and Enlarge
                Writer.WriteLine(lblHeader.Text)
                Writer.WriteLine("")

                For k As Integer = 0 To TotalLen

                    Writer.Write("=")

                Next

                Dim strCOl As String = ""
                Dim strRow As String = ""

                ''============= Write Col Header for First Page ======================================
                Dim iC As Integer = 1
                Dim iR As Integer = 1
                For j = 0 To dgvreport.ColumnCount - 1
                    If dgvreport.Columns(j).Visible = True Then
                        strCOl = strCOl + "  " + dgvreport.Columns(j).HeaderText.ToString() + Space(CInt(Collist(j)) - CInt(dgvreport.Columns(j).HeaderText.Length))

                        iC = iC + 1
                    End If
                Next

                Writer.WriteLine("")
                Writer.WriteLine(Chr(27) + Chr(27) + strCOl + Chr(27) + Chr(72))

                For k As Integer = 0 To TotalLen
                    StrSeprator = StrSeprator + "="
                Next

                Writer.WriteLine(StrSeprator)
                Writer.WriteLine("")

                ''======== End First Col ========================




                For i = 0 To dgvreport.RowCount - 1

                    If LineCount >= 60 Then  '' Check Lines per page
                        LineCount = 0
                        '' Ending First Page
                        Writer.WriteLine(StrSeprator)
                        Writer.WriteLine("Page: " + PageCount.ToString) ''Write Page Number
                        PageCount = PageCount + 1
                        Writer.WriteLine("")
                        Writer.Write(Chr(13)) '' Line Break


                        ''============= Write Col Header for Other Page ======================================
                        Writer.WriteLine("")
                        Writer.WriteLine(StrSeprator)
                        Writer.WriteLine(Chr(27) + Chr(27) + strCOl + Chr(27) + Chr(72))
                        Writer.WriteLine(StrSeprator)
                        Writer.WriteLine("")

                        ''======== End Other Col header ========================


                    End If

                    If dgvreport.Rows(i).Visible = True Then
                        iR = iR + 1
                        iC = 1
                        For j = 0 To dgvreport.ColumnCount - 1
                            If dgvreport.Columns(j).Visible = True Then
                                strRow = strRow + "  " + dgvreport(j, i).Value.ToString() + Space(CInt(Collist(j)) - CInt(dgvreport(j, i).Value.ToString.Length))
                                iC = iC + 1
                            End If
                        Next
                    End If


                    Writer.WriteLine(strRow)
                    strRow = ""
                    LineCount = LineCount + 1

                Next



                Writer.WriteLine(StrSeprator)
                Writer.Close()

            End Using



        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub