EDN Admin
Well-known member
Hi,
A little background first:
Im trying to setup a datagrid that will retrieve all fields from a table calle tbl_Media. The table has a key identity field called MediaID. The other fields are MediaName, MediaType, MediaOwner and MediaFile (an image type field). Ive
tested the below code and it correctly pulls all the table record data and places it in the gridview. However, the image column only shows nothing or a broken link icon depending on the browser Im testing. Ive spent the last 3 days trying to
get the images to display with no luck. Any help is very much appreciated. Thanks in advance for your help. Below is the code for Default.aspx, Default.aspx.cs, Handler.ashx and web.config:
----------------------------Default.aspx--------------------------------------
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile=" Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent <br/>
</asp:Content><br/>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent <br/>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large"
<br/>
Text="Main Media Page </asp:Label><br/>
<br /><br/>
<br /><br/>
<asp:Menu ID="Menu1" runat="server" BackColor="#B5C7DE" <br/>
DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em"
<br/>
ForeColor="#284E98" StaticSubMenuIndent="10px <br/>
<DynamicHoverStyle BackColor="#284E98" ForeColor="White" /><br/>
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /><br/>
<DynamicMenuStyle BackColor="#B5C7DE" /><br/>
<DynamicSelectedStyle BackColor="#507CD1" /><br/>
<Items><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Agreements/Default.aspx"
<br/>
Text="Official Documents" Value="Official Documents </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl=""
<br/>
Text="Billing" Value="Billing" Target="_blank </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Contact/Default.aspx"
<br/>
Text="Edit Contact Info" Value="Edit Contact Info </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Media/Default.aspx"
<br/>
Text="Media" Value="Media <br/>
</asp:MenuItem><br/>
<asp:MenuItem NavigateUrl=""
<br/>
Text="Project Collaboration" Value="Project Collaboration" Target="_blank </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Remote/Default.aspx"
<br/>
Text="Remote Access" Value="Remote Access </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/Account/ChangePassword.aspx"
<br/>
Text="Change Password" Value="Change Password </asp:MenuItem><br/>
</Items><br/>
<StaticHoverStyle BackColor="#284E98" ForeColor="White" /><br/>
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /><br/>
<StaticSelectedStyle BackColor="#507CD1" /><br/>
</asp:Menu><br/>
<br /><br/>
This page allows your to upload and view files related to your project(s).
<br/>
If you have any files you'd like to add to your project, such as images,
<br/>
audio files, video files, web pages, pdf files, or zip files, click on the browse
<br/>
button below and navigate to the saved location of the file (i.e. Desktop, My
<br/>
Documents foler, etc.). This is very similar to the process of adding an
<br/>
attachment to an email. Once you click on the "Upload" button, please be
<br/>
patient. Depending on the size of the file you've selected to upload and
<br/>
your internet connection, the upload may take some time to load. Once the
<br/>
image is loaded, this page will reload and you will see a "File Uploaded
<br/>
Successfully!" message below the "Browse" button. <br/>
<asp:TextBox ID="MediaID" runat="server" Visible="False </asp:TextBox><br/>
<br /><br/>
Owner: <br/>
<asp:LoginName ID="LoginName1" runat="server" /><br/>
<br /><br/>
<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"<br/>
OnClick="btnUpload_Click" /><br/>
<br /><br/>
<asp:Label ID="lblMessage" runat="server" Text=""<br/>
Font-Names = "Arial </asp:Label> <br /><br/>
<br /><br/>
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Italic="True"
<br/>
Text="All Uploaded Project Files </asp:Label><br/>
<br /><br/>
<br /><br/>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
<br/>
AutoGenerateColumns="False" DataKeyNames="MediaID"
<br/>
DataSourceID="SqlDataSource1" HorizontalAlign="Center" Width="500px <br/>
<Columns><br/>
<asp:BoundField DataField="MediaID" HeaderText="MediaID" InsertVisible="False"
<br/>
ReadOnly="True" SortExpression="MediaID" /><br/>
<asp:BoundField DataField="MediaName" HeaderText="MediaName"
<br/>
SortExpression="MediaName" /><br/>
<asp:BoundField DataField="MediaType" HeaderText="MediaType"
<br/>
SortExpression="MediaType" /><br/>
<asp:BoundField DataField="MediaOwner" HeaderText="MediaOwner"
<br/>
SortExpression="MediaOwner" /><br/>
<asp:TemplateField HeaderText="Image <br/>
<ItemTemplate><br/>
<asp:Image MediaID="Image1" runat="server" Width="200px" ImageUrl=<%# "Handler.ashx?MediaID=" + Eval("MediaID")%>
/><br/>
</ItemTemplate><br/>
</asp:TemplateField><br/>
</Columns><br/>
</asp:GridView><br/>
<br /><br/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" <br/>
ConnectionString="<%$ ConnectionStrings:MYCONNECTIONSTRINGHERE %>"
<br/>
SelectCommand="SELECT * FROM [tbl_Media]"
<br/>
ConflictDetection="CompareAllValues" <br/>
DeleteCommand="DELETE FROM [tbl_Media] WHERE [MediaID] = @original_MediaID AND (([MediaName] = @original_MediaName) OR ([MediaName] IS NULL AND @original_MediaName IS NULL)) AND (([MediaType] = @original_MediaType)
OR ([MediaType] IS NULL AND @original_MediaType IS NULL)) AND (([MediaFile] = @original_MediaFile) OR ([MediaFile] IS NULL AND @original_MediaFile IS NULL)) AND (([MediaOwner] = @original_MediaOwner) OR ([MediaOwner] IS NULL AND @original_MediaOwner IS NULL))"
<br/>
InsertCommand="INSERT INTO [tbl_Media] ([MediaName], [MediaType], [MediaFile], [MediaOwner]) VALUES (@MediaName, @MediaType, @MediaFile, @MediaOwner)"
<br/>
OldValuesParameterFormatString="original_{0}"
<br/>
UpdateCommand="UPDATE [tbl_Media] SET [MediaName] = @MediaName, [MediaType] = @MediaType, [MediaFile] = @MediaFile, [MediaOwner] = @MediaOwner WHERE [MediaID] = @original_MediaID AND (([MediaName] = @original_MediaName)
OR ([MediaName] IS NULL AND @original_MediaName IS NULL)) AND (([MediaType] = @original_MediaType) OR ([MediaType] IS NULL AND @original_MediaType IS NULL)) AND (([MediaFile] = @original_MediaFile) OR ([MediaFile] IS NULL AND @original_MediaFile IS NULL))
AND (([MediaOwner] = @original_MediaOwner) OR ([MediaOwner] IS NULL AND @original_MediaOwner IS NULL)) <br/>
<DeleteParameters><br/>
<asparameter Name="original_MediaID" Type="Int64" /><br/>
<asparameter Name="original_MediaName" Type="String" /><br/>
<asparameter Name="original_MediaType" Type="String" /><br/>
<asparameter Name="original_MediaFile" Type="Object" /><br/>
<asparameter Name="original_MediaOwner" Type="String" /><br/>
</DeleteParameters><br/>
<InsertParameters><br/>
<asparameter Name="MediaName" Type="String" /><br/>
<asparameter Name="MediaType" Type="String" /><br/>
<asparameter Name="MediaFile" Type="Object" /><br/>
<asparameter Name="MediaOwner" Type="String" /><br/>
</InsertParameters><br/>
<UpdateParameters><br/>
<asparameter Name="MediaName" Type="String" /><br/>
<asparameter Name="MediaType" Type="String" /><br/>
<asparameter Name="MediaFile" Type="Object" /><br/>
<asparameter Name="MediaOwner" Type="String" /><br/>
<asparameter Name="original_MediaID" Type="Int64" /><br/>
<asparameter Name="original_MediaName" Type="String" /><br/>
<asparameter Name="original_MediaType" Type="String" /><br/>
<asparameter Name="original_MediaFile" Type="Object" /><br/>
<asparameter Name="original_MediaOwner" Type="String" /><br/>
</UpdateParameters><br/>
</asp:SqlDataSource><br/>
<br /><br/>
</asp:Content>
------------------------------------------------Default.aspx.cs---------------------------------------------
using System;<br/>
using System.Data;<br/>
using System.Data.SqlClient;<br/>
using System.Configuration;<br/>
using System.Web;<br/>
using System.Web.Security;<br/>
using System.Web.UI;<br/>
using System.Web.UI.WebControls;<br/>
using System.Web.UI.WebControls.WebParts;<br/>
using System.Web.UI.HtmlControls;<br/>
using System.IO;<br/>
using System.Drawing.Imaging;<br/>
using System.Drawing;
public partial class _Default : System.Web.UI.Page<br/>
{<br/>
protected void Page_Load(object sender, EventArgs e)<br/>
{
}
private Boolean InsertUpdateData(SqlCommand cmd)<br/>
{<br/>
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MYCONNECTIONSTRINGHERE"].ConnectionString;<br/>
SqlConnection con = new SqlConnection(strConnString);<br/>
cmd.CommandType = CommandType.Text;<br/>
cmd.Connection = con;<br/>
try<br/>
{<br/>
con.Open();<br/>
cmd.ExecuteNonQuery();<br/>
return true;<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
Response.Write(ex.Message);<br/>
return false;<br/>
}<br/>
finally<br/>
{<br/>
con.Close();<br/>
con.Dispose();<br/>
}<br/>
}
protected void btnUpload_Click(object sender, EventArgs e)<br/>
{<br/>
// Read the file and convert it to Byte Array<br/>
string filePath = FileUpload1.PostedFile.FileName;<br/>
string filename = Path.GetFileName(filePath);<br/>
string ext = Path.GetExtension(filename);<br/>
string contenttype = String.Empty;
//Set the contenttype based on File Extension<br/>
switch (ext)<br/>
{<br/>
case ".doc":<br/>
contenttype = "application/vnd.ms-word";<br/>
break;<br/>
case ".docx":<br/>
contenttype = "application/vnd.ms-word";<br/>
break;<br/>
case ".xls":<br/>
contenttype = "application/vnd.ms-excel";<br/>
break;<br/>
case ".xlsx":<br/>
contenttype = "application/vnd.ms-excel";<br/>
break;<br/>
case ".jpg":<br/>
contenttype = "image/jpg";<br/>
break;<br/>
case ".png":<br/>
contenttype = "image/png";<br/>
break;<br/>
case ".gif":<br/>
contenttype = "image/gif";<br/>
break;<br/>
case ".pdf":<br/>
contenttype = "application/pdf";<br/>
break;<br/>
}<br/>
if (contenttype != String.Empty)<br/>
{<br/>
<br/>
Stream fs = FileUpload1.PostedFile.InputStream;<br/>
BinaryReader br = new BinaryReader(fs);<br/>
Byte[] bytes = br.ReadBytes((Int32)fs.Length);<br/>
string strQuery = "INSERT INTO tbl_Media(MediaName, MediaType, MediaFile, MediaOwner) VALUES (@MediaName, @MediaType, @MediaFile, @MediaOwner)";<br/>
SqlCommand cmd = new SqlCommand(strQuery);<br/>
String owner = @Profile.UserName;<br/>
<br/>
cmd.Parameters.Add("@MediaName", SqlDbType.VarChar).Value = filename;<br/>
cmd.Parameters.Add("@MediaType", SqlDbType.VarChar).Value = contenttype;<br/>
cmd.Parameters.Add("@MediaFile", SqlDbType.Binary).Value = bytes;<br/>
cmd.Parameters.Add("@MediaOwner", SqlDbType.VarChar).Value = owner;<br/>
<br/>
InsertUpdateData(cmd);<br/>
lblMessage.ForeColor = System.Drawing.Color.Green;<br/>
lblMessage.Text = "File Uploaded Successfully";<br/>
}<br/>
else<br/>
{<br/>
lblMessage.ForeColor = System.Drawing.Color.Red;<br/>
lblMessage.Text = "File format not accepted. Upload Image/Word/PDF/Excel formats";<br/>
}<br/>
}<br/>
}
------------------------------------------------Handler.ashx-------------------------------------------------
<%@ WebHandler Language="C#" Class="Handler" %>
using System;<br/>
using System.Web;<br/>
using System.Configuration;<br/>
using System.Data;<br/>
using System.Data.SqlClient;<br/>
using System.Drawing;<br/>
using System.Drawing.Imaging;<br/>
using System.IO;
public class Handler : IHttpHandler<br/>
{
public void ProcessRequest(HttpContext context)<br/>
{<br/>
SqlConnection con = new SqlConnection();<br/>
con.ConnectionString = ConfigurationManager.ConnectionStrings<br/>
["MYCONNECTIONSTRINGHERE"].ConnectionString;
// Create SQL Command <br/>
SqlCommand cmd = new SqlCommand();<br/>
cmd.CommandText = "Select MediaID, MediaName, MediaType, MediaOwner, MediaImage from tbl_Media";<br/>
cmd.CommandType = System.Data.CommandType.Text;<br/>
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter<br/>
("@MediaID", System.Data.SqlDbType.Int);<br/>
ImageID.Value = context.Request.QueryString["MediaID"];<br/>
cmd.Parameters.Add(ImageID);<br/>
con.Open();<br/>
SqlDataReader dReader = cmd.ExecuteReader();<br/>
dReader.Read();<br/>
context.Response.BinaryWrite((byte[])dReader["MediaID"]);<br/>
dReader.Close();<br/>
con.Close();<br/>
}<br/>
}
-----------------------------------------------------------web.config------------------------------------------------
<?xml version="1.0"?><br/>
<!--<br/>
For more information on how to configure your ASP.NET application, please visit<br/>
http://go.microsoft.com/fwlink/?LinkId=169433 http://go.microsoft.com/fwlink/?LinkId=169433 <br/>
--><br/>
<configuration><br/>
<connectionStrings><br/>
<add name="MYCONNECTIONSTRINGHERE" connectionString="Data Source=DBHOSTADDRESS;Initial Catalog=INITIALDB;User ID=TESTUSER;Password=TESTPASS"<br/>
providerName="System.Data.SqlClient" /><br/>
</connectionStrings><br/>
<system.web><br/>
<customErrors defaultRedirect="~/Error.aspx"/><br/>
<authentication mode="Forms <br/>
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/><br/>
</authentication><br/>
<membership><br/>
<providers><br/>
<clear/><br/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/><br/>
</providers><br/>
</membership><br/>
<profile><br/>
<providers><br/>
<clear/><br/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/><br/>
</providers><br/>
<properties><br/>
<add name="CompanyName"/><br/>
<add name="FirstName" /><br/>
<add name="LastName"/><br/>
<add name="Address1"/><br/>
<add name="Address2"/><br/>
<add name="City"/><br/>
<add name="State"/><br/>
<add name="Zip"/><br/>
<add name="Phone"/><br/>
<add name="Email"/><br/>
</properties><br/>
</profile><br/>
<roleManager enabled="true <br/>
<providers><br/>
<clear/><br/>
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/><br/>
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider"/><br/>
</providers><br/>
</roleManager><br/>
<compilation debug="true"/><br/>
</system.web><br/>
<system.webServer><br/>
<modules runAllManagedModulesForAllRequests="true"/><br/>
</system.webServer><br/>
<system.net><br/>
<mailSettings><br/>
<smtp from= mailto:no-reply@test.com no-reply@test.com ><br/>
<network host="MYSMTPSERVER" password="" userName=""/><br/>
</smtp><br/>
</mailSettings><br/>
</system.net><br/>
</configuration>
View the full article
A little background first:
Im trying to setup a datagrid that will retrieve all fields from a table calle tbl_Media. The table has a key identity field called MediaID. The other fields are MediaName, MediaType, MediaOwner and MediaFile (an image type field). Ive
tested the below code and it correctly pulls all the table record data and places it in the gridview. However, the image column only shows nothing or a broken link icon depending on the browser Im testing. Ive spent the last 3 days trying to
get the images to display with no luck. Any help is very much appreciated. Thanks in advance for your help. Below is the code for Default.aspx, Default.aspx.cs, Handler.ashx and web.config:
----------------------------Default.aspx--------------------------------------
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile=" Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent <br/>
</asp:Content><br/>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent <br/>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large"
<br/>
Text="Main Media Page </asp:Label><br/>
<br /><br/>
<br /><br/>
<asp:Menu ID="Menu1" runat="server" BackColor="#B5C7DE" <br/>
DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em"
<br/>
ForeColor="#284E98" StaticSubMenuIndent="10px <br/>
<DynamicHoverStyle BackColor="#284E98" ForeColor="White" /><br/>
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /><br/>
<DynamicMenuStyle BackColor="#B5C7DE" /><br/>
<DynamicSelectedStyle BackColor="#507CD1" /><br/>
<Items><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Agreements/Default.aspx"
<br/>
Text="Official Documents" Value="Official Documents </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl=""
<br/>
Text="Billing" Value="Billing" Target="_blank </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Contact/Default.aspx"
<br/>
Text="Edit Contact Info" Value="Edit Contact Info </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Media/Default.aspx"
<br/>
Text="Media" Value="Media <br/>
</asp:MenuItem><br/>
<asp:MenuItem NavigateUrl=""
<br/>
Text="Project Collaboration" Value="Project Collaboration" Target="_blank </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/members/clients/pfcihconsulting/Remote/Default.aspx"
<br/>
Text="Remote Access" Value="Remote Access </asp:MenuItem><br/>
<asp:MenuItem NavigateUrl="~/Account/ChangePassword.aspx"
<br/>
Text="Change Password" Value="Change Password </asp:MenuItem><br/>
</Items><br/>
<StaticHoverStyle BackColor="#284E98" ForeColor="White" /><br/>
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /><br/>
<StaticSelectedStyle BackColor="#507CD1" /><br/>
</asp:Menu><br/>
<br /><br/>
This page allows your to upload and view files related to your project(s).
<br/>
If you have any files you'd like to add to your project, such as images,
<br/>
audio files, video files, web pages, pdf files, or zip files, click on the browse
<br/>
button below and navigate to the saved location of the file (i.e. Desktop, My
<br/>
Documents foler, etc.). This is very similar to the process of adding an
<br/>
attachment to an email. Once you click on the "Upload" button, please be
<br/>
patient. Depending on the size of the file you've selected to upload and
<br/>
your internet connection, the upload may take some time to load. Once the
<br/>
image is loaded, this page will reload and you will see a "File Uploaded
<br/>
Successfully!" message below the "Browse" button. <br/>
<asp:TextBox ID="MediaID" runat="server" Visible="False </asp:TextBox><br/>
<br /><br/>
Owner: <br/>
<asp:LoginName ID="LoginName1" runat="server" /><br/>
<br /><br/>
<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"<br/>
OnClick="btnUpload_Click" /><br/>
<br /><br/>
<asp:Label ID="lblMessage" runat="server" Text=""<br/>
Font-Names = "Arial </asp:Label> <br /><br/>
<br /><br/>
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Italic="True"
<br/>
Text="All Uploaded Project Files </asp:Label><br/>
<br /><br/>
<br /><br/>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
<br/>
AutoGenerateColumns="False" DataKeyNames="MediaID"
<br/>
DataSourceID="SqlDataSource1" HorizontalAlign="Center" Width="500px <br/>
<Columns><br/>
<asp:BoundField DataField="MediaID" HeaderText="MediaID" InsertVisible="False"
<br/>
ReadOnly="True" SortExpression="MediaID" /><br/>
<asp:BoundField DataField="MediaName" HeaderText="MediaName"
<br/>
SortExpression="MediaName" /><br/>
<asp:BoundField DataField="MediaType" HeaderText="MediaType"
<br/>
SortExpression="MediaType" /><br/>
<asp:BoundField DataField="MediaOwner" HeaderText="MediaOwner"
<br/>
SortExpression="MediaOwner" /><br/>
<asp:TemplateField HeaderText="Image <br/>
<ItemTemplate><br/>
<asp:Image MediaID="Image1" runat="server" Width="200px" ImageUrl=<%# "Handler.ashx?MediaID=" + Eval("MediaID")%>
/><br/>
</ItemTemplate><br/>
</asp:TemplateField><br/>
</Columns><br/>
</asp:GridView><br/>
<br /><br/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" <br/>
ConnectionString="<%$ ConnectionStrings:MYCONNECTIONSTRINGHERE %>"
<br/>
SelectCommand="SELECT * FROM [tbl_Media]"
<br/>
ConflictDetection="CompareAllValues" <br/>
DeleteCommand="DELETE FROM [tbl_Media] WHERE [MediaID] = @original_MediaID AND (([MediaName] = @original_MediaName) OR ([MediaName] IS NULL AND @original_MediaName IS NULL)) AND (([MediaType] = @original_MediaType)
OR ([MediaType] IS NULL AND @original_MediaType IS NULL)) AND (([MediaFile] = @original_MediaFile) OR ([MediaFile] IS NULL AND @original_MediaFile IS NULL)) AND (([MediaOwner] = @original_MediaOwner) OR ([MediaOwner] IS NULL AND @original_MediaOwner IS NULL))"
<br/>
InsertCommand="INSERT INTO [tbl_Media] ([MediaName], [MediaType], [MediaFile], [MediaOwner]) VALUES (@MediaName, @MediaType, @MediaFile, @MediaOwner)"
<br/>
OldValuesParameterFormatString="original_{0}"
<br/>
UpdateCommand="UPDATE [tbl_Media] SET [MediaName] = @MediaName, [MediaType] = @MediaType, [MediaFile] = @MediaFile, [MediaOwner] = @MediaOwner WHERE [MediaID] = @original_MediaID AND (([MediaName] = @original_MediaName)
OR ([MediaName] IS NULL AND @original_MediaName IS NULL)) AND (([MediaType] = @original_MediaType) OR ([MediaType] IS NULL AND @original_MediaType IS NULL)) AND (([MediaFile] = @original_MediaFile) OR ([MediaFile] IS NULL AND @original_MediaFile IS NULL))
AND (([MediaOwner] = @original_MediaOwner) OR ([MediaOwner] IS NULL AND @original_MediaOwner IS NULL)) <br/>
<DeleteParameters><br/>
<asparameter Name="original_MediaID" Type="Int64" /><br/>
<asparameter Name="original_MediaName" Type="String" /><br/>
<asparameter Name="original_MediaType" Type="String" /><br/>
<asparameter Name="original_MediaFile" Type="Object" /><br/>
<asparameter Name="original_MediaOwner" Type="String" /><br/>
</DeleteParameters><br/>
<InsertParameters><br/>
<asparameter Name="MediaName" Type="String" /><br/>
<asparameter Name="MediaType" Type="String" /><br/>
<asparameter Name="MediaFile" Type="Object" /><br/>
<asparameter Name="MediaOwner" Type="String" /><br/>
</InsertParameters><br/>
<UpdateParameters><br/>
<asparameter Name="MediaName" Type="String" /><br/>
<asparameter Name="MediaType" Type="String" /><br/>
<asparameter Name="MediaFile" Type="Object" /><br/>
<asparameter Name="MediaOwner" Type="String" /><br/>
<asparameter Name="original_MediaID" Type="Int64" /><br/>
<asparameter Name="original_MediaName" Type="String" /><br/>
<asparameter Name="original_MediaType" Type="String" /><br/>
<asparameter Name="original_MediaFile" Type="Object" /><br/>
<asparameter Name="original_MediaOwner" Type="String" /><br/>
</UpdateParameters><br/>
</asp:SqlDataSource><br/>
<br /><br/>
</asp:Content>
------------------------------------------------Default.aspx.cs---------------------------------------------
using System;<br/>
using System.Data;<br/>
using System.Data.SqlClient;<br/>
using System.Configuration;<br/>
using System.Web;<br/>
using System.Web.Security;<br/>
using System.Web.UI;<br/>
using System.Web.UI.WebControls;<br/>
using System.Web.UI.WebControls.WebParts;<br/>
using System.Web.UI.HtmlControls;<br/>
using System.IO;<br/>
using System.Drawing.Imaging;<br/>
using System.Drawing;
public partial class _Default : System.Web.UI.Page<br/>
{<br/>
protected void Page_Load(object sender, EventArgs e)<br/>
{
}
private Boolean InsertUpdateData(SqlCommand cmd)<br/>
{<br/>
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MYCONNECTIONSTRINGHERE"].ConnectionString;<br/>
SqlConnection con = new SqlConnection(strConnString);<br/>
cmd.CommandType = CommandType.Text;<br/>
cmd.Connection = con;<br/>
try<br/>
{<br/>
con.Open();<br/>
cmd.ExecuteNonQuery();<br/>
return true;<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
Response.Write(ex.Message);<br/>
return false;<br/>
}<br/>
finally<br/>
{<br/>
con.Close();<br/>
con.Dispose();<br/>
}<br/>
}
protected void btnUpload_Click(object sender, EventArgs e)<br/>
{<br/>
// Read the file and convert it to Byte Array<br/>
string filePath = FileUpload1.PostedFile.FileName;<br/>
string filename = Path.GetFileName(filePath);<br/>
string ext = Path.GetExtension(filename);<br/>
string contenttype = String.Empty;
//Set the contenttype based on File Extension<br/>
switch (ext)<br/>
{<br/>
case ".doc":<br/>
contenttype = "application/vnd.ms-word";<br/>
break;<br/>
case ".docx":<br/>
contenttype = "application/vnd.ms-word";<br/>
break;<br/>
case ".xls":<br/>
contenttype = "application/vnd.ms-excel";<br/>
break;<br/>
case ".xlsx":<br/>
contenttype = "application/vnd.ms-excel";<br/>
break;<br/>
case ".jpg":<br/>
contenttype = "image/jpg";<br/>
break;<br/>
case ".png":<br/>
contenttype = "image/png";<br/>
break;<br/>
case ".gif":<br/>
contenttype = "image/gif";<br/>
break;<br/>
case ".pdf":<br/>
contenttype = "application/pdf";<br/>
break;<br/>
}<br/>
if (contenttype != String.Empty)<br/>
{<br/>
<br/>
Stream fs = FileUpload1.PostedFile.InputStream;<br/>
BinaryReader br = new BinaryReader(fs);<br/>
Byte[] bytes = br.ReadBytes((Int32)fs.Length);<br/>
string strQuery = "INSERT INTO tbl_Media(MediaName, MediaType, MediaFile, MediaOwner) VALUES (@MediaName, @MediaType, @MediaFile, @MediaOwner)";<br/>
SqlCommand cmd = new SqlCommand(strQuery);<br/>
String owner = @Profile.UserName;<br/>
<br/>
cmd.Parameters.Add("@MediaName", SqlDbType.VarChar).Value = filename;<br/>
cmd.Parameters.Add("@MediaType", SqlDbType.VarChar).Value = contenttype;<br/>
cmd.Parameters.Add("@MediaFile", SqlDbType.Binary).Value = bytes;<br/>
cmd.Parameters.Add("@MediaOwner", SqlDbType.VarChar).Value = owner;<br/>
<br/>
InsertUpdateData(cmd);<br/>
lblMessage.ForeColor = System.Drawing.Color.Green;<br/>
lblMessage.Text = "File Uploaded Successfully";<br/>
}<br/>
else<br/>
{<br/>
lblMessage.ForeColor = System.Drawing.Color.Red;<br/>
lblMessage.Text = "File format not accepted. Upload Image/Word/PDF/Excel formats";<br/>
}<br/>
}<br/>
}
------------------------------------------------Handler.ashx-------------------------------------------------
<%@ WebHandler Language="C#" Class="Handler" %>
using System;<br/>
using System.Web;<br/>
using System.Configuration;<br/>
using System.Data;<br/>
using System.Data.SqlClient;<br/>
using System.Drawing;<br/>
using System.Drawing.Imaging;<br/>
using System.IO;
public class Handler : IHttpHandler<br/>
{
public void ProcessRequest(HttpContext context)<br/>
{<br/>
SqlConnection con = new SqlConnection();<br/>
con.ConnectionString = ConfigurationManager.ConnectionStrings<br/>
["MYCONNECTIONSTRINGHERE"].ConnectionString;
// Create SQL Command <br/>
SqlCommand cmd = new SqlCommand();<br/>
cmd.CommandText = "Select MediaID, MediaName, MediaType, MediaOwner, MediaImage from tbl_Media";<br/>
cmd.CommandType = System.Data.CommandType.Text;<br/>
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter<br/>
("@MediaID", System.Data.SqlDbType.Int);<br/>
ImageID.Value = context.Request.QueryString["MediaID"];<br/>
cmd.Parameters.Add(ImageID);<br/>
con.Open();<br/>
SqlDataReader dReader = cmd.ExecuteReader();<br/>
dReader.Read();<br/>
context.Response.BinaryWrite((byte[])dReader["MediaID"]);<br/>
dReader.Close();<br/>
con.Close();<br/>
}<br/>
}
-----------------------------------------------------------web.config------------------------------------------------
<?xml version="1.0"?><br/>
<!--<br/>
For more information on how to configure your ASP.NET application, please visit<br/>
http://go.microsoft.com/fwlink/?LinkId=169433 http://go.microsoft.com/fwlink/?LinkId=169433 <br/>
--><br/>
<configuration><br/>
<connectionStrings><br/>
<add name="MYCONNECTIONSTRINGHERE" connectionString="Data Source=DBHOSTADDRESS;Initial Catalog=INITIALDB;User ID=TESTUSER;Password=TESTPASS"<br/>
providerName="System.Data.SqlClient" /><br/>
</connectionStrings><br/>
<system.web><br/>
<customErrors defaultRedirect="~/Error.aspx"/><br/>
<authentication mode="Forms <br/>
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/><br/>
</authentication><br/>
<membership><br/>
<providers><br/>
<clear/><br/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/><br/>
</providers><br/>
</membership><br/>
<profile><br/>
<providers><br/>
<clear/><br/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/><br/>
</providers><br/>
<properties><br/>
<add name="CompanyName"/><br/>
<add name="FirstName" /><br/>
<add name="LastName"/><br/>
<add name="Address1"/><br/>
<add name="Address2"/><br/>
<add name="City"/><br/>
<add name="State"/><br/>
<add name="Zip"/><br/>
<add name="Phone"/><br/>
<add name="Email"/><br/>
</properties><br/>
</profile><br/>
<roleManager enabled="true <br/>
<providers><br/>
<clear/><br/>
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/><br/>
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider"/><br/>
</providers><br/>
</roleManager><br/>
<compilation debug="true"/><br/>
</system.web><br/>
<system.webServer><br/>
<modules runAllManagedModulesForAllRequests="true"/><br/>
</system.webServer><br/>
<system.net><br/>
<mailSettings><br/>
<smtp from= mailto:no-reply@test.com no-reply@test.com ><br/>
<network host="MYSMTPSERVER" password="" userName=""/><br/>
</smtp><br/>
</mailSettings><br/>
</system.net><br/>
</configuration>
View the full article