How to get relative time for the given time?

One of my colleague asked me how to get the relative time for the given datetime. Some thing like

  • less than a minute ago
  • about a minute ago
  • 10 minutes ago
  • 1 hour ago
  • 5 days ago

Here is the a VB.Net source code which will provide the relative time for the given date:

Instructions:

  • Open a New Console application
  • Add a new bas module called Module1
  • Copy the following code to Module1 bas module
Module Module1
  Sub Main()
    Console.WriteLine(GetRelativeTime("6/3/2011 23:00:51"))
    Console.WriteLine("Hit enter to exit...")
    Console.ReadLine()
  End Sub
  Private Function GetRelativeTime(ByVal dt As Date) As String
    Dim Diff As Long = DateDiff(DateInterval.Second, dt, Now)
    Select Case Diff
      Case Is < 60
        Return "less than a minute ago"
      Case Is < 120
        Return "about a minute ago"
      Case Is < 2700
        Return String.Format("{0} minutes ago", Int(Diff / 60))
      Case Is < 5400
        Return "about an hour ago"
      Case Is < 86400
        Return String.Format("{0} hours ago", Int(Diff / 3600))
      Case Is < 172800
        Return "about 1 day ago"
      Case Else
        Return String.Format("{0} days ago", Int(Diff / 86400))
    End Select
  End Function
End Module

Project Type: Console
Language: VB.Net
Tested with: VS 2010
DotNet Framework: 2.0

Posted in VB.Net | Tagged calculate relative time, how to get relative time, vb.net source code | Leave a comment

How to extract the zip file using SharpZipLib .net library

Here is the a VB.Net code which will extract the files from given .zip file. This code uses OpenSource SharpZipLib .net library component.

Instructions:

'You need to add a reference to the ICSharpCode.SharpZipLib.dll assembly. It is located in the main World Wind folder.
'You could also download the library from http://www.icsharpcode.net/OpenSource/SharpZipLib/.
'http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip

Module Mod1

  'How to extract the zip file using SharpZipLib
  Sub Main()
    Dim sZipFile As String = "C:\temp\test.zip"

    If ExtractZipFile(sZipFile, "C:\temp\") Then
      Console.WriteLine("Zip file extracted successfully.")
    Else
      Console.WriteLine("Zip file extraction - failed.")
    End If
  End Sub

  Public Function ExtractZipFile(ByVal ZipFilePath As String, ByVal TargetDirectory As String) As Boolean
    Try
      If File.Exists(ZipFilePath) Then
        Using zs As New ZipInputStream(File.OpenRead(ZipFilePath))
          Dim ze As ZipEntry = Nothing
          While (InlineAssignHelper(ze, zs.GetNextEntry())) IsNot Nothing
            If ze.IsFile Then
              If ze.Name <> "" Then
                Dim sFile As String = TargetDirectory & "\" & ze.Name
                If File.Exists(sFile) Then
                  Continue While
                End If

                Using sw As FileStream = File.Create(sFile)
                  Dim iSize As Integer = 2048
                  Dim data As Byte() = New Byte(2047) {}
                  While True
                    iSize = zs.Read(data, 0, data.Length)
                    If iSize > 0 Then
                      sw.Write(data, 0, iSize)
                    Else
                      Exit While
                    End If
                  End While
                  sw.Close()
                End Using
              End If
            ElseIf ze.IsDirectory Then

              Dim sDir As String = TargetDirectory & "\" & ze.Name
              If Not Directory.Exists(sDir) Then
                Directory.CreateDirectory(sDir)
              End If
            End If
          End While
          zs.Close()
        End Using
      End If
      Return True
    Catch ex As Exception
      Console.WriteLine("Error occurred: " & ex.Message)
      Return False
    End Try
  End Function

  Public Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
  End Function
End Module

Project Type: Console
Language: VB.Net
Tested with: VS 2010

Posted in VB.Net | Tagged extract zip file, ICSharpCode, SharpZipLib, zip file | Leave a comment

How to check whether the zip file is password protected using SharpZipLib .net library

Here is the a VB.Net code which will check the given .zip file is password protected or not. This code uses OpenSource SharpZipLib .net library component.

Instructions:

'You need to add a reference to the ICSharpCode.SharpZipLib.dll assembly. It is located in the main World Wind folder.
'You could also download the library from http://www.icsharpcode.net/OpenSource/SharpZipLib/.
'http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip

Module modMain

    'How to check whether the zip file is password protected
    Sub Main()
        Dim sZipFile As String = "C:\temp\test.zip"
        If IsZipFilePasswordProtected(sZipFile) Then
            Console.WriteLine("Zip file is password protected.")
        Else
            Console.WriteLine("Zip file is not password protected.")
        End If
    End Sub

    Private Function IsZipFilePasswordProtected(ByVal ZipFile As String) As Boolean
        Using fsIn As New FileStream(ZipFile, FileMode.Open, FileAccess.Read)
            Using zipInStream As New ZipInputStream(fsIn)
                Dim zEntry As ZipEntry = zipInStream.GetNextEntry()
                Return zEntry.IsCrypted
            End Using
        End Using
    End Function

End Module

Project Type: Console
Language: VB.Net
Tested with: VS 2010

Posted in VB.Net | Tagged check zip password protection, ICSharpCode, SharpZipLib, zip file, zip file protection | Leave a comment

How to create zip file using SharpZipLib library

Here is the a VB.Net code to create .zip file using open source SharpZipLib .net library:

Instructions:

'You need to add a reference to the ICSharpCode.SharpZipLib.dll assembly.
'You can download the library from http://www.icsharpcode.net/OpenSource/SharpZipLib/.
'http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip

Module Module1

  Sub Main()
    Dim sFiles As New ArrayList
    'Add the files which needs to be added to the .zip file
    'Adding list of files to an array list
    sFiles.add("C:\temp\test1.txt")
    sFiles.add("C:\temp\test2.txt")
    sFiles.add("C:\temp\test3.txt")
    sFiles.add("C:\temp\test4.txt")
    sFiles.add("C:\temp\test5.txt")

    'Set the Password to zip files
    Dim sPass As String = "test"

    'We need to specify the parent folder of the files we are adding to zip file
    Dim sParentFolder As String = "C:\temp\"

    'Target zip file name with full path
    Dim sZipFile As String = "C:\temp\test.zip"

    'create the zip file
    If ZipFiles(sParentFolder, sZipFile, sPass, sFiles) Then
      Console.Writeline("Zip file created successfully.")
    Else
      Console.Writeline("Zip file creation failed.")
    End If
  End Sub

  Public Function ZipFiles(ByVal inputFolder As String, ByVal OutputZipFilePath As String, ByVal sPass As String, ByVal ar As ArrayList) As Boolean
    Try
      Dim fs As FileStream
      Dim buf As Byte()
      Dim zs As New ZipOutputStream(File.Create(OutputZipFilePath))
      ' create zip stream
      If sPass IsNot Nothing AndAlso sPass <> [String].Empty Then
        zs.Password = sPass
      End If
      zs.SetLevel(9)
      ' maximum compression
      Dim ze As ZipEntry
      Dim sFile As String
      For Each sFile In ar
        ' for each file, generate a zipentry
        ze = New ZipEntry(sFile.Remove(0, inputFolder.Length))
        Dim fi As New FileInfo(sFile)
        ze.DateTime = fi.LastWriteTime
        zs.PutNextEntry(ze)

        If Not sFile.EndsWith("/") Then
          ' if a file ends with '/' its a directory
          fs = File.OpenRead(sFile)
          buf = New Byte(CType(fs.Length, Integer) - 1) {}
          fs.Read(buf, 0, buf.Length)
          zs.Write(buf, 0, buf.Length)
        End If
      Next
      zs.Finish()
      zs.Close()
      Return True
    Catch ex As Exception
      'error occurred while creating the zip file
      Console.writeline(ex.message)
      Return False
    End Try
  End Function

End Module

Project Type: Console
Language: VB.Net
Tested with: VS 2010

Posted in VB.Net | Tagged create zip file, ICSharpCode, SharpZipLib | Leave a comment

How to print out a table of numbers 0 to 20 in decimal, hexa-decimal, octal and binary notation

Here is the VB.Net code which lists a table of numbers 0 to 20 in decimal, hexa-decimal, octal and binary in listview control.

Instructions:

  • Add a new windows project
  • Add a new form to your project and name it as frmMain
  • Add a listview control to the newly added form and name it as ListView1
  • Add 4 columns to your listview control. (Select the control. Right click > Properties. Navigate to Columns property. Click on the button next to Columns property value. It will open a new dialog where you can add new columns and set the required properties for that column)

Copy the following code to Form1:

Public Class frmMain
  Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim num As Short
    For num = 0 To 20
      Dim Base16 As String = Convert.ToString(num, 16)
      Dim Base8 As String = Convert.ToString(num, icon cool How to print out a table of numbers 0 to 20 in decimal, hexa decimal, octal and binary notation
      Dim Base2 As String = Convert.ToString(num, 2)
      Dim lvItem As New ListViewItem(num.ToString)
      lvItem.SubItems.Add(Base16)
      lvItem.SubItems.Add(Base8)
      lvItem.SubItems.Add(Base2.PadLeft(8, "0"))
      ListView1.Items.Add(lvItem)
    Next
  End Sub
End Class

Project Type: Windows
Language: VB.Net
Tested with: VS 2010

VB.net Source code Project Download

Posted in VB.Net | Leave a comment