lunes, 31 de enero de 2011

Clases para Carga y Descarga de BLOBs a MS SQL (C# ASP.NET)

En la siguiente entrada se podrán observar un par de clases una utilizada para la descarga de BLOBs desde una base de datos y otra para la carga de BLOBs en una base de datos SQL, en el caso de la de carga también tiene funcionalidad para subir archivos en un File System.


Listado de código

using System;

using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;


namespace F.Web.IO
{
    public class Download
    {

        #region Private Members
        private string _ConnectionString;
        private string _TableName;
        private string _ContentField;
        private string _FileNameField;
        private string _ContentTypeField;
        private string _KeyField;
        #endregion

        #region Public Properties
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Database Connection String Property
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string ConnectionString
        {
            get
            {
                return _ConnectionString;
            }
            set
            {
                _ConnectionString = value;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Name of documents repository table
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string TableName
        {
            get
            {
                return _TableName;
            }
            set
            {
                _TableName = value;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Content field in document repository table
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string ContentField
        {
            get
            {
                return _ContentField;
            }
            set
            {
                _ContentField = value;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Filename field in document repository
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string FileNameField
        {
            get
            {
                return _FileNameField;
            }
            set
            {
                _FileNameField = value;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Content Type field in document repository
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string ContentTypeField
        {
            get
            {
                return _ContentTypeField;
            }
            set
            {
                _ContentTypeField = value;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Key Field of document repository
        /// </summary>
        /// <value>string</value>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [bonifacio]  7/4/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string KeyField
        {
            get
            {
                return _KeyField;
            }
            set
            {
                _KeyField = value;
            }
        }
        #endregion

        #region Methods

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Chuck BLOB to file converter
        /// </summary>
        /// <param name="DocumentoID">Document identifier</param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///             [bonifacio]        7/4/2006           Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public System.IO.StringWriter SqlChunkBLOB2File(long DocumentoID)
        {
            System.IO.StringWriter functionReturnValue = null;

            int PictureCol = 0;
            // position of Picture column in DataReader
            int BUFFER_LENGTH = 32768;
            // chunk size
            SqlConnection cn = new SqlConnection(this.ConnectionString);
            //
            // Make sure that Photo is non-NULL and return TEXTPTR to it.
            //
            SqlCommand cmdGetPointer = new SqlCommand("SELECT @Pointer=TEXTPTR([" + _ContentField + "]), @Length=DataLength([" + _ContentField + "]) FROM " + _TableName + " WHERE " + _KeyField + "=" + DocumentoID, cn);
            SqlParameter PointerOutParam = cmdGetPointer.Parameters.Add("@Pointer", SqlDbType.VarBinary, 500);
            PointerOutParam.Direction = ParameterDirection.Output;
            SqlParameter LengthOutParam = cmdGetPointer.Parameters.Add("@Length", SqlDbType.Int);
            LengthOutParam.Direction = ParameterDirection.Output;
            cn.Open();
            cmdGetPointer.ExecuteNonQuery();
            if (object.ReferenceEquals(PointerOutParam.Value, DBNull.Value))
            {
                cn.Close();
                return functionReturnValue;
                // Add code to deal with NULL BLOB.
            }
            //
            // Set up READTEXT command, parameters, and open BinaryReader.
            //
            SqlCommand cmdReadBinary = new SqlCommand("READTEXT [" + _TableName + "].[" + _ContentField + "] @Pointer @Offset @Size HOLDLOCK", cn);
            SqlParameter PointerParam = cmdReadBinary.Parameters.Add("@Pointer", SqlDbType.VarBinary, 16);
            SqlParameter OffsetParam = cmdReadBinary.Parameters.Add("@Offset", SqlDbType.Int);
            SqlParameter SizeParam = cmdReadBinary.Parameters.Add("@Size", SqlDbType.Int);
            SqlDataReader dr = null;

            int Offset = 0;
            OffsetParam.Value = Offset;
            byte[] Buffer = new byte[BUFFER_LENGTH];

            //
            // Read buffer full of data and write to the file stream.
            //
            do
            {
                PointerParam.Value = PointerOutParam.Value;
                //
                // Calculate the buffer size - may be less than BUFFER_LENGTH for the last block.
                //
                if (Offset + BUFFER_LENGTH >= LengthOutParam.Value)
                {
                    SizeParam.Value = LengthOutParam.Value - Offset;
                }
                else
                {
                    SizeParam.Value = BUFFER_LENGTH;
                }
                dr = cmdReadBinary.ExecuteReader(CommandBehavior.SingleResult);
                dr.Read();
                dr.GetBytes(PictureCol, 0, Buffer, 0, SizeParam.Value);
                //dr.GetChars(PictureCol, 0, BufferChar, 0, SizeParam.Value)
                dr.Close();

                //stringWrite.Write(BufferChar, 0, SizeParam.Value)
                HttpContext.Current.Response.BinaryWrite(Buffer);


                Offset += SizeParam.Value;
                OffsetParam.Value = Offset;
            } while (!(Offset >= LengthOutParam.Value));

            cn.Close();
            return functionReturnValue;
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Chuck BLOB to File
        /// </summary>
        /// <param name="DocumentoID">Document identifier</param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///             [bonifacio]        8/28/2006         Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static System.IO.StringWriter SqlChunkBLOB2File(string pConnectionString, long DocumentoID, string pContentField, string pTableName, string pKeyField)
        {
            System.IO.StringWriter functionReturnValue = null;

            int PictureCol = 0;
            // position of Picture column in DataReader
            int BUFFER_LENGTH = 32768;
            // chunk size
            SqlConnection cn = new SqlConnection(pConnectionString);
            //
            // Make sure that Photo is non-NULL and return TEXTPTR to it.
            //
            SqlCommand cmdGetPointer = new SqlCommand("SELECT @Pointer=TEXTPTR([" + pContentField + "]), @Length=DataLength([" + pContentField + "]) FROM " + pTableName + " WHERE " + pKeyField + "=" + DocumentoID, cn);
            SqlParameter PointerOutParam = cmdGetPointer.Parameters.Add("@Pointer", SqlDbType.VarBinary, 500);
            PointerOutParam.Direction = ParameterDirection.Output;
            SqlParameter LengthOutParam = cmdGetPointer.Parameters.Add("@Length", SqlDbType.Int);
            LengthOutParam.Direction = ParameterDirection.Output;
            cn.Open();
            cmdGetPointer.ExecuteNonQuery();
            if (object.ReferenceEquals(PointerOutParam.Value, DBNull.Value))
            {
                cn.Close();
                return functionReturnValue;
                // Add code to deal with NULL BLOB.
            }
            //
            // Set up READTEXT command, parameters, and open BinaryReader.
            //
            SqlCommand cmdReadBinary = new SqlCommand("READTEXT [" + pTableName + "].[" + pContentField + "] @Pointer @Offset @Size HOLDLOCK", cn);
            SqlParameter PointerParam = cmdReadBinary.Parameters.Add("@Pointer", SqlDbType.VarBinary, 16);
            SqlParameter OffsetParam = cmdReadBinary.Parameters.Add("@Offset", SqlDbType.Int);
            SqlParameter SizeParam = cmdReadBinary.Parameters.Add("@Size", SqlDbType.Int);
            SqlDataReader dr = null;

            int Offset = 0;
            OffsetParam.Value = Offset;
            byte[] Buffer = new byte[BUFFER_LENGTH];

            //
            // Read buffer full of data and write to the file stream.
            //
            do
            {
                PointerParam.Value = PointerOutParam.Value;
                //
                // Calculate the buffer size - may be less than BUFFER_LENGTH for the last block.
                //
                if (Offset + BUFFER_LENGTH >= LengthOutParam.Value)
                {
                    SizeParam.Value = LengthOutParam.Value - Offset;
                }
                else
                {
                    SizeParam.Value = BUFFER_LENGTH;
                }
                dr = cmdReadBinary.ExecuteReader(CommandBehavior.SingleResult);
                dr.Read();
                dr.GetBytes(PictureCol, 0, Buffer, 0, SizeParam.Value);
                //dr.GetChars(PictureCol, 0, BufferChar, 0, SizeParam.Value)
                dr.Close();

                //stringWrite.Write(BufferChar, 0, SizeParam.Value)
                HttpContext.Current.Response.BinaryWrite(Buffer);


                Offset += SizeParam.Value;
                OffsetParam.Value = Offset;
            } while (!(Offset >= LengthOutParam.Value));

            cn.Close();
            return functionReturnValue;
        }

        /// <summary>
        /// Download a file from Database taking his ID as parameter
        /// </summary>
        /// <param name="pdocumentID">DocumentID</param>
        /// <param name="disposition">Content-disposition parameter, can be as Attachment or embeded</param>
        public void DownloadFile(long pdocumentID, string disposition)
        {
            SqlDataReader dr = null;
            SqlConnection cn = new SqlConnection(_ConnectionString);
            SqlCommand cmd = null;
            try
            {
                cn.Open();

                string command = "SELECT [" + _ContentField + "],[" + _ContentTypeField + "],[" + _FileNameField + "], Length=DataLength([" + _ContentField + "])  FROM [" + _TableName + "] WHERE [" + _KeyField + "]=" + pdocumentID;
                cmd = cn.CreateCommand();
                cmd.CommandText = command;
                cmd.CommandType = CommandType.Text;

                dr = cmd.ExecuteReader();
               
                if (dr.Read())
                {
                    byte[] buffer = null;
                    dr.GetBytes(0, 0, buffer, 0, System.Convert.ToInt32(dr["Length"]));
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Charset = "";
                    HttpContext.Current.Response.ContentType = dr[_ContentTypeField].ToString();
                    HttpContext.Current.Response.AddHeader("Content-Disposition", disposition + ";Filename=" + dr[_FileNameField].ToString());
                    dr.Close();
                    HttpContext.Current.Response.BinaryWrite(buffer);
                }
            }
            catch
            {
                if (Text.Input.IsNotNull(dr))
                    dr.Close();
                throw;
            }
            finally {
                if (cn != null) {
                    cn.Close();
                }
            }
        }

        #endregion

    }
    /// <summary>
    /// Summary description for Upload.
    /// </summary>
    public class Upload
    {
        #region Private members
        F.Web.IO.Upload.ConnectionType connectiontype = ConnectionType.Sql;

        //string connstring ="";

        string filename, fileextension;
        int filesize;
        string destinationpath;
        bool imagesonly = false;
        bool overwritefile = false;
        int maxsize = 2000000;

        string db_table;
        string filecontenttype;
        SaveTo saveto = SaveTo.Directory;
        bool autocreatedirectory = false;

        string allowed_extension = "";

        string connectionstring;

        private System.Web.UI.HtmlControls.HtmlInputFile file;

        byte[] filebinary;

        string dbFieldsIdentifier = "";

        #endregion

        #region Properties
        /// <summary>
        /// Stores each file properties, set in WebUpload.Upload properties
        /// in a key value that represents each field names of the DataTable
        /// to WebUpload.Upload can relate each property to a tablefield and
        /// save data to database.
        /// </summary>
        public System.Collections.Hashtable DBFields = new System.Collections.Hashtable();

        /// <summary>
        /// (string) Specifies the DB Connection to use when SaveTo.Database
        /// is specified.
        /// </summary>
        public string ConnectionString
        {
            get { return this.connectionstring; }
            set { this.connectionstring = value; }
        }

        public string fileName
        {
            get { return this.filename; }
            set { this.filename = value; }
        }

        public string fileExtension
        {
            get { return this.fileextension; }
            set { this.fileextension = value; }
        }

        private SaveTo saveTo
        {
            get { return this.saveto; }
            set { this.saveto = value; }
        }

        /// <summary>
        /// (int) Returns the Uploaded File's filesize int bytes.
        /// </summary>
        public int fileSize
        {
            get { return this.filesize; }
        }

        /// <summary>
        /// (string) Gets or Sets Table identifier field name.Must specify also DBField
        /// </summary>
        public string DBFieldsIdentifier
        {
            get { return this.dbFieldsIdentifier; }
            set { this.dbFieldsIdentifier = value; }
        }


        /// <summary>
        /// (string) Set or Get allowed File Extensions for the UploadFile.
        /// Must be separated by a comma (",")
        /// If not set, any file extension is allowed.
        /// </summary>
        /// <example>
        ///  allowedExtensions = " jpg, exe, gif, html";
        /// </example>
        public string allowedExtensions
        {
            get { return this.allowed_extension; }
            set { this.allowed_extension = value; }
        }

        private enum SaveTo
        {
            Directory,
            Database
        } ;


        /// <summary>
        /// (boolean) Specifies if the Uploaded file must be an image type format only files.
        /// Only BMP JPEG/JPG PNG and GIF image file format are supported.
        /// Default = false
        /// </summary>
        public bool imagesOnly
        {
            get { return this.imagesonly; }
            set { this.imagesonly = value; }
        }

        /// <summary>
        /// (boolean) If set to true, and if the specified destination directory
        /// does not exists, the class automatically creates the directory.
        /// Default = false.
        /// </summary>
        public bool autoDirectoryCreation
        {
            get { return this.autocreatedirectory; }
            set { this.autocreatedirectory = value; }
        }


        /// <summary>
        /// (string) Specifies the server path where to save the Uploaded file.
        /// Must include a \ and the end of string
        /// Doesn't work if SaveTo.Database is specified
        /// </summary>
        public string destinationPath
        {
            get { return this.destinationpath; }
            set { this.destinationpath = value; }
        }

        /// <summary>
        /// (boolean) Specifies if the Uploaded file should overwrite
        /// files with the same destination filename.
        /// If set to false, the filename of the Uploaded file will be
        /// changed to filename001 and so on...
        /// Default = false
        /// </summary>
        public bool overwriteFile
        {
            get { return this.overwritefile; }
            set { this.overwritefile = value; }
        }


        /// <summary>
        /// (int) Specifies the Maximum Allowed File Size of the Uploaded file.
        /// Default is 2.000.000 bytes = 2Mbytes.
        /// </summary>
        public int maxSize
        {
            get { return this.maxsize; }
            set { this.maxsize = value; }
        }

        /// <summary>
        /// (string) Specifies the TableName of where to save the Uploaded file.
        /// Only works if SaveTo.Database is specified. Must specify also DBFields
        /// </summary>
        public string DBTable
        {
            get { return this.db_table; }
            set { this.db_table = value; }
        }


        /// <summary>
        /// (string) Returns the Content Type of the Uploaded File
        /// </summary>
        public string fileContentType
        {
            get { return this.filecontenttype; }
            //i removed the set for security reasons
            //set{this.filecontenttype = value; }
        }

        /// <summary>
        /// (byte[]) Returns the content of the Uploaded File
        /// </summary>
        public byte[] fileBinary
        {
            get { return this.filebinary; }
        }


        #endregion

        #region Constructors
        public Upload(System.Web.UI.HtmlControls.HtmlInputFile formfieldName)
        {
            this.getFileFromHTMLInputFile(formfieldName);
        }


        public Upload()
        {
        }

        #endregion

        #region Methods
      


        /// <summary>
        /// Does the file Upload . If any, returns an error string
        /// </summary>
        /// <returns></returns>
        public string DoUpload()
        {


            if (this.saveTo == SaveTo.Directory)
            {
                string NewFileName = this.fileName;

                if (this.allowedExtensions.Length > 0)
                {
                    if (!checkAllowedExtensions())
                    {
                        return "File Extension not allowed!";
                    }
                }

                if (this.imagesOnly)
                {
                    if (!checkFileIsImage())
                    {
                        return "File is not an image or bitmap type";
                    }
                }
                if (!this.createDirectory(this.destinationPath))
                {
                    return "Couldn't create destination path.Please set  autoDirectoryCreation property to True.";
                }

                if (this.fileSize > this.maxSize)
                {
                    return String.Format("File's size ({1} bytes) extends allowed MaxSize({0} bytes)", this.maxSize.ToString(), this.fileSize.ToString());
                }

                if (!this.overwriteFile)
                {
                    NewFileName = this.GetUniqueName(this.destinationPath + "/" + this.fileName);
                }


                this.file.PostedFile.SaveAs(this.destinationPath + NewFileName);
                return this.destinationPath + NewFileName;
            }
            else
            {
                return doSaveToDB(this.fileBinary);

            }


        }

        /// <summary>
        /// Specifies what kind of connection is being used to connect to database.
        /// Values are ConnectionType  Sql,OleDb,ODBC
        /// Default is ConnectionType.Sql
        /// </summary>
        public F.Web.IO.Upload.ConnectionType ConnectionStringType
        {
            get { return this.connectiontype; }
            set
            {
                if (value.ToString().ToUpper() == "SQL")
                {
                    this.connectiontype = F.Web.IO.Upload.ConnectionType.Sql;
                }
                else if (value.ToString().ToUpper() == "OLEDB")
                {
                    this.connectiontype = F.Web.IO.Upload.ConnectionType.OleDb;
                }
                else if (value.ToString().ToUpper() == "ODBC")
                {
                    this.connectiontype = F.Web.IO.Upload.ConnectionType.ODBC;
                }
                else
                {
                    this.connectiontype = value;
                }

            }
        }

        public enum ConnectionType
        {
            Sql,
            OleDb,
            ODBC
        }


        /// <summary>
        /// this function build a SQLquery getting DB FieldName and Value
        /// from the hashtable DBFields(key, value)
        /// </summary>
        /// <param name="buffer"></param>
        private string doSaveToDB(byte[] buffer)
        {
            string nFileID = "";
            try
            {
             
                //connect and retrieve table structure
                string sql = String.Format("SELECT * TOP 1 FROM {0}", this.DBTable);
                DataSet dbSet = new DataSet();
                DataRow dbRow;
                int total;

                switch (this.ConnectionStringType)
                {
                    case F.Web.IO.Upload.ConnectionType.Sql:
                        SqlConnection dbConn = new SqlConnection(this.ConnectionString);
                        SqlDataAdapter dbAdapt = new SqlDataAdapter(sql, dbConn);
                        dbAdapt.AcceptChangesDuringFill = true;
                        dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                        SqlCommandBuilder cmd = new SqlCommandBuilder(dbAdapt);
                        dbConn.Open();
                        dbAdapt.Fill(dbSet, this.DBTable);

                        dbRow = dbSet.Tables[this.DBTable].NewRow();
                        total = dbSet.Tables[0].Rows.Count;
                        foreach (DictionaryEntry item in this.DBFields)
                        {
                            dbRow[item.Key.ToString()] = item.Value;
                        }
                        dbSet.Tables[this.DBTable].Rows.Add(dbRow);

                        dbAdapt.InsertCommand = cmd.GetInsertCommand();
                        dbAdapt.Update(dbSet, this.DBTable);
                        dbAdapt = new SqlDataAdapter(String.Format("SELECT @@IDENTITY", this.DBTable), dbConn);
                        cmd = new SqlCommandBuilder(dbAdapt);
                        dbSet = new DataSet();
                        dbAdapt.Fill(dbSet, this.DBTable);

                        if (dbSet.Tables[0].Rows.Count >= 1)
                        {
                            nFileID = dbSet.Tables[0].Rows[0][0].ToString();
                        }

                        dbConn.Close();
                        break;
                    case F.Web.IO.Upload.ConnectionType.OleDb:
                        System.Data.OleDb.OleDbConnection dbConn2 = new System.Data.OleDb.OleDbConnection(this.ConnectionString);
                        System.Data.OleDb.OleDbDataAdapter dbAdapt2 = new System.Data.OleDb.OleDbDataAdapter(sql, dbConn2);
                        dbAdapt2.AcceptChangesDuringFill = true;
                        dbAdapt2.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                        System.Data.OleDb.OleDbCommandBuilder cmd2 = new System.Data.OleDb.OleDbCommandBuilder(dbAdapt2);
                        dbConn2.Open();
                        dbAdapt2.Fill(dbSet, this.DBTable);

                        dbRow = dbSet.Tables[this.DBTable].NewRow();
                        total = dbSet.Tables[0].Rows.Count;
                        foreach (DictionaryEntry item in this.DBFields)
                        {
                            dbRow[item.Key.ToString()] = item.Value;
                        }
                        dbSet.Tables[this.DBTable].Rows.Add(dbRow);

                        dbAdapt2.InsertCommand = cmd2.GetInsertCommand();
                        dbAdapt2.Update(dbSet, this.DBTable);
                        dbAdapt2 = new System.Data.OleDb.OleDbDataAdapter(String.Format("SELECT @@IDENTITY", this.DBTable), dbConn2);
                        cmd2 = new System.Data.OleDb.OleDbCommandBuilder(dbAdapt2);
                        dbSet = new DataSet();
                        dbAdapt2.Fill(dbSet, this.DBTable);

                        if (dbSet.Tables[0].Rows.Count >= 1)
                        {
                            nFileID = dbSet.Tables[0].Rows[0][0].ToString();
                        }


                        dbConn2.Close();
                        break;
                    case F.Web.IO.Upload.ConnectionType.ODBC:
                        System.Data.Odbc.OdbcConnection dbConn3 = new System.Data.Odbc.OdbcConnection(this.ConnectionString);
                        System.Data.Odbc.OdbcDataAdapter dbAdapt3 = new System.Data.Odbc.OdbcDataAdapter(sql, dbConn3);
                        dbAdapt3.AcceptChangesDuringFill = true;
                        dbAdapt3.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                        System.Data.Odbc.OdbcCommandBuilder cmd3 = new System.Data.Odbc.OdbcCommandBuilder(dbAdapt3);
                        dbConn3.Open();
                        dbAdapt3.Fill(dbSet, this.DBTable);

                        dbRow = dbSet.Tables[this.DBTable].NewRow();
                        total = dbSet.Tables[0].Rows.Count;
                        foreach (DictionaryEntry item in this.DBFields)
                        {
                            dbRow[item.Key.ToString()] = item.Value;
                        }
                        dbSet.Tables[this.DBTable].Rows.Add(dbRow);

                        dbAdapt3.InsertCommand = cmd3.GetInsertCommand();
                        dbAdapt3.Update(dbSet, this.DBTable);
                        dbAdapt3 = new System.Data.Odbc.OdbcDataAdapter(String.Format("SELECT @@IDENTITY", this.DBTable), dbConn3);
                        cmd3 = new System.Data.Odbc.OdbcCommandBuilder(dbAdapt3);
                        dbSet = new DataSet();
                        dbAdapt3.Fill(dbSet, this.DBTable);

                        if (dbSet.Tables[0].Rows.Count >= 1)
                        {
                            nFileID = dbSet.Tables[0].Rows[0][0].ToString();
                        }

                        dbConn3.Close();
                        break;

                }
            }
            catch (Exception x)
            {
                nFileID = x.ToString();
            }
            return nFileID;
        }

        /// <summary>
        /// (boolean) Returns false if the Uploaded File extension is
        /// not allowed as specified in allowedExtensions. Returns true otherwise.
        /// </summary>
        /// <returns></returns>
        private bool checkAllowedExtensions()
        {
            foreach (string s in this.allowedExtensions.Split(new char[] { ',' }))
            {
                if (this.fileExtension == s)
                    return true;
            }

            return false;
        }


        /// <summary>
        /// (boolean) Checks if the specified file to upload is of type image, by
        /// checking its Content Type. Return false if not an image.
        /// </summary>
        /// <returns></returns>
        private bool checkFileIsImage()
        {
            bool ret;
            switch (this.fileContentType)
            {
                case "image/gif":
                case "image/jpeg":
                case "image/x-ms-bmp":
                case "image/x-png":
                    ret = true;
                    break;
                default:
                    ret = false;
                    break;
            }
            return ret;
        }


        /// <summary>
        /// (string) Specifies which form field should WebTools.Upload use
        /// to work with. Sets fileName, fileExtension, fileContentType and
        /// fileSize values.
        /// </summary>                
        /// <param name="file"></param>            
        public void getFileFromHTMLInputFile(System.Web.UI.HtmlControls.HtmlInputFile formfieldName)
        {
            this.file = formfieldName;
            this.fileName = Path.GetFileName(file.PostedFile.FileName);
            this.fileExtension = Path.GetExtension(file.PostedFile.FileName).Substring(1);
            this.filecontenttype = file.PostedFile.ContentType;
            this.filesize = file.PostedFile.ContentLength;
            this.filebinary = new byte[this.fileSize];
            this.file.PostedFile.InputStream.Read(this.fileBinary, 0, this.fileSize);
        }


        public bool createDirectory(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists)
            {
                if (this.autoDirectoryCreation)
                {
                    dir.Create();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Specifies that the file will be saved to a directory
        /// </summary>
        public void SaveToDirectory()
        {
            this.saveTo = SaveTo.Directory;
        }

        /// <summary>
        /// Specifies that the file will be saved to database
        /// </summary>
        public void SaveToDataBase()
        {
            this.saveTo = SaveTo.Database;
        }


        /// <summary>
        /// Returns the "next filename" related to the specified filename.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private string GetUniqueName(string filename)
        {
            string temp = filename;

            for (int x = 1; System.IO.File.Exists(temp); x++)
                temp = filename.Substring(0, filename.LastIndexOf(".")) + x + filename.Substring(filename.LastIndexOf("."));

            return new System.IO.FileInfo(temp).Name;
        }
        #endregion

    }


}

Transacciones Fiori

  /UI2/CACHE Register service for UI2 cache use /UI2/CACHE_DEL Delete cache entries /UI2/CHIP Chip Registration /UI2/CUST Customizing of UI ...