using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using System.Data.SqlClient;

public partial class Default : System.Web.UI.Page
{
    const int MaxTotalBytes = 1048576; // 1 MB
    int totalBytes;

    public bool? IsRadAsyncValid
    {
        get
        {
            if (Session["IsRadAsyncValid"] == null)
            {
                Session["IsRadAsyncValid"] = true;
            }

            return Convert.ToBoolean(Session["IsRadAsyncValid"].ToString());
        }
        set
        {
            Session["IsRadAsyncValid"] = value;
        }
    }

    public static string ConnectionString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings["TelerikConnectionString35"].ConnectionString;
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        IsRadAsyncValid = null;
    }

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            RadAsyncUpload upload = ((GridEditableItem)e.Item)["Upload"].FindControl("AsyncUpload1") as RadAsyncUpload;
            TableCell cell = (TableCell)upload.Parent;

            CustomValidator validator = new CustomValidator();
            validator.ErrorMessage = "Please select file to be uploaded";
            validator.ClientValidationFunction = "validateRadUpload";
            validator.Display = ValidatorDisplay.Dynamic;
            cell.Controls.Add(validator);
        }
    }

    protected string TrimDescription(string description)
    {
        if (!string.IsNullOrEmpty(description) && description.Length > 200)
        {
            return string.Concat(description.Substring(0, 200), "...");
        }
        return description;
    }


    private static DataTable GetDataTable(string queryString)
    {
        SqlConnection MySqlConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter MySqlDataAdapter = new SqlDataAdapter();
        MySqlDataAdapter.SelectCommand = new SqlCommand(queryString, MySqlConnection);

        DataTable myDataTable = new DataTable();
        MySqlConnection.Open();
        try
        {
            MySqlDataAdapter.Fill(myDataTable);
        }
        finally
        {
            MySqlConnection.Close();
        }

        return myDataTable;
    }
    protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = GetDataTable("SELECT * FROM [Images]");
    }
    protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
    {
        if (!IsRadAsyncValid.Value)
        {
            e.Canceled = true;
            RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB");
            return;
        }

        GridEditFormInsertItem insertItem = e.Item as GridEditFormInsertItem;
        string imageName = (insertItem["ImageName"].FindControl("txbName") as RadTextBox).Text;
        string description = (insertItem["Description"].FindControl("txbDescription") as RadTextBox).Text;
        RadAsyncUpload radAsyncUpload = insertItem["Upload"].FindControl("AsyncUpload1") as RadAsyncUpload;

        UploadedFile file = radAsyncUpload.UploadedFiles[0];
        byte[] fileData = new byte[file.InputStream.Length];
        file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO [Images] ([Name], [Description], [Data]) VALUES (@Name, @Description, @Data)", conn);

            cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
            cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 4000, "Description");
            cmd.Parameters.Add("@Data", SqlDbType.Image);

            cmd.Parameters["@Name"].Value = imageName;
            cmd.Parameters["@Description"].Value = description;
            cmd.Parameters["@Data"].Value = fileData;

            cmd.ExecuteScalar();
        }
    }
    protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
    {
        if (!IsRadAsyncValid.Value)
        {
            e.Canceled = true;
            RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB");
            return;
        }
        GridEditableItem editedItem = e.Item as GridEditableItem;
        int ID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"].ToString());
        string imageName = (editedItem["ImageName"].FindControl("txbName") as RadTextBox).Text;
        string description = (editedItem["Description"].FindControl("txbDescription") as RadTextBox).Text;
        RadAsyncUpload radAsyncUpload = editedItem["Upload"].FindControl("AsyncUpload1") as RadAsyncUpload;

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            SqlCommand cmd;
            if (radAsyncUpload.UploadedFiles.Count > 0)
            {
                cmd = new SqlCommand("UPDATE [Images] SET [Name] = @Name, [Description] = @Description, [Data] = @Data WHERE [ID] = @ID", conn);
                UploadedFile file = radAsyncUpload.UploadedFiles[0];
                byte[] fileData = new byte[file.InputStream.Length];
                file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
                cmd.Parameters.Add("@Data", SqlDbType.Image);
                cmd.Parameters["@Data"].Value = fileData;
            }
            else
            {
                cmd = new SqlCommand("UPDATE [Images] SET [Name] = @Name, [Description] = @Description WHERE [ID] = @ID", conn);
            }

            cmd.Parameters.Add("@ID", SqlDbType.Int);
            cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
            cmd.Parameters.Add("@Description", SqlDbType.NVarChar);

            cmd.Parameters["@ID"].Value = ID;
            cmd.Parameters["@Name"].Value = imageName;
            cmd.Parameters["@Description"].Value = description;
            cmd.ExecuteScalar();
        }
    }
    protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
    {
        string ID = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("DELETE FROM Images WHERE ID = @ID", conn);

            cmd.Parameters.Add("@ID", SqlDbType.Int);

            cmd.Parameters["@ID"].Value = ID;
            cmd.ExecuteScalar();
        }
    }
    public void RadAsyncUpload1_ValidatingFile(object sender, Telerik.Web.UI.Upload.ValidateFileEventArgs e)
    {
        if ((totalBytes < MaxTotalBytes) && (e.UploadedFile.ContentLength < MaxTotalBytes))
        {
            e.IsValid = true;
            totalBytes += e.UploadedFile.ContentLength;
            IsRadAsyncValid = true;
        }
        else
        {
            e.IsValid = false;
            IsRadAsyncValid = false;
        }
    }
    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.EditCommandName)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SetEditMode", "isEditMode = true;", true);
        }
    }
}
