Thursday, August 13, 2009

Master Detail Group Report Using Crystal Report XI



Report generation Plays a Major Role in Application Project, So I will show you how create a simple report using Crystal Report XI


Say Table A --> Describes the student Details


Table A
Student Id (Primary Key)
Student Name
Student Class




Say Table B --> Describes the Student Fees Paid Details


Table B
Paid Id (Primary Key)
Student Id (Foreign Key)
Paid Amount
Paid Date

Table B will have multiple Entries for Single Entry of Table A


I will Explain Step by Step Method to display in the Crystal Report XI


Step 1: Open Crystal Report XI
Step 2: File-> New-> Standard Report
Step 3: Create New Connection-> OLE DB (ADO) -> Microsoft OLE DB Provider for Oracle
I have mentioned for Oracle Provider, you can select your own data source
Step 4: Service: Server Name; UserId: Username; Password: Password of the server
Step 5: Select the Two Tables from Left Side Pan of Available Data source and Move to Right Side
Step 6: Click Next
Step 7: You will see two tables in the Report Creation Wizard, Now Select the Primary Key of Table A and Drag to Table B’s Foreign Key
Step 8: Select the Line/Link of the two tables and Right Click it Select Link Option
Step 9: Select the Radio Button of Left Outer Join and Press Ok button
Step 10: Click Finish Button
Step 11: Select from Menu Insert-> Group Select the Primary Key of Table A and Select Ascending Order and Press Ok Button
Now you can see Detail Section below Group Section
Step 12: Now place the Table A Details in Group Header Section and Place the Table B Details in Details Section



If you preview, you can see the Table B Details of Every Record of Table A
And you can filter by record selection formula.



Happy To Share!




Monday, August 10, 2009

To Select All Checkboxes in Grid View Using JavaScript

In this I have given simple tip to select all the check boxes in the template field of a gridview
Using JavaScript,

Place the JavaScript where the gridview you have to bind

JavaScript in the Page

<script type="text/javascript" language="javascript">
function fncheckAll()
{
var eleChk=event.srcElement;
var eleTbody=eleChk.parentNode.parentNode.parentNode;
var i=1;
for(i=1;i<eleTbody.children.length;i++)
eleTbody.children[i].children[2].children[0].checked=eleChk.checked;
}
</script>


Grid View

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="CustomerName" HeaderText="Name" />
<asp:BoundField DataField="CustomerAge" HeaderText="Age" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkId" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Code Behind

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
CType(e.Row.Cells(2).FindControl("chkSelectAll"), CheckBox).Attributes.Add("onclick", "fncheckAll()")
End If
End Sub

Close Project Coordination -We know who to blame.

Sunday, August 9, 2009

Validating a Textbox in Grid View Using JavaScript

In this post I will show you how to validate a textbox placed in template field of grid view
Say for eg, we have grid view listing Currency and Exchange rate
Where the exchange is in textbox field where you the user can change it
Now we will validate for the currency

If the Currency Code is USD then the exchange rate should not be less that of 3.665

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="Currency" HeaderText="Currency" />
<asp:TemplateField HeaderText="Exchg Rate" >
<ItemTemplate>
<asp:TextBox ID="txtExchgRate" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



Code Behind

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

If e.Row.RowType = DataControlRowType.DataRow Then

If e.Row.Cells(0).Text = "USD" Then
CType(e.Row.Cells(1).FindControl("txtExchgRate"), TextBox).Attributes.Add("onblur", "fnValUSDExchg(this)")
End If

End If

End Sub


JavaScript Function

<script language="javascript" type="text/javascript">

function fnValUSDExchg(txtbox)
{
if (txtbox.value<=3.665)
txtbox.value=3.665;
}
</script>

Low Maintenance - Impossible to fix if broken.

To Create an Corresponding Button Event by Hitting on Enter key

I will show you simple tip how to create an event by hitting on enter key after writing some text in corresponding textbox without conflicts in other events
Say if you have two textboxes and corresponding buttons, in which you write text to textbox of the two, corresponding button event should fire when enter key is hit


<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" DefaultButton="Button2">
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" Style="height: 26px" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</asp:Panel>




Savings are achieved when the power switch is off

Thursday, August 6, 2009

Reading Data from Excel file in Asp.net

Create Excel Connection for the Excel file
Then data is read from the sheet and returned as dataset

Protected Function ExcelConnection() As DataSet

Dim xConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("Uploads/ExcelFile.xls") & ";" & _
"Extended Properties=""Excel 8.0; IMEX=1;"""

Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
Dim dsExcelData As New DataSet
Dim objCommand As New OleDbCommand("SELECT * FROM [Sheet1$]", objXConn)
Dim objAdapter As New OleDbDataAdapter
objAdapter.SelectCommand = objCommand
objAdapter.Fill(dsExcelData)

objAdapter.Dispose()
objCommand.Dispose()
objXConn.Close()
Return dsExcelData
End Function


A Number Of Different Approaches Are Being Tried We're still guessing.

Wednesday, August 5, 2009

Creating Custom Paging With Usercontrol

As we know paging becomes a big issue when we come across huge data which becomes slow and slow when data grows.
Though we have built in paging in grid view they may not be useful in all the cases because, there won’t be lesser data when we come up with live projects.

So here I will show you how to create custom paging in Asp.net 2.0 Web application for customer table

Add new item in the project, Select the Web User Control



Name it as WUCTLPager, and add the code in it


<%@ Control Language@="VB" AutoEventWireup@="false" CodeFile@="WUCTLPager.ascx.vb" Inherits="General_WUCTLPager" %>
<table>
<tr>
<td><asp:LinkButton ID="btnFirst" runat="server" ToolTip="First">< </asp:LinkButton></td>
<td><asp:LinkButton ID="btnPrevoius" runat="server" ToolTip="Previous"> < </asp:LinkButton></td>
<td><asp:TextBox ID="txtPageno" runat="server" Width="60px"></asp:TextBox></td>
<td><asp:LinkButton ID="btnGo" runat="server">Go</asp:LinkButton></td>
<td><asp:LinkButton ID="btnNext" runat="server">></asp:LinkButton></td>
</tr>

Instead of ‘<’ for Previous and all other direction symbols you can use your own images which would look pretty good.
Then add the code Behind of the Usercontrol Page


Partial Class General_WUCTLPager
Inherits System.Web.UI.UserControl

Public Event PageNavigate(ByVal paramPageNo As Integer)

Public Property PageNo() As Integer
Get
Return IIf(IsNothing(ViewState("pageno")), 0, ViewState("pageno"))
End Get
Set(ByVal value As Integer)
ViewState("pageno") = value
txtPageno.Text = value
End Set
End Property

Protected Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click
PageNo = 1
RaiseEvent PageNavigate(PageNo)
End Sub

Protected Sub btnPrevoius_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevoius.Click
PageNo = PageNo - 1
If PageNo < 1 Then PageNo = 1
RaiseEvent PageNavigate(PageNo)
End Sub


Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
PageNo = PageNo + 1
RaiseEvent PageNavigate(PageNo)
End Sub

Protected Sub btnGo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGo.Click
PageNo = Val(txtPageno.Text)
RaiseEvent PageNavigate(PageNo)
End Sub

End Class



Write a Query To Retrive Data with Page Number,I have binded the Gridview with datareader
You can do your own logic to bind whether with Dataset, Custom Entity what ever it may be


Public Sub BindCustomer(ByVal PageNo As Integer)

Dim Conn As New OleDb.OleDbConnection
Dim Cmd As New OleDb.OleDbCommand
Dim Query As String
Dim PageSize As Integer

Dim dr As OleDb.OleDbDataReader

PageSize = 10

‘Oracle Query Syntax

Query = "Select * From"
Query = Query & "(Select A.*,ROWNUM row_num From "
Query = Query & "(Select * From Tab_Customer) A "
Query = Query & "Where ROWNUM <=" & PageNo & "*" & PageSize & ") "
Query = Query & "Where row_num >=(" & PageNo & "-1)*" & PageSize & "+1"

Conn.ConnectionString = “Connection String”
Conn.Open()
Cmd.Connection = Conn
Cmd.CommandType = CommandType.Text
Cmd.CommandText = Query

dr = Cmd.ExecuteReader()
gvCustomer.DataSource = dr
gvCustomer.DataBind()

Conn.Close()

End Sub


Then Drag and Drop the Usercontrol to the Page which you want to use the control

Then the user control would looks like this

Then add the Events to Fire


This event is to fire to search the customer First

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Pager.PageNo = 1
BindCustomer(Pager.PageNo)

End Sub

This is the event to Navigate

Protected Sub Pager_PageNavigate(ByVal paramPageNo As Integer) Handles Pager.PageNavigate
BindCustomer(Pager.PageNo)
End Sub


Happy To Share!!

Tuesday, August 4, 2009

Converting a Text File to Image File

You will find useful converting a text file to image file when you have to send a fax through application,
You can find the vb code snippet below for converting the text file to image and save it as your own file type such as tiff file.




Imports System.Drawing
Imports System.Drawing.Graphics
Imports System.Drawing.Imaging

Private Function CreateBitmapImage(ByVal sImageText As String) As Bitmap

Dim objBmpImage As Bitmap = New Bitmap(1, 1)

Dim intWidth As Integer = 0
Dim intHeight As Integer = 0

' Create the Font object for the image text drawing.
Dim objFont As Font = New Font("Arial", 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel)

' Create a graphics object to measure the text's width and height.
Dim objGraphics As Graphics = Graphics.FromImage(objBmpImage)

' This is where the bitmap size is determined.
intWidth = CType(objGraphics.MeasureString(sImageText, objFont).Width, Integer)
intHeight = CType(objGraphics.MeasureString(sImageText, objFont).Height, Integer)

intWidth = 500
intHeight = 900

' Create the bmpImage again with the correct size for the text and font.
objBmpImage = New Bitmap(objBmpImage, New Size(intWidth, intHeight))

' Add the colors to the new bitmap.
objGraphics = Graphics.FromImage(objBmpImage)

' Set Background color
objGraphics.Clear(Color.White)
'objGraphics.SmoothingMode = SmoothingMode.AntiAlias
'objGraphics.TextRenderingHint = TextRenderingHInteger.AntiAlias
'objGraphics.DrawString(sImageText, objFont, New SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0)
objGraphics.DrawString(sImageText, objFont, Brushes.Black, 0, 0)
objGraphics.Flush()

Return (objBmpImage)

End Function

Using it

CreateBitmapImage(strText).Save("D:\Files\FileName.tif",ImageFormat.Tiff)


Accessing FTP Server using Asp.net

Accessing FTP Server using Asp.net

In this post I have given the code which is used to access the FTP server, where you can upload, download, delete, rename and many other useful functions


Imports System.Collections.Generic
Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions


Namespace FTP

#Region "FTP client class"
'''
''' A wrapper class for .NET 2.0 FTP
'''

'''
''' This class does not hold open an FTP connection but
''' instead is stateless: for each FTP request it
''' connects, performs the request and disconnects.
'''

Public Class FTPclient

#Region "CONSTRUCTORS"
'''
''' Blank constructor
'''

''' Hostname, username and password must be set manually
Sub New()
End Sub

'''
''' Constructor just taking the hostname
'''

''' in either ftp://ftp.host.com or ftp.host.com form
'''
Sub New(ByVal Hostname As String)
_hostname = Hostname
End Sub

'''
''' Constructor taking hostname, username and password
'''

''' in either ftp://ftp.host.com or ftp.host.com form
''' Leave blank to use 'anonymous' but set password to your email
'''
'''
Sub New(ByVal Hostname As String, ByVal Username As String, ByVal Password As String)
_hostname = Hostname
_username = Username
_password = Password
End Sub
#End Region

#Region "Directory functions"
'''
''' Return a simple directory listing
'''

''' Directory to list, e.g. /pub
''' A list of filenames and directories as a List(of String)
''' For a detailed directory listing, use ListDirectoryDetail
Public Function ListDirectory(Optional ByVal directory As String = "") As List(Of String)
'return a simple list of filenames in directory
Dim ftp As Net.FtpWebRequest = GetRequest(GetDirectory(directory))
'Set request to do simple list
ftp.Method = Net.WebRequestMethods.Ftp.ListDirectory

Dim str As String = GetStringResponse(ftp)
'replace CRLF to CR, remove last instance
str = str.Replace(vbCrLf, vbCr).TrimEnd(Chr(13))
'split the string into a list
Dim result As New List(Of String)
result.AddRange(str.Split(Chr(13)))
Return result
End Function

'''
''' Return a detailed directory listing
'''

''' Directory to list, e.g. /pub/etc
''' An FTPDirectory object
Public Function ListDirectoryDetail(Optional ByVal directory As String = "") As FTPdirectory
Dim ftp As Net.FtpWebRequest = GetRequest(GetDirectory(directory))
'Set request to do simple list
ftp.Method = Net.WebRequestMethods.Ftp.ListDirectoryDetails

Dim str As String = GetStringResponse(ftp)
'replace CRLF to CR, remove last instance
str = str.Replace(vbCrLf, vbCr).TrimEnd(Chr(13))
'split the string into a list
Return New FTPdirectory(str, _lastDirectory)
End Function

#End Region

#Region "Upload: File transfer TO ftp server"
'''
''' Copy a local file to the FTP server
'''

''' Full path of the local file
''' Target filename, if required
'''
''' If the target filename is blank, the source filename is used
''' (assumes current directory). Otherwise use a filename to specify a name
''' or a full path and filename if required.

Public Function Upload(ByVal localFilename As String, Optional ByVal targetFilename As String = "") As Boolean
'1. check source
If Not File.Exists(localFilename) Then
Throw New ApplicationException("File " & localFilename & " not found")
End If
'copy to FI
Dim fi As New FileInfo(localFilename)
Return Upload(fi, targetFilename)
End Function

'''
''' Upload a local file to the FTP server
'''

''' Source file
''' Target filename (optional)
'''
Public Function Upload(ByVal fi As FileInfo, Optional ByVal targetFilename As String = "") As Boolean
'copy the file specified to target file: target file can be full path or just filename (uses current dir)

'1. check target
Dim target As String
If targetFilename.Trim = "" Then
'Blank target: use source filename & current dir
target = Me.CurrentDirectory & fi.Name
ElseIf targetFilename.Contains("/") Then
'If contains / treat as a full path
target = AdjustDir(targetFilename)
Else
'otherwise treat as filename only, use current directory
target = CurrentDirectory & targetFilename
End If

Dim URI As String = Hostname & target
'perform copy
Dim ftp As Net.FtpWebRequest = GetRequest(URI)

'Set request to upload a file in binary
ftp.Method = Net.WebRequestMethods.Ftp.UploadFile
ftp.UseBinary = True

'Notify FTP of the expected size
ftp.ContentLength = fi.Length

'create byte array to store: ensure at least 1 byte!
Const BufferSize As Integer = 2048
Dim content(BufferSize - 1) As Byte, dataRead As Integer

'open file for reading
Using fs As FileStream = fi.OpenRead()
Try
'open request to send
Using rs As Stream = ftp.GetRequestStream
Do
dataRead = fs.Read(content, 0, BufferSize)
rs.Write(content, 0, dataRead)
Loop Until dataRead < ftp =" Nothing">
''' Copy a file from FTP server to local
'''
''' Target filename, if required
''' Full path of the local file
'''
''' Target can be blank (use same filename), or just a filename
''' (assumes current directory) or a full path and filename

Public Function Download(ByVal sourceFilename As String, ByVal localFilename As String, Optional ByVal PermitOverwrite As Boolean = False) As Boolean
'2. determine target file
Dim fi As New FileInfo(localFilename)
Return Me.Download(sourceFilename, fi, PermitOverwrite)
End Function

'Version taking an FtpFileInfo
Public Function Download(ByVal file As FTPfileInfo, ByVal localFilename As String, Optional ByVal PermitOverwrite As Boolean = False) As Boolean
Return Me.Download(file.FullName, localFilename, PermitOverwrite)
End Function

'Another version taking FtpFileInfo and FileInfo
Public Function Download(ByVal file As FTPfileInfo, ByVal localFI As FileInfo, Optional ByVal PermitOverwrite As Boolean = False) As Boolean
Return Me.Download(file.FullName, localFI, PermitOverwrite)
End Function

'Version taking string/FileInfo
Public Function Download(ByVal sourceFilename As String, ByVal targetFI As FileInfo, Optional ByVal PermitOverwrite As Boolean = False) As Boolean
'1. check target
If targetFI.Exists And Not (PermitOverwrite) Then Throw New ApplicationException("Target file already exists")

'2. check source
Dim target As String
If sourceFilename.Trim = "" Then
Throw New ApplicationException("File not specified")
ElseIf sourceFilename.Contains("/") Then
'treat as a full path
target = AdjustDir(sourceFilename)
Else
'treat as filename only, use current directory
target = CurrentDirectory & sourceFilename
End If

Dim URI As String = Hostname & target

'3. perform copy
Dim ftp As Net.FtpWebRequest = GetRequest(URI)

'Set request to download a file in binary mode
ftp.Method = Net.WebRequestMethods.Ftp.DownloadFile
ftp.UseBinary = True

'open request and get response stream
Using response As FtpWebResponse = CType(ftp.GetResponse, FtpWebResponse)
Using responseStream As Stream = response.GetResponseStream
'loop to read & write to file
Using fs As FileStream = targetFI.OpenWrite
Try
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
Catch ex As Exception
'catch error and delete file only partially downloaded
fs.Close()
'delete target file as it's incomplete
targetFI.Delete()
Throw
End Try
End Using
responseStream.Close()
End Using
response.Close()
End Using

Return True
End Function
#End Region

#Region "Other functions: Delete rename etc."
'''
''' Delete remote file
'''

''' filename or full path
'''
'''
Public Function FtpDelete(ByVal filename As String) As Boolean
'Determine if file or full path
Dim URI As String = Me.Hostname & GetFullPath(filename)

Dim ftp As Net.FtpWebRequest = GetRequest(URI)
'Set request to delete
ftp.Method = Net.WebRequestMethods.Ftp.DeleteFile
Try
'get response but ignore it
Dim str As String = GetStringResponse(ftp)
Catch ex As Exception
Return False
End Try
Return True
End Function

'''
''' Determine if file exists on remote FTP site
'''

''' Filename (for current dir) or full path
'''
''' Note this only works for files
Public Function FtpFileExists(ByVal filename As String) As Boolean
'Try to obtain filesize: if we get error msg containing "550"
'the file does not exist
Try
Dim size As Long = GetFileSize(filename)
Return True

Catch ex As Exception
'only handle expected not-found exception
If TypeOf ex Is System.Net.WebException Then
'file does not exist/no rights error = 550
If ex.Message.Contains("550") Then
'clear
Return False
Else
Throw
End If
Else
Throw
End If
End Try
End Function

'''
''' Determine size of remote file
'''

'''
'''
''' Throws an exception if file does not exist
Public Function GetFileSize(ByVal filename As String) As Long
Dim path As String
If filename.Contains("/") Then
path = AdjustDir(filename)
Else
path = Me.CurrentDirectory & filename
End If
Dim URI As String = Me.Hostname & path
Dim ftp As Net.FtpWebRequest = GetRequest(URI)
'Try to get info on file/dir?
ftp.Method = Net.WebRequestMethods.Ftp.GetFileSize
Dim tmp As String = Me.GetStringResponse(ftp)
Return GetSize(ftp)
End Function

Public Function FtpRename(ByVal sourceFilename As String, ByVal newName As String) As Boolean
'Does file exist?
Dim source As String = GetFullPath(sourceFilename)
If Not FtpFileExists(source) Then
Throw New FileNotFoundException("File " & source & " not found")
End If

'build target name, ensure it does not exist
Dim target As String = GetFullPath(newName)
If target = source Then
Throw New ApplicationException("Source and target are the same")
ElseIf FtpFileExists(target) Then
Throw New ApplicationException("Target file " & target & " already exists")
End If

'perform rename
Dim URI As String = Me.Hostname & source

Dim ftp As Net.FtpWebRequest = GetRequest(URI)
'Set request to delete
ftp.Method = Net.WebRequestMethods.Ftp.Rename
ftp.RenameTo = target
Try
'get response but ignore it
Dim str As String = GetStringResponse(ftp)
Catch ex As Exception
Return False
End Try
Return True
End Function

Public Function FtpCreateDirectory(ByVal dirpath As String) As Boolean
'perform create
Dim URI As String = Me.Hostname & AdjustDir(dirpath)
Dim ftp As Net.FtpWebRequest = GetRequest(URI)
'Set request to MkDir
ftp.Method = Net.WebRequestMethods.Ftp.MakeDirectory
Try
'get response but ignore it
Dim str As String = GetStringResponse(ftp)
Catch ex As Exception
Return False
End Try
Return True
End Function

Public Function FtpDeleteDirectory(ByVal dirpath As String) As Boolean
'perform remove
Dim URI As String = Me.Hostname & AdjustDir(dirpath)
Dim ftp As Net.FtpWebRequest = GetRequest(URI)
'Set request to RmDir
ftp.Method = Net.WebRequestMethods.Ftp.RemoveDirectory
Try
'get response but ignore it
Dim str As String = GetStringResponse(ftp)
Catch ex As Exception
Return False
End Try
Return True
End Function
#End Region

#Region "private supporting fns"
'Get the basic FtpWebRequest object with the
'common settings and security
Private Function GetRequest(ByVal URI As String) As FtpWebRequest
'create request
Dim result As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
'Set the login details
result.Credentials = GetCredentials()
'Do not keep alive (stateless mode)
result.KeepAlive = False
Return result
End Function


'''
''' Get the credentials from username/password
'''

Private Function GetCredentials() As Net.ICredentials
Return New Net.NetworkCredential(Username, Password)
End Function

'''
''' returns a full path using CurrentDirectory for a relative file reference
'''

Private Function GetFullPath(ByVal file As String) As String
If file.Contains("/") Then
Return AdjustDir(file)
Else
Return Me.CurrentDirectory & file
End If
End Function

'''
''' Amend an FTP path so that it always starts with /
'''

''' Path to adjust
'''
'''
Private Function AdjustDir(ByVal path As String) As String
Return CStr(IIf(path.StartsWith("/"), "", "/")) & path
End Function

Private Function GetDirectory(Optional ByVal directory As String = "") As String
Dim URI As String
If directory = "" Then
'build from current
URI = Hostname & Me.CurrentDirectory
_lastDirectory = Me.CurrentDirectory
Else
If Not directory.StartsWith("/") Then Throw New ApplicationException("Directory should start with /")
URI = Me.Hostname & directory
_lastDirectory = directory
End If
Return URI
End Function

'stores last retrieved/set directory
Private _lastDirectory As String = ""

'''
''' Obtains a response stream as a string
'''

''' current FTP request
''' String containing response
''' FTP servers typically return strings with CR and
''' not CRLF. Use respons.Replace(vbCR, vbCRLF) to convert
''' to an MSDOS string

Private Function GetStringResponse(ByVal ftp As FtpWebRequest) As String
'Get the result, streaming to a string
Dim result As String = ""
Using response As FtpWebResponse = CType(ftp.GetResponse, FtpWebResponse)
Dim size As Long = response.ContentLength
Using datastream As Stream = response.GetResponseStream
Using sr As New StreamReader(datastream)
result = sr.ReadToEnd()
sr.Close()
End Using
datastream.Close()
End Using
response.Close()
End Using
Return result
End Function

'''
''' Gets the size of an FTP request
'''

'''
'''
'''
Private Function GetSize(ByVal ftp As FtpWebRequest) As Long
Dim size As Long
Using response As FtpWebResponse = CType(ftp.GetResponse, FtpWebResponse)
size = response.ContentLength
response.Close()
End Using
Return size
End Function
#End Region

#Region "Properties"
Private _hostname As String
'''
''' Hostname
'''

'''
''' Hostname can be in either the full URL format
''' ftp://ftp.myhost.com or just ftp.myhost.com
'''

Public Property Hostname() As String
Get
If _hostname.StartsWith("ftp://") Then
Return _hostname
Else
Return "ftp://" & _hostname
End If
End Get
Set(ByVal value As String)
_hostname = value
End Set
End Property
Private _username As String
'''
''' Username property
'''

'''
''' Can be left blank, in which case 'anonymous' is returned
Public Property Username() As String
Get
Return IIf(_username = "", "anonymous", _username)
End Get
Set(ByVal value As String)
_username = value
End Set
End Property
Private _password As String
Public Property Password() As String
Get
Return _password
End Get
Set(ByVal value As String)
_password = value
End Set
End Property

'''
''' The CurrentDirectory value
'''

''' Defaults to the root '/'
Private _currentDirectory As String = "/"
Public Property CurrentDirectory() As String
Get
'return directory, ensure it ends with /
Return _currentDirectory & CStr(IIf(_currentDirectory.EndsWith("/"), "", "/"))
End Get
Set(ByVal value As String)
If Not value.StartsWith("/") Then Throw New ApplicationException("Directory should start with /")
_currentDirectory = value
End Set
End Property


#End Region

End Class
#End Region

#Region "FTP file info class"
'''
''' Represents a file or directory entry from an FTP listing
'''

'''
''' This class is used to parse the results from a detailed
''' directory list from FTP. It supports most formats of
'''

Public Class FTPfileInfo
'Stores extended info about FTP file

#Region "Properties"
Public ReadOnly Property FullName() As String
Get
Return Path & Filename
End Get
End Property
Public ReadOnly Property Filename() As String
Get
Return _filename
End Get
End Property
Public ReadOnly Property Path() As String
Get
Return _path
End Get
End Property
Public ReadOnly Property FileType() As DirectoryEntryTypes
Get
Return _fileType
End Get
End Property
Public ReadOnly Property Size() As Long
Get
Return _size
End Get
End Property
Public ReadOnly Property FileDateTime() As Date
Get
Return _fileDateTime
End Get
End Property
Public ReadOnly Property Permission() As String
Get
Return _permission
End Get
End Property
Public ReadOnly Property Extension() As String
Get
Dim i As Integer = Me.Filename.LastIndexOf(".")
If i >= 0 And i < (Me.Filename.Length - 1) Then Return Me.Filename.Substring(i + 1) Else Return "" End If End Get End Property Public ReadOnly Property NameOnly() As String Get Dim i As Integer = Me.Filename.LastIndexOf(".") If i > 0 Then
Return Me.Filename.Substring(0, i)
Else
Return Me.Filename
End If
End Get
End Property
Private _filename As String
Private _path As String
Private _fileType As DirectoryEntryTypes
Private _size As Long
Private _fileDateTime As Date
Private _permission As String

#End Region

'''
''' Identifies entry as either File or Directory
'''

Public Enum DirectoryEntryTypes
File
Directory
End Enum

'''
''' Constructor taking a directory listing line and path
'''

''' The line returned from the detailed directory list
''' Path of the directory
'''
Sub New(ByVal line As String, ByVal path As String)
'parse line
Dim m As Match = GetMatchingRegex(line)
If m Is Nothing Then
'failed
Throw New ApplicationException("Unable to parse line: " & line)
Else
_filename = m.Groups("name").Value
_path = path
_size = CLng(m.Groups("size").Value)
_permission = m.Groups("permission").Value
Dim _dir As String = m.Groups("dir").Value
If (_dir <> "" And _dir <> "-") Then
_fileType = DirectoryEntryTypes.Directory
Else
_fileType = DirectoryEntryTypes.File
End If

Try
_fileDateTime = Date.Parse(m.Groups("timestamp").Value)
Catch ex As Exception
_fileDateTime = Nothing
End Try

End If
End Sub

Private Function GetMatchingRegex(ByVal line As String) As Match
Dim rx As Regex, m As Match
For i As Integer = 0 To _ParseFormats.Length - 1
rx = New Regex(_ParseFormats(i))
m = rx.Match(line)
If m.Success Then Return m
Next
Return Nothing
End Function

#Region "Regular expressions for parsing LIST results"
'''
''' List of REGEX formats for different FTP server listing formats
'''

'''
''' The first three are various UNIX/LINUX formats, fourth is for MS FTP
''' in detailed mode and the last for MS FTP in 'DOS' mode.
''' I wish VB.NET had support for Const arrays like C# but there you go
'''

Private Shared _ParseFormats As String() = { _
"(?
[\-d])(?([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?\d+)\s+(?\w+\s+\d+\s+\d{4})\s+(?.+)", _
"(?
[\-d])(?([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?\d+)\s+(?\w+\s+\d+\s+\d{4})\s+(?.+)", _
"(?
[\-d])(?([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?\d+)\s+(?\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?.+)", _
"(?
[\-d])(?([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?\d+)\s+(?\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?.+)", _
"(?
[\-d])(?([\-r][\-w][\-xs]){3})(\s+)(?(\d+))(\s+)(?(\w+\s\w+))(\s+)(?(\d+))\s+(?\w+\s+\d+\s+\d{2}:\d{2})\s+(?.+)", _
"(?\d{2}\-\d{2}\-\d{2}\s+\d{2}:\d{2}[AaPp][mM])\s+(?
\<\w+\>){0,1}(?\d+){0,1}\s+(?.+)"}
#End Region
End Class
#End Region

#Region "FTP Directory class"
'''
''' Stores a list of files and directories from an FTP result
'''

'''
Public Class FTPdirectory
Inherits List(Of FTPfileInfo)

Sub New()
'creates a blank directory listing
End Sub

'''
''' Constructor: create list from a (detailed) directory string
'''

''' directory listing string
'''
'''
Sub New(ByVal dir As String, ByVal path As String)
For Each line As String In dir.Replace(vbLf, "").Split(CChar(vbCr))
'parse
If line <> "" Then Me.Add(New FTPfileInfo(line, path))
Next
End Sub

'''
''' Filter out only files from directory listing
'''

''' optional file extension filter
''' FTPdirectory listing
Public Function GetFiles(Optional ByVal ext As String = "") As FTPdirectory
Return Me.GetFileOrDir(FTPfileInfo.DirectoryEntryTypes.File, ext)
End Function

'''
''' Returns a list of only subdirectories
'''

''' FTPDirectory list
'''
Public Function GetDirectories() As FTPdirectory
Return Me.GetFileOrDir(FTPfileInfo.DirectoryEntryTypes.Directory)
End Function

'internal: share use function for GetDirectories/Files
Private Function GetFileOrDir(ByVal type As FTPfileInfo.DirectoryEntryTypes, Optional ByVal ext As String = "") As FTPdirectory
Dim result As New FTPdirectory()
For Each fi As FTPfileInfo In Me
If fi.FileType = type Then
If ext = "" Then
result.Add(fi)
ElseIf ext = fi.Extension Then
result.Add(fi)
End If
End If
Next
Return result

End Function

Public Function FileExists(ByVal filename As String) As Boolean
For Each ftpfile As FTPfileInfo In Me
If ftpfile.Filename = filename Then
Return True
End If
Next
Return False
End Function

Private Const slash As Char = "/"

Public Shared Function GetParentDirectory(ByVal dir As String) As String
Dim tmp As String = dir.TrimEnd(slash)
Dim i As Integer = tmp.LastIndexOf(slash)
If i > 0 Then
Return tmp.Substring(0, i - 1)
Else
Throw New ApplicationException("No parent for root")
End If
End Function
End Class
#End Region

End Namespace





Using the FTP Client

Code in Upload Button Click Event

Dim ftp As New FTP.FTPclient("123.4.5.6", "username", "password")
ftp.Upload(source, path)


Happy Coding!