ASP.NET upload a file HtmlInputFile Control

When developing a web application it often may be necessary to allow a user to ‘send’ (upload) a file. With HtmlInputFile control the this seemingly complicated task is much easier than one would expect. The HtmlInputFile control is not listed in the toolbox by default but can be easily added using HTML in your page. In order to use the HtmlInputFile control the following form code must be added to your .aspx page:




<form id="Form1" method="post" runat="server" enctype="multipart/form-data">


<input id="btnSelectFile" type="file" runat="server" style="Z-INDEX: 101; LEFT: 24px; WIDTH: 470px; POSITION: absolute; TOP: 48px; HEIGHT: 22px" size="59">


<asp:Label id="lblStatus" style="Z-INDEX: 103; LEFT: 176px; POSITION: absolute; TOP: 88px" runat="server" Width="224px">Status:</asp:Label>
<asp:Button id="btnUpload" style="Z-INDEX: 102; LEFT: 96px; POSITION: absolute; TOP: 88px" runat="server" Text="Upload"></asp:Button>
</form>


The size and position of the controls can be what ever you desire. Once the HtmlInputFile code is added you can visually design its size and position. In the above code I have also included a label for the displaying of status information and a button that will actually execute the code for the uploading of the file selected with the HtmlInputFile.
The code to upload the file is simple:

' Root Data path
‘ ensure the proper permissions are set on this folder default is the ASP.NET account
Const ROOTPATH = "C:\Data\"

Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click

Dim filename As String

' Extract the selected filename
filename = System.IO.Path.GetFileName(btnSelectFile.PostedFile.FileName)

' Set the label to display where the file will be saved – this could also be used to display the file size uploaded
lblStatus.Text = "Status: " & ROOTPATH & filename

' Save the file
btnSelectFile.PostedFile.SaveAs(ROOTPATH & filename)

' This calls a procedure that I had created that will display the contents of a directory in a table
ListDirectory()

End Sub


Private Sub ListDirectory()

Dim currentdir As New DirectoryInfo(ROOTPATH)
Dim files As FileInfo
Dim tr As TableRow
Dim tcFile As TableCell
Dim tcSize As TableCell

For Each files In currentdir.GetFiles()
tr = New TableRow
tcFile = New TableCell
tcSize = New TableCell
tcFile.Text = files.Name
tcSize.HorizontalAlign = HorizontalAlign.Right
tcSize.Text = FormatNumber(files.Length, 0, TriState.False, TriState.True, TriState.True)
tr.Cells.Add(tcFile)
tr.Cells.Add(tcSize)
tblFiles.Rows.Add(tr)
Next

End Sub



In reviewing the previous code sample one can see how easy it is to upload a file through a web application.



   

More Hash - Part II

Taking the same approach and design as Part I of this 'post' here is the resulting code for 'hashing' Delphi style. Again, this uses the System.Security.Cryptography Namespace to compute the hash values. This application used the MD5, SHA1,SHA2566, SHA384 and SHA512 classes. I did change the visibility of some of the functions as compared to the 'other' version.

uses System.IO, System.Security.Cryptography, System.Text;

type
hashtype = (MD5,SHA1,SHA256,SHA384,SHA512);

frmMain = class(System.Windows.Forms.Form)
procedure GroupCompare_CheckedChanged(sender: System.Object; e: System.EventArgs);
procedure btnFile_Click(sender: System.Object; e: System.EventArgs);
procedure btnCompare_Click(sender: System.Object; e: System.EventArgs);
private
procedure ClearForm;
function GetHash(contents: array of byte; hasht: hashtype): string;
function GetByteString(data: array of Byte): string;
public
function GetFileHash(const filename: string; hasht: hashtype): string;
function GetStringHash(const input: string; hasht: hashtype): string;
end;

procedure frmMain.ClearForm;
begin
txtValue1.Text := '';
txtValue2.Text := '';
txtResults1.Text := '';
txtResults2.Text := '';
end;

procedure frmMain.btnFile_Click(sender: System.Object; e: System.EventArgs);
begin
if ofdFiles.ShowDialog = System.Windows.Forms.DialogResult.OK then
begin
case Convert.ToInt32(Button(sender).Tag.ToString) of
0: txtValue1.Text:= ofdFiles.FileName;
1: txtValue2.Text:= ofdFiles.FileName;
end;
end;
end;

function frmMain.GetByteString(data: array of Byte): string;
var
sBuilder: StringBuilder;
i: integer;
begin
sBuilder:= StringBuilder.Create();
for i:= 0 to Length(data) - 1 do
begin
sBuilder.Append(data[i].ToString('x2'));
end;
result:= sBuilder.ToString();
end;

function frmMain.GetFileHash(const filename: string; hasht: hashtype): string;
var
oFileStream: System.IO.FileStream;
instance: FileInfo;
lBytes: System.Int64;
filecontents: array of byte;
begin
try
if
(filename '') then
begin
instance:= FileInfo.Create(filename);
oFileStream:= instance.OpenRead;
lBytes:= oFileStream.Length;
SetLength(filecontents, lBytes);
oFileStream.Read(filecontents, 0, lBytes);
oFileStream.Close();
result:= GetHash(filecontents, hasht);
end
else
begin

result:= '';
end;
except on
ex: Exception do
begin
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
result:= '';
end;
end;
end;

function frmMain.GetHash(contents: array of byte; hasht: hashtype): string;
var
res: array of Byte;
HashA: HashAlgorithm;
begin
Case hasht of
hashtype.MD5: begin
HashA:= MD5CryptoServiceProvider.Create;
res:= HashA.ComputeHash(contents)
end;
hashtype.SHA1: begin
HashA:= SHA1Managed.Create;
res:= HashA.ComputeHash(contents);
end;
hashtype.SHA256: begin
HashA:= SHA256Managed.Create;
res:= HashA.ComputeHash(contents);
end;
hashtype.SHA384: begin
HashA:= SHA384Managed.Create;
res:= HashA.ComputeHash(contents);
end;
hashtype.SHA512: begin
HashA:= SHA512Managed.Create;
res:= HashA.ComputeHash(contents);
end;
end;

result:= GetByteString(res);
end;

function frmMain.GetStringHash(const input: string; hasht: hashtype): string;
begin
result:= GetHash(Encoding.Default.GetBytes(input), hasht);
end;

procedure frmMain.btnCompare_Click(sender: System.Object; e: System.EventArgs);
var
myCursor: System.Windows.Forms.Cursor;
hasht: hashtype;
begin
myCursor:= Cursor;
Cursor:= Cursors.WaitCursor;
try
try
if
radMD5.Checked then
hasht:= hashtype.MD5;
if radSHA1.Checked then
hasht:= hashtype.SHA1;
if radSHA256.Checked then
hasht:= hashtype.SHA256;
if radSHA384.Checked then
hasht:= hashtype.SHA384;
if radSHA512.Checked then
hasht:= hashtype.SHA512;

if radFiles.Checked then
begin
txtResults1.Text:= GetFileHash(txtValue1.Text, hasht);
txtResults2.Text:= GetFileHash(txtValue2.Text, hasht);
end
else
begin
txtResults1.Text:= GetStringHash(txtValue1.Text, hasht);
txtResults2.Text:= GetStringHash(txtValue2.Text, hasht);
end;

if (System.&String.Compare(txtResults1.Text, txtResults2.Text) = 0) then
begin
picResult.Image:= ImageList1.Images[1];
end
else
begin
picResult.Image:= ImageList1.Images[0];
end;

except
on ex: Exception do
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
end;
finally
Cursor:= myCursor;
end;
end;

procedure frmMain.GroupCompare_CheckedChanged(sender: System.Object; e: System.EventArgs);
var
i: System.Int32;
begin
ClearForm;
if sender is control then
begin
try

i:= Convert.ToInt32(Control(Sender).Tag.ToString);
except
i:= 0;
end;
end;

case i of
0: begin
lblValue1.Text:= 'File 1:';
lblValue2.Text:= 'File 2:';
txtValue1.ReadOnly:= True;
txtValue2.ReadOnly:= True;
btnValue1.Visible:= True;
btnValue2.Visible:= True;
end;
1: begin
lblValue1.Text:= 'String 1:';
lblValue2.Text:= 'String 2:';
txtValue1.ReadOnly:= False;
txtValue2.ReadOnly:= False;
btnValue1.Visible:= False;
btnValue2.Visible:= False;
end;
end;
end;



   

More Hash - Part I

Yesterday I discussed using the System.Security.Cryptography Namespace to compute the hash value of files. Hash values of files can be used to quickly compare two files to see if they are identical. Due to the irreversible nature of Hash values, they are useful in password situations. For example, if you have an application that requires authentication you can compute the hash of a user's password and store that information. When it comes time to authenticate the user you can compare the hash value of the entered password with the stored hash value. This eliminates the storage of the actual password value, which could lead to well, problems. I had put together an application that compares the hash values of two files or strings to determine if the data is identical. This application can also be used to generate hash values. This application used the MD5, SHA1, SHA256, SHA384 and SHA512 classes. The hash values are displayed in Hexadecimal notation. If you're interested in just the application it can be downloaded here. Here is the VB.NET source. I will post the Delphi source later.

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class frmMain
Enum HashType
MD5
SHA1
SHA256
SHA384
SHA512
End Enum

Private Sub GroupCompare_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radFiles.CheckedChanged, radStrings.CheckedChanged
ClearForm()
Select Case CType(sender, Control).Tag
Case "Files"
lblValue1.Text = "File 1:"
lblValue2.Text = "File 2:"
txtValue1.ReadOnly = True
txtValue2.ReadOnly = True
btnValue1.Visible = True
btnValue2.Visible = True
Case "Strings"
lblValue1.Text = "String 1:"
lblValue2.Text = "String 2:"
txtValue1.ReadOnly = False
txtValue2.ReadOnly = False
btnValue1.Visible = False
btnValue2.Visible = False
End Select
End Sub

Private Sub txt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles txtValue1.TextChanged, txtValue2.TextChanged, _
txtResults1.TextChanged, txtResults2.TextChanged

ToolTip1.SetToolTip(CType(sender, Control), CType(sender, Control).Text)

End Sub

Private Sub btnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValue1.Click, btnValue2.Click
If ofdFiles.ShowDialog Then
Select Case CType(sender, Button).Tag
Case 0
txtValue1.Text = ofdFiles.FileName
Case 1
txtValue2.Text = ofdFiles.FileName
End Select
End If
End Sub

Private Sub ClearForm()
txtValue1.Text = ""
txtValue2.Text = ""
txtResults1.Text = ""
txtResults2.Text = ""
End Sub

Private Sub btnCompare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompare.Click
Dim myCursor As Cursor
Dim hasht As hashtype

myCursor = Cursor
Cursor = Cursors.WaitCursor
Try
If
radMD5.Checked Then
hasht = hashtype.MD5
End If
If
radSHA1.Checked Then
hasht = hashtype.SHA1
End If
If
radSHA256.Checked Then
hasht = hashtype.SHA256
End If
If
radSHA384.Checked Then
hasht = hashtype.SHA384
End If
If
radSHA512.Checked Then
hasht = hashtype.SHA512
End If

If radFiles.Checked Then
txtResults1.Text = GetFileHash(txtValue1.Text, hasht)
txtResults2.Text = GetFileHash(txtValue2.Text, hasht)
ElseIf radStrings.Checked Then
txtResults1.Text = GetStringHash(txtValue1.Text, hasht)
txtResults2.Text = GetStringHash(txtValue2.Text, hasht)
End If

If (String.Compare(txtResults1.Text, txtResults2.Text) = 0) Then
picResult.Image = ImageList1.Images(1)
Else
picResult.Image = ImageList1.Images(0)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
Cursor = myCursor
End Try
End Sub

Private Function GetFileHash(ByVal filename As String, ByVal hasht As hashtype) As String
Dim oFileStream As System.IO.FileStream
Dim lBytes As Long

Try
If
filename "" Then
Dim instance As New FileInfo(filename)
oFileStream = instance.OpenRead()
lBytes = oFileStream.Length
Dim filecontents(lBytes) As Byte
oFileStream.Read(filecontents, 0, lBytes)
oFileStream.Close()

Return GetHash(filecontents, hasht)
Else
Return
""
End If
Catch ex As Exception
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)
Return ""
End Try

End Function

Private Function GetStringHash(ByVal input As String, ByVal hasht As hashtype) As String

Return GetHash(Encoding.Default.GetBytes(input), hasht)

End Function

Public Function GetHash(ByRef contents As Byte(), ByVal hasht As hashtype) As String
Dim result() As Byte

Select Case hasht
Case hashtype.MD5
Dim MD5 As MD5 = MD5.Create
result = MD5.ComputeHash(contents)
Case hashtype.SHA1
Dim sha1M As New SHA1Managed
result = sha1M.ComputeHash(contents)
Case hashtype.SHA256
Dim sha256M As New SHA256Managed
result = sha256M.ComputeHash(contents)
Case hashtype.SHA384
Dim sha384M As New SHA384Managed
result = sha384M.ComputeHash(contents)
Case hashtype.SHA512
Dim sha512M As New SHA512Managed
result = sha512M.ComputeHash(contents)
End Select

Return GetByteString(result)
End Function

Public Function GetByteString(ByVal data As Byte())
Dim sBuilder As New StringBuilder()
Dim i As Integer

For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
Return sBuilder.ToString()
End Function
End Class