Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Question regarding ASP.NET (CodeFile -vs- Codebehind)

  • 17-01-2009 3:46am
    #1
    Closed Accounts Posts: 7,097 ✭✭✭


    Hi folks,

    I'm milling away at my website here and I have an MS SQL 2005 DB set up on my server which works fine in conjunction with a 3 layer cascading drop down list.

    What I'm trying to do now, is add an image into each record in my DB and have this image displayed on my webpage when a particular record is pulled from the DB, dependent upon what items are selected from the cascading drop down list.

    So, far without the image functionality, everything is working grand.

    In order to learn how to upload an image into a my DB, I downloaded a solution from the web that does this in a simple way. What I'll do is cut the code I need from this, modify it and set up a connection to my DB on the server and I should be elected.

    What I've noticed is that when I compile the solution I've downloaded, I get a compiler error saying "Codebehind in the @ Page Directive is no longer supported". The webpage will still compile and it does upload images into the database in the local folder, but the error annoyed me.

    I thought that I hadn't seen this "Codebehind" before so I changed:

    <%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>


    To

    <%@ Page language="c#" AutoEventWireUp="false" CodeFile="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>


    And then the page won't compile and I get an error saying:

    Compiler Error Message: ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl).

    What I'm wondering is there any way to use the CodeFile approach to refer to the default.aspx.cs instead of Codebehind, or to modify the code so that this error doesn't appear, because I will be modifying this script and I'd like to have an error free script before I start so at least I know any subsequent errors are down to the changes I make.

    <%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>

    <html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
    <title>My Image Upload Page</title>
    </head>
    <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
    <asp:label id="lblFile" runat="server" Font-Bold="True">Picture:</asp:label>
    <input id="filMyFile" type="file" runat="server" />
    <p></p>
    <asp:button id="cmdSend" runat="server" Text="Send"/>
    <p></p>
    <asp:Label id="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
    <p></p>
    <table>
    <tr>
    <td>
    <asp:Label id="lblText1" runat="server" Font-Bold="True" Visible="false">This was stored as file</asp:Label>
    </td>
    <td>
    <asp:Label id="lblText2" runat="server" Font-Bold="True" Visible="false">This was stored in database</asp:Label>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Image id="imgFile" runat="server" Visible="False"></asp:Image>
    </td>
    <td>
    <asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>



    C# page below..

    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Data;
    using System.Data.OleDb;
    using System.Web.UI.WebControls.WebParts;
    using System.Configuration;
    using System.Collections;
    using System.Web.Security;
    using System.Web.Services;
    using System.Collections.Specialized;
    using System.Data.SqlClient;


    namespace FileUpload
    {
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class Webform1 : System.Web.UI.Page
    {
    private const string MDBFILE = "FileUpload.mdb";

    protected Label lblFile;
    protected HtmlInputFile filMyFile;
    protected System.Web.UI.WebControls.Label lblInfo;
    protected System.Web.UI.WebControls.Button cmdSend;
    protected System.Web.UI.WebControls.Image imgFile;
    protected System.Web.UI.WebControls.Image imgDB;
    protected System.Web.UI.WebControls.Label lblText1;
    protected System.Web.UI.WebControls.Label lblText2;

    override protected void OnInit(EventArgs e)
    {
    InitializeComponent();
    base.OnInit(e);
    }

    private void InitializeComponent()
    {
    this.Load += new System.EventHandler(this.Page_Load);
    this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
    // Check if FileID was passed to this page as a parameter
    if( Request.QueryString["FileID"] != null )
    {
    // Get the file out of database and return it to requesting client
    ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
    }

    }

    // Processes click on our cmdSend button
    private void cmdSend_Click(object sender, System.EventArgs e)
    {
    // Check to see if file was uploaded
    if( filMyFile.PostedFile != null )
    {
    // Get a reference to PostedFile object
    HttpPostedFile myFile = filMyFile.PostedFile;

    // Get size of uploaded file
    int nFileLen = myFile.ContentLength;

    // make sure the size of the file is > 0
    if( nFileLen > 0 )
    {
    // Allocate a buffer for reading of the file
    byte[] myData = new byte[nFileLen];

    // Read uploaded file from the Stream
    myFile.InputStream.Read(myData, 0, nFileLen);

    // Create a name for the file to store
    string strFilename = Path.GetFileName(myFile.FileName);

    // Write data into a file
    WriteToFile(Server.MapPath(strFilename), ref myData);

    // Store it in database
    int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData);

    // Set label's text
    lblInfo.Text =
    "Filename: " + strFilename + "<br>" +
    "Size: " + nFileLen.ToString() + "<p>";


    // Set URL of the the object to point to the file we've just saved
    imgFile.ImageUrl = strFilename;
    imgFile.ToolTip = "This file was stored to as file.";
    lblText1.Text = imgFile.ImageUrl;

    // Set URL of the the object to point to the this script with ID of the file
    // that will retreive file out the database
    imgDB.ImageUrl = GetMyName() + "?FileID=" + nFileID.ToString();
    imgDB.ToolTip = "This file was stored in database.";
    lblText2.Text = imgDB.ImageUrl;

    // show the images and text
    imgFile.Visible = true;
    imgDB.Visible = true;
    lblText1.Visible = true;
    lblText2.Visible = true;
    }
    }
    }

    // Writes file to current folder
    private void WriteToFile(string strPath, ref byte[] Buffer)
    {
    // Create a file
    FileStream newFile = new FileStream(strPath, FileMode.Create);

    // Write data to the file
    newFile.Write(Buffer, 0, Buffer.Length);

    // Close file
    newFile.Close();
    }

    // Generates database connection string
    private string GetConnectionString()
    {
    return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
    }

    // Writes file to the database
    private int WriteToDB(string strName, string strType, ref byte[] Buffer)
    {
    int nFileID = 0;

    // Create connection
    OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

    // Create Adapter
    OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);

    // We need this to get an ID back from the database
    dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

    // Create and initialize CommandBuilder
    OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

    // Open Connection
    dbConn.Open();

    // New DataSet
    DataSet dbSet = new DataSet();

    // Populate DataSet with data
    dbAdapt.Fill(dbSet, "tblFile");

    // Get reference to our table
    DataTable dbTable = dbSet.Tables["tblFile"];

    // Create new row
    DataRow dbRow = dbTable.NewRow();

    // Store data in the row
    dbRow["FileName"] = strName;
    dbRow["FileSize"] = Buffer.Length;
    dbRow["ContentType"] = strType;
    dbRow["FileData"] = Buffer;

    // Add row back to table
    dbTable.Rows.Add(dbRow);

    // Update data source
    dbAdapt.Update(dbSet, "tblFile");

    // Get newFileID
    if( !dbRow.IsNull("FileID") )
    nFileID = (int)dbRow["FileID"];

    // Close connection
    dbConn.Close();

    // Return FileID
    return nFileID;
    }

    // Read file out of the database and returns it to client
    private void ShowTheFile(int FileID)
    {
    // Define SQL select statement
    string SQL = "SELECT FileSize, FileData, ContentType FROM tblFile WHERE FileID = "
    + FileID.ToString();

    // Create Connection object
    OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

    // Create Command Object
    OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

    // Open Connection
    dbConn.Open();

    // Execute command and receive DataReader
    OleDbDataReader dbRead = dbComm.ExecuteReader();

    // Read row
    dbRead.Read();

    // Clear Response buffer
    Response.Clear();

    // Set ContentType to the ContentType of our file
    Response.ContentType = (string)dbRead["ContentType"];

    // Write data out of database into Output Stream
    Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

    // Close database connection
    dbConn.Close();

    // End the page
    Response.End();
    }

    // Reads the name of current web page
    private string GetMyName()
    {
    // Get the script name
    string strScript = Request.ServerVariables["SCRIPT_NAME"];

    // Get position of last slash
    int nPos = strScript.LastIndexOf("/");

    // Get everything after slash
    if( nPos > -1 )
    strScript = strScript.Substring(nPos + 1);

    return strScript;
    }
    }
    }



    Also, this MS_POSITIONING code below is causing an error but it isn't a show stopper at the moment...

    <body MS_POSITIONING="GridLayout">

    Error 2 Validation (XHTML 1.0 Transitional): Attribute 'MS_POSITIONING' is not a valid attribute of element 'body'. C:\Documents and Settings\CATHAL SINCLAIR\Desktop\FileUpload_demo\default.aspx 7 8 C:\...\FileUpload_demo\


Comments

  • Registered Users, Registered Users 2 Posts: 2,793 ✭✭✭John_Mc


    Add the Partial keyword to the Class declaration in the code behind.

    Not sure what MS_Positioning is meant to be, try removing it and getting the page to compile


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    John_Mc wrote: »
    Not sure what MS_Positioning is meant to be, try removing it and getting the page to compile

    MS_Positioning goes back to Visual Studio 2003 where you could create your web pages in design mode using a grid or as normal (MS_Positioning="flow"). It used that attribute to tell the designer which to use. Back in the days when completely illegal attributes in a deployed page didn't seem like an issue. The grid was truly horrible as you could drag controls onto your web page and in the html it would create style attributes to position the elements where you had dragged them. Long gone now thankfully.


  • Registered Users, Registered Users 2 Posts: 2,793 ✭✭✭John_Mc


    musician wrote: »
    MS_Positioning goes back to Visual Studio 2003 where you could create your web pages in design mode using a grid or as normal (MS_Positioning="flow"). It used that attribute to tell the designer which to use. Back in the days when completely illegal attributes in a deployed page didn't seem like an issue. The grid was truly horrible as you could drag controls onto your web page and in the html it would create style attributes to position the elements where you had dragged them. Long gone now thankfully.

    I see, nice one for the info. Best off for the OP to remove it so!


Advertisement