Santosh's profileSantosh KumarPhotosBlogListsMore Tools Help

Blog


    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
     

    Embedding google maps into web pages

     
    Google Maps (for a time named Google Local) is a web mapping service application and technology provided by Google, free (for non-commercial use), that powers many map-based services, including the Google Maps website, Google Ride Finder, Google Transit, and maps embedded on third-party websites via the Google Maps API.
     
    It offers street maps, a route planner for traveling by foot, car, or public transport and an urban business locator for numerous countries around the world.
     
    According to one of its creators (Lars Rasmussen), Google Maps is "a way of organizing the world's information geographically"
     
    Ref: http: //code.google.com/apis/maps/documentation/introduction.html
    Ref: http: //en.wikipedia.org/wiki/Google_Maps
      
    Sample Code
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <title>Google Maps JavaScript API Example: Simple Map</title>
            <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abcdefg&sensor=true_or_false" type="text/javascript"></script>
            <script type="text/javascript">
                function initialize() {
                    var map = new GMap2(document.getElementById("map_canvas"));
                    map.setCenter(new GLatLng(20,77), 3);
                    map.setUIToDefault();
                }
            </script>
        </head>
        <body onload="initialize()" onunload="GUnload()" leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>
            <div id="map_canvas" style="width: 600px; height: 450px"></div>
        </body>
    </html>
     
     

    JavaScript, Browser compatibility for getElementById

     
    Browser detection is one of the most common scripting task that we face. The variety of different strategies in use for detecting browsers is unlimited. Here in this article I am not going to discuss it in details. Rather I am giving the following example that will help you to identified the HTML object independent of browsers. Instead of using the method getElementById in your javascript code you use getObjectById("elementname"). Please Find the following code
     
    function getObjectByID(faObj){
        if (window.document[faObj])    {
            return window.document[faObj];
        }
        if (document.embeds[faObj]){
            return document.embeds[faObj];
        }
        if (document.getElementById(faObj)){
            return document.getElementById(faObj);
        }
    }
     
    »»»»»»»   by Santosh Kumar ? Original @ http://santu4you.spaces.live.com
     

    Short Story ... Is your life worth saving?

     
    A boy was drowning in a river and he shouted for help. A man passing by jumped in the river and saved the boy's life. As the man was leaving the boy said, Thank-you.'' The man asked, "For what?" The boy replied, "For saving my life."
     
    The man looked into the boy's eyes and said,
     
    "Upon, make sure when you grow up that your life was worth saving."
     
    by Shiv Khera { You Can Win }
     

    Short Story ... Meaningless goals

     
    A farmer had a dog who used to sit by the roadside waiting for vehicles to come around. As soon as one came he would run down the road, barking and trying to overtake it. One day a neighbor asked the farmer "Do you think your dog is ever going to catch a car?" The farmer replied, "That is not what bothers me. What bothers me is what he would do if he ever caught one."
     
    Many people in life behave like that dog who is pursuing meaningless goals.
     
    by Shiv Khera { You Can Win }