Question

I am now having problem of deploying my website to a shared windows hosting.

I am currently hosting it with hostgator.

The problem is, my ThumbnailHandler which is supposed to return an image file, stopped working once the project is deployed to web server. It works properly in local IIS virtual folder, and vs2010 debug.

e.g-

http://www.myweb.com/imageHandler.ashx?i=0 - ERROR

http://www.myweb.com/imageHandler.ashx - ERROR

http://www.myweb.com/image-handler?i=0 - (routed with IRouteHandler) ERROR

http://www.myweb.com/img/theimage.jpg - OK !

No exception is thrown. If I open the url, it returns 'The image (path) cannot be displayed because it contains error'.

ThumbnailHandler.ashx

public void ProcessRequest(HttpContext context) {
    context.Response.Flush();
    Size maxSize = new Size(98, 98);
    byte[] buffer = Imaging.GetImage(context.Server.MapPath("~/img/noimage98.png"), maxSize).GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
    try {
        Int32 index = GetImageIndex(context);
        maxSize = GetMaxSize(context);
        if (index < 0 || maxSize == null)
            throw new Exception("Index size is not specified.");
        String authToken = GetAuthenticationToken(context);
        DirectoryInfo directoryInfo = AdvertisementDirectory.GetDirectoryInfo(authToken);
        List<FileInfo> fileInfos = AdvertisementDirectory.GetImageFileInfoList(directoryInfo);
        using (System.Drawing.Image thumbnailImage = Imaging.GetImage(fileInfos[index].FullName, maxSize)) {
            buffer = thumbnailImage.GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
    catch (Exception ex) {
        throw ex;
    }
    finally {
        context.Response.ContentType = "image/jpeg";
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        context.Response.Flush();
        context.Response.Close();
        context.ApplicationInstance.CompleteRequest();
    }
}
public bool IsReusable { get { return false; } }

web.config

<globalization requestEncoding="iso-8859-1" responseEncoding="iso-8859-1" fileEncoding="utf-8" culture="en-US" uiCulture="en-US"/>

<pages buffer="true" clientIDMode="Static" controlRenderingCompatibilityVersion="4.0" enableViewStateMac="true" validateRequest="true" enableEventValidation="true" enableSessionState="true" viewStateEncryptionMode="Auto" >
  <controls>
    <add tagPrefix="ATK" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
  </controls>
</pages>

<httpHandlers>
  <add verb="*" path="*.ashx" type="Tradepost.ThumbnailHandler, Tradepost"/>
</httpHandlers>

<httpRuntime executionTimeout="600" maxRequestLength="40000" maxUrlLength="260" maxQueryStringLength="2048" requestLengthDiskThreshold="80" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="5000" enableKernelOutputCache="true" enableVersionHeader="true" requireRootedSaveAsPath="true" enable="true" shutdownTimeout="90" delayNotificationTimeout="5" waitChangeNotification="0" maxWaitChangeNotification="0" enableHeaderChecking="true" sendCacheControlHeader="true" apartmentThreading="false" requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Has anyone experienced this before? I've also tried to check folder permission security setting. Any help is appreciated, thanks in advance.

Note: This occurs to any images in any folder.

Was it helpful?

Solution 2

Ok, I found out the issue. Literally my host provider doesn't support full trust policy, so I had to change it to medium trust. Even if I set the full trust on my web.config, It'll just change it back to medium trust or display the error.

So, the error occured on my 'GetImage' function, which was

public static System.Drawing.Image GetImage(String fileName, System.Drawing.Size maxSize) {
    System.Drawing.Image result = null;
    try {
        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(fs, true, false)) {
                Size sz = GetProportionalSize(maxSize, img.Size);
                result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
                }
            fs.Close();
        }
    }
    catch (Exception ex) {
        throw ex;
    }
    return result;
}

or

using (FileStream fs = File.OpenRead(fileName)) {
    using (StreamReader sr = new StreamReader(fs)) {
        using (System.Drawing.Image img = System.Drawing.Image.FromStream(sr.BaseStream, true, false)) {
            System.Drawing.Size sz = GetProportionalSize(maxSize, img.Size);
            result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
        }
        sr.Close();
    }
    fs.Close();
}

and throws...

System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer

BUT, I still don't know WHY the following code WORKS

using (System.Drawing.Image img = System.Drawing.Image.FromFile(fileName)) {
    System.Drawing.Size sz = GetProportionalSize(maxSize, img.Size);
    result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
}

I've tested it with my host provider and my local IIS with this in my web.config

<trust level="Medium" originUrl=""/>

Anyway, it works now. I still haven't got the right time to find out why Stream type object would act differently to Image.FromFile, since what I know is those two still streams for the file. I'll post more update if I found out something interesting.

Cheers.

OTHER TIPS

When Images are load in img folder , img folder have no access to read/write files. So first give all access to img folder to read and write images .

or you try to give full path of image because some time client server have different root path So Server.MapPath

not get exact path of image .

May you try path of starting domain name define in web.config appsetting control and then this path use in handler to get path of images.

<appSettings>
        <add key="ProjectName" value="/www.myweb.com"/>
</appSettings>

In handler page use

string ProjectName = System.Configuration.ConfigurationManager.AppSettings["ProjectName"].ToString().Trim();
byte[] buffer = Imaging.GetImage(ProjectName+"/img/noimage98.png", maxSize).GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top