Link to home
Start Free TrialLog in
Avatar of Peter Chan
Peter ChanFlag for Hong Kong

asked on

Problem to picture file

Hi,
Further to this
https://www.experts-exchange.com/questions/29029100/Problem-to-show-list.html?anchor=a42174635¬ificationFollowed=190745230&anchorAnswerId=42174635#a42174635

and I have ImageHandler.cs like
using System;
using System.IO;
using System.IO.Compression;
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.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Data.OleDb;
using System.Xml;
using System.Globalization;
using System.Collections.Generic;
using System.Drawing;
using System.Text; // This was needed to make ASCIIEncoding function
using System.Security.Cryptography; // This was needed to make everything related to MD5 function
using System.Web.Services;

namespace Own_rec
{
    public class ImageHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            //string userId = string.Empty;
            int userId = 0;
            //-- get the ID from query string you get from <img src tag
            if (null != context.Request.QueryString &&
                !string.IsNullOrEmpty(context.Request.QueryString["ImID"]))
                userId = Convert.ToInt32(context.Request.QueryString["ImID"]);

            OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=213461;Data Source=C:\inetpub\VS2012\DB1.accdb");
            try
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand("SELECT [photo_file] FROM [user_pict] where [user_id]=@par_id", conn);
                cmd.Parameters.Add("@par_id", OleDbType.Integer).Value = userId;
                byte[] bArray = (byte[])cmd.ExecuteScalar();
                if (bArray != null)
                    context.Response.BinaryWrite(bArray);
            }
            catch (System.Data.SqlClient.SqlException)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
...
                using (SqlCommand sqlCmd = new SqlCommand("SELECT house_name, address1, address2, price, price_curr, ltrim(rtrim(cast(raised_by_user_id as varchar))) raised_by_user_id FROM house_tab", sqlConn))
                {
                    sqlConn.Open();
                    sqlCmd.CommandType = CommandType.Text;
                    SqlDataAdapter sqlAd = new SqlDataAdapter(sqlCmd);
                    DataTable sqlDt = new DataTable();
                    sqlAd.Fill(sqlDt);
                    sqlConn.Close();
                    if (null != sqlDt)
                    {
                        houseList = sqlDt
                                        .AsEnumerable()
                                        .Select(dataRow => new HouseData
                                        {
                                            house_name = dataRow.Field<string>("house_name"),
                                            address1 = dataRow.Field<string>("address1"),
                                            address2 = dataRow.Field<string>("address2"),
                                            price = dataRow.Field<decimal>("price"),
                                            price_curr = dataRow.Field<string>("price_curr"),
                                            raised_by_user_id = dataRow.Field<string>("raised_by_user_id"),
                                        })
                                        .ToList();
                    }
                }
            }
            return houseList;
            ...
        success: function (response) {
            var html = "";
            $.each(response.d, function (index, house) {
                html += "<dl><dt>" + house.house_name + "</dt>";
                html += "<dd>" + house.address1 + "</dd>";
                html += "<dd>" + house.address2 + "</dd>";
                html += "<dd>" + house.price + " ";
                html += house.price_curr + "</dd>";
                var dd = (house.house_name != "") ? "<img src='ImageHandler.ashx?ImID=" + house.raised_by_user_id + "' />" : "";
                html += "<dd>" + dd + "</dd>";
            });
            if (html != "")
                $("#houses").html(html);
        },

Open in new window

and now only problem is that I cannot show the picture file below, as expected.

http://my-friend.co/Test_rec4/Default.aspx?userid=mc23
Avatar of Peter Chan
Peter Chan
Flag of Hong Kong image

ASKER

Good afternoon Andrew.
No, the list is shown in there, right above the message in color.
check this

How to: Register HTTP Handlers
https://msdn.microsoft.com/en-us/library/46c5ddfy.aspx

need something like this in your web.config

<configuration>
  <system.web>
    <httpHandlers>
       <!-- Simple Handler -->
       <add verb="*" path="*.ashx" 
         type="skmHttpHandlers.SimpleHandler, skmHttpHandlers" />
    </httpHandlers>
  </system.web>
</configuration>

Open in new window


check this as well

https://msdn.microsoft.com/en-us/library/ms972953.aspx
Hi Huseyin,
I've applied your change but then I get this issue

Server Error

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
what do you have in your web.config?

it should be something like this

<add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />

Open in new window

by the way, page is requesting image like this

http://my-friend.co/Test_rec4/ImageHandler.ashx?ImID=12

Open in new window

                 

for reference...
post your web config file...

* remove any confidential data
Hi,
Here is Web.config file

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
      <httpHandlers>
        <!-- Simple Handler -->
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers>      
    </system.web>

</configuration>

Open in new window

but after re-deployment, I still get this

Server Error

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
restart your server / pool
check your app pool and make sure it is .Net 4.5

web config looks good...
I re-started the server but I still get problem - 500.
are you getting 500 after changing the web.config?
comment out that and restart to see if thats the issue...
Yes, I get 500 error, even if I've re-started the server.
what is EXACT message? + details for that message?

"HTTP Error 500.0 – Internal Server Error" error when you you open an IIS 7.0 Webpage
https://support.microsoft.com/en-us/help/942031/-http-error-500.0-internal-server-error-error-when-you-you-open-an-iis-7.0-webpage
Here is the exact error
Server Error

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
or you can go to

http://my-friend.co/Test_rec4/Default.aspx?userid=mc23
did you remove

      <httpHandlers>
        <!-- Simple Handler -->
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers> 

Open in new window


and restart?
Here is Web.config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
      <httpHandlers>
        <!-- Simple Handler -->
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers>      
    </system.web>

</configuration>

Open in new window

do you mean I now need to remove "httpHandlers"?
just comment out line 23 or delete
and restart... just to see if it is the issue...
Yes, I remark that line then I do not have error "500" but the problem is that I still cannot show the picture file.
what version of IIS are you using?
also what is the mode/.net version of app pool for that web site?
what happens when you use this?

<add verb="*" path="ImageHandler.ashx" type="Own_rec.ImageHandler, Own_rec" />

Open in new window

what version of IIS are you using?
also what is the mode/.net version of app pool for that web site?

Many thanks. What do you want to see, below?
User generated image
right click on site (left side, not on image above)
manage application - advanced settings
get the Application Pool value

then click Application pools on left side, and tell what are the pool properties
.net framework
managed?
Sorry, what to choose below?
User generated image
Application pools - VS2012

what are the properties
Sorry, where to choose property below?
User generated image
Application pools - VS2012

what are the properties
then click Application pools on left side, and tell what are the pool properties
.net framework
managed?
it is on top, left side!
Sorry, what to choose below?
User generated image
ok it is integrated mode, v4.0

add this to web.config

<configuration>
...
<system.webServer>
      <httpHandlers>
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers>      
</system.webServer>

</configuration>

Open in new window


check the link below, if you have any issues...
Read "To register an HTTP handler for IIS 7.0 running in Integrated Mode" section...

How to: Register HTTP Handlers
https://msdn.microsoft.com/en-us/library/46c5ddfy.aspx
Here is current Web.config file
<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
      <httpHandlers>
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers>      
    </system.web>
</configuration>

Open in new window

after re-deployment, I still get
Server Error

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.

Open in new window

you are not careful!

check my last post and compare the code with your web.config

mine uses

<system.webServer>
Yes, I did try it with
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=Ws345678" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=Ws345678" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
<system.webServer>
      <httpHandlers>
        <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
      </httpHandlers>      
</system.webServer>

</configuration>

Open in new window


and still get error - 500, and httpHandlers is highlighted below
User generated image
try

httpHandlers
>>>
handlers


in config file...
add is underlined, using handler below
User generated image
whats the issue? underline does not say anything to me...
maybe you need to add

name="MyImageHandler"

Open in new window

I still get error 500 using these
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=123456" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
    <system.webServer>
          <handlers>
            <add verb="*" path="*.ashx" type="Own_rec.ImageHandler, Own_rec" />
          </handlers>      
    </system.webServer>

</configuration>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
also try these one by one

<add name="MyImageHandler" verb="*" path="*.ashx" type="ImageHandler, Own_rec" resourceType="Unspecified" />
<add name="MyImageHandler" verb="*" path="*.ashx" type="Own_rec, ImageHandler" resourceType="Unspecified" />
<add name="MyImageHandler" verb="*" path="*.ashx" type="Own_rec, Own_rec.ImageHandler" resourceType="Unspecified" />

Open in new window

Using these
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
      <!--
      <add name="SqlConnectionString"
   connectionString="Data Source=XE;Persist Security Info=True;User Id=web_schema;Password=ws1317" providerName="System.Data.OracleClient" />
      -->
      <add name="Mssqlconn2" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=web_schema;Integrated Security=False;User ID=ws_login;Password=Ws345678" providerName="System.Data.SqlClient"/>
      <add name="Mssqlconn3" connectionString="Data Source=WIN-0NGDCBCTNKP\SS2012EXPR;Initial Catalog=house_sch;Integrated Security=False;User ID=ws_login;Password=Ws345678" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
      <customErrors mode="Off"/>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
    <system.webServer>
          <handlers>
            <add name="MyImageHandler" verb="*" path="*.ashx" type="ImageHandler, Own_rec" resourceType="Unspecified" />
            <add name="MyImageHandler" verb="*" path="*.ashx" type="Own_rec, ImageHandler" resourceType="Unspecified" />
            <add name="MyImageHandler" verb="*" path="*.ashx" type="Own_rec, Own_rec.ImageHandler" resourceType="Unspecified" />
    </handlers>      
    </system.webServer>

</configuration>

Open in new window

I still get error - 500, after re-deployment.
I meant try one by one not all 3 :)

also, if still does not work, check the link above...
you got your code from that page...
I am getting

Server Error in '/Test_rec4' Application.

Could not load file or assembly 'Own_rec.ImageHandler' or one of its dependencies. The system cannot find the file specified.

did you copy dlls to bin folder your web server?
Thanks a lot to you!
I see the same version of Own_rec.dll (from my project) is currently existing within

C:\inetpub\VS2012\Test_rec4\bin
still it is not found

http://my-friend.co/Test_rec4/ImageHandler.ashx?ImID=12

Could not load file or assembly 'Own_rec.ImageHandler' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Own_rec.ImageHandler' or one of its dependencies. The system cannot find the file specified.
omg, you finally solved your issue :)

http://my-friend.co/Test_rec4/ImageHandler.ashx?ImID=12

but I guess you should set the headers as

context.Response.ContentType = "image/jpeg"
context.Response.AddHeader("Cache-Control", "private,must-revalidate,post-check=1,pre-check=2,no-cache")

Open in new window


right now, I see text...

BMîT6(ÎjÃÃöööööööööö...

Open in new window


I should see image
the context.Response.ContentType can be

image/*
image/xyz

or find the image type from extension and use it

image/bmp
image/jpeg
image/png

see available formats here
http://www.iana.org/assignments/media-types/media-types.xhtml#image