Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / General / March 2008

Tip: Looking for answers? Try searching our database.

pop up alert

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
James Page - 10 Mar 2008 20:08 GMT
I have a aspx page where the user selects a image to upload to a sql
database. In the code behind on the item_inserting event i am halting the
insert event if the user has not selected an image file. Here's the select
case code:

Select Case fileExtension
           Case ".gif"
               MIMETypePic = "image/gif"
           Case ".jpg", ".jpeg", ".jpe"
               MIMETypePic = "image/jpeg"
           Case ".png"
               MIMETypePic = "image/png"

           Case Else
               
               e.Cancel = True
               Exit Sub
       End Select

What i'd like to do is alert the user with a pop up box that the file was
not a valid image file. I think this requires some form of clientside script.
can anybody advise how to do this?
Cowboy (Gregory A. Beamer) - 10 Mar 2008 20:29 GMT
There are a couple of ways to handle this. The down and dirty way is
something like this:

Dim builder as new StringBuilder

builder.Append("<script type='JavaScript'>");
builder.Append(CrLf);

builder.Append("alert('")
'Separated here for Select Case
builder.Append("invalid graphics type")

builder.Append("');")
builder.Append(CrLf)

builder.Append("</script>")

Dim lit as new LiteralControl(builder.ToString())

Panel1.Controls.Add(lit)

You then add a Panel to the page where you want the message to show up.

There are other ways to accomplish this. One is to have a set JavaScript
function that you write the code to fire only when there is a mistake in
type. Your upload control can also Emit JavaScript when there is a problem.

Signature

Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

*************************************************

| Think outside the box!

*************************************************
>I have a aspx page where the user selects a image to upload to a sql
> database. In the code behind on the item_inserting event i am halting the
[quoted text clipped - 19 lines]
> script.
> can anybody advise how to do this?
Mark Rae [MVP] - 10 Mar 2008 21:34 GMT
> builder.Append("<script type='JavaScript'>");

builder.Append("<script type=\"text/javascript\">");

Signature

Mark Rae
ASP.NET MVP
http://www.markrae.net

James Page - 11 Mar 2008 01:45 GMT
Thanks guys this is what i've come up with:

Private Sub MessageBox(ByVal strMsg As String)
       
       Dim lbl As New Label()
       lbl.Text = "<script language='javascript'>" & Environment.NewLine &
"window.alert('" + strMsg + "')</script>"
       Page.Controls.Add(lbl)

   End Sub

.....

Select Case extensionPic
           Case ".gif"
               MIMETypePic = "image/gif"
           Case ".jpg", ".jpeg", ".jpe"
               MIMETypePic = "image/jpeg"
           Case ".png"
               MIMETypePic = "image/png"

           Case Else
               MessageBox("Product picture:\r\nOnly .gif, .jpg and .png
file types\r\ncan be selected for upload to database.")
               UploadedFilePic.Focus()
               e.Cancel = True
               Exit Sub
       End Select

Any comments?
Mark Rae [MVP] - 11 Mar 2008 02:10 GMT
> lbl.Text = "<script language='javascript'>" & Environment.NewLine &

Once again...

lbl.Text = "<script type=""text/javascript"">" & Environment.NewLine &

The language tag has been deprecated for some time...

> MessageBox

Will someone be logged on to the server to see that...?

Signature

Mark Rae
ASP.NET MVP
http://www.markrae.net

James Page - 11 Mar 2008 02:18 GMT
Thanks I'll change that.

Logged on??

>> lbl.Text = "<script language='javascript'>" & Environment.NewLine &
>
[quoted text clipped - 7 lines]
>
> Will someone be logged on to the server to see that...?
Mark Rae [MVP] - 11 Mar 2008 02:46 GMT
>>> lbl.Text = "<script language='javascript'>" & Environment.NewLine &
>>
[quoted text clipped - 5 lines]
>
> Thanks I'll change that.

>>> MessageBox
>>
>> Will someone be logged on to the server to see that...?
>
> Logged on??

Yes - you are using MessageBox in your server-side code... For one thing,
shouldn't it be MessageBox.Show(...)? And where do you expect this message
box to display...?

Signature

Mark Rae
ASP.NET MVP
http://www.markrae.net

James Page - 11 Mar 2008 12:09 GMT
MessageBox is the subroutine that is called if the select case fails and
passes string back to it and display a client side alertbox.
Here's the full code:

Private Sub MessageBox(ByVal strMsg As String)
        ' define a javascript alertbox containing
        ' the string passed in as argument
        ' create a new label

        Dim lbl As New Label()
        ' add the javascript to fire an alertbox to the label and
        ' add the string argument passed to the subroutine as the
        ' message payload for the alertbox
        lbl.Text = "<script type=""text/javascript"">" &
Environment.NewLine & "window.alert('" + strMsg + "')</script>"
        ' add the label to the page to display the alertbox
        Page.Controls.Add(lbl)

    End Sub

Private Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.FormViewInsertEventArgs) Handles
FormView1.ItemInserting
        'Reference the FileUpload control
        Dim UploadedFilePic As FileUpload =
CType(FormView1.FindControl("fileUploadProdPict"), FileUpload)

        'Make sure we are dealing with a JPG,  GIF or PNG file
        Dim extensionPic As String =
Path.GetExtension(UploadedFilePic.PostedFile.FileName).ToLower()
        Dim filenamePic As String =
Path.GetFileName(UploadedFilePic.PostedFile.FileName)
        Dim MIMETypePic As String = Nothing

        Select Case extensionPic
            Case ".gif"
                MIMETypePic = "image/gif"
            Case ".jpg", ".jpeg", ".jpe"
                MIMETypePic = "image/jpeg"
            Case ".png"
                MIMETypePic = "image/png"

            Case Else
                MessageBox("Product picture:\r\nOnly .gif, .jpg and
.png file types\r\ncan be selected for upload to database.")
                UploadedFilePic.Focus()
                e.Cancel = True
                Exit Sub
        End Select

        'Specify the values for the MIMEType and ImageData parameters
        e.Values("productPicMimeType") = MIMETypePic
        'Load FileUpload's InputStream into Byte array
        Dim
imageBytesPic(UploadedFilePic.PostedFile.InputStream.Length) As Byte
        UploadedFilePic.PostedFile.InputStream.Read(imageBytesPic, 0,
imageBytesPic.Length)
        e.Values("productPic") = imageBytesPic
        e.Values("productPicFileName") = filenamePic
    End Sub

Therefore if the item Inserting event fails, at the select case stage,
the user is prompted to try again. I know its not the technically
correct solution but it does work. Ideally i'd like full client side
validation before the item inserting event is fired but javascript is
not my strong suit!

>>>> lbl.Text = "<script language='javascript'>" & Environment.NewLine &
>>>
[quoted text clipped - 15 lines]
> thing, shouldn't it be MessageBox.Show(...)? And where do you expect
> this message box to display...?
Mark Rae [MVP] - 11 Mar 2008 13:10 GMT
>>> Logged on??
>>
[quoted text clipped - 4 lines]
> MessageBox is the subroutine that is called if the select case fails and
> passes string back to it and display a client side alertbox.

Ah - OK...

Signature

Mark Rae
ASP.NET MVP
http://www.markrae.net

Cowboy (Gregory A. Beamer) - 11 Mar 2008 03:32 GMT
Labels are not the best place to attach text, due to the order in which they
display. I am not completely convinced it will not work, but I still find
attaching to a Panel is better.

Also, you should note you are mixing server side code and client side. When
someone goes to upload, it will be a single request (multi-part) to the
server, which contains the form information, plus a binary representation of
image someone is uploading. Once you see it is the incorrect image, you are
finished with the server side code, which means your MessageBox() routine
cannot be contacted without creating a second trip to the server. This is
what Mark was talking about.

On your form submit routine, you should check for image type and then either
give the user a success message or a failure message (and/or popup). Do not
try to contact server side code from the client side, except through events.

Signature

Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

*************************************************

| Think outside the box!

*************************************************
> Thanks guys this is what i've come up with:
>
[quoted text clipped - 26 lines]
>
> Any comments?
bruce barker - 11 Mar 2008 01:55 GMT
check on client before submit (could use a custom validator).

string script = @"
function filetest() {
  var f = document.getElementById('"+fileupload.ClientID+@"');
  if (!/\.(gif|jpg|jpeg|png)$/.text(f.value)) {
    alert('Invalid file extension');
    return false;
  }
}
"
Page.ClientScript.RegisterStartupScript(this.GetType(),
      "check",
       script,
       true);
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(),
      "check",
      "if(!filetest())return false;");

> I have a aspx page where the user selects a image to upload to a sql
> database. In the code behind on the item_inserting event i am halting the
[quoted text clipped - 18 lines]
> not a valid image file. I think this requires some form of clientside script.
> can anybody advise how to do this?
James Page - 11 Mar 2008 02:04 GMT
Which event  - page load?

> check on client before submit (could use a custom validator).
>
[quoted text clipped - 36 lines]
>> was not a valid image file. I think this requires some form of
>> clientside script. can anybody advise how to do this?
Paul Shapiro - 11 Mar 2008 04:21 GMT
I've used a regular expression validator to check on the client before the
file is submitted.
   <asp:FileUpload ID="FileUploadAbstract" runat="server" Width="450px" />
   <asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
       ControlToValidate="FileUploadAbstract"
       ErrorMessage="Only .pdf files can be submitted"
       ValidationExpression=".*\.pdf$"
       Display="Dynamic">
   </asp:RegularExpressionValidator>
   <asp:Button ID="ButtonFileUpload" runat="server" Text="Submit PDF File"
OnClick="ButtonFileUpload_Click" />
Unless the file type is .pdf, the submit button remains unavailable.

On the server I check the mime type as a further verification before saving
the file, but unless the user is playing games, I think the client side
check would usually be sufficient.
Paul Shapiro

> check on client before submit (could use a custom validator).
>
[quoted text clipped - 36 lines]
>> not a valid image file. I think this requires some form of clientside
>> script. can anybody advise how to do this?
James Page - 11 Mar 2008 12:12 GMT
Thanks Paul

Two questions:

what is the expresssion syntax for checking multiple file types and how
do you get the validation message to refresh when the user has selected
the correct file type i.e.
1. User selects .doc
2. validation shows error
3. User tries again and selects .pdf
4 validation still shows error.

> I've used a regular expression validator to check on the client before
> the file is submitted.
[quoted text clipped - 55 lines]
>>> was not a valid image file. I think this requires some form of
>>> clientside script. can anybody advise how to do this?
Paul Shapiro - 11 Mar 2008 12:28 GMT
I am not familiar enough with regEx syntax to give the correct version for
mutltiple file types, but I think it's straightforward to specify
alternates. So maybe something like ".*\.(pdf|doc|txt)$"?

The validation refresh is automatic. I didn't add any code for it.

> Thanks Paul
>
[quoted text clipped - 68 lines]
>>>> was not a valid image file. I think this requires some form of
>>>> clientside script. can anybody advise how to do this?
james page - 13 Mar 2008 18:57 GMT
Paul -

I've discovered the syntax to check for file extension types prior to
upload - thought I'd post it to help others in the same boat I was in:

To check for .pdf files:

^.*(([^\.][\.][pP][dD][fF]))$

To check for (my original requirements) .pdf, .txt, .doc, zip & .jpg:

^.*(([^\.][\.][pP][dD][fF])|([^\.][\.][tT][xX][tT])|([^\.][\.][dD][oO][cC])|([^\.][\.][zZ][iI][pP])|([^\.][\.][jJ][pP][gG]))$

Works a treat!

My head hurts now  - I'm going for a lie down!!

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.