private MensajeDto RecuperarDocumento(string nombre, string rutaDestino)
        {
            var mensajeConnString = RecuperarElconnectionStrings("ArchivosDb");
            if (mensajeConnString.Error) {
                return mensajeConnString;
            }
            string CadConexion = mensajeConnString.Valor;

            using (SqlConnection conexionBD = new SqlConnection(CadConexion)) {
                try {
                    conexionBD.Open();
                    if (conexionBD.State == ConnectionState.Open) {
                        using (SqlTransaction transaccion = conexionBD.BeginTransaction()) {
                            byte[] arrayContexto = null;
                            string ubicacionFichero = string.Empty;
                            string cadSql = string.Empty;

                            //obtengo el PathName()
                            cadSql = "SELECT DocumentoFile.PathName() from dbo.[ArchivosMovimientos] where NombreArchivo=@nombre";
                            using (SqlCommand cmdUbicacion = new SqlCommand(cadSql, conexionBD, transaccion)) {
                                cmdUbicacion.Parameters.AddWithValue("@Nombre", nombre);
                                object objUbicacion = cmdUbicacion.ExecuteScalar();
                                if (objUbicacion != null) {
                                    ubicacionFichero = objUbicacion.ToString();
                                }
                            }
                            if (!string.IsNullOrEmpty(ubicacionFichero)) {
                                //todas las operaciones FILESTREAM BLOB deben ocurrir dentro del contexto de una transaccion
                                cadSql = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
                                using (SqlCommand cmdContexto = new SqlCommand(cadSql, conexionBD, transaccion)) {
                                    object objContexto = cmdContexto.ExecuteScalar();
                                    if (objContexto != null) {
                                        arrayContexto = (byte[])objContexto;
                                    }
                                }

                                //obtener el handle que sera pasado al WIN32 API FILE
                                using (SqlFileStream sqlFS = new SqlFileStream(ubicacionFichero, arrayContexto, FileAccess.Read)) {
                                    byte[] datosFichero = new byte[sqlFS.Length];

                                    sqlFS.Read(datosFichero, 0, (int)sqlFS.Length);
                                    var rutaCompleta = Path.Combine(rutaDestino, nombre);
                                    File.WriteAllBytes(rutaCompleta, datosFichero);
                                    sqlFS.Close();
                                }
                            }
                            transaccion.Commit();
                        }
                    }

                } catch (UnauthorizedAccessException ex) {
                    return new MensajeDto() {
                        Error = true,
                        MensajeDelProceso = "No tiene autorizacion para acceder al recurso: " + ex.Message
                    };
                } catch (Exception ex) {
                    return new MensajeDto() {
                        Error = true,
                        MensajeDelProceso = "Error: " + ex.Message
                    };
                } finally {
                    if ((conexionBD != null) && (conexionBD.State == ConnectionState.Open)) {
                        conexionBD.Close();
                    }
                }
            }

            return new MensajeDto() {
                Error = false,
                MensajeDelProceso = "Archivo generado",
                Valor = nombre
            };
        }
Example #2
0
        private static void play_video()
        {
            string video_name;

            Console.WriteLine("Play Video ==========");

            list_video();
            Console.Write("Insert Video Name : ");
            video_name = Console.ReadLine();
            Console.Write("Retrieving Video ...");
            using (TransactionScope transactionScope = new TransactionScope())
            {
                SqlConnection sqlConnection = connect_database();
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = sqlConnection;
                    command.CommandType = System.Data.CommandType.Text;
                    command.CommandText = String.Format("SELECT FileData.PathName() As Path, GET_FILESTREAM_TRANSACTION_CONTEXT() As TransactionContext FROM {0} WHERE description=@video_name", table_name);
                    command.Parameters.AddWithValue("@video_name", video_name);

                    try
                    {
                        SqlDataReader reader = command.ExecuteReader();
                        while (reader.Read()) {
                            string filePath = (string) reader["Path"];
                            byte[] transactionContext = (byte[]) reader["TransactionContext"];
                            SqlFileStream sqlFileStream = new SqlFileStream(filePath,transactionContext,FileAccess.Read);
                            byte[] video_data = new byte[sqlFileStream.Length];
                            sqlFileStream.Read(video_data,0,Convert.ToInt32(sqlFileStream.Length));
                            sqlFileStream.Close();

                            string filename = @"C:\Users\UA\Documents\Project\Database Systems\Program\temp\" + video_name;
                            FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write,FileShare.Write);
                            fs.Write(video_data,0,video_data.Length);
                            fs.Flush();
                            fs.Close();
                            Console.WriteLine("Successfull");

                            Console.Write("Playing Video ...");
                            Process process = new Process();
                            process.StartInfo.FileName = filename;
                            process.Start();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0}", e);
                    }
                    disconnect_database(sqlConnection);
                    transactionScope.Complete();
                }
            }
        }
Example #3
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset + count > buffer.Length)
            {
                throw new ArgumentException("Offset + count must not be greater than the buffer length.");
            }
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", "The offset must be greater than zero.");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count", "The count must be greater than zero.");
            }

            // Calculate the maximum count of the bytes that can be read.
            // Return immediately if nothing to read.
            var maximumReadableByteCount = Length - Position;

            if (maximumReadableByteCount < 1)
            {
                return(0);
            }

            var isLocalTransaction = false;
            var realCount          = (int)Math.Min(count, maximumReadableByteCount);

            if (CanInnerBufferHandleReadRequest(realCount))
            {
                Array.Copy(_innerBuffer, (int)Position - _innerBufferFirstPostion, buffer, offset, realCount);
            }
            else
            {
                if (!TransactionScope.IsActive)
                {
                    //make sure we do not use an obsolete value
                    _fileStreamData = null;

                    //Start a new transaction here to serve the needs of the SqlFileStream type.
                    TransactionScope.Begin();
                    isLocalTransaction = true;
                }

                try
                {
                    //Load transaction data for SqlFilestream. If this is not a local transaction,
                    //than we will be able to use this data in the future if the client calls
                    //the Read method multiple times and will not have to execute SQL queries
                    //every time.
                    if (_fileStreamData == null || _fileStreamData.TransactionContext == null)
                    {
                        _fileStreamData = DataProvider.Current.LoadFileStreamData(this.BinaryPropertyId);
                    }

                    if (_fileStreamData == null)
                    {
                        throw new InvalidOperationException("Transaction data and file path could not be retrieved for SqlFilestream");
                    }

                    using (var fs = new System.Data.SqlTypes.SqlFileStream(_fileStreamData.Path, _fileStreamData.TransactionContext, FileAccess.Read, FileOptions.SequentialScan, 0))
                    {
                        fs.Seek(Position, SeekOrigin.Begin);

                        _innerBuffer = null;

                        var bytesRead = 0;
                        var bytesStoredInInnerBuffer = 0;

                        while (bytesRead < realCount)
                        {
                            var bytesToReadInThisIteration  = (int)Math.Min(this.Length - Position - bytesRead, RepositoryConfiguration.BinaryChunkSize);
                            var bytesToStoreInThisIteration = Math.Min(bytesToReadInThisIteration, realCount - bytesRead);
                            var tempBuffer = new byte[bytesToReadInThisIteration];

                            //copy the bytes from the file stream to the temp buffer
                            //(it is possible that we loaded a lot more bytes than the client requested)
                            fs.Read(tempBuffer, 0, bytesToReadInThisIteration);

                            //first iteration: create inner buffer for caching a part of the stream in memory
                            if (_innerBuffer == null)
                            {
                                _innerBuffer             = new byte[GetInnerBufferSize(realCount)];
                                _innerBufferFirstPostion = Position;
                            }

                            //store a fragment of the data in the inner buffer if possible
                            if (bytesStoredInInnerBuffer < _innerBuffer.Length)
                            {
                                var bytesToStoreInInnerBuffer = Math.Min(bytesToReadInThisIteration, _innerBuffer.Length - bytesStoredInInnerBuffer);

                                Array.Copy(tempBuffer, 0, _innerBuffer, bytesStoredInInnerBuffer, bytesToStoreInInnerBuffer);
                                bytesStoredInInnerBuffer += bytesToStoreInInnerBuffer;
                            }

                            //copy the chunk from the temp buffer to the buffer of the caller
                            Array.Copy(tempBuffer, 0, buffer, bytesRead, bytesToStoreInThisIteration);
                            bytesRead += bytesToReadInThisIteration;
                        }
                    }
                }
                catch
                {
                    if (isLocalTransaction && TransactionScope.IsActive)
                    {
                        TransactionScope.Rollback();

                        //cleanup
                        isLocalTransaction = false;
                        _fileStreamData    = null;
                    }

                    throw;
                }
                finally
                {
                    if (isLocalTransaction && TransactionScope.IsActive)
                    {
                        TransactionScope.Commit();

                        //Set filestream data to null as this was a local transaction and we cannot use it anymore
                        _fileStreamData = null;
                    }
                }
            }

            Position += realCount;

            return(realCount);
        }