Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 4.5 > ASP.NET 4.5 General Discussion
|
ASP.NET 4.5 General Discussion For ASP.NET 4.5 discussions not relating to a specific Wrox book
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 4.5 General Discussion section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 6th, 2013, 09:55 AM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

It was something like this. I was testing it on just the thumbnail file first to test the water as it were, while I temporarily changed the other image upload to a textbox so i could type in a fake path (all my fields are set to NOT NULL).

Code:
string ThumbPath = Request.QueryString.Get("ThumbPath"));
    Picture myPicture = (Picture)e.Entity;
    myPicture.ThumbPath = ThumbPath;

    FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
    string virtualFolder = "~/Thumb/";
    string physicalFolder = Server.MapPath(virtualFolder);
    string fileName = Guid.NewGuid().ToString();
    string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
    FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
    myPicture.ImageUrl = virtualFolder + fileName + extension;
That's all I have tried so far. IIRC this only does the uploading but not the inserting? the EF does the writing to the DB?

Here's is the AddEditItem.aspx without the other fields and datasources which is just simple data binding from SQL Data sources.

Code:
<asp:FormView ID="FormView1" runat="server" RenderOuterTable="False" DataKeyNames="ItemID" DataSourceID="sdsItem" DefaultMode="Insert" OnItemInserted="FormView1_ItemInserted" OnItemUpdated="FormView1_ItemUpdated">
        <EditItemTemplate>
            <h2>Update an Existing Item</h2>
           

            <asp:Label ID="lblThumb" runat="server" Text="Box Art (Thumbnail):"/>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <br />
            <asp:Label ID="lblCurrentThumb" runat="server" Text="Current Box Art Thumbnail:"/>
            <br />
            <asp:Image ID="imgCurrentThumb" runat="server" ImageUrl='<%#  "../" + Eval("ThumbPath") %>'/>
            <br />

            <asp:Label ID="lblFull" runat="server" Text="Box Art (Full):"/>
            <asp:FileUpload ID="FileUpload2" runat="server" />
            <br />
            <asp:Label ID="lblCurrentFull" runat="server" Text="Current Box Art:"/>
            <br />
            <asp:Image ID="imgCurrentFull" runat="server" ImageUrl='<%#  "../" + Eval("PhotoPath") %>'/>
            <br />




            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
            &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        <InsertItemTemplate>

            <h2>Insert a New Item</h2>


            <asp:Label ID="lblThumb" runat="server" Text="Box Art (Thumbnail):"/><asp:FileUpload ID="FileUpload1a" runat="server" />
            <br />

            <asp:Label ID="lblFull" runat="server" Text="Box Art (Full):"/><asp:FileUpload ID="FileUpload2a" runat="server" />
            <br />

           

            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
            &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
        


    </asp:FormView>
EDIT: If i don't reply it means it's midnight here in Australia and so it's time to sleep. I will check back as I get email notifications.

Last edited by thgh0sts; May 6th, 2013 at 10:08 AM..
 
Old May 6th, 2013, 10:07 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Quote:
Picture myPicture = (Picture)e.Entity;
You're not using Entity Framework or an EntityDataSource control here, are you? Just checking, before I look into this and come up with a solution you don't need.

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 6th, 2013, 10:10 AM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

Quote:
Originally Posted by Imar View Post
You're not using Entity Framework or an EntityDataSource control here, are you? Just checking, before I look into this and come up with a solution you don't need.

Imar
I do have it set up (as per the book) but I was looking to see if there was a way to do it with just sqldatasources.
 
Old May 6th, 2013, 10:49 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Since I am still guessing as to what you need and how exactly, I cooked up an example that may, or may not, be what you're looking for. It assumes the presence of a database table with an Id, a Name and an ImageUrl column, The FormView is then used to insert new records. When you hit Insert, the Inserting event is raised which then stores the file on disk and the path to it in the database by assigning it to e.Values["ImageUrl"]

Hope this helps,

Imar

[Markup]
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" 
             DataSourceID="SqlDataSource1" DefaultMode="Insert" 
             OnItemInserting="FormView1_ItemInserting">
        <InsertItemTemplate>
          Name:
          <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
          <br />
          ImageUrl:
          <asp:FileUpload ID="FileUpload1" runat="server" />
          <br />
          <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
                  CommandName="Insert" Text="Insert" />
          &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" 
                  CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
      </asp:FormView>
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
       ConnectionString="<%$ ConnectionStrings:ConnectionString %> 
       "InsertCommand="INSERT INTO [Picture] ([Name], [ImageUrl]) VALUES (@Name, @ImageUrl)">
        <DeleteParameters>
          <asp:Parameter Name="Id" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
          <asp:Parameter Name="Name" Type="String" />
          <asp:Parameter Name="ImageUrl" Type="String" />
        </InsertParameters>
        <UpdateParameters>
          <asp:Parameter Name="Name" Type="String" />
          <asp:Parameter Name="ImageUrl" Type="String" />
          <asp:Parameter Name="Id" Type="Int32" />
        </UpdateParameters>
      </asp:SqlDataSource>
    </div>
  </form>
</body>
</html>
[Code Behind]
Code:
using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
  protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
  {
    FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
    string virtualFolder = "~/Thumb/";
    string physicalFolder = Server.MapPath(virtualFolder);
    string fileName = Guid.NewGuid().ToString();
    string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
    FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
    e.Values["ImageUrl"] = virtualFolder + fileName + extension;
  }
}
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
The Following User Says Thank You to Imar For This Useful Post:
thgh0sts (May 6th, 2013)
 
Old May 6th, 2013, 08:38 PM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

OK, I'll give that a try and report back.

EDIT: just tried the code on just one upload control and it worked!

Thanks Imar.

Last edited by thgh0sts; May 6th, 2013 at 09:38 PM..
 
Old May 8th, 2013, 11:52 PM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

OK, that bit of code behind worked really well and I was able to adapt it to the ItemUpdating event for when a user needs to update the image in the database.

Now I have another question:

If a user is updating a product and they don't upload any selected images, the two fields (ThumbPath and PhotoPath) will become NULL in the database. I have instigated a check to see if the fileupload control has a file then upload and write to DB else update everything else in the table except for the images.

Here's some of the code behind:

Code:
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    { FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload3");
      FileUpload FileUpload2 = (FileUpload)FormView1.FindControl("FileUpload4");
      

      if (FileUpload1.HasFile)
      {
          string virtualFolder1 = "~/ProductArt/Thumb/";
          string physicalFolder1 = Server.MapPath(virtualFolder1);
          string oldkey = e.Keys["ItemID"].ToString();
          //string photopath1 = e.OldValues["ThumbPath"].ToString();
          string ext1 = System.IO.Path.GetExtension(FileUpload1.FileName);
          FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder1, oldkey + ext1));
          //e.Values["ThumbPath"] = photopath1 + ext1;
          e.NewValues["ThumbPath"] = virtualFolder1 + oldkey + ext1;
      }
      else
      {
          //throw new Exception("Error, no thumb file selected");
          SqlConnection moddedInsert = new SqlConnection("TTEConnectionString");
          moddedInsert.Open();
          SqlCommand newUpdateQuery = moddedInsert.CreateCommand();
          newUpdateQuery.CommandText = "UPDATE Item SET ItemName='" + lblItemNameTextBox.Text + "',";
      }

      if (FileUpload2.HasFile)
      {
          string virtualFolder2 = "~/ProductArt/";
          string physicalFolder2 = Server.MapPath(virtualFolder2);
          string oldkey2 = e.Keys["ItemID"].ToString();
          //string photopath1 = e.OldValues["ThumbPath"].ToString();
          string ext2 = System.IO.Path.GetExtension(FileUpload2.FileName);
          FileUpload2.SaveAs(System.IO.Path.Combine(physicalFolder2, oldkey2 + ext2));
          //e.Values["ThumbPath"] = photopath1 + ext1;
          e.NewValues["PhotoPath"] = virtualFolder2 + oldkey2 + ext2;
      }
      else
      {
          throw new Exception("Error, no full box file selected");
      }
    }
I am not sure about how to update the DB through C# that connects to the database and runs a modified update query that does not contain the image not being updated.
 
Old May 9th, 2013, 07:38 AM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

No one? i don't get why i am getting the error for the names not existing.
 
Old May 9th, 2013, 08:49 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Can you provide more detail? In your last post you didn't say anything about errors; now you mention an "error for the names not existing". More details would surely help.

A few other observations:

1. You're not executing the SQL Command
2. Can't you simply assign the value from e.Values to e.NewValues for the images if no new image is uploaded? Haven't checked this though, so not sure if the old values are even available.

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 9th, 2013, 09:33 AM
Authorized User
 
Join Date: Mar 2013
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
Default

I have tried:

string photopath = e.CommandArgument.ToString();

that gives an entry of "~/ProductArt/Thumb/.jpg" so it doesn't seem to carry over - only the text and selected values are kept.

I would like to assign a filename that can be able to carry over when updating but things like ItemID are no good because the information has not been assigned an ItemID at the time of insertion. I am not sure as to how to carry e.Values over into e.NewValues but the updating code definitely reuses the same filename even though it's still being written to the DB.


What I am attempting to do with the updating part of the page is (this is within the ItemUpdating event)...

1) Check the fileupload control has a file, if it does contain a file then upload to the site and add to the DB saved as the ItemID #.

2) if there's no file in one of the controls then the web application assumes that no change to the image in the DB has been made and it should not upload nor update the DB but still update the other fields in the table sans the image path.

3) if neither control has a file then the web application has to assume the user is not updating the images and updates the remaining fields in the DB.

for 2) and 3) I want to call the values from the form, and i tried using txtItemNameBox.Text (which is one of the textboxes that was databound in the form) as a reference point and it gave the 'the name does not exist in the current context'....probably because it's not being properly used/used in the wrong spot.

I was able to make it throw a customized exception error but when it comes to making it do a nonExecutableQuery based on form data is a bit of a struggle.

While I was able to come up with a secondary solution in which i created a 2 tier system where the user would need to click on a link to another page that carried over the ItemID in order to alter a single image. the above problem has both images on the 1 page and pretty much assumes you're altering both images at the same time.

I think the secondary solution is OK but I would like to reduce the number of pages.

Last edited by thgh0sts; May 9th, 2013 at 09:35 AM..
 
Old May 9th, 2013, 11:20 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

e.CommandArgument? Why are you using that? That would contain the command that was executed, like Update or Delete.

Take another look at my previous reply. In addition, take a look at the data you have available when handling the ItemUpdating event: http://msdn.microsoft.com/en-us/libr...oldvalues.aspx

I think what you want to do is something like this:

Code:
if (user has not picked a new thumb)
{  
  e.NewValues["ThumbPath"] = e.OldValues["ThumbPath"]
}
Then get rid of all the stuff that tries to update the database manually.

This takes the old / previous value and makes it the new value, effectively maintaining the existing data.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!





Similar Threads
Thread Thread Starter Forum Replies Last Post
File Upload in form view thgh0sts BOOK: Beginning ASP.NET 4.5 : in C# and VB 4 May 5th, 2013 08:16 AM
Upload file and insert filename into access db pluribus Classic ASP Databases 0 February 28th, 2013 02:50 PM
Creating a file upload form with PHP gilbertsavier Beginning PHP 0 July 31st, 2009 06:41 AM
How to upload complex xml file to 1 db table vangogh XML 3 October 8th, 2007 04:43 AM
Q. How do I upload files to a DB and view them? richard.york PHP FAQs 0 April 3rd, 2004 07:45 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.