Re: Fatal error in Paging - InsertGallery

  •  08-31-2006, 4:28 AM

    Re: Fatal error in Paging - InsertGallery

    Hi
     
    Yes, I have tried that. In an earlier release it works fine even without CustomFileProvider.dll! So I don't think this file makes a different. I use the dll included in the zip. I have not compiled my own CustomFileProvider.dll.
     
    Our current production relase works fine, but the new release which runs in our develpment- and test enviroment doesn't work, and we will soon deploy a new production release, but this error stops us from doing that. We can't see any differences in the settings between the diffent environments.
     
    I send the whole content of the modified SqlFileStorage.cs file. Maybe that you can see some suspicious things in the file.
     
    /Torben
     
     
    namespace CustomFileProvider.SqlSample
    {
     using System;
     using System.Collections;
     using System.IO;
     using System.Data;
     using System.Data.SqlClient;
     using System.Web;
     using System.Text;
     using CustomFileProvider.SqlSample;
     using KMD.OA.Infrastruktur;
     public class SqlFileStorage : CuteEditor.Impl.FileStorage
     //public class SqlFileStorage : NormalPage
     {
      /// <summary>
      /// Connection String
      /// </summary>
      ///
      public string ConnectionString= KMD.OA.Util.General.GetEnvironmentKey("CS_OA6001");
      HttpContext c;
      SqlConnection conn;
      CuteEditor.EditorSetting setting;
      
      /// <summary>
      /// the aspx page whose sole responsibility is to display a specific image
      /// </summary>
      string downfile;
      
      public SqlFileStorage(HttpContext context):base(context)
      {
       c=context;
       setting=CuteEditor.EditorSetting.GetFromContext(c,true);
       
       //set the downloadfile RUL
       downfile=setting["DownFile"];
       conn=new SqlConnection();
      }
      //EnterQuery , make sure the connection is open
      #region protected IDisposable EnterQuery()
      protected IDisposable EnterQuery()
      {
       
       if(conn.State==ConnectionState.Closed)
       {
        conn.ConnectionString=ConnectionString;
        conn.Open();
        
        Disposer d=new Disposer();
        d.fs=this;
        return d;
       }
       
       return new Disposer();
      }
      class Disposer : IDisposable
      {
       public SqlFileStorage fs;
       public void Dispose()
       {
        if(fs!=null)
        {
         fs.conn.Dispose();
         fs=null;
        }
       }
      }
      #endregion
      public void ExecuteNonQuery(string commandtext,params object[] args)
      {
       ExecuteReader(commandtext,args).Close();
      }
      
      static public void SetParameter(SqlParameterCollection pcoll,string pname,object obj)
      {
       if(pcoll==null)throw(new ArgumentNullException("pcoll"));
       if(obj==null||Convert.IsDBNull(obj))
       {
        pcoll.Add(pname,SqlDbType.NVarChar,50).Value=DBNull.Value;
        return;
       }
       if(obj is string)
       {
        if(obj.ToString().Length>4000)
        {
         pcoll.Add(pname,SqlDbType.NText).Value=obj;
         return;
        }
       }
       else if(obj is byte[])
       {
        byte[] bs=(byte[])obj;
        if(bs.Length>8000)
        {
         pcoll.Add(pname,SqlDbType.Binary).Value=bs;
         return;
        }
       }
       else if(obj is SqlParameter)
       {
        SqlParameter sp=(SqlParameter)obj;
        //pcoll.Add(sp);
        pcoll.Add(new SqlParameter(pname,sp.SqlDbType,sp.Size,sp.Direction,true,sp.Precision,sp.Scale,sp.SourceColumn,sp.SourceVersion,sp.Value));
        return;
       }
       else if(obj is DateTime)
       {
        pcoll.Add(pname,SqlDbType.NVarChar,50).Value=((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss")+"."+((DateTime)obj).Millisecond.ToString().PadLeft(3,'0');
        return;
       }
       pcoll.Add(pname,obj);
      }
      //get the id of an item
      protected int GetItemId(string path)
      {
       int intSkoleId = Convert.ToInt32(HttpContext.Current.Session["SkoleId"]);
       int intBrugerId = General.UserPersonId();
       StringBuilder strSQL = new StringBuilder();
       strSQL.Append("select id from Websidefil where path='");
       strSQL.Append(path);
       strSQL.Append("' and Fk_Institution_Id=");
       strSQL.Append(intSkoleId);
       //Er det ikke en fælles mappe kan samme filnavn forekomme flere gange - dog kun 1 gang pr. bruger
       if (path.StartsWith("/Skolen") == false)
       {
        strSQL.Append(" and Fk_Owner_Id=");
        strSQL.Append(intBrugerId);
       }
       using(EnterQuery())
       {    
        //using(SqlDataReader reader=ExecuteReader("select id from Websidefil where path={0} and Fk_Owner_Id=" + intBrugerId + " and Fk_Institution_Id={2}",path))
        using(SqlDataReader reader=ExecuteReader(strSQL.ToString(),path))
        {
         if(reader.Read())
          return reader.GetInt32(0);
        }
       }
       return 0;
      }
      //get the path of an item
      protected string GetItemPath(int id)
      {
       using(EnterQuery())
       {
        using(SqlDataReader reader=ExecuteReader("select path from Websidefil where id={0}",id))
        {
         if(reader.Read())
          return reader.GetString(0);
        }
       }
       return null;
      }
      public override CuteEditor.Impl.DirectoryItem[] GetDirectoryItems(string dirpath,bool getcount)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       ArrayList arr=new ArrayList();
       using(EnterQuery())
       {
        using(SqlDataReader reader=ExecuteReader("select * from Websidefil where isdir=1 and parentpath={0} order by path ",dirpath))
       {
         while(reader.Read())
         {
          CuteEditor.Impl.DirectoryItem item=new CuteEditor.Impl.DirectoryItem();
          item.Path=reader["path"].ToString();
          item.Name=Path.GetFileName(item.Path);
          arr.Add(item);
         }
        }
        if(getcount)
        {
         foreach(CuteEditor.Impl.DirectoryItem item in arr)
         {
          using(SqlDataReader reader=ExecuteReader("select count(*) from Websidefil where parentpath={0}",item.Path))
          {
           reader.Read();
           item.ChildCount=reader.GetInt32(0);
          }
         }
        }
       }
       return (CuteEditor.Impl.DirectoryItem[])arr.ToArray(typeof(CuteEditor.Impl.DirectoryItem));
      }
     
      public override CuteEditor.Impl.FileItem[] GetFileItems(string dirpath, string searchpattern)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       int intSkoleId = Convert.ToInt32(HttpContext.Current.Session["SkoleId"]);
       if (intSkoleId < 1)
        return null;
       int intBrugerId = General.UserPersonId();
       
       StringBuilder strSQL = new StringBuilder();
       switch (dirpath)
       {        
        case "/":
         strSQL.Append("select id,path,createdt,filename,filesize from Websidefil where isdir=0 and parentpath={0} and path like {1} and Fk_Institution_Id = ");
         strSQL.Append(intSkoleId);
         strSQL.Append(" order by path ");
         break;
        case "/Skolens":
         strSQL.Append("select id,path,createdt,filename,filesize from Websidefil where isdir=0 and parentpath={0} and path like {1} and Fk_Institution_Id = ");
         strSQL.Append(intSkoleId);
         strSQL.Append(" order by path ");
         break;
        case "/Mine":
         strSQL.Append("select id,path,createdt,filename,filesize from Websidefil where isdir=0 and parentpath={0} and path like {1} and Fk_Institution_Id = ");
         strSQL.Append(intSkoleId);
         strSQL.Append(" and Fk_Owner_Id = ");
         strSQL.Append(intBrugerId);
         strSQL.Append(" order by path ");
         break;
        default:
         dirpath="/";
         strSQL.Append("select id,path,createdt,filename,filesize from Websidefil where isdir=0 and parentpath={0} and path like {1} and Fk_Institution_Id = ");
         strSQL.Append(intSkoleId);
         strSQL.Append(" order by path ");
         break;
       }

       ArrayList arr=new ArrayList();
       using(EnterQuery())
       {
        if(searchpattern==null)searchpattern="%";
        searchpattern=searchpattern.Replace("*","%");
        using(SqlDataReader reader=ExecuteReader(strSQL.ToString(),dirpath,searchpattern))
        //using(SqlDataReader reader=ExecuteReader("select id,path,createdt,filename,filesize from Websidefil where isdir=0 and parentpath={0} and path like {1} order by path ",dirpath,searchpattern))
        {
         while(reader.Read())
         {
          CuteEditor.Impl.FileItem item=new CuteEditor.Impl.FileItem();
          item.Path=reader["path"].ToString();
          item.Name=Path.GetFileName(item.Path);
          item.Length=(int)reader["filesize"];
          item.CreationTime=item.LastWriteTime=(DateTime)reader["createdt"];
          item.Url=downfile+"?fileid="+reader["id"];
          arr.Add(item);
         }
        }
       }
       return (CuteEditor.Impl.FileItem[])arr.ToArray(typeof(CuteEditor.Impl.FileItem));
      }
      /// <summary>
      /// Get the display path of the dirpath
      /// </summary>
      public override string GetDirectoryText(string dirpath)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       return dirpath;
      }
      /// <summary>
      /// GetDirectorySize
      /// </summary>
      /// <param name="dirpath"></param>
      /// <returns></returns>
      public override double GetDirectorySize(string dirpath)
      {
       return 0;
      }  
      public override string GetParentDirectory(string dirpath)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       if(dirpath=="/")
        return null;
       try
       {
        return Path.GetDirectoryName(dirpath);
       }
       catch
       {
        throw(new Exception(dirpath));
       }
      }
      private string GetFileDirectory(string filepath)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       return Path.GetDirectoryName(filepath);
      }
      
      public override string GetFileName(string filepath)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       return Path.GetFileName(filepath);
      }
      
      public override byte[] GetFileData(string filepath)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       using(EnterQuery())
       {
        using(SqlDataReader reader=ExecuteReader("select filedata from Websidefil where path={0}",filepath))
        {
         if(reader.Read())
          return (byte[])reader[0];
        }
       }
       return null;
      }
      
      
      public override string CreateFile(string dirpath, string filename, byte[] filedata)
      {
       int intSkoleId = Convert.ToInt32(HttpContext.Current.Session["SkoleId"]);
       if (intSkoleId < 1)
        return "";
       int intBrugerId = General.UserPersonId();
       dirpath=CalcPath(VirtualRoot,dirpath);
       filename=Path.GetFileName(filename);
       string newpath=Path.Combine(dirpath,filename).Replace(@"\","/");
       using(EnterQuery())
       {
        if(dirpath=="/")
        { 
         //throw(new Exception("Du skal udpege en mappe"));
         return "abc";
        }
    //    Dette tjek er ikke nødvendigt, da mulige mapper er oprettet i databasen og kun kan vælges/udpeges
    //    if(dirpath!="/")
    //    {
    //     int dirid=GetItemId(dirpath);
    //     if(dirid==0)throw(new Exception("path '"+dirpath+"' ikke fundet"));
    //    }
        int fileid=GetItemId(newpath);
        if(fileid!=0)
        {
         //Der udføres ikke opdatering af filer
         throw(new DuplicateNameException("Der findes allerede en fil i denne mappe med samme navn!"));
         //ExecuteNonQuery("update Websidefil set createdt={1},filesize={2},filedata={3} where id={0}",fileid,DateTime.Now,filedata.Length,filedata);
        }
        else
        {
         ExecuteNonQuery("insert into Websidefil (path,isdir,parentpath,createdt,filename,filesize,filedata,Fk_Owner_Id,Fk_Institution_Id) values ({0},0,{1},{2},{3},{4},{5},{6},{7})"
          ,newpath
          ,dirpath
          ,DateTime.Now
          ,filename
          ,filedata.Length
          ,filedata
          ,intBrugerId
          ,intSkoleId
          );
        }
        return newpath;
       }
      }
      public override string CreateDirectory(string dirpath, string dirname)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       dirname=Path.GetFileName(dirname);
       string newpath=Path.Combine(dirpath,dirname).Replace(@"\","/");
       using(EnterQuery())
       {
        if(dirpath!="/")
        {
         int dirid=GetItemId(dirpath);
         if(dirid==0)throw(new Exception("path '"+dirpath+"' not found"));
        }
        if(GetItemId(newpath)==0)
        {
         ExecuteNonQuery("insert into Websidefil (path,isdir,parentpath) values ({0},1,{1})",newpath,dirpath);
        }
        return newpath;
       }
      }
      
      
      public override void DeleteDirectory(string dirpath)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       using(EnterQuery())
       {
        ExecuteNonQuery("delete from Websidefil where path={0}",dirpath);
        ExecuteNonQuery("delete from Websidefil where path like {0}+'/%'",dirpath);
       }
      }
      public override void DeleteFile(string filepath)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       using(EnterQuery())
       {
        ExecuteNonQuery("delete from Websidefil where isdir=0 and path={0}",filepath);
       }
      }
      
      
      public override string RenameDirectory(string dirpath, string name)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       string dir=GetFileDirectory(dirpath);
       string newpath=Path.Combine(dir,name).Replace(@"\","/");
       using(EnterQuery())
       {
        ExecuteNonQuery("update Websidefil set path={0} where path={1}",newpath,dirpath);
        ExecuteNonQuery("update Websidefil set path={0}+right(path,len(path)-{2}) , parentpath={0}+right(parentpath,len(parentpath)-{2}) where path like {1}+'/%'",newpath,dirpath,dirpath.Length);
       }
       return newpath;
      }
      public override string RenameFile(string filepath, string name)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       string dir=GetFileDirectory(filepath);
       string newpath=Path.Combine(dir,name).Replace(@"\","/");
       using(EnterQuery())
       {
        ExecuteNonQuery("update Websidefil set path={0} where path={1}",newpath,filepath);
       }
       return newpath;
      }

      public override string MoveDirectory(string dirpath, string targetdir)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       targetdir=CalcPath(VirtualRoot,targetdir);
       string name=Path.GetFileName(dirpath);
       string newpath=Path.Combine(targetdir,name).Replace(@"\","/");
       using(EnterQuery())
       {
        ExecuteNonQuery("update Websidefil set path={0} ,parentpath={2} where path={1}",newpath,dirpath,targetdir);
        ExecuteNonQuery("update Websidefil set path={0}+right(path,len(path)-{2}) , parentpath={0}+right(parentpath,len(parentpath)-{2}) where path like {1}+'/%'",newpath,dirpath,dirpath.Length);
       }
       return newpath;
      }
      public override string MoveFile(string filepath, string targetdir)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       GetFileDirectory(filepath);
       targetdir=CalcPath(VirtualRoot,targetdir);
       string newfilepath=targetdir.TrimEnd('/')+"/"+GetFileName(filepath);
     
       using(EnterQuery())
       {
        ExecuteNonQuery("update Websidefil set path={2} , parentpath={1} where path={0}",filepath,targetdir,newfilepath);
       }
       return newfilepath;
      }
      public override string CopyDirectory(string dirpath, string targetdir)
      {
       dirpath=CalcPath(VirtualRoot,dirpath);
       targetdir=CalcPath(VirtualRoot,targetdir);
       using(EnterQuery())
       {
        throw(new NotImplementedException());
       }
      }
      public override string CopyFile(string filepath, string targetdir)
      {
       using(EnterQuery())
       {
        throw(new NotImplementedException());
       }
      }
      
      string root="/";
      public override string VirtualRoot
      {
       get
       {
        return root;
       }
       set
       {
        if(value==null)
         throw(new ArgumentNullException("VirtualRoot"));
        if(value.StartsWith("~/"))
         value=value.Remove(0,1);
        if(!value.StartsWith("/"))
         throw(new ArgumentException("Stien skal pege på roden"));
        root=value;
        if(root!="/")
         root=root.TrimEnd('/');
       }
      }
      private string CalcPath(string path, string relpath)
      {
       path=path.Replace('\\','/');
       if(!path.StartsWith("/"))
        path=CalcPath(VirtualRoot,path);
       if(relpath==null||relpath=="")
       {
        return path;
       }
       if(relpath.StartsWith("/"))
       {
        if(relpath.IndexOf("..")!=-1)
         throw(new Exception("Den absolutte sti må ikke indeholde '..'"));
        if(relpath=="/")
         return relpath;
        //Et lille hack, som er indført for at håndtere den fejl der opstår i Editoren
        //hvis brugeren trykker på mappe ikonet ud for mappens navn.
        if(relpath.Length > 8)
        {
         string strReturn = "";
         string[] strArr = relpath.Split('/');
         if (relpath.EndsWith("/Skolens"))
          strReturn = "/Skolens";
         if (relpath.EndsWith("/Mine"))
          strReturn = "/Mine";
     
         if (strArr.Length > 2)
         {
          if (strArr[strArr.Length-2] == "Skolens")
           strReturn = "/Skolens/" + strArr[strArr.Length-1];
          if (strArr[strArr.Length-2] == "Mine")
           strReturn = "/Mine/" + strArr[strArr.Length-1];
         }
         return strReturn;
        }
        return relpath.TrimEnd('/');
       }
       foreach(string str in relpath.Split(@"/\".ToCharArray()))
       {
        if(str=="")
         continue;
        if(str=="..")
        {
         int pos=-1;
         if(path!=null&&path!="")
          pos=path.LastIndexOf('/',path.Length-2);
         if(pos==-1)
         {
          path=null;
         }
         else
         {
          path=path.Substring(0,pos);
         }
        }
        else
        {
         path+="/"+str;
        }
       }
       if(path=="")
        return "/";
       return path.Replace("//","/");
      }
      public override string GetFileUrl(string filepath)
      {
       filepath=CalcPath(VirtualRoot,filepath);
       return downfile+"?fileid="+GetItemId(filepath);
      }
      public override string TranslateTargetDirectory(string dirpath, string relpath)
      {
       if(relpath.StartsWith("/"))
        return (VirtualRoot+relpath).Replace("//","/");
       return CalcPath(dirpath,relpath);
      }
      
      //execute the reader , commandtext is formatted by string.Format
      #region SqlDataReader ExecuteReader(string commandtext,params object[] args)

      SqlDataReader ExecuteReader(string commandtext,params object[] args)
      {
       int len=args==null?0:args.Length;
       SqlCommand cmd=new SqlCommand(commandtext,conn);
       
       object[] argnames=new object[len];
       SqlParameterCollection ps=cmd.Parameters;
       for(int i=0;i<len;i++)
       {
        object val=argsIdea;
        string pname="@cdq_"+i;
        SetParameter(ps,pname,val);
         
        if(val is DateTime)
        {
         argnamesIdea="CONVERT(DATETIME,"+pname+")";
        }
        else
        {
         argnamesIdea=pname;
        }
       }
        
       commandtext=string.Format(commandtext,argnames);
       cmd.CommandText=commandtext;
       return cmd.ExecuteReader();
       
      }
      
      #endregion
     }
    }
     
     
     
View Complete Thread