0

I have a DB with 3 tables one of which has uploaded images from users with a profile page each.I had managed to show the pictures with gridview in login and search but it wasn't very pleasing to the eye so i decided to follow the asp:image method :)

What i can't do now tho, is show the image referred to the user loging in or the user's profile that's been shown after the search.

So if i find a way to pass the id to the handler? or...?

Thanks for any help!

Default.aspx.cs (stuff happens at Imageupload() and ImagebindGrid() i have bypassed the gridview code so i can try to show it with the other way.

 using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Security.Principal;
using System.Data.Common;



namespace DisplayingImages
{
public partial class Default : System.Web.UI.Page
{

    public string query, constr, query1, query2, query3;
    public SqlConnection con, conn;
    public void connection()
    {
        constr = ConfigurationManager.ConnectionStrings["Myconnection"].ToString();
        con = new SqlConnection(constr);
        con.Open();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Visible = false;
        if (!IsPostBack)
        {


            EM = (string)(Session["Email_Account"]); 
            lblemail.Text = EM;
            SN = Convert.ToString(Session["Surname"]);
            lblname.Text = SN; 
            PS = (string)(Session["Password"]);
            PID = (int)(Session["id"]);
            HttpContext context = HttpContext.Current;
            context.Session["Email_Account"] = EM;
            EM = (string)(context.Session["Email_Account"]);
            if (PID == null)
            {
                Response.Redirect("Login.aspx");
            }
            imagebindGrid();
            PostSelection();


        }
    }

    private void InitializeComponent()
    {
        throw new NotImplementedException();
    }


    protected void upload(object sender, EventArgs e) // button για το upload της φωτο. Καλειται η κλαση Imageupload()
    {

        Imageupload();
    }
    /* Κλασση για upload εικονας . Ελεγχος και περασμα εικονας */
    private void Imageupload()
    {
        if (FileUpload1.HasFile)
        {
            PID = (int)(Session["id"]);
            if (PID != null)
            {
                int imagefilelenth = FileUpload1.PostedFile.ContentLength;
                byte[] imgarray = new byte[imagefilelenth];
                HttpPostedFile image = FileUpload1.PostedFile;
                image.InputStream.Read(imgarray, 0, imagefilelenth);
                connection();
                query = "Insert into  ImageToDB (user_id,ImageName,Image) values (@user_id,@Name,@Image)";
                SqlCommand com = new SqlCommand(query, con);
                com.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
                com.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = imgarray;
                com.Parameters.AddWithValue("@user_id", PID);
                com.ExecuteNonQuery();
                Label1.Visible = true;
                Label1.Text = "Image Is Uploaded successfully";
                imagebindGrid();

            }
        }
    }
    /* Gridview για εικονες */
    public void imagebindGrid()
    {
        connection();
        query = "Select id,ImageName,Image from ImageToDB where user_id= " + PID;
        SqlCommand com = new SqlCommand(query, con);
        SqlDataReader dr = com.ExecuteReader();
        //Image.ImageUrl = "/Handler.ashx?id_Image=" + PID.ToString();      


        //Gridview1.DataSource = dr;
        //Gridview1.DataBind();


    }
    /*Logout Button */
    protected void Button1_Click(object sender, EventArgs e)
    {

        System.Web.Security.FormsAuthentication.SignOut();
        Session.Clear();
        Session.RemoveAll();
        Session.Abandon();
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
        HttpContext.Current.Response.AddHeader("Expires", "0");
        FormsAuthentication.SignOut();
        HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
        Response.Redirect("~/Logout.aspx");
    }
    /* Κλασση για το Post */
    private void Txt()
    {
        try
        {
            PID = (int)(Session["id"]);
            if (PID != null)
            {
                connection();
                query1 = "Insert into  Posttext (user_id,Posttext) values (@user_id,@Your_Post)";
                SqlCommand com2 = new SqlCommand(query1, con);
                com2.Parameters.AddWithValue("@Your_Post", SqlDbType.VarChar).Value = PostBox.Text;
                com2.Parameters.AddWithValue("@user_id", PID);
                com2.ExecuteNonQuery();
                lbluser.Text = PostBox.Text;
                PostSelection();
            }

        }



        catch (Exception ex)
        {
            //con.Close();
        }

    }
    /* Κανει select τα κειμενα και τα ανεβαζει απο την βαση στο grid */
    public void PostSelection()
    {
        connection();

        query2 = "Select Posttext from Posttext where user_id= " + PID;
        SqlCommand com1 = new SqlCommand(query2, con);
        SqlDataReader Read = com1.ExecuteReader();
        grdemployee7.DataSource = Read;
        grdemployee7.DataBind();
        Read.Close();

    }
    /* Καλειται η Txt() για να γινει το Post */
    protected void Button2_Click(object sender, EventArgs e)
    {
        Txt();
    }

    public string USER_PID { get; set; }
    public DateTime _myid { get; set; }

    /* --------------------Κουμπι για search PROFILE -----------------------------------*/
    public void Button3_Click1(object sender, EventArgs e)
    {
                Response.Redirect("~/WebForm7.aspx");
    }

    public string SN { get; set; }
    public string PS { get; set; }
    public string EM { get; set; }
    public int PID { get; set; }

    protected void PostBox_TextChanged(object sender, EventArgs e)
    {

    }
}
}

here is my handler

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace DisplayingImages
{
/// <summary>
/// Summary description for Handler1
/// this application is created by vithal wadje for C# corner
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Handler1 : IHttpHandler
{
    //createting the object of Default.aspx class page to 
    //call connection and use strings variable
    Default cls = new Default();

    public void ProcessRequest(HttpContext context)
    {
        //storing the querystring value that comes from Defaul.aspx page

        string displayimgid = context.Request.QueryString["id_Image"].ToString();
        cls.connection();
        //retriving the images on the basis of id of uploaded 
        //images,by using the querysting valaues which comes from Defaut.aspx page
        cls.query = "select Image from ImageToDB where id=" + displayimgid;
        SqlCommand com = new SqlCommand(cls.query, cls.con);
        SqlDataReader dr = com.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        context.Response.End();

    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}
}

and here is the way i try to pass the id

<asp:Image ID="Image" runat="server" ImageUrl='<%# "Handler1.ashx?id_Image="+ Eval("id") %>' "/>

The code might seem a bit messy, but im trying some things without any success.

Thanks again!!

frcake
  • 229
  • 1
  • 3
  • 18
  • What happens when you execute that handler directly in your browser? – Patrick Hofman Oct 15 '14 at 12:15
  • 1
    Please note that you have a SQL injection vulnerability in your code. You should never treat user input as *executable SQL code*. (In some of your queries you already use parameters to prevent this. Why not use them in *all* of your queries?) More to the point... Where/how exactly does this code fail? Is the URL rendering correctly? Is it requesting the handler correctly? Is the handler responding with the image data? Where is the problem exactly? – David Oct 15 '14 at 12:16
  • yes i will fix all these SQL insecurities, thank you for mentioning! :) – frcake Oct 15 '14 at 12:46
  • the code is just not showing the image, when i was putting static id_Image=1 at .aspx it was showing the 1st pic of the Table but for every user... now im trying the dynamic approach that changes the picture depending on user id! – frcake Oct 15 '14 at 12:48

1 Answers1

0

You need to setup contenttype for this. Else it will be binary only. Use this .

context.Response.ContentType = "image/png";

This depends on which type of image you are writing. So based on that use image/jpg etc.

Apart from this, i can see in your code, you have used imagebindGrid to bind image to grid by querying to SQL, but you have not used dr.Read() before binding to grid, this will not open rowset and hence no data is bind and you are not seeing new image. So new code will be like following.

 SqlDataReader dr = com.ExecuteReader();
 dr.Read();
 Gridview1.DataSource = dr;
 Gridview1.DataBind();

If you can show aspx code where you have Gridview1, that will be more helpful to help you, in case you face issue after changing this.

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
  • Yes, but this is not the actual image file, and you are intercepting this, so content type has to be set in the interceptor. To verify this, load the page with – Arindam Nayak Oct 15 '14 at 12:19
  • Because browser needs to interpret binary data as image, else it is just text response to browser, you can see the browser console, it will say that error, See some helpful post - http://stackoverflow.com/questions/3467404/chrome-says-resource-interpreted-as-script-but-transferred-with-mime-type-text, this might not be related to OP's problem, but still a good example of what i am trying to explain. – Arindam Nayak Oct 15 '14 at 12:21
  • You might be right. Will remove comment. Let OP check it. – Patrick Hofman Oct 15 '14 at 12:22
  • well i changed it to img src="" and got the context response in the code but nothing, the real problem is the id parsing to the id_Image (html) , cause when i use a static number such as i get the picture fine! – frcake Oct 15 '14 at 13:13
  • @frcake , i can see in your code, you have used `imagebindGrid` to bind image to grid by querying to SQL, but you have not used `dr.Read()` before binding to grid, this will not open rowset and hence no data is bind and you are not seeing new image. – Arindam Nayak Oct 15 '14 at 14:55
  • ah no sorry man, the real actual problem is parsing the id of the default page to the HTML code calling the handler – frcake Oct 16 '14 at 05:51
  • I can see that you have set `PID` from session, my question is, are you able to get that from `session` or is that in `querystring`? – Arindam Nayak Oct 16 '14 at 05:54