Medium Trust FileUpload

unicode

Guppy
Hi,

Anyone has tried getting FileUpload working on JH Servers (Medium Trust Enviorment) - using ASP.NET - C#

We've tried a whole lot of stuff using Virtual / Physical Path - nothing works.

What's happening - is the moment we are putting a FileUpload Control or Input - with nothing on the page and on button click putting a response.write - that is also causing the issue.

We've even tried ASP.NET Ajax 3.5 Async File Upload control.

PLEASE HELP !!!

Sample of code:

Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Testpage.aspx.cs" Inherits="Admin_Backend_Testpage" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" method="post">
    
   <%-- <div>
      
        <asp:FileUpload ID="Fileupload1" runat="server" />
     
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" />

    </div>
    <div>
        <asp:FileUpload ID="Fileupload2" runat="server" />
      
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" />
    </div>
    <div>
      
        <input id="Fileupload3" type="file" runat="server" />
        <asp:Button ID="Button3" runat="server" onclick="Button3_Click" />
    </div>--%>
    <div>
  
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
       <asp1:AsyncFileUpload runat="server" id="AsyncFileUpload1" CompleteBackColor="Lime" UploaderStyle="Modern" ErrorBackColor="Red" ThrobberID="Throbber"  >
    </asp1:AsyncFileUpload>
    </div>
   
    </form>
</body>
</html>

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.IO;
using System.Drawing.Design;
using System.Drawing;

public partial class Admin_Backend_Testpage : System.Web.UI.Page
{
    //protected void Page_Load(object sender, EventArgs e)
    //{
    //    //string strpath = Request.PhysicalApplicationPath;
    //    //FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, strpath);
    //    ////Fileupload1.SaveAs(Server.MapPath("~/UploadPhotos") + Fileupload1.FileName);
    //    //perm.Demand();
    //    //string appPath = Path.Combine(strpath, "/Admin/Backend/UploadPhotos");
    //    if (!IsPostBack)
    //    {
            //string strpath = Request.PhysicalApplicationPath;
            //string appPath = Path.Combine(strpath, "/Admin/Backend/UploadPhotos/");
            //Response.Write("File 1 will be uploaded to this directory:" + Request.MapPath("~/Admin/Backend/UploadPhotos/"));
            //Response.Write("<br/>File 2 will be uploaded to this directory:" + appPath);
    //    }
    //}
    //protected void Button1_Click(object sender, EventArgs e)
    //{
    //    Response.Write("hello");
      

    //    Response.Write("hello");
    //   // string strpath = Server.MapPath("UploadPhotos");
       
    //    //FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, strpath);
    //    ////Fileupload1.SaveAs(Server.MapPath("~/UploadPhotos") + Fileupload1.FileName);
    //    //perm.Demand();
    //    //Fileupload1.SaveAs(Server.MapPath("./UploadPhotos/") + Fileupload1.FileName);

    //    //Response.Write(appPath);
    //    //string strpath = Request.PhysicalApplicationPath;
    //    //FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, strpath);
    //    ////Fileupload1.SaveAs(Server.MapPath("~/UploadPhotos/") + Fileupload1.FileName.ToString());
        
    //    //perm.Demand();
    //    //string appPath = Path.Combine(strpath, "/Admin/Backend/UploadPhotos/");
    //    Fileupload1.SaveAs(Request.MapPath("~/Admin/Backend/UploadPhotos/") + Fileupload1.FileName.ToString());
        


    //}
    //protected void Button2_Click(object sender, EventArgs e)
    //{
    //    Response.Write("hello");
      

    //    Response.Write("hello");
    //    string strpath = Request.PhysicalApplicationPath;
    //    string appPath = Path.Combine(strpath, "/Admin/Backend/UploadPhotos/");
    //    Fileupload1.SaveAs(appPath + Fileupload2.FileName.ToString());
    //    Response.Write(appPath);
    //}
    //protected void Button3_Click(object sender, EventArgs e)
    //{
    //    Response.Write("hello");
     
    //    HttpPostedFile filPostedFile = Fileupload3.PostedFile;
    //    int intLength = 0;
    //    byte[] bytUpload = new byte[0];

    //   // filPostedFile = Fileupload3.PostedFile;
    //    intLength = filPostedFile.ContentLength;
    //    if (filPostedFile.ContentLength > 0)
    //    {
    //        bytUpload = new byte[intLength];
    //        filPostedFile.InputStream.Read(bytUpload, 0, intLength);

    //        WriteToDB(filPostedFile.FileName.ToString(), ref bytUpload);
    //    }
    //    else
    //    {
    //        Response.Write("ContentLength is zero.");
    //    }
    //}
    //private void WriteToDB(String strName, ref byte[] oBuffer)
    //{
      
    //}

    protected void Page_Load(object sender, EventArgs e)  
 {  
        AsyncFileUpload1.UploadedComplete += new EventHandler<AjaxControlToolkit.AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedComplete);  
        AsyncFileUpload1.UploadedFileError += new EventHandler<AjaxControlToolkit.AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedFileError);
        string strpath = Request.PhysicalApplicationPath;
        string appPath = Path.Combine(strpath, "/Admin/Backend/UploadPhotos/");
        Response.Write("File 1 will be uploaded to this directory:" + Request.MapPath("~/Admin/Backend/UploadPhotos/"));
        Response.Write("<br/>File 2 will be uploaded to this directory:" + appPath);
   }  
 [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]  
    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)  
    {
        
        string fileloc = @"\UploadPhotos\";
       // string strpath = Request.PhysicalApplicationPath;
        //string fileloc = Path.Combine(strpath, "/Admin/Backend/UploadPhotos/");
        

        System.Threading.Thread.Sleep(5000);  
       string randomstr;
       if (AsyncFileUpload1.HasFile)  
       {  
            //create random filename and test it against server dir for dups  
            randomstr = RandomString(10, false);  
           string imagename = randomstr + System.IO.Path.GetExtension(e.filename);  
            if (System.IO.File.Exists(MapPath(fileloc) + imagename))  
            {  
              randomstr = RandomString(10, false);  
              imagename = randomstr + System.IO.Path.GetExtension(e.filename);  
           }
          //FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, fileloc + imagename);
         //   perm.Demand();
         //   // Create a bitmap of the content of the fileUpload control in memory  
         //   Bitmap originalBMP = new Bitmap(AsyncFileUpload1.FileContent);  
  
         //// Calculate the new image dimensions  
         //  int origWidth = originalBMP.Width;  
         //   int origHeight = originalBMP.Height;  
         //  int sngRatio = origWidth / origHeight;  
         //   int newWidth = 100;  
         //  int newHeight = newWidth / sngRatio;  
  
          // Create a new bitmap which will hold the previous resized bitmap  
           //Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);                // Create a graphic based on the new bitmap  
           //Graphics oGraphics = Graphics.FromImage(newBMP);  
   
         // Set the properties for the new graphic file  
           //oGraphics.SmoothingMode = oGraphicsSmoothingMode.AntiAlias; 
          // oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;                // Draw the new graphic based on the resized bitmap  
          // oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);  
 
          // Save the new graphic file to the server  
           //newBMP.Save(MapPath(fileloc) + imagename);  
 
           // // Once finished with the bitmap objects, we deallocate them.  
           // originalBMP.Dispose();  
           // newBMP.Dispose();  
           //oGraphics.Dispose();  
          // Image1.Visible = true;  
           // Image1.ImageUrl = @"/useruploads/" + imagename;  
            AsyncFileUpload1.SaveAs(MapPath(fileloc) + imagename);  
      }  
        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + uploadResult.ClientID + "\").innerHTML = 'Uploaded size: " + AsyncFileUpload1.FileBytes.Length.ToString() + "';", true);  
    }  
   void AsyncFileUpload1_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)  
    {  
       //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "top.$get(\"" + uploadResult.ClientID + "\").innerHTML = 'Error: " + e.statusMessage + "';", true);  
    }  
   
   /// <summary>  
    /// Generates a random string with the given length  
    /// </summary>  
  /// <param name="size">Size of the string</param>  
   /// <param name="lowerCase">If true, generate lowercase string</param>  
    /// <returns>Random string</returns>  
  private string RandomString(int size, bool lowerCase)  
      {  
        System.Text.StringBuilder builder = new System.Text.StringBuilder();  
       Random random = new Random();  
       char ch;  
        for (int i = 0; i < size; i++)  
        {  
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
             builder.Append(ch);  
       }  
        if (lowerCase)  
            return builder.ToString().ToLower();  
        return builder.ToString();  
  }  
}
 
it works for sure because I use mojoportal with medium trust, and mom does too, and upload work perfectly :)

Probably it is how you have the location for save configured.

mojoportal is open source, maybe you can download it and see how it works? :)
 
MojoPortal - is using NeatUpload.

We need installation for the same !!! ...

The best part that is happening is that we are not able to get into Click event after the file has been selected and the event fired.

Before it even goes into the click event - it vomits the exception out !!! ...
 
Back
Top