/// <summary>
        /// Deletes file records that are marked as deleted from the metadata database and also from the blob storage.
        /// </summary>
        /// <returns>Whether there was at least one row that was deleted.</returns>
        public bool CleanupFiles()
        {
            using (var proc = new SqlProcedure {
                CommandText = CleanupFileScript, CommandType = CommandType.Text
            })
            {
                proc.CommandType = CommandType.Text;

                try
                {
                    var deleted = false;
                    using (var reader = proc.ExecuteReader())
                    {
                        var    fileId       = 0;
                        var    size         = 0L;
                        string providerName = null;
                        string providerData = null;
                        // We do not care about the number of deleted rows,
                        // we only want to know if a row was deleted or not.
                        if (reader.Read())
                        {
                            deleted      = true;
                            fileId       = reader.GetSafeInt32(reader.GetOrdinal("FileId"));
                            size         = reader.GetSafeInt64(reader.GetOrdinal("Size"));
                            providerName = reader.GetSafeString(reader.GetOrdinal("BlobProvider"));
                            providerData = reader.GetSafeString(reader.GetOrdinal("BlobProviderData"));
                        }

                        // delete bytes from the blob storage
                        // Delete algorithm is same in the BuiltIn and SqlFs providers.
                        var provider = BlobStorageBase.GetProvider(providerName);
                        var ctx      = new BlobStorageContext(provider, providerData)
                        {
                            VersionId = 0, PropertyTypeId = 0, FileId = fileId, Length = size
                        };

                        ctx.Provider.Delete(ctx);
                    }
                    return(deleted);
                }
                catch (Exception ex)
                {
                    throw new DataException("Error during binary cleanup.", ex);
                }
            }
        }
        private static Tuple <VersionNumber, VersionNumber> GetLastVersions(string path)
        {
            VersionNumber majorVersion = null;
            VersionNumber minorVersion = null;

            SqlProcedure  cmd    = null;
            SqlDataReader reader = null;

            try
            {
                cmd = new SqlProcedure
                {
                    CommandText = Scripts.LastVersions,
                    CommandType = CommandType.Text
                };
                cmd.Parameters.Add("@Path", SqlDbType.NVarChar, 450).Value = path;
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    var majorNumber = reader.GetInt16(reader.GetOrdinal("MajorNumber"));
                    var minorNumber = reader.GetInt16(reader.GetOrdinal("MinorNumber"));
                    var statusCode  = reader.GetInt16(reader.GetOrdinal("Status"));
                    var isLastMajor = reader.GetBoolean(reader.GetOrdinal("LastMajor"));
                    var isLastMinor = reader.GetBoolean(reader.GetOrdinal("LastMinor"));

                    var versionNumber = new VersionNumber(majorNumber, minorNumber, (VersionStatus)statusCode);

                    if (isLastMajor)
                    {
                        majorVersion = versionNumber;
                    }
                    if (isLastMinor)
                    {
                        minorVersion = versionNumber;
                    }
                }
            }
            finally
            {
                reader?.Dispose();
                cmd?.Dispose();
            }

            return(new Tuple <VersionNumber, VersionNumber>(majorVersion, minorVersion));
        }
Esempio n. 3
0
        private static void WriteSqlFileStream(Stream stream, int fileId, SqlFileStreamData fileStreamData = null)
        {
            SqlProcedure cmd = null;

            try
            {
                // if we did not receive a path and transaction context, retrieve it now from the database
                if (fileStreamData == null)
                {
                    cmd = new SqlProcedure {
                        CommandText = UpdateBinaryPropertyFileStreamScript, CommandType = CommandType.Text
                    };
                    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = fileId;

                    string path;
                    byte[] transactionContext;

                    // Set Stream column to NULL and retrieve file path and
                    // transaction context for the Filestream column.
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        path = reader.GetString(0);
                        transactionContext = reader.GetSqlBytes(1).Buffer;
                    }

                    fileStreamData = new SqlFileStreamData {
                        Path = path, TransactionContext = transactionContext
                    };
                }

                stream.Seek(0, SeekOrigin.Begin);

                using (var fs = new SqlFileStream(fileStreamData.Path, fileStreamData.TransactionContext, FileAccess.Write))
                {
                    // default buffer size is 4096
                    stream.CopyTo(fs);
                }
            }
            finally
            {
                cmd?.Dispose();
            }
        }
        /// <summary>
        /// Starts a chunked save operation on an existing content. It does not write any binary data
        /// to the storage, it only makes prerequisite operations - e.g. allocates a new slot in the storage.
        /// </summary>
        /// <param name="blobProvider">Blob storage provider.</param>
        /// <param name="versionId">Content version id.</param>
        /// <param name="propertyTypeId">Binary property type id.</param>
        /// <param name="fullSize">Full size (stream length) of the binary value.</param>
        /// <returns>A token containing all the information (db record ids) that identify a single entry in the blob storage.</returns>
        public string StartChunk(IBlobProvider blobProvider, int versionId, int propertyTypeId, long fullSize)
        {
            var isLocalTransaction = !TransactionScope.IsActive;

            if (isLocalTransaction)
            {
                TransactionScope.Begin();
            }

            var ctx = new BlobStorageContext(blobProvider)
            {
                VersionId = versionId, PropertyTypeId = propertyTypeId, FileId = 0, Length = fullSize
            };
            string blobProviderName = null;
            string blobProviderData = null;
            bool   useSqlFileStream;

            if (IsBuiltInOrSqlFileStreamProvider(blobProvider))
            {
                useSqlFileStream = SqlFileStreamBlobProvider.UseFileStream(blobProvider, fullSize);
            }
            else
            {
                useSqlFileStream = false;
                blobProvider.Allocate(ctx);
                blobProviderName = blobProvider.GetType().FullName;
                blobProviderData = BlobStorageContext.SerializeBlobProviderData(ctx.BlobProviderData);
            }

            try
            {
                using (var cmd = new SqlProcedure {
                    CommandText = InsertStagingBinaryScript, CommandType = CommandType.Text
                })
                {
                    cmd.Parameters.Add("@VersionId", SqlDbType.Int).Value              = versionId;
                    cmd.Parameters.Add("@PropertyTypeId", SqlDbType.Int).Value         = propertyTypeId;
                    cmd.Parameters.Add("@Size", SqlDbType.BigInt).Value                = fullSize;
                    cmd.Parameters.Add("@UseSqlFileStream", SqlDbType.TinyInt).Value   = useSqlFileStream ? 2 : 0;
                    cmd.Parameters.Add("@BlobProvider", SqlDbType.NVarChar, 450).Value = blobProviderName != null ? (object)blobProviderName : DBNull.Value;
                    cmd.Parameters.Add("@BlobProviderData", SqlDbType.NVarChar, int.MaxValue).Value = blobProviderData != null ? (object)blobProviderData : DBNull.Value;

                    int binaryPropertyId;
                    int fileId;

                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            binaryPropertyId = reader.GetSafeInt32(0);
                            fileId           = reader.GetSafeInt32(1);
                        }
                        else
                        {
                            throw new DataException("File row could not be inserted.");
                        }
                    }

                    ctx.FileId = fileId;

                    return(new ChunkToken
                    {
                        VersionId = versionId,
                        PropertyTypeId = propertyTypeId,
                        BinaryPropertyId = binaryPropertyId,
                        FileId = fileId
                    }.GetToken());
                }
            }
            catch (Exception ex)
            {
                if (isLocalTransaction && TransactionScope.IsActive)
                {
                    TransactionScope.Rollback();
                }

                throw new DataException("Error during saving binary chunk to SQL Server.", ex);
            }
            finally
            {
                if (isLocalTransaction && TransactionScope.IsActive)
                {
                    TransactionScope.Commit();
                }
            }
        }
        /// <summary>
        /// Loads a cache item into memory that either contains the raw binary (if its size fits into the limit) or
        /// just the blob metadata pointing to the blob storage.
        /// </summary>
        /// <param name="versionId">Content version id.</param>
        /// <param name="propertyTypeId">Binary property type id.</param>
        public BinaryCacheEntity LoadBinaryCacheEntity(int versionId, int propertyTypeId)
        {
            var commandText = string.Format(LoadBinaryCacheentityFormatScript, BlobStorage.BinaryCacheSize);

            using (var cmd = new SqlProcedure {
                CommandText = commandText
            })
            {
                cmd.Parameters.Add("@VersionId", SqlDbType.Int).Value      = versionId;
                cmd.Parameters.Add("@PropertyTypeId", SqlDbType.Int).Value = propertyTypeId;
                cmd.CommandType = CommandType.Text;

                using (var reader = cmd.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
                {
                    if (!reader.HasRows || !reader.Read())
                    {
                        return(null);
                    }

                    var length           = reader.GetInt64(0);
                    var binaryPropertyId = reader.GetInt32(1);
                    var fileId           = reader.GetInt32(2);

                    var providerName     = reader.GetSafeString(3);
                    var providerTextData = reader.GetSafeString(4);

                    byte[] rawData = null;

                    SqlFileStreamData fileStreamData = null;
                    var useFileStream = providerName == null && reader.GetInt32(6) == 1;
                    if (useFileStream)
                    {
                        // fill Filestream info if we really need it
                        fileStreamData = new SqlFileStreamData
                        {
                            Path = reader.GetSafeString(7),
                            TransactionContext = reader.GetSqlBytes(8).Buffer
                        };
                    }

                    var provider = useFileStream
                        ? new SqlFileStreamBlobProvider()
                        : BlobStorageBase.GetProvider(providerName);

                    var context = new BlobStorageContext(provider, providerTextData)
                    {
                        VersionId      = versionId,
                        PropertyTypeId = propertyTypeId,
                        FileId         = fileId,
                        Length         = length
                    };

                    if (provider == BlobStorageBase.BuiltInProvider)
                    {
                        context.BlobProviderData = new BuiltinBlobProviderData();
                    }
                    else if (provider is SqlFileStreamBlobProvider)
                    {
                        context.BlobProviderData = new SqlFileStreamBlobProviderData {
                            FileStreamData = fileStreamData
                        }
                    }
                    ;

                    if (IsBuiltInOrSqlFileStreamProvider(provider))
                    {
                        if (!reader.IsDBNull(5))
                        {
                            rawData = (byte[])reader.GetValue(5);
                        }
                    }

                    return(new BinaryCacheEntity
                    {
                        Length = length,
                        RawData = rawData,
                        BinaryPropertyId = binaryPropertyId,
                        FileId = fileId,
                        Context = context
                    });
                }
            }
        }
        /// <summary>
        /// Updates an existing binary property value in the database and the blob storage.
        /// </summary>
        /// <param name="blobProvider">Blob storage provider.</param>
        /// <param name="value">Binary data to update.</param>
        public void UpdateBinaryProperty(IBlobProvider blobProvider, BinaryDataValue value)
        {
            var streamLength = value.Stream?.Length ?? 0;
            var isExternal   = false;

            if (!IsBuiltInOrSqlFileStreamProvider(blobProvider))
            {
                var ctx = new BlobStorageContext(blobProvider, value.BlobProviderData)
                {
                    VersionId      = 0,
                    PropertyTypeId = 0,
                    FileId         = value.FileId,
                    Length         = streamLength,
                };

                blobProvider.Allocate(ctx);
                isExternal = true;

                value.BlobProviderName = ctx.Provider.GetType().FullName;
                value.BlobProviderData = BlobStorageContext.SerializeBlobProviderData(ctx.BlobProviderData);
            }
            else
            {
                value.BlobProviderName = null;
                value.BlobProviderData = null;
            }

            var isRepositoryStream = value.Stream is RepositoryStream || value.Stream is SenseNetSqlFileStream;
            var hasStream          = isRepositoryStream || value.Stream is MemoryStream;

            if (!isExternal && !hasStream)
            {
                // do not do any database operation if the stream is not modified
                return;
            }

            SqlFileStreamData fileStreamData = null;
            SqlProcedure      cmd            = null;

            try
            {
                string      sql;
                CommandType commandType;
                if (IsBuiltInOrSqlFileStreamProvider(blobProvider))
                {
                    commandType = CommandType.StoredProcedure;
                    sql         = "proc_BinaryProperty_Update";
                }
                else
                {
                    commandType = CommandType.Text;
                    sql         = UpdateBinarypropertyNewFilerowFilestreamScript;
                }

                cmd = new SqlProcedure {
                    CommandText = sql, CommandType = commandType
                };
                cmd.Parameters.Add("@BinaryPropertyId", SqlDbType.Int).Value      = value.Id;
                cmd.Parameters.Add("@ContentType", SqlDbType.NVarChar, 450).Value = value.ContentType;
                cmd.Parameters.Add("@FileNameWithoutExtension", SqlDbType.NVarChar, 450).Value = value.FileName.FileNameWithoutExtension == null ? DBNull.Value : (object)value.FileName.FileNameWithoutExtension;
                cmd.Parameters.Add("@Extension", SqlDbType.NVarChar, 50).Value     = ValidateExtension(value.FileName.Extension);
                cmd.Parameters.Add("@Size", SqlDbType.BigInt).Value                = value.Size;
                cmd.Parameters.Add("@Checksum", SqlDbType.VarChar, 200).Value      = value.Checksum != null ? (object)value.Checksum : DBNull.Value;
                cmd.Parameters.Add("@BlobProvider", SqlDbType.NVarChar, 450).Value = value.BlobProviderName != null ? (object)value.BlobProviderName : DBNull.Value;
                cmd.Parameters.Add("@BlobProviderData", SqlDbType.NVarChar, int.MaxValue).Value = value.BlobProviderData != null ? (object)value.BlobProviderData : DBNull.Value;

                int    fileId;
                string path;
                byte[] transactionContext;

                // Update row and retrieve file path and
                // transaction context for the Filestream column
                using (var reader = cmd.ExecuteReader())
                {
                    reader.Read();

                    fileId             = reader.GetInt32(0);
                    path               = reader.GetSafeString(1);
                    transactionContext = reader.IsDBNull(2) ? null : reader.GetSqlBytes(2).Buffer;
                }

                if (!string.IsNullOrEmpty(path))
                {
                    fileStreamData = new SqlFileStreamData {
                        Path = path, TransactionContext = transactionContext
                    }
                }
                ;

                if (fileId > 0 && fileId != value.FileId)
                {
                    value.FileId = fileId;
                }
            }
            finally
            {
                cmd?.Dispose();
            }

            if (blobProvider == BlobStorageBase.BuiltInProvider)
            {
                var ctx = new BlobStorageContext(blobProvider, value.BlobProviderData)
                {
                    VersionId        = 0,
                    PropertyTypeId   = 0,
                    FileId           = value.FileId,
                    Length           = streamLength,
                    BlobProviderData = new SqlFileStreamBlobProviderData {
                        FileStreamData = fileStreamData
                    }
                };

                BuiltInBlobProvider.UpdateStream(ctx, value.Stream);
            }
            else if (blobProvider is SqlFileStreamBlobProvider)
            {
                var ctx = new BlobStorageContext(blobProvider, value.BlobProviderData)
                {
                    VersionId        = 0,
                    PropertyTypeId   = 0,
                    FileId           = value.FileId,
                    Length           = streamLength,
                    BlobProviderData = new SqlFileStreamBlobProviderData {
                        FileStreamData = fileStreamData
                    }
                };

                SqlFileStreamBlobProvider.UpdateStream(ctx, value.Stream);
            }
            else
            {
                var ctx = new BlobStorageContext(blobProvider, value.BlobProviderData)
                {
                    VersionId      = 0,
                    PropertyTypeId = 0,
                    FileId         = value.FileId,
                    Length         = streamLength,
                };

                using (var stream = blobProvider.GetStreamForWrite(ctx))
                    value.Stream?.CopyTo(stream);
            }
        }
        /// <summary>
        /// Inserts a new binary property value into the metadata database and the blob storage,
        /// removing the previous one if the content is not new.
        /// </summary>
        /// <param name="blobProvider">Blob storage provider.</param>
        /// <param name="value">Binary data to insert.</param>
        /// <param name="versionId">Content version id.</param>
        /// <param name="propertyTypeId">Binary property type id.</param>
        /// <param name="isNewNode">Whether this value belongs to a new or an existing node.</param>
        public void InsertBinaryProperty(IBlobProvider blobProvider, BinaryDataValue value, int versionId, int propertyTypeId, bool isNewNode)
        {
            var streamLength  = value.Stream?.Length ?? 0;
            var useFileStream = SqlFileStreamBlobProvider.UseFileStream(blobProvider, streamLength);
            var ctx           = new BlobStorageContext(blobProvider)
            {
                VersionId = versionId, PropertyTypeId = propertyTypeId, FileId = 0, Length = streamLength
            };

            // In case of an external provider allocate the place for bytes and
            // write the stream beforehand and get the generated provider data.
            // Note that the external provider does not need an existing record
            // in the Files table to work, it just stores the bytes.
            if (!IsBuiltInOrSqlFileStreamProvider(blobProvider))
            {
                blobProvider.Allocate(ctx);

                using (var stream = blobProvider.GetStreamForWrite(ctx))
                    value.Stream?.CopyTo(stream);

                value.BlobProviderName = ctx.Provider.GetType().FullName;
                value.BlobProviderData = BlobStorageContext.SerializeBlobProviderData(ctx.BlobProviderData);
            }

            SqlProcedure      cmd            = null;
            SqlFileStreamData fileStreamData = null;

            try
            {
                cmd = useFileStream
                    ? new SqlProcedure {
                    CommandText = isNewNode ? InsertBinaryPropertyFilestreamScript : DeleteAndInsertBinaryPropertyFilestream, CommandType = CommandType.Text
                }
                    : new SqlProcedure {
                    CommandText = isNewNode ? InsertBinaryPropertyScript : DeleteAndInsertBinaryProperty, CommandType = CommandType.Text
                };

                cmd.Parameters.Add("@VersionId", SqlDbType.Int).Value             = versionId != 0 ? (object)versionId : DBNull.Value;
                cmd.Parameters.Add("@PropertyTypeId", SqlDbType.Int).Value        = propertyTypeId != 0 ? (object)propertyTypeId : DBNull.Value;
                cmd.Parameters.Add("@ContentType", SqlDbType.NVarChar, 450).Value = value.ContentType;
                cmd.Parameters.Add("@FileNameWithoutExtension", SqlDbType.NVarChar, 450).Value = value.FileName.FileNameWithoutExtension == null ? DBNull.Value : (object)value.FileName.FileNameWithoutExtension;
                cmd.Parameters.Add("@Extension", SqlDbType.NVarChar, 50).Value     = ValidateExtension(value.FileName.Extension);
                cmd.Parameters.Add("@Size", SqlDbType.BigInt).Value                = Math.Max(0, value.Size);
                cmd.Parameters.Add("@BlobProvider", SqlDbType.NVarChar, 450).Value = value.BlobProviderName != null ? (object)value.BlobProviderName : DBNull.Value;
                cmd.Parameters.Add("@BlobProviderData", SqlDbType.NVarChar, int.MaxValue).Value = value.BlobProviderData != null ? (object)value.BlobProviderData : DBNull.Value;
                cmd.Parameters.Add("@Checksum", SqlDbType.VarChar, 200).Value = value.Checksum != null ? (object)value.Checksum : DBNull.Value;

                // insert binary and file rows and retrieve file path and transaction context for the Filestream column
                using (var reader = cmd.ExecuteReader())
                {
                    reader.Read();

                    value.Id        = Convert.ToInt32(reader[0]);
                    value.FileId    = Convert.ToInt32(reader[1]);
                    value.Timestamp = Utility.Convert.BytesToLong((byte[])reader.GetValue(2));
                    if (useFileStream)
                    {
                        fileStreamData = new SqlFileStreamData
                        {
                            Path = reader.GetString(3),
                            TransactionContext = reader.GetSqlBytes(4).Buffer
                        };
                    }
                }
            }
            finally
            {
                cmd.Dispose();
            }

            // The BuiltIn blob provider saves the stream after the record
            // was saved into the Files table, because simple varbinary
            // and sql filestream columns must exist before we can write a
            // stream into the record.
            // ReSharper disable once InvertIf
            if (blobProvider == BlobStorageBase.BuiltInProvider && value.Stream != null)
            {
                ctx.FileId           = value.FileId;
                ctx.BlobProviderData = new SqlFileStreamBlobProviderData {
                    FileStreamData = fileStreamData
                };

                BuiltInBlobProvider.AddStream(ctx, value.Stream);
            }
            else if (blobProvider is SqlFileStreamBlobProvider && value.Stream != null)
            {
                ctx.FileId           = value.FileId;
                ctx.BlobProviderData = new SqlFileStreamBlobProviderData {
                    FileStreamData = fileStreamData
                };

                SqlFileStreamBlobProvider.AddStream(ctx, value.Stream);
            }
        }