<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <title>ASP.NET Grid Demo - Attachment Column</title>
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
    <telerik:RadSkinManager ID="QsfSkinManager" runat="server" ShowChooser="true" />
    <telerik:RadFormDecorator ID="QsfFromDecorator" runat="server" DecoratedControls="All"
        EnableRoundedCorners="false" />
    <asp:RadioButtonList ID="DownloadOptionsRBL" runat="server">
        <asp:ListItem Text="Automatically download attachment from GridAttachmentColumn's data source"
            Value="Automatic" Selected="True">
        </asp:ListItem>
        <asp:ListItem Text="Manually download attachment using RadGrid's ItemCommand event"
            Value="Manual">
        </asp:ListItem>
    </asp:RadioButtonList>
    <br />
    <br />
    <div style="margin-bottom: 5px;">
        <asp:RadioButtonList ID="FireCommandOptionsRBL" runat="server" Style="display: inline;
            vertical-align: bottom; margin-right: 10px" RepeatDirection="Horizontal">
            <asp:ListItem Text="Fire from server-side" Value="Server" Selected="True">
            </asp:ListItem>
            <asp:ListItem Text="Fire from client-side" Value="Client">
            </asp:ListItem>
        </asp:RadioButtonList>
        <telerik:RadComboBox ID="FileNamesComboBox" runat="server" DataSourceID="SqlDataSource1"
            DataTextField="FileName" DataValueField="ID">
        </telerik:RadComboBox>
        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
            <script type="text/javascript">
                //<![CDATA[
                function download(args)
                {
                    if ($get("<%= FireCommandOptionsRBL.ClientID %>" + "_0").checked)
                    {
                        return true;
                    }

                    var grid = $find('<%= RadGrid1.ClientID %>');
                    var masterTable = grid.get_masterTableView();
                    var combo = $find('<%= FileNamesComboBox.ClientID %>');

                    var parameters = {};
                    parameters.ColumnUniqueName = "AttachmentColumn";
                    parameters.FileName = encodeURI(combo.get_text());
                    parameters.ID = +combo.get_value();

                    var json = Sys.Serialization.JavaScriptSerializer.serialize(parameters);
                    masterTable.fireCommand("DownloadAttachment", json);

                    return false;
                }

                    //]]>
            </script>
        </telerik:RadCodeBlock>
        <asp:Button ID="DownloadButton" runat="server" Text="Download" OnClientClick="return download(event);"
            OnClick="DownloadButton_Click"></asp:Button>
    </div>
    <telerik:RadCodeBlock ID="RadCodeBlock2" runat="server">
        <script type="text/javascript">
        //<![CDATA[
            function gridCommand(sender, args)
            {
                if (args.get_commandName() == "DownloadAttachment")
                {
                    var manager = $find('<%= RadAjaxManager.GetCurrent(Page).ClientID %>');
                    manager.set_enableAJAX(false);

                    setTimeout(function ()
                    {
                        manager.set_enableAJAX(true);
                    }, 0);
                }
            }

            function conditionalPostback(sender, eventArgs)
            {
                var eventArgument = eventArgs.get_eventArgument();

                if (eventArgument.indexOf("Update") > -1 || eventArgument.indexOf("PerformInsert") > -1)
                {
                    if (upload && upload.getFileInputs()[0].value != "")
                    {
                        eventArgs.set_enableAjax(false);
                    }
                }
            }

            var upload = null;


            function uploadFileSelected(sender, args)
            {
                upload = sender;
                var uploadContainer = sender.get_element();
                var fileNameTextBox = upload.getFileInputs()[0].title;
                fileNameTextBox.value = args.get_fileInputField().title;
                var nameWithPath = args.get_fileInputField().title;
                var realfileName = nameWithPath.split("\\");
                var fileName = realfileName[realfileName.length - 1];
                sender.get_parent().get_editItems()[0].get_cell("FileName").getElementsByTagName("input")[0].value = realfileName[realfileName.length - 1];
            }

            //]]>
        </script>
    </telerik:RadCodeBlock>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" EnableAJAX="true" DefaultLoadingPanelID="RadAjaxLoadingPanel1">
        <ClientEvents OnRequestStart="conditionalPostback"></ClientEvents>
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1"></telerik:AjaxUpdatedControl>
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
    </telerik:RadAjaxLoadingPanel>
    <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
        AllowSorting="True" AllowAutomaticUpdates="True" AllowAutomaticInserts="True"
        OnItemCommand="RadGrid1_ItemCommand" OnItemCreated="RadGrid1_ItemCreated" AutoGenerateEditColumn="True"
        CellSpacing="0" GridLines="None">
        <MasterTableView DataKeyNames="ID" EditMode="InPlace" CommandItemDisplay="Top" Width="100%">
            <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
            <RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
            </RowIndicatorColumn>
            <ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridBoundColumn DataField="ID" HeaderText="ID" ReadOnly="true" DataType="System.Int32"
                    SortExpression="ID">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="FileName" HeaderText="FileName" SortExpression="FileName">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="UploadDate" HeaderText="UploadDate" DataType="System.DateTime"
                    FilterControlAltText="Filter UploadDate column" SortExpression="UploadDate" UniqueName="UploadDate">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="UploadedBy" FilterControlAltText="Filter UploadedBy column"
                    HeaderText="UploadedBy" SortExpression="UploadedBy" UniqueName="UploadedBy">
                </telerik:GridBoundColumn>
                <telerik:GridAttachmentColumn DataSourceID="SqlDataSource2" MaxFileSize="1048576"
                    EditFormHeaderTextFormat="Upload File:" HeaderText="Download" AttachmentDataField="BinaryData"
                    AttachmentKeyFields="ID" FileNameTextField="FileName" DataTextField="FileName"
                    UniqueName="AttachmentColumn">
                </telerik:GridAttachmentColumn>
            </Columns>
            <EditFormSettings>
                <EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column">
                </EditColumn>
            </EditFormSettings>
        </MasterTableView>
        <ClientSettings>
            <ClientEvents OnCommand="gridCommand"></ClientEvents>
        </ClientSettings>
        <FilterMenu EnableImageSprites="False">
        </FilterMenu>
    </telerik:RadGrid>
    <div class="module" style="margin-top: 10px;">
        <label>
            <b>Note:</b> Maximum file size allowed: 1MB</label>
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TelerikConnectionString35 %>"
        InsertCommand="INSERT INTO [Files] ([FileName], [UploadDate], [UploadedBy]) VALUES (@FileName, @UploadDate, @UploadedBy) SET @InsertedID = SCOPE_IDENTITY()"
        SelectCommand="SELECT [ID], [FileName], [UploadDate], [UploadedBy] FROM [Files]"
        UpdateCommand="UPDATE [Files] SET [FileName] = @FileName, [UploadDate] = @UploadDate, [UploadedBy] = @UploadedBy WHERE [ID] = @ID"
        OnInserted="SqlDataSource1_Inserted" OnUpdated="SqlDataSource1_Updated">
        <UpdateParameters>
            <asp:Parameter Name="FileName" Type="String"></asp:Parameter>
            <asp:Parameter Name="UploadDate" Type="DateTime"></asp:Parameter>
            <asp:Parameter Name="UploadedBy" Type="String"></asp:Parameter>
            <asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="FileName" Type="String"></asp:Parameter>
            <asp:Parameter Name="UploadDate" Type="DateTime"></asp:Parameter>
            <asp:Parameter Name="UploadedBy" Type="String"></asp:Parameter>
            <asp:Parameter Name="InsertedID" Type="Int32" Direction="Output"></asp:Parameter>
        </InsertParameters>
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TelerikConnectionString35 %>"
        SelectCommand="SELECT [ID], [BinaryData] FROM [FileData] WHERE [ID] = @ID">
        <SelectParameters>
            <asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
        </SelectParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>
