using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using Telerik.Web.UI;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        fileId = (int)e.Command.Parameters["@InsertedID"].Value;
        UpdateInsertFileData("INSERT INTO [FileData] ([ID], [BinaryData]) VALUES (@ID, @BinaryData)", fileId);
    }

    protected void SqlDataSource1_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
        UpdateInsertFileData("UPDATE [FileData] SET [BinaryData] = @BinaryData WHERE [ID] = @ID", fileId);
    }

    int fileId;
    byte[] fileData;

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            RadUpload upload = (item.EditManager.GetColumnEditor("AttachmentColumn") as GridAttachmentColumnEditor).RadUploadControl;
            upload.OnClientFileSelected = "uploadFileSelected";
        }
    }

    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.DownloadAttachmentCommandName)
        {
            if (DownloadOptionsRBL.SelectedValue == "Manual")
            {
                e.Canceled = true;

                GridDownloadAttachmentCommandEventArgs args = e as GridDownloadAttachmentCommandEventArgs;
                string fileName = args.FileName;
                int attachmentId = (int)args.AttachmentKeyValues["ID"];

                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TelerikConnectionString35"].ConnectionString);
                SqlCommand comm = new SqlCommand("SELECT [BinaryData] FROM [FileData] WHERE [ID] = @ID", conn);
                comm.Parameters.Add(new SqlParameter("@ID", attachmentId));

                SqlDataAdapter adapter = new SqlDataAdapter(comm);
                DataSet data = new DataSet();
                adapter.Fill(data);

                byte[] binaryData = (byte[])data.Tables[0].Rows[0]["BinaryData"];

                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                Response.BinaryWrite(binaryData);
                Response.End();
            }
        }

        if (e.CommandName == RadGrid.UpdateCommandName ||
            e.CommandName == RadGrid.PerformInsertCommandName)
        {
            GridEditableItem item = e.Item as GridEditableItem;

            if (!(item is GridEditFormInsertItem))
            {
                fileId = (int)item.GetDataKeyValue("ID");
            }

            string fileName = (item.EditManager.GetColumnEditor("FileName") as GridTextBoxColumnEditor).Text;
            
            string test = ((item.EditManager.GetColumnEditor("AttachmentColumn") as GridAttachmentColumnEditor).RadUploadControl as RadUpload).UploadedFiles[0].FileName;

            fileData = (item.EditManager.GetColumnEditor("AttachmentColumn") as GridAttachmentColumnEditor).UploadedFileContent;
            DateTime? uploadDate = (item.EditManager.GetColumnEditor("UploadDate") as GridDateTimeColumnEditor).PickerControl.SelectedDate;
            string uploadedBy = (item.EditManager.GetColumnEditor("UploadedBy") as GridTextBoxColumnEditor).TextBoxControl.Text;

            if (fileData.Length == 0 || fileName.Trim() == string.Empty)
            {
                e.Canceled = true;
                RadGrid1.Controls.Add(new LiteralControl("<b style='color:red;'>No file uploaded. Action canceled.</b>"));
            }

            if (!uploadDate.HasValue || String.IsNullOrEmpty(uploadedBy.Trim()))
            {
                e.Canceled = true;
                RadGrid1.Controls.Add(new LiteralControl("<b style='color:red;'>Please, fill in all the fields.</b>"));
            }
        }
    }

    private int UpdateInsertFileData(string command, int fileId)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TelerikConnectionString35"].ConnectionString))
        {
            using (SqlCommand comm = new SqlCommand(command, conn))
            {
                comm.Parameters.Add(new SqlParameter("ID", fileId));
                comm.Parameters.Add(new SqlParameter("BinaryData", fileData));

                conn.Open();
                return comm.ExecuteNonQuery();
            }
        }
    }

    protected void DownloadButton_Click(object sender, EventArgs e)
    {
        int attachmentId = Int32.Parse(FileNamesComboBox.SelectedValue);
        string fileName = FileNamesComboBox.SelectedItem.Text;

        Dictionary<string, object> parameters = new Dictionary<string, object>();
        parameters["ColumnUniqueName"] = "AttachmentColumn";
        parameters["FileName"] = fileName;
        parameters["ID"] = attachmentId;

        RadGrid1.Items[0].FireCommandEvent(RadGrid.DownloadAttachmentCommandName, parameters);

    }
}
