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 / December 2007

Tip: Looking for answers? Try searching our database.

Serve a file on page load (save file as)

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Alain Quesnel - 05 Dec 2007 21:32 GMT
Hi,

I'm trying to do something fairly simple. I want to create a web page that
will take a parameter in the URL and return a file on page load. The file is
stored in a MSSQL 2005 database in an XML field (which is similar to a
varchar(max) field). The URL would look something like this:

http://www.mydomain.com/myspecialpage/?MyTableID=99

99 being the value for primary key of the table, and the XML file would come
from the XML field in that record. When the user loads such a URL in a
browser, he/she would be prompted to save that file on disk. Could someone
point me in the right direction? I've looked for examples on how to do this,
but had no luck so far. BTW, I'm more familiar with C# than VB. I've set up
a SqlDataSource on my page, and that works fine. I tested it with a GridView
and I can see the contents of my XML field. Obviously, I don't wnt that page
to display anything. I juat want to return the XML field content as a file
to save.

Signature

Thank you,

Alain Quesnel
alainsansspam@logiquel.com

www.logiquel.com

Milosz Skalecki [MCAD] - 05 Dec 2007 23:11 GMT
Hi Alain,

The task at hand is fairly simple:
You need two pages:
1. The main page with html content with "invisible" iframe
2. aspx page serving XML files
The reason for that is diffrent types of MIME content cannot be mixed on a
single page.

1. ASPX Page user is redirected to get the file:
-- begin MyPage.aspx code --

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs"
Inherits="MyPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            asjdhajskdhaskjdhasdha dsaj hdkasjdh sahd
            <iframe src="<%= ResolveUrl("~/File.aspx?MyTableID=") +
Request.QueryString["MyTableID"]  %>"
                width="0" marginheight="0" marginwidth="0" scrolling="no" style="width:
0px;
                height: 0px"></iframe>
            blah blah...
            <table>
                <tr>
                    <td>
                        Some content</td>
                    <td>
                        More content...</td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

-- end MyPage.aspx code --

2. Page referenced in src attribute of the iframe tag allowing user to
download the file or displaying javascript error dialog box if file cannot be
found.

-- begin File.aspx code --

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="File.aspx.cs"
Inherits="File" %>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <script type="text/javascript">
           
            var queryStringValue = '<%= Request.QueryString["MyTableID"] %>';
           
            if (queryStringValue != '')
            {
                alert('Could not find file with ID = "' + queryStringValue + '"');
            }
           
        </script>
    </body>
</html>

-- end File.aspx code --

-- begin File.aspx.cs behind/beside code --

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class File : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int id;

        if (int.TryParse(Request.QueryString["MyTableID"], out id))
        {
            string xml = GetXML(id);

            if (xml != null)
            {

                Response.Clear();
                Response.ContentType = "xml";
                Response.AddHeader("Content-Disposition", "attachment;
filename=whatever.xml");
                Response.Write(xml);
                Response.End();
            }
        }
    }

    private string ConnectionString
    {
        get
        {
            // currently connection string is read from web.config
            // but it may be replaced with a constant value
            // i.e return
"server=myserverName;database=dbName;uid=userId;pwd=secretPassword"
            return
ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
        }
    }

    private string GetXML(int id)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            string query = "SELECT [XML] FROM [MyTable] WHERE MyTableID = @id";

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();
                command.Parameters.Add("@id", SqlDbType.Int).Value = id;
                return Convert.ToString(command.ExecuteScalar());
            }
        }
    }
}

-- end File.aspx.cs behind/beside code --

Done. You  should be fine from this point. There are few little things
missing as i didn't want to confuse you at this stage (i.e. if XML content is
big we should use sequential access instead).

Hope this helps
--
Milosz

> Hi,
>
[quoted text clipped - 14 lines]
> to display anything. I juat want to return the XML field content as a file
> to save.
Alain Quesnel - 06 Dec 2007 02:56 GMT
Wow! This is beyond my wildest dreams. I can't wait to try this out. I'll
let you know how it all works out.

Thank you,

Alain Quesnel
alainsansspam@logiquel.com

www.logiquel.com

> Hi Alain,
>
[quoted text clipped - 177 lines]
>> file
>> to save.
Alain Quesnel - 06 Dec 2007 05:48 GMT
Works great. I'll have to make a few adjustments, but I'm glad it works.

Thank you,

Alain Quesnel
alainsansspam@logiquel.com

www.logiquel.com

> Hi Alain,
>
[quoted text clipped - 177 lines]
>> file
>> to save.

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.