Santosh's profileSantosh KumarPhotosBlogListsMore Tools Help
Photo 1 of 36

Santosh Kumar

Occupation
Location

Santosh Kumar

The space where I am sharing my knowledge and thoughts

VB.Net, Finding very first day number for Sun, Mon, ..., Sat of the Year

 
Public Shared Function GetVery1stDayNoOfTheYear(ByVal faDay As String, ByVal faYear As Integer) As Integer
    Dim vRet As Integer = 0
    For vRet = 1 To 7
        If UCase(Format(CDate("0" & vRet & "-Jan-" & faYear), "ddd")) = UCase(faDay) Then
            Exit For
        End If
    Next
    Return vRet
End Function 
 
Input: GetVery1stDayNoOfTheYear("SUN",2008), Output: 6
Input: GetVery1stDayNoOfTheYear("SUN",2009), Output: 4
Input: GetVery1stDayNoOfTheYear("MON",2009), Output: 5
 
»»»»»»»   by Santosh Kumar ? Original @ http://santu4you.spaces.live.com
 

ASP.Net, Designing a site visit counter module

 
There are many sites offering visit analysis for your web site including google. Once you register with them, you will get some client side script. You can put them in each of your page, and thing are over. You can try your own visit analysis module with the help of the following codes. It uses an xml file i.e. AppVisitCount.Xml, the structure is given below. All you need is to call the following functions
 
LetVisitCount(): For page load of every aspx file or master file
GetVisitCount(): To know the current visit count
GetCountBoard(): To have the following output
 
 1   5   0   8   1   9   4   7 
 
You can also write additional functions to maintain a database level logs for capturing statistics for various analysis. The function LetVisitCount() is the right place for calling your functions for such data captures.
 
'''''''''file:AppVisitCount.Xml
 
<?xml version="1.0" standalone="yes"?>
<table>
  <row>
    <hitcounter>15081947</hitcounter>
  </row>
</table>
 
'''''''''code:forVisitCount
 
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Xml
Imports System.IO
 
Private Shared Function GetVisitCount() As Long
    Dim vDs As New DataSet
    Dim vHits As Long = 0
    vDs.ReadXml(HttpContext.Current.Request.PhysicalApplicationPath & "\AppVisitCount.Xml")
    vHits = CLng(vDs.Tables(0).Rows(0).Item("hitcounter").ToString)
    Return vHits
End Function
 
Public Shared Sub LetVisitCount()
    Dim vHits As Long = 0
    If HttpContext.Current.Session("hitcounter") Is Nothing Then
        vHits = SetVisitCount()
        HttpContext.Current.Session("hitcounter") = vHits
    Else
        vHits = GetVisitCount()
    End If
End Sub
 
Public Shared Function GetCountBoard() As String
    Dim vHitsBoard As String = ""
    If Not HttpContext.Current.Session("Hits") Is Nothing Then
        Dim vHits As String = Format(CLng(HttpContext.Current.Session("hitcounter")), "0000000")
        Dim vCnt As Integer = Len(vHits)
        Dim vCtr As Integer = 0
        vHitsBoard = vHitsBoard & "<table border=1 cellpadding=1 cellspacing=0><tr>"
        For vCtr = 1 To vCnt
            vHitsBoard = vHitsBoard & "<td height=25px bgcolor='#000000' "
            vHitsBoard = vHitsBoard & "style='color:#ffffff;font-weight:bold'>"
            vHitsBoard = vHitsBoard & Mid(vHits, vCtr, 1) & "</td>"
        Next
        vHitsBoard = vHitsBoard & "</tr></table>"
    End If
    Return vHitsBoard
End Function
 
Private Shared Function SetVisitCount() As Long
    Dim vDs As New DataSet
    Dim vHits As Long = 0
    vDs.ReadXml(HttpContext.Current.Request.PhysicalApplicationPath & "\AppVisitCount.Xml")
    vHits = CLng(vDs.Tables(0).Rows(0).Item("hitcounter").ToString) + 1
    vDs.Tables(0).Rows(0).Item("hitcounter") = vHits
    vDs.WriteXml(HttpContext.Current.Request.PhysicalApplicationPath & "\AppVisitCount.Xml")
    Return vHits
End Function
 
»»»»»»»   by Santosh Kumar ?
Original @ http://santu4you.spaces.live.com
 

ASP.Net, Downloading files and images which are kept outside the web application folder

 
There are many situations where your application requires giving facilities for uploading files. If this files require sharing publically you should keep it in your web application folder so that search engines can easily search it and index then. This will also help you to ease your site search engines also. But it not a good idea to keep it inside your web application folder if you want to make it secured from unauthorized access. In such case you must keep this folder outside. But this will restrict you to use href tag from downloading. The following code will help you.
 
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.IO
 
Public Shared Function DoDownload_File(ByVal faType As String, ByVal faFile As String, ByVal faPath As String) As Boolean 
    Dim vRet As Boolean = False
    Try
        HttpContext.Current.Response.ContentType = "application/" & faType
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" & faFile)
        HttpContext.Current.Response.TransmitFile(faPath)
        HttpContext.Current.Response.End()
        vRet = True
    Catch ex As Exception
        vRet = False
    Finally
        'doNothing
    End Try
    Return vRet
End Function
 
Public Shared Function DoDownload_Image(ByVal faFile As String, ByVal faPath As String) As Boolean 
    Dim vRet As Boolean = False
    Try
        Dim contenttype As String = "image/" & Path.GetExtension(faFile).Replace(".", "")
        Dim fs As FileStream = New FileStream(faPath & faFile, FileMode.Open, FileAccess.Read)
        Dim br As BinaryReader = New BinaryReader(fs)
        Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
        br.Close()
        fs.Close()
        HttpContext.Current.Response.Buffer = True
        HttpContext.Current.Response.Charset = ""
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
        HttpContext.Current.Response.ContentType = contenttype
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & faFile)
        HttpContext.Current.Response.BinaryWrite(bytes)
        HttpContext.Current.Response.Flush()
        HttpContext.Current.Response.End()
        vRet = True
    Catch ex As Exception
        vRet = False
    Finally
        'doNothing
    End Try
    Return vRet
End Function 
 
»»»»»»»   by Santosh Kumar ?
Original @ http://santu4you.spaces.live.com
 

VB.Net, Reading text from most common document formats like .txt, .doc, .xls, .pdf and web pages like (.html, .aspx, .jsp, .php .etc)

 
Reading text from different files format may give directions to most of the challenges faced for building various tools like site search engine. Once you are able to extract texts, coding of very simple logic will be sufficient to design hundreds of web and window based tools. Here in this article, I am using itextsharp.dll apart from .NET and COM libraries. 
 
You need the following binaries. iTextSharp is a free binary. All other are from Miscrosoft and should be used as per Miscrosoft guidelines. If you have MS Office installed in you system you don't need these binaries. You can simply add COM reference of MS Word and MS Excel object libraries.
  
Interop.Excel.dll for .Net 2.0
(download attachment | download from original link)
 
Interop.Word.dll for .Net 2.0
(download attachment | download from original link)
 
Interop.Office.dll for .Net 2.0
(download attachment | download from original link)
 
Interop.VBIDE.dll for .Net 2.0
(download attachment | download from original link)
 
iTextSharp for .Net 2.0
(download attachment | download from original link)
 
'''''Code Begins herefrom 
 
Imports System.IO
Imports System.Data
Imports System.Xml
Imports System.Text
Imports System.Diagnostics
Imports Microsoft.VisualBasic
Imports System.Text.RegularExpressions
Imports iTextSharp.text.pdf
Imports System.Windows.Forms
 
Public Function ReadText_TXT(ByVal faPath As String) As String
    Dim vRet As String = ""
    Dim vStreamReader As StreamReader = File.OpenText(faPath)
    Try
        vRet = vStreamReader.ReadToEnd()
        vStreamReader.Close()
    Catch ex As Exception
        vRet = ""
    End Try
    Return vRet
End Function
 
Public Function ReadText_DOC(ByVal faPath As String) As String
    Dim vRet As String = ""
    Dim vRTB As New RichTextBox
    Dim vWD As New Word.Application
    vWD.Documents.Open(faPath)
    vWD.Selection.WholeStory()
    vWD.Selection.Copy()
    vRTB.Paste()
    vRet = vRTB.Text
    vWD.Quit()
    DoGarbageCollection(vWD)
    Return vRet
End Function
 
Public Function ReadText_XLS(ByVal faPath As String) As String
    Dim vRet As String = ""
    Dim vRTB As New RichTextBox
    Dim vXL As New Excel.Application
    Dim vWB As Excel.Workbook = Nothing
    Dim vWS As Excel.Worksheet = Nothing
    Dim vUR As Excel.Range = Nothing
    Dim vCnt As Integer
    Dim vCtr As Integer
    Dim vRow As Integer
    Dim vCol As Integer
    Dim vRows As Integer
    Dim vCols As Integer
    vWB = vXL.Workbooks.Open(faPath)
    vXL.Calculation = Excel.XlCalculation.xlCalculationManual
    vXL.AlertBeforeOverwriting = False
    vCnt = vWB.Worksheets.Count
 
    For vCtr = 1 To vCnt
        vWS = vWB.Worksheets(vCtr)
        vUR = vWS.UsedRange
        vRows = vUR.Rows.Count
        vCols = vUR.Columns.Count
        For vRow = 1 To vRows
            For vCol = 1 To vCols
                vRet = vRet & CType(vUR.Cells(vRow, vCol), Excel.Range).Value & " "
            Next vCol
        Next vRow
    Next
 
    vWB.Close(False)
    DoGarbageCollection(vWB)
    vXL.Quit()
    DoGarbageCollection(vXL)
 
    Return vRet
End Function
 
Public Function ReadText_PDF(ByVal faPath As String, Optional ByVal faFromPageNum As Integer = 0, _
    Optional ByVal faUptoPageNum As Integer = 0) As String
    Dim sb As New System.Text.StringBuilder()
    Try
        Dim reader As New PdfReader(faPath)
        Dim pageBytes() As Byte = Nothing
        Dim token As PRTokeniser = Nothing
        Dim tknType As Integer = -1
        Dim tknValue As String = String.Empty
        If faFromPageNum = 0 Then
            faFromPageNum = 1
        End If
        If faUptoPageNum = 0 Then
            faUptoPageNum = reader.NumberOfPages
        End If
        If faFromPageNum > faUptoPageNum Then
            Throw New ApplicationException("Err: faFromPageNum > faUptoPageNum")
        End If
 
        For i As Integer = faFromPageNum To faUptoPageNum Step 1
            pageBytes = reader.GetPageContent(i)
            If Not IsNothing(pageBytes) Then
                token = New PRTokeniser(pageBytes)
                While token.NextToken()
                    tknType = token.TokenType()
                    tknValue = token.StringValue
                    If tknType = PRTokeniser.TK_STRING Then
                        sb.Append(token.StringValue)
                    ElseIf tknType = 1 AndAlso tknValue = "-600" Then
                        sb.Append(" ")
                    ElseIf tknType = 10 AndAlso tknValue = "TJ" Then
                        sb.Append(" ")
                    End If
                    Application.DoEvents()
                End While
            End If
        Next i
        sb = New StringBuilder(sb.ToString)
    Catch ex As Exception
        Return String.Empty
 
    End Try
    Return sb.ToString()
End Function
 
Public Function ReadText_WEB(ByVal faUrl As String) As String
    Dim vRet As String = ""
    Try
        Dim vSNWebClient As System.Net.WebClient
        Dim vUTF8Encoding As UTF8Encoding
        vSNWebClient = New System.Net.WebClient()
        vUTF8Encoding = New UTF8Encoding()
        vRet = vUTF8Encoding.GetString(vSNWebClient.DownloadData(faUrl))
    Catch ex As Exception
        vRet = ""
    End Try
    Return ReadText_HTM(vRet)
End Function
 
Private Sub DoGarbageCollection(ByVal faObj As Object)
    Try
        Runtime.InteropServices.Marshal.ReleaseComObject(faObj)
    Catch
    Finally
        faObj = Nothing
    End Try
End Sub
 
Private Function ReadText_HTM(ByVal faContent As String) As String
    Dim vRet As String = faContent
    Try
        Dim vRegEx As Regex
        vRegEx = New Regex("", RegexOptions.IgnoreCase)
        vRet = Regex.Replace(vRet, "<(select|option|script|style|title)(.*?)>((.|\n)*?)</(select|option|script|style|title)>", " ", RegexOptions.IgnoreCase)
        vRet = Regex.Replace(vRet, "&(nbsp|quot|copy);", "")
        vRet = Regex.Replace(vRet, "<([\s\S])+?>", " ", RegexOptions.IgnoreCase)
        vRet = Regex.Replace(vRet, "\W", " ")
    Catch ex As Exception
        vRet = ""
    End Try
    Return Trim(vRet)
End Function
 
»»»»»»»   by Santosh Kumar ?
Original @ http://santu4you.spaces.live.com
 

VB.Net, Working with FTP

 
FTP Transfers files to and from a computer running a File Transfer Protocol (FTP) server service such as Internet Information Services. Ftp can be used interactively or in batch mode by processing ASCII text files. The following codes illustrates how to do the related operations programatically using VB.Net environment. 
 
Imports System.IO
Imports System.Net
 
Public Function doActionFTP_GetFileList( _
    ByVal FullFtpUrl As String,
    Optional ByVal Usr As String = "", _
    Optional ByVal Pwd As String = "" _
    ) As String
    Dim vDirList As String = ""
    Try
        Dim fwreqObj As FtpWebRequest = DirectCast(WebRequest.Create(FullFtpUrl), FtpWebRequest)
        fwreqObj.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        fwreqObj.Credentials = New NetworkCredential(Usr, Pwd)
        Dim fwresObj As FtpWebResponse = DirectCast(fwreqObj.GetResponse(), FtpWebResponse)
        Dim srObj As New StreamReader(fwresObj.GetResponseStream, System.Text.Encoding.ASCII)
        vDirList = srObj.ReadToEnd
 
    Catch ex As Exception
        vDirList = ""
 
    End Try
    Return vDirList
End Function
 
Public Function doActionFTP_GetFileCrDate( _
    ByVal FullFtpUrl As String, _
    Optional ByVal Usr As String = "", _
    Optional ByVal Pwd As String = "" _
    ) As Date
    Dim fcDate As Date = Now
    Try
        Dim fwreqObj As FtpWebRequest = DirectCast(WebRequest.Create(FullFtpUrl), FtpWebRequest)
        fwreqObj.Method = WebRequestMethods.Ftp.GetDateTimestamp
        fwreqObj.Credentials = New NetworkCredential(Usr, Pwd)
        Dim fwresObj As FtpWebResponse = DirectCast(fwreqObj.GetResponse(), FtpWebResponse)
        fcDate = fwresObj.LastModified
 
    Catch ex As FileNotFoundException
        fcDate = DateValue("15-AUG-1947")
 
    Catch ex As Exception
        fcDate = DateValue("26-JAN-1951")
 
    End Try
    Return fcDate
End Function
 
Public Function doActionFTP_Upload( _
    ByVal FullFilePath As String, _
    ByVal FullFtpUrl As String, _
    Optional ByVal Usr As String = "", _
    Optional ByVal Pwd As String = "" _
    ) As Boolean
    Try
        Dim fwreqObj As FtpWebRequest = DirectCast(WebRequest.Create(FullFtpUrl), FtpWebRequest)
        fwreqObj.Method = WebRequestMethods.Ftp.UploadFile
        fwreqObj.Credentials = New NetworkCredential(Usr, Pwd)
 
        Dim byteObj As Byte() = File.ReadAllBytes(FullFilePath)
        fwreqObj.ContentLength = byteObj.Length
 
        Dim sObj As Stream = fwreqObj.GetRequestStream()
        sObj.Write(byteObj, 0, byteObj.Length)
        sObj.Close()
 
        Dim fwresObj As FtpWebResponse = DirectCast(fwreqObj.GetResponse(), FtpWebResponse)
        fwresObj.Close()
    Catch ex As Exception
        vRet = False
 
    Finally
     'do nothing
 
    End Try
    Return vret
End Function
 
Public Function doActionFTP_Dnload( _
    ByVal FullFtpUrl As String, _
    ByVal FullFilePath As String, _
    Optional ByVal Usr As String = "", _
    Optional ByVal Pwd As String = "" _
    ) As Boolean
    Dim vRet As Boolean = False
    Try
        Dim fwreqObj As FtpWebRequest = DirectCast(WebRequest.Create(FullFtpUrl), FtpWebRequest)
        fwreqObj.Method = WebRequestMethods.Ftp.DownloadFile
        fwreqObj.Credentials = New NetworkCredential(Usr, Pwd)
 
        Dim fwresObj As FtpWebResponse = DirectCast(fwreqObj.GetResponse(), FtpWebResponse)
        Dim sObj As Stream = fwresObj.GetResponseStream()
 
        Dim rObj As New StreamReader(sObj)
        Dim fsObj As New FileStream(FullFilePath, FileMode.Create)
        Dim wObj As New StreamWriter(fsObj)
 
        wObj.Write(rObj.ReadToEnd)
        wObj.Flush()
        wObj.Close()
        fsObj.Close()
        rObj.Close()
        sObj.Close()
        fwresObj.Close()
        vret = True
    Catch ex As Exception
        vRet = False
 
    Finally
     'do nothing
 
    End Try
    Return vret
End Function
 
»»»»»»»   by Santosh Kumar ? Original @ http://santu4you.spaces.live.com
 
 
Thanks for visiting!
Please wait...
Sorry, the comment you entered is too long. Please shorten it.
You didn't enter anything. Please try again.
Sorry, we can't add your comment right now. Please try again later.
To add a comment, you need permission from your parent. Ask for permission
Your parent has turned off comments.
Sorry, we can't delete your comment right now. Please try again later.
You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
Complete the security check below to finish leaving your comment.
The characters you type in the security check must match the characters in the picture or audio.