Back to Devexpress

ASPxBinaryImage.BinaryStorageMode Property

aspnet-devexpress-dot-web-dot-aspxbinaryimage-ac5732d7.md

latest15.7 KB
Original Source

ASPxBinaryImage.BinaryStorageMode Property

Gets or sets a value that specifies the storage of binary data.

Namespace : DevExpress.Web

Assembly : DevExpress.Web.v25.2.dll

NuGet Package : DevExpress.Web

Declaration

csharp
[DefaultValue(BinaryStorageMode.Default)]
public BinaryStorageMode BinaryStorageMode { get; set; }
vb
<DefaultValue(BinaryStorageMode.Default)>
Public Property BinaryStorageMode As BinaryStorageMode

Property Value

TypeDefaultDescription
BinaryStorageModeDefault

One of the BinaryStorageMode enumeration values.

|

Available values:

NameDescription
Default

The Cache mode is used if another configuration isn’t defined by the BinaryStorageConfigurator.Mode field.

| | Cache |

Binary data is stored within a cache.

| | Session |

Binary data is stored within a session.

| | Custom |

Custom mode provides for implementing a custom scenario for storing and accessing binary data.

|

Remarks

This property is a wrapper of the BinaryImageEditProperties.BinaryStorageMode property.

Example

This example demonstrates how to implement different storage strategies for the DevExpress control’s binary images.

The FileCacheStrategy scenario implies the use of a specific folder on the server for storing the ASPxGauge’s binary images. Changing the control’s value causes generating its new image, which is stored into a specified folder. Cache is cleared every 10 minutes. Each image can be obtained by using its recourse key.

The StaticImageStrategy scenario implements storing the ASPxGridView binary data (a specific column with binary images) into a public folder within an application. Each image within the folder has its own static URL. In this scenario, cache is cleared every 60 minutes.

aspx
FileCacheStrategy demonstration:

<dx:ASPxGaugeControl ID="gaugeControl1" runat="server" BackColor="White" Height="260px" Value="20" Width="260px">
    <Gauges>
        <dx:CircularGauge Bounds="0, 0, 260, 260" Name="cGauge1">
            <BackgroundLayers>
                <dx:ArcScaleBackgroundLayerComponent Name="bg1" ScaleCenterPos="0.5, 0.61" ScaleID="scale1"
                    Size="250, 205" ZOrder="1000" ShapeType="CircularThreeFourth_Style7"></dx:ArcScaleBackgroundLayerComponent>
            </BackgroundLayers>
            <Needles>
                <dx:ArcScaleNeedleComponent EndOffset="-25" StartOffset="-21" ScaleID="scale1" Name="needle1"
                    ZOrder="-50" ShapeType="CircularFull_Style7"></dx:ArcScaleNeedleComponent>
            </Needles>
            <EffectLayers>
                <dx:ArcScaleEffectLayerComponent Name="effect1" 
                    Shader="&lt;ShaderObject Type=&quot;Opacity&quot; Data=&quot;Opacity[0.75]&quot;/&gt;"
                    ScaleID="scale1" Size="230, 110" ZOrder="-1000" ShapeType="CircularThreeFourth_Style7">
                </dx:ArcScaleEffectLayerComponent>
            </EffectLayers>
            <Scales>
                <dx:ArcScaleComponent Name="scale1" MaxValue="100" Value="20" MinorTickmark-ShapeType="Circular_Style7_1"
                    Center="125, 140" EndAngle="30" MajorTickCount="9" MinorTickCount="4" MajorTickmark-TextOffset="22"
                    MajorTickmark-TextOrientation="LeftToRight" MajorTickmark-FormatString="{0:F0}"
                    MajorTickmark-ShapeType="Circular_Style7_2" StartAngle="-210" RadiusX="83" RadiusY="83">
                </dx:ArcScaleComponent>
            </Scales>
        </dx:CircularGauge>
    </Gauges>
</dx:ASPxGaugeControl>

<dx:ASPxButton ID="ASPxButton1" runat="server" OnClick="ASPxButton1_Click" Text="Generate random value">
</dx:ASPxButton>

StaticImageStrategy demonstration:
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
                 OnHtmlDataCellPrepared="ASPxGridView1_HtmlDataCellPrepared"
                 DataSourceID="AccessDataSource1" KeyFieldName="CategoryID">
    <Columns>
        <dx:GridViewDataTextColumn FieldName="CategoryID" ReadOnly="True" />
            <EditFormSettings Visible="False" />
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="CategoryName" />
        <dx:GridViewDataTextColumn FieldName="Description" />
        <dx:GridViewDataBinaryImageColumn FieldName="Picture" Name="Picture" />
    </Columns>
</dx:ASPxGridView>
csharp
public void ASPxGridView1_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridViewTableDataCellEventArgs e) {
    if (e.DataColumn.FieldName == "Picture")
        (e.Cell.Controls[0] as BinaryImageDisplayControl).Attributes.Add("data-key", e.KeyValue.ToString());
}
protected void ASPxButton1_Click(object sender, EventArgs e) {
    Random rnd = new Random();
    gaugeControl1.Value = rnd.Next(100).ToString();
}
vb
Public Sub ASPxGridView1_HtmlDataCellPrepared(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridViewTableDataCellEventArgs)
    If e.DataColumn.FieldName = "Picture" Then
        TryCast(e.Cell.Controls(0), BinaryImageDisplayControl).Attributes.Add("data-key", e.KeyValue.ToString())
    End If
End Sub
Protected Sub ASPxButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim rnd As New Random()
    gaugeControl1.Value = rnd.Next(100).ToString()
End Sub
cshtml
<%@ Application Language="C#" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e) {
        DevExpress.Web.BinaryStorageConfigurator.Mode = DevExpress.Web.BinaryStorageMode.Custom;
        DevExpress.Web.BinaryStorageConfigurator.RegisterCustomStorageStrategy(new StaticImageStrategy());
        DevExpress.Web.BinaryStorageConfigurator.RegisterStorageStrategy(new FileCacheStrategy(),
            SupportsStrategy);
    }
    private bool SupportsStrategy(DevExpress.Web.ASPxWebControlBase control) {
        return control.GetType() == typeof(DevExpress.Web.ASPxGauges.ASPxGaugeControl);
    }
    void Application_End(object sender, EventArgs e) {
        // Code that runs on application shutdown
    }
    void Application_Error(object sender, EventArgs e) { 
        // Code that runs when an unhandled error occurs
    }
    void Session_Start(object sender, EventArgs e) {
        // Code that runs when a new session is started
    }
    void Session_End(object sender, EventArgs e) {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
    }
</script>
csharp
public class FileCacheStrategy : RuntimeStorageStrategy {
    public string FileCacheFolderPath = "~/FileCacheFolder/";
    public const int CacheClearingInterval = 1; // minutes
    public const int CacheExpirationTime = 10; // minutes

    public static DateTime LastCacheClearing = DateTime.MinValue;

    /* GetResourceKey
        1) the mime type is saved as a file's extension for further 
           use within the GetResourceData method.
        2) received key is used to generate the image url for further 
           use within the StoreResourceData, GetResourceData
    */
    public override string GetResourceKey(ASPxWebControlBase control, byte[] content, string mimeType) {

        string fileExtension = "";
        if(mimeType.StartsWith("image/"))
            fileExtension = "." + mimeType.Substring("image/".Length);
        return Guid.NewGuid().ToString() + fileExtension;
    }
    public override void StoreResourceData(ASPxWebControlBase control, string key, BinaryStorageData data) {
        ClearFileCacheIfNeeded(GetFolderPath());
        using(FileStream stream = new FileStream(GetFilePath(key), FileMode.OpenOrCreate))
            stream.Write(data.Content, 0, data.Content.Length);
    }
    public override BinaryStorageData GetResourceData(string key) {
        using(FileStream stream = new FileStream(GetFilePath(key), FileMode.Open)) {
            byte[] content = new byte[stream.Length];
            stream.Read(content, 0, content.Length);
            string mimeType = "image/" + key.Split('.')[1];
            return new BinaryStorageData(content, mimeType);
        }
        return null;
    }

    private static void ClearFileCacheIfNeeded(string physicalPath) {
        DateTime now = DateTime.Now;
        // cache clearing is launched after the specified time interval
        if(now - LastCacheClearing < TimeSpan.FromMinutes(CacheClearingInterval))
            return;

        string[] fileNames = Directory.GetFiles(physicalPath);
        foreach(string fileName in fileNames) {
            if(now - File.GetCreationTime(fileName) > TimeSpan.FromMinutes(CacheExpirationTime)) {
                try {
                    File.Delete(fileName);
                } catch { }
            }
        }
        LastCacheClearing = now;
    }
    private string GetFilePath(string key) {
        return GetFolderPath() + key;
    }
    private string GetFolderPath() {
        return HttpContext.Current.Server.MapPath(FileCacheFolderPath);
    }
}

// images are cached within the predefined public folder. The method returns an image url.
public class StaticImageStrategy : RuntimeStorageStrategy {
    public string StaticCacheFolderName = "StaticCacheFolder"; // public folder
    public const int FileExpirationTime = 60; // minutes

    public override string GetResourceUrl(ASPxWebControlBase control, byte[] content, string mimeType, string contentDisposition) {
        string fileExtension = "";
        var a = control.NamingContainer.BindingContainer;
        if (mimeType.StartsWith("image/"))
            fileExtension = "." + mimeType.Substring("image/".Length);

        string fileName = control.Attributes["data-key"] + fileExtension;
        string physicalPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}/", StaticCacheFolderName)) + fileName;

        if(File.Exists(physicalPath) && DateTime.Now - File.GetCreationTime(physicalPath) > TimeSpan.FromMinutes(FileExpirationTime))
            File.Delete(physicalPath);// an image is refreshed every hour
        if(!File.Exists(physicalPath)) {
            using(FileStream stream = new FileStream(physicalPath, FileMode.OpenOrCreate))
                stream.Write(content, 0, content.Length);
        }

        return String.Format("{0}/{1}", StaticCacheFolderName, fileName);
    }
}
vb
Public Class FileCacheStrategy
    Inherits RuntimeStorageStrategy

    Public FileCacheFolderPath As String = "~/FileCacheFolder/"
    Public Const CacheClearingInterval As Integer = 1 ' minutes
    Public Const CacheExpirationTime As Integer = 10 ' minutes

    Public Shared LastCacheClearing As Date = Date.MinValue

' GetResourceKey
' 1) the mime type is saved as a file's extension for further 
' use within the GetResourceData method.
' 2) received key is used to generate the image url for further 
' use within the StoreResourceData, GetResourceData
'    
    Public Overrides Function GetResourceKey(ByVal control As ASPxWebControlBase, ByVal content() As Byte, ByVal mimeType As String) As String

        Dim fileExtension As String = ""
        If mimeType.StartsWith("image/") Then
            fileExtension = "." & mimeType.Substring("image/".Length)
        End If
        Return Guid.NewGuid().ToString() & fileExtension
    End Function
    Public Overrides Sub StoreResourceData(ByVal control As ASPxWebControlBase, ByVal key As String, ByVal data As BinaryStorageData)
        ClearFileCacheIfNeeded(GetFolderPath())
        Using stream As New FileStream(GetFilePath(key), FileMode.OpenOrCreate)
            stream.Write(data.Content, 0, data.Content.Length)
        End Using
    End Sub
    Public Overrides Function GetResourceData(ByVal key As String) As BinaryStorageData
        Using stream As New FileStream(GetFilePath(key), FileMode.Open)
            Dim content(stream.Length - 1) As Byte
            stream.Read(content, 0, content.Length)
            Dim mimeType As String = "image/" & key.Split("."c)(1)
            Return New BinaryStorageData(content, mimeType)
        End Using
        Return Nothing
    End Function

    Private Shared Sub ClearFileCacheIfNeeded(ByVal physicalPath As String)
        Dim now As Date = Date.Now
        ' cache clearing is launched after the specified time interval
        If now.Subtract(LastCacheClearing) < TimeSpan.FromMinutes(CacheClearingInterval) Then
            Return
        End If

        Dim fileNames() As String = Directory.GetFiles(physicalPath)
        For Each fileName As String In fileNames
            If now - File.GetCreationTime(fileName) > TimeSpan.FromMinutes(CacheExpirationTime) Then
                Try
                    File.Delete(fileName)
                Catch
                End Try
            End If
        Next fileName
        LastCacheClearing = now
    End Sub
    Private Function GetFilePath(ByVal key As String) As String
        Return GetFolderPath() & key
    End Function
    Private Function GetFolderPath() As String
        Return HttpContext.Current.Server.MapPath(FileCacheFolderPath)
    End Function
End Class

' images are cached within the predefined public folder. The method returns an image url.
Public Class StaticImageStrategy
    Inherits RuntimeStorageStrategy

    Public StaticCacheFolderName As String = "StaticCacheFolder" ' public folder
    Public Const FileExpirationTime As Integer = 60 ' minutes

    Public Overrides Function GetResourceUrl(ByVal control As ASPxWebControlBase, ByVal content() As Byte, ByVal mimeType As String, ByVal contentDisposition As String) As String
        Dim fileExtension As String = ""
        Dim a = control.NamingContainer.BindingContainer
        If mimeType.StartsWith("image/") Then
            fileExtension = "." & mimeType.Substring("image/".Length)
        End If

        Dim fileName As String = control.Attributes("data-key") & fileExtension
        Dim physicalPath As String = HttpContext.Current.Server.MapPath(String.Format("~/{0}/", StaticCacheFolderName)) & fileName

        If File.Exists(physicalPath) AndAlso Date.Now - File.GetCreationTime(physicalPath) > TimeSpan.FromMinutes(FileExpirationTime) Then
            File.Delete(physicalPath) ' an image is refreshed every hour
        End If
        If Not File.Exists(physicalPath) Then
            Using stream As New FileStream(physicalPath, FileMode.OpenOrCreate)
                stream.Write(content, 0, content.Length)
            End Using
        End If

        Return String.Format("{0}/{1}", StaticCacheFolderName, fileName)
    End Function
End Class

See Also

BinaryStorageMode

Binary Image

ASPxBinaryImage Class

ASPxBinaryImage Members

DevExpress.Web Namespace