BPSoftware.com
Home   Utilities   Purchase   FAQ   Support   Contact        
Shareware Utilities
 APrintDirect
 AIconExtract
 AFile Attribute Manager
Freeware Utilities
 AddrMon
 AFileSync
 ASysIcon
 B&P Table Utilities
 BPACLer
 BPSNMPMon
 BPSNMPUtil
 CharCount
 Delphi® Components
 MacAddr
Miscellaneous
 BPSoftware Blog
 Purchase Shareware
 Support

 


Saturday, January 27, 2007
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:



<!-- Add enctype="multipart/form-data" to the form declaration -->
<form id="Form1" method="post" runat="server" enctype="multipart/form-data">

<!-- the following line was manually entered to display the file control -->
<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.

Labels: , , ,

posted by Brad Prendergast at 3:54:00 PM (0 comments)
Links to this post
Permalink
Saturday, July 08, 2006
Who does not like cookies?

As I was doing some odd exploration of an older ASP application I decided to do some experimentation with cookies. As with most of my posts I try to drop things back significantly allowing for some basic examples. Cookies are a way for a web application to store specific information. Cookies are small text files that are stored on a client machine and are contained in the Response and Request traffic between a client and host computer. Web applications can read cookies whenever a user visits the site. Information such as user preferences could be stored in a cookie.

Within .NET there the HttpCookie Class is used for dealing with cookie information. Basic dealing with cookies is a lot easier than it may initially sound. I was able to put together a sample application that stores a textbox, validated textbox and calendar date (cookies store strings) in a cookie in only a few minutes.

Start a new ASP.NET Web Application from within BDS2006. On the default design form place a two text boxes, a calendar control, a RegularExpressionValidator and three buttons. I also placed some labels for identification.

Set the properties for RegularExpression1 as follows:
// This checks for a proper email address
ValidationExpression:= ‘\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*’;
ControlToValidate:= txtEmail;
ErrorMessage:= ‘Invalid Email’;

The following is the code behind the page (For maintenance, I’d use constants for the value and cookie names):
procedure TWebForm1.Page_Load(sender: System.Object; e: System.EventArgs);
begin
// The calendar defaults to a selected date of 01/01/0001
if Calendar1.SelectedDate = DateTime.Parse('01/01/0001') then
Calendar1.SelectedDate:= DateTime.Now;
end;

procedure TWebForm1.btnClear_Click(sender: System.Object; e: System.EventArgs);
var
hc: HttpCookie;
begin
if Request.Cookies['MySite'] <> nil then
begin
hc:= Request.Cookies['MySite'];
// This method may work, however the proper way to clear a cookie
// is to set the cookie to have a prior expiration date
// hc.Values.Clear;
// Response.Cookies.Add(hc);
// Calendar1.SelectedDate:= DateTime.Now;

hc.Expires:= DateTime.Now.AddDays(-100);
txtName.Text:='';
txtEmail.Text:= '';
Calendar1.SelectedDate:= DateTime.Now;
end;
end;

procedure TWebForm1.btnRead_Click(sender: System.Object; e: System.EventArgs);
var
hc: HttpCookie;
begin
if Request.Cookies['MySite'] <> nil then
begin
txtEmail.Text:= Request.Cookies['MySite'].Values['email'];
txtName.Text:= Request.Cookies['MySite'].Values['name'];
Calendar1.SelectedDate:= DateTime.Parse(Request.Cookies['MySite'].Values['date']);
end
else
begin

txtEmail.Text:= '';
txtName.Text:= '';
Calendar1.SelectedDate:= DateTime.Now;
end;
end;

procedure TWebForm1.btnWrite_Click(sender: System.Object; e: System.EventArgs);
var
hc: HttpCookie;
begin
if
RegularExpressionValidator1.IsValid then
begin
hc:= HttpCookie.Create('MySite');
hc.Values['name']:= txtName.Text;
hc.Values['email']:= txtEmail.Text;
hc.Values['date']:= Calendar1.SelectedDate.ToShortDateString;
// Expire cookie in 1hour. Always set an expiration
// if you do not set an expiration date the cookie is not
// stored; it will be treated as a session variable
// DateTime.MaxValue will make it last forever
hc.Expires:= DateTime.Now.AddHours(1);
Response.Cookies.Add(hc);
end;
end;


For some more information take a look at ASP.NET Cookies Overview on MSDN. Another valuable link is How to Share Session State Between Classic ASP and ASP.NET.

Labels: , , ,

posted by Brad Prendergast at 6:47:00 PM (0 comments)
Links to this post
Permalink
Saturday, July 01, 2006
DayLightTime

In an attempt to better understand what’s available and come up with new ways of doing things, I often browse through various class definitions. As I was browsing through some classes this morning, I came across the DaylightTime Class. The DaylightTime Class is part of the System.Globalization namespace. This class is used to define the period of daylight-savings time. The GetDaylightChanges Method of the TimeZone Class returns a timezone’s DaylightTime for a specified year. This may not all sound so interesting, however using this in an ASP.NET application a semi-useful utility can be developed. This example also shows how to dynamically work with a System.Web.UI.WebControls.Table Class. Dynamically created table data is not persistent and would need to be ‘refreshed’ on each postback page display. In this example I just use one row for displaying a year’s calculation. A System.Web.UI.WebControls.RangeValidator is also used in this demonstration. Check out my new DayLightTime Display.



In the page class:

public
localzone: TimeZone;
daylight: System.Globalization.DaylightTime;
tr: TableRow;
tcYear,
tcStart,
tcEnd,
tcChange: TableCell;

procedure TWebForm1.Page_Load(sender: System.Object; e: System.EventArgs);
begin
localzone:= TimeZone.CurrentTimeZone;
lblTimeZone.Text:= localzone.StandardName;
//txtYear.Text:= '1999';
end;

procedure TWebForm1.btnProcess_Click(sender: System.Object; e: System.EventArgs);
var
year: Integer;
begin
if RangeValidator1.IsValid then
begin
try

year:= Convert.ToInt32(txtYear.Text);
except
//dynamically setting it to the current year
//is also an option

year:= 2006;
txtYear.Text:= year.ToString;
end;
tblOutput.Rows.Add(CreateDaylightRow(year));
end;
end;

function TWebForm1.CreateDaylightRow(year: integer): TableRow;
begin
daylight:= localzone.GetDaylightChanges(year);

tr:= TableRow.Create;

tcYear:= TableCell.Create;
tcStart:= TableCell.Create;
tcEnd:= TableCell.Create;
tcChange:= TableCell.Create;

tcYear.Text:= year.ToString;
tr.Cells.Add(tcYear);

tcStart:= TableCell.Create;
tcStart.HorizontalAlign:= HorizontalAlign.Right;
tcStart.Text:= daylight.Start.ToString('yyyy-MM-dd HH:mm');
tr.Cells.Add(tcStart);

tcEnd:= TableCell.Create;
tcEnd.HorizontalAlign:= HorizontalAlign.Right;
tcEnd.Text:= daylight.&End.ToString('yyyy-MM-dd HH:mm');
tr.Cells.Add(tcEnd);

tcChange:= TableCell.Create;
tcChange.HorizontalAlign:= HorizontalAlign.Right;
tcChange.Text:= daylight.Delta.ToString;
tr.Cells.Add(tcChange);

Result:= tr;
end;

Labels: , , ,

posted by Brad Prendergast at 8:50:00 AM (0 comments)
Links to this post
Permalink
Saturday, June 24, 2006
Conversion Utility

The conversion utility I posted about a few months back is accessible HERE. Feel free to use this tool to assist with unit conversions you need to solve.

Labels: , , ,

posted by Brad Prendergast at 4:28:00 PM (0 comments)
Links to this post
Permalink
Sunday, March 26, 2006
Rock Paper Scissors

Rock-Paper-Scissors-Shoot...

This game is an adaptation of the popular Rock Paper Scissors game. Rock Paper Scissors is a popular game that is typically played between two people. It is a game that can be played pretty much anywhere and is fun for all ages. This page allows you to play against a computer.

Rock Paper Scissors has three basic rules:

  1. Each players substitute the three elements of Rock, Paper and Scissors with hand signals.
  2. The hand signals are delivered simultaneously by each player (Typically one player will say ‘Rock Paper Scissors Shoot’ and both players will display their hand signal when as ‘Shoot’ is said)
  3. The Outcome of play is determined by the following:
    Rock beats Scissors
    Scissors beats Paper
    Paper beats Rock

To play, simply click your button choice. As you make your selection the computer will also choose. Let's see how well you do.

ready to play? Click Here

Labels: , ,

posted by Brad Prendergast at 9:35:00 AM (0 comments)
Links to this post
Permalink
Saturday, March 25, 2006
HTML Element

When developing an ASP.NET application with BDS® 2006 the Web Controls allow you to create code and control events to manage the flow of your application. The interaction with HTML elements via code is not as obvious, but is possible. Placing an HTML Div HTML Element on an ASP.NET Web Application page results in the following page code:
<div>Div</div>
Change the code to look something like:
<div runat="server" id="divarea"></div>
Declare a strict protected variable for your ‘divarea’ in your webform class. The variable name should match the id you give your element.
strict protected
divarea: System.Web.UI.HtmlControls.HtmlGenericControl;
Your HTML Element is now accessible in you codebehind page. You have access to the controls properties and can do something like the following in your code to change the text of the ‘divarea’:
divarea.InnerHtml:= ‘This is a HTML Div Element’;
Putting this together with the information in a previous post I created a ‘blogroll’ page that displays the most recent 5 posts from a few feeds I monitor. BDS® 2006 truly simplifies ASP.NET.

Labels: , ,

posted by Brad Prendergast at 8:01:00 AM (0 comments)
Links to this post
Permalink
Saturday, February 25, 2006
I did not win

Lately, all of my focus has been on the Olympics so things have been a little quiet. In my last post I talked about an ASP.NET Random Number Generator created with BDS 2006. Believe it or not, it is surprisingly simple to get something like this up and running. I have worked on a number of ASP.NET applications developed with BDS 2006, in both the internally and externally hosted environments. Typically, any SNAFUs that I have encountered (excluding code typos and incorrectness) have been due to server configuration issues and not a problem with the tool used to create the application.

To get the Random Number Generator running I first needed a Virtual Directory on the server hosting the application. I started out with a new ASP.NET Web Application and saved it with the same name as the application name for the Virtual Directory (by default it the name of the virtual directory).

I then created a ‘form’ and decorated it with a few items from the Web Controls section of the Tool Palette.


With the layout of the form in place a few lines of code were needed to get things going (I created a few functions of my own for dealing with input):

function TWebForm1.IsNumeric(str: string): Boolean;
var
code: integer;
v: integer;
begin
Val(str,v,code);
Result:= (code = 0);
end;

function TWebForm1.ToInteger(str: string): Integer;
var
code: integer;
v: integer;
begin
Val(str,v,code);
if (code = 0) then
Result:= v
else
Result:= 0;
end;

procedure TWebForm1.txtCount_TextChanged(sender: System.Object; e: System.EventArgs);
begin
if Not(IsNumeric(TextBox(Sender).Text)) then
begin
TextBox(Sender).ForeColor:= Color.Red;
TextBox(Sender).Font.Bold:= True;
TextBox(Sender).Text:= '#ERROR#';
end
else
begin
TextBox(Sender).ForeColor:= Color.Black;
TextBox(Sender).Font.Bold:= False;
end;
end;

procedure TWebForm1.btnGenerate_Click(sender: System.Object; e: System.EventArgs);
var
i, y: Integer;
z: single;
lowerbound, upperbound, counter: integer;
intRnd: Single;
// mylist: System.Collections.Hashtable;
mylist: System.Collections.SortedList;
st: System.Text.StringBuilder;
DictEntry: DictionaryEntry;
Enumerator: IEnumerator;
begin
// mylist:= Hashtable.Create;
myList:= SortedList.Create;
lbNumbers.Items.Clear;
lbStats.Items.Clear;

upperbound:= ToInteger(txtUpperBound.Text);
lowerbound:= ToInteger(txtLowerBound.Text);
counter:= ToInteger(txtCount.Text);

if (IsNumeric(txtUpperBound.Text) and
IsNumeric(txtLowerBound.Text) and
IsNumeric(txtCount.Text)) then
begin
Randomize;
For i := 1 To counter do
begin
intRnd := Int((upperbound - lowerbound + 1) * Random + lowerbound);

// HashTable for statistics
if Not mylist.ContainsKey(intRnd.ToString('#,###')) then
mylist.Add(intRnd.ToString('#,###'),'1')
else
begin
y:= ToInteger(mylist.Item[intRnd.ToString].ToString) + 1;
mylist.Item[intRnd.ToString]:= y.ToString('#,###');
end;

if (chkDupes.Checked and
(lbNumbers.Items.FindByText(intRnd.ToString('#,###')) = Nil))
or Not(chkDupes.Checked) then
lbNumbers.Items.Add(intRnd.ToString('#,###'));
end;

// enumerate hash for statistical output
Enumerator := Mylist.GetEnumerator;
st:= StringBuilder.Create;
while Enumerator.MoveNext do
begin
st.Remove(0,st.Length);
DictEntry := DictionaryEntry(Enumerator.Current);
z:= (ToInteger(DictEntry.Value.ToString)/counter * 100);
st.Append(z.ToString('00.00') + '% - ');
st.Append(DictEntry.Key.ToString + ' - (');
st.Append(DictEntry.Value.ToString + ' entries)');
lbStats.Items.Add(st.ToString);
end;
end;
end;


That’s pretty much all the code that is needed. In order to ‘manually publish’ the application, after testing the code and ensuring the application functions as desired, copy the .DLL from application’s Bin directory and the form’s .aspx file to the hosting site (if you do not have a web.config file on the published site you will need to copy that file as well).

With BDS 2006 you can get this up and running rather quickly, I think it takes longer to write this post; unfortunately it didn’t serve up any winning numbers for me…….

Labels: , , ,

posted by Brad Prendergast at 12:53:00 PM (0 comments)
Links to this post
Permalink
Sunday, January 22, 2006
MyOwnConversion

There are a number of ‘tools’ available to create ASP.NET code. Having created a number of ASP.NET ‘applications’ in an environment other than Delphi® (Don’t interpret this wrong, Delphi® is my passion and always my FIRST choice. Unfortunately, limitations and guidelines can often restrict the tools used.) and having a little time available I decided to create an ASP.NET web application with my reaffirmed passion BDS 2006 (a.k.a. Delphi 10). Question: What could I throw together quick that could serve as something useful? Answer: I do like the ConvertIt demo that shipped with both Delphi® 2005 and BDS 2006.
I fired up ‘Delphi for the Microsoft .NET Framework’ (The ability to selectively load personalities is one thing I am very fond of) and decided to get stared on a new ASP.NET Web Application. On a form I dropped a ComboBox (cbxConversions), TextBox (txtValue), and two ListBoxes (lstFrom and lstTo).



To ensure the ‘proper’ flow of my design I set the AutoPostBack property to True for cbxConversions, lstFrom and txtValue. Now for the code (the events coincide with the defaults for the controls):

unit WebForm1;

interface

uses
System.Collections, System.ComponentModel,
System.Data, System.Drawing, System.Web, System.Web.SessionState,
System.Web.UI, System.Web.UI.WebControls, System.Web.UI.HtmlControls,
ConvUtils, Borland.Vcl.Classes, Borland.Vcl.StdConvs,Borland.Vcl.StrUtils,
Borland.Vcl.SysUtils;

type
TWebForm1 = class(System.Web.UI.Page)
{$REGION 'Designer Managed Code'}
strict private
procedure
InitializeComponent;
procedure cbxConversions_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
procedure lbFrom_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
procedure txtValue_TextChanged(sender: System.Object; e: System.EventArgs);
{$ENDREGION}
strict private
procedure
Page_Load(sender: System.Object; e: System.EventArgs);
strict protected
lstFrom: System.Web.UI.WebControls.ListBox;
lstTo: System.Web.UI.WebControls.ListBox;
cbxConversions: System.Web.UI.WebControls.DropDownList;
txtValue: System.Web.UI.WebControls.TextBox;
procedure OnInit(e: EventArgs); override;
end;

implementation

{$REGION 'Designer Managed Code'}
///
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
///

procedure TWebForm1.InitializeComponent;
begin
Include(Self.lstFrom.SelectedIndexChanged, Self.lbFrom_SelectedIndexChanged);
Include(Self.cbxConversions.SelectedIndexChanged, Self.cbxConversions_SelectedIndexChanged);
Include(Self.txtValue.TextChanged, Self.txtValue_TextChanged);
Include(Self.Load, Self.Page_Load);
end;
{$ENDREGION}

procedure TWebForm1.Page_Load(sender: System.Object; e: System.EventArgs);
var
LFamilies: TConvFamilyArray;
i: integer;
begin
if
cbxConversions.Items.Count <= 0 then
begin
GetConvFamilies(LFamilies);
for I := 0 to Length(LFamilies) - 1 do
cbxConversions.Items.Add(ConvFamilyToDescription(LFamilies[I]));
end;
end;

procedure TWebForm1.OnInit(e: EventArgs);
begin
//
// Required for Designer support
//
InitializeComponent;
inherited OnInit(e);
end;

procedure TWebForm1.txtValue_TextChanged(sender: System.Object; e: System.EventArgs);
begin
lbFrom_SelectedIndexChanged(sender,e);
end;

procedure TWebForm1.lbFrom_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
var
LValue: Double;
LBaseType, LTestType: TConvType;
I: Integer;
begin
lstTo.Items.Clear;
try
LValue := StrToFloatDef(txtValue.Text, 0);
if lstFrom.SelectedIndex <> -1 then
begin
DescriptionToConvType(
lstFrom.Items.Item[lstFrom.SelectedIndex].Text,
LBaseType
);
for I := 0 to lstFrom.Items.Count - 1 do
begin
DescriptionToConvType(lstFrom.Items.Item[i].Text, LTestType);
lstTo.Items.Add(Format('%n %s', [Convert(LValue, LBaseType, LTestType),
ConvTypeToDescription(LTestType)]));
end;
end;

except
lstTo.Items.Add('Cannot parse value');
end;
end;


procedure TWebForm1.cbxConversions_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
var
LFamily: TConvFamily;
LTypes: TConvTypeArray;
I: Integer;
begin
lstFrom.Items.Clear;
lstTo.Items.Clear;
if DescriptionToConvFamily(
cbxConversions.Items[cbxConversions.SelectedIndex].Text,
LFamily) then
begin
GetConvTypes(LFamily, LTypes);
for I := 0 to Length(LTypes) - 1 do
lstFrom.Items.Add(ConvTypeToDescription(LTypes[I]));
end;
end;

end.


I built the application and fired up one of my test Virtual Machines (As I had mentioned before, Microsoft® Virtual PC is a developers dream) and configured an application root for my newly created ASP.NET application. I copied over the ‘application’ and within minutes I had a functional web based variation of a conversion program a la BDS 2006 style.

Labels: , , ,

posted by Brad Prendergast at 11:12:00 AM (0 comments)
Links to this post
Permalink
Recent Posts
 Off-topic: Uhm, Rickroll?
 SQL: Where are the database files?
 Show Desktop in my QuickLaunch Toolbar?
 Command Line: Visual Source Safe
 SQL: Remove / Delete Orphan Users
 SQL Delete/Drop a User from each Database
 Is there an 'I' in phone?
 SQL Optimization: Am I missing any indexes? - Part...
 Meaningful Signature File Quotes
 My Shared RSS Items


Labels



Archives
 October 2005
 November 2005
 December 2005
 January 2006
 February 2006
 March 2006
 April 2006
 May 2006
 June 2006
 July 2006
 August 2006
 September 2006
 December 2006
 January 2007
 February 2007
 March 2007
 September 2007
 October 2007
 November 2007
 July 2008
 November 2008
Powered by Blogger