Skip to main content
Tab

ASPxBinaryImage.BinaryStorageMode Property

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

Namespace: DevExpress.Web

Assembly: DevExpress.Web.v23.2.dll

NuGet Package: DevExpress.Web

Declaration

[DefaultValue(BinaryStorageMode.Default)]
public BinaryStorageMode BinaryStorageMode { get; set; }

Property Value

Type Default Description
BinaryStorageMode Default

One of the BinaryStorageMode enumeration values.

Available values:

Name Description
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.

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>
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();
}
<%@ 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>
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);
    }
}
See Also