public static void DeleteFile(string filename)
 {
     string account = (string)HttpContext.Current.Session["user"].ToString();
     BlobManager blob = new BlobManager();
     blob.DeleteBlob("Temp/" + account + "/" + filename);
     //new Upload<DetailsFile>().PostedFiles.Remove(filename);
 }
 protected void deleteFile(string fname)
 {
     FileInforMa.File_Delete(fileId.Text, fname);
     getFile(fileId.Text);
     BlobManager blobManager = new BlobManager();
     blobManager.DeleteBlob(HiddenFieldCustomerID.Value + "/" + fname);
     if (fileGrid.Rows.Count ==0)
         Server.Transfer("CheckOwnFile.aspx");
 }
 protected void ButtonAllFilesDelete_Click(object sender, EventArgs e)
 {
     BlobManager blobManager = new BlobManager();
     foreach (GridViewRow row in fileGrid.Rows)
     {
         string fname = row.Cells[2].Text;
         FileInforMa.File_Delete(fileId.Text, fname);
     }
     blobManager.DeleteBlobDirectory(HiddenFieldCustomerID.Value);
     ButtonBack_Click(sender, e);
 }
        /// <summary>
        /// ButtonAdd Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                List<FileInfoMation> list = new List<FileInfoMation>();
                //Check exist file file
                txtFilePath.Text = "";
                if (PostedFiles.ContainsKey(Path.GetFileName(FileUploadSelect.PostedFile.FileName)))
                {
                    //already exist file
                    PostedFiles.Remove(Path.GetFileName(FileUploadSelect.PostedFile.FileName));
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_SELECTED_FILE_ALREADY_UPLOAD") + "');", true);
                    return;
                }
                if (string.IsNullOrEmpty(Path.GetFileName(FileUploadSelect.PostedFile.FileName)))
                {
                    //Not file
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_SELECTED_FILE_NOT_EXIST") + "');", true);
                    return;
                }
                // pass
                if (!PostedFiles.ContainsKey(Path.GetFileName(FileUploadSelect.PostedFile.FileName)))
                {
                    List<FileInfoMation> listtemp = new List<FileInfoMation>();
                    FileInfoMation obj = new FileInfoMation();

                    if (ViewState["HashCheckArray"] != null)
                        list = (List<FileInfoMation>)ViewState["HashCheckArray"];

                    listtemp = list.Where(c => c.File_Name == Path.GetFileName(FileUploadSelect.PostedFile.FileName)).ToList();
                    if (listtemp.Count > 0)
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_SELECTED_FILE_ALREADY_UPLOAD") + "');", true);
                        return;
                    }

                    if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "" && FileUploadSelect.FileContent.Length >= Constant.MAX_FILE_COMPARE)
                    {
                        string blobName = "Temp/" + HiddenFieldAccount.Value + "/" +   FileUploadSelect.PostedFile.FileName;
                        BlobManager blob = new BlobManager();
                        blob.UploadFromStream(FileUploadSelect.PostedFile.InputStream, blobName);

                        PostedFiles.Add(Path.GetFileName(FileUploadSelect.PostedFile.FileName), null);
                    }
                    else
                    {
                        PostedFiles.Add(Path.GetFileName(FileUploadSelect.PostedFile.FileName), FileUploadSelect.PostedFile);
                    }
                    obj.File_Sharing_ID = HiddenFieldID.Value;
                    obj.File_Name = Path.GetFileName(FileUploadSelect.PostedFile.FileName);
                    obj.File_Size = FileUploadSelect.PostedFile.ContentLength.ToString();
                    obj.Upload_Date = DateTime.Now.ToString();
                    list.Add(obj);
                    ViewState.Add("HashCheckArray", list);
                    FillGridview(list);
                }
            }
            catch (Exception ex)
            {
                ButtonAddFile.Enabled = true;
                txtFilePath.Text = "";
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_ERROR"), ex.Message) + "\");");
            }
        }
        /// <summary>
        /// Upload............
        /// </summary>
        /// <param name="dicPostedFiles"></param>
        private void StartUpload(Dictionary<string, HttpPostedFile> dicPostedFiles)
        {
            string EmailCustomer = "";
            string EmailMember = "";
            string listName = "";

            #region Upload file
            if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
            {
                BlobManager blobManager = new BlobManager();
                foreach (string fileName in dicPostedFiles.Keys)
                {
                    HttpPostedFile postedFile = dicPostedFiles[fileName];
                    long ContentLength = 0;
                    if (postedFile == null)
                    {
                        ContentLength = blobManager.CopyBlob("Temp/" + HiddenFieldAccount.Value + "/" +  fileName, LabelCustomerName.Text + "/" + fileName);
                    }
                    else
                    {
                        ContentLength = postedFile.ContentLength;
                        blobManager.UploadFromStream(postedFile.InputStream, LabelCustomerName.Text + "/" + fileName);
                    }

                    listName += fileName + ", ";
                    FileInfoMation obj = new FileInfoMation();
                    obj.File_Sharing_ID = HiddenFieldID.Value;
                    obj.File_Name = Path.GetFileName(fileName);
                    obj.File_Size = ContentLength.ToString();
                    obj.Upload_Date = DateTime.Now.ToString();
                    FileInforMa.File_Insert(obj);
                }
            }
            else
            {
                foreach (HttpPostedFile postedFile in dicPostedFiles.Values)
                {
                    CreateFolder();
                    string directoryPath = Server.MapPath("~/" + Constant.UPLOAD_STORAGE + "\\" + LabelCustomerName.Text.Trim());
                    postedFile.SaveAs(directoryPath + "\\" + Path.GetFileName(postedFile.FileName));

                    listName += Path.GetFileName(postedFile.FileName) + ", ";
                    FileInfoMation obj = new FileInfoMation();
                    obj.File_Sharing_ID = HiddenFieldID.Value;
                    obj.File_Name = Path.GetFileName(postedFile.FileName);
                    obj.File_Size = postedFile.ContentLength.ToString();
                    obj.Upload_Date = DateTime.Now.ToString();
                    FileInforMa.File_Insert(obj);
                }

            }
            #endregion

            #region SendMail
            if (!string.IsNullOrEmpty(listName))
            {
                listName = listName.Remove(listName.Length - 2);
                ///// send mail customer
                List<CustomerInfo> listCustomer = new List<CustomerInfo>();
                listCustomer = CustomerCallControl.File_GetByAll();
                listCustomer = listCustomer.Where(c => c.File_Sharing_ID == HiddenFieldID.Value).ToList();
                EmailCustomer = listCustomer[0].CustomerEmail;

                UserMail mailSystemCus = new UserMail(HiddenFieldAccount.Value, HiddenFieldAccount.Value, EmailCustomer);
                mailSystemCus.AddParams("{FileName}", listName);
                string mailBody = GetMailBody("Alert_mail_upload.txt");
                mailSystemCus.SendEmail(mailSystemCus, Common.GetResourceString("MAIL_UploadSubject"), mailBody);

                ///// send mail member
                List<DDMemberInfoCustomer> listMemberAccount = new List<DDMemberInfoCustomer>();
                listMemberAccount = DDMemberCallControlCustomer.File_GetByAll();
                listMemberAccount = listMemberAccount.Where(c => c.Account == HiddenFieldAccount.Value).ToList();
                EmailMember = listMemberAccount[0].Email;

                UserMail mailSystemMem = new UserMail(HiddenFieldAccount.Value, HiddenFieldAccount.Value, EmailMember);
                mailSystemMem.AddParams("{FileName}", listName);
                mailSystemMem.SendEmail(mailSystemMem, Common.GetResourceString("MAIL_UploadSubject"), mailBody);
                PostedFiles = new Dictionary<string, HttpPostedFile>();
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_SUCESS"), GetResource("MSG_UPLOAD_SUCESS")) + "\");");
            }
            else
                throw new Exception(GetResource("MSG_AT_LEAST_ONE_CUSTOMER"));
            #endregion
        }
        /// <summary>
        /// Delete event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewlistUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string count = GridViewlistUpload.Rows[e.RowIndex].Cells[0].Text.ToString();
            string id = GridViewlistUpload.Rows[e.RowIndex].Cells[1].Text.ToString();
            string name = GridViewlistUpload.Rows[e.RowIndex].Cells[2].Text.ToString();

            List<FileInfoMation> list = new List<FileInfoMation>();
            List<FileInfoMation> listOld = new List<FileInfoMation>();
            List<FileInfoMation> listtemp = new List<FileInfoMation>();

            list = (List<FileInfoMation>)ViewState["HashCheckArray"];
            listOld = FileInforMa.File_GetByAll();
            listOld = listOld.Where(c => c.File_Sharing_ID == id).ToList();
            //check value data
            listtemp = listOld.Where(c => c.File_Name == name).ToList();
            if (listtemp.Count > 0)
            {
                FileInforMa.File_Delete(id, name);
                if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                {
                    BlobManager blobManger = new BlobManager();
                    blobManger.DeleteBlob(LabelCustomerName.Text + "/" + name);
                }
                else
                {
                    string customerFoler = Path.Combine(GetMapPath() + Constant.UPLOAD_STORAGE + "\\" + LabelCustomerName.Text);
                    if (File.Exists(customerFoler + "\\" + name))
                    {
                        File.Delete(customerFoler + "\\" + name);
                    }
                }
            }
            else if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
            {
                BlobManager blobManger = new BlobManager();
                blobManger.DeleteBlob("Temp/" + HiddenFieldAccount.Value + "/" +  name);
            }

            PostedFiles.Remove(name);
            list = list.Where(c => c.File_Name != name).ToList();

            ViewState.Remove("HashCheckArray");
            ViewState["HashCheckArray"] = list;
            FillGridview(list);
        }
        /// <summary>
        /// ButtonUpload Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonUpload_Click(object sender, EventArgs e)
        {
            Dictionary<string, HttpPostedFile> dicPostedFiles = PostedFiles;
            try
            {
                StartUpload(dicPostedFiles);
                List<FileInfoMation> listFile = new List<FileInfoMation>();
                listFile = FileInforMa.File_GetByAll();
                listFile = listFile.Where(c => c.File_Sharing_ID == HiddenFieldID.Value).ToList();
                ViewState.Remove("HashCheckArray");
                ViewState.Add("HashCheckArray", listFile);
                FillGridview(listFile);
            }
            catch (Exception ex)
            {
                ButtonUpload.Enabled = true;
                if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                {
                    BlobManager blobManager = new BlobManager();
                    foreach (string fileName in dicPostedFiles.Keys)
                    {
                        HttpPostedFile postedFile = dicPostedFiles[fileName];
                        if (postedFile == null)
                        {
                            blobManager.DeleteBlob("Temp/" + HiddenFieldAccount.Value + "/" +  fileName);
                        }
                        else
                            blobManager.DeleteBlob(LabelCustomerName.Text + "/" + fileName);
                    }
                }
                else
                {
                    foreach (HttpPostedFile postedFile in dicPostedFiles.Values)
                    {
                        string directoryPath = Server.MapPath("~/" + Constant.UPLOAD_STORAGE + "\\" + LabelCustomerName.Text.Trim() + "\\" + Path.GetFileName(postedFile.FileName));
                        if (File.Exists(directoryPath))
                            File.Delete(directoryPath);

                    }
                }
                logger.Error("Error btnUpload_Click", ex);
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_ERROR"), ex.Message) + "\");");
            }
        }
        /// <summary>
        /// Download Azure
        /// </summary>
        protected void DownloadAzure()
        {
            string fileName = "";
            string listName = "";
            List<String> names = new List<String>();
            string Email = "";
            ZipFile zip = new ZipFile();

            // Get Name
            for (int i = 0; i < CheckBoxListFile.Items.Count; i++)
            {
                if (CheckBoxListFile.Items[i].Selected)
                {
                    fileName = CheckBoxListFile.Items[i].ToString();
                    listName += fileName + ", ";
                    names.Add(fileName);
                }
            }
            //Send Mail And download
            if (!string.IsNullOrEmpty(listName))
            {
                //Send Mail
                try
                {
                    List<DDMemberInfoCustomer> listMemberAccount = new List<DDMemberInfoCustomer>();
                    listMemberAccount = DDMemberCallControlCustomer.File_GetByAll();
                    listMemberAccount = listMemberAccount.Where(c => c.Account == HiddenFieldAcount.Value).ToList();
                    Email = listMemberAccount[0].Email;

                    UserMail mailSystem = new UserMail(HiddenFieldAcount.Value, HiddenFieldAcount.Value, Email);
                    var listNamenew = listName.Remove(listName.Length - 2);
                    mailSystem.AddParams("{FileName}", listNamenew);
                    string mailBody = GetMailBody("Alert_mail_download.txt");

                    mailSystem.SendEmail(mailSystem, Common.GetResourceString("MAIL_DownloadSubject"), mailBody);
                }
                catch
                {

                }

                // Download
                BlobManager blobManager = new BlobManager();
                foreach (string namenew in names)
                {

                    WebClient client = new WebClient();
                    var s = client.OpenRead(blobManager.GetURi(LabelCustomerName.Text  + "/" + namenew));
                    zip.MaxOutputSegmentSize = 1024 * 1024 * 1024;
                    zip.AddEntry(namenew, s);
                }

                ButtonDownload.Enabled = true;
                Response.Clear();
                Response.Buffer = false;
                Response.BufferOutput = false;
                Response.ContentType = "application/zip";
                if (names.Count > 1)
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + LabelCustomerName.Text + GetResource("All_Files") + ".zip");
                else
                {
                    fileName = fileName.Remove(fileName.Length - 4);
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
                }
                Response.Flush();
                zip.Save(Response.OutputStream);
               Response.End();
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_AT_LEST_ONE_FILE_DOWNLOAD") + "');", true);
                return;
            }
        }
        protected void downloadFile(string fName)
        {
            try
            {
                string fileName = "";
                string filePath = "";
                string listName = "";
                List<String> names = new List<String>();
                string Email = "";

                ZipFile zip = new ZipFile();
                if (fName == null)
                {
                    foreach (GridViewRow row in fileGrid.Rows)
                    {
                        fileName = row.Cells[2].Text;
                        listName += fileName + ", ";
                        names.Add(fileName);
                    }
                }
                else
                {
                    fileName = fName;
                    listName += fileName + ", ";
                    names.Add(fileName);
                }
                #region User Azure
                if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                {
                    // Send Mail
                    foreach( GridViewRow row in gridCustomers.Rows)
                    {
                        Email = row.Cells[1].Text;
                    }

                    UserMail mailSystem = new UserMail("A", "A", Email);
                    var listNamenew = listName.Remove(listName.Length - 2);
                    mailSystem.AddParams("{FileName}", listNamenew);
                    string mailBody = GetMailBody("Alert_mail_download.txt");
                    mailSystem.SendEmail(mailSystem, "Download Notice", mailBody);

                    // Download
                    BlobManager blobManager = new BlobManager();
                    foreach (string namenew in names)
                    {
                        WebClient client = new WebClient();
                        var s = client.OpenRead(blobManager.GetURi(LabelCustomerName.Text + "/" + namenew));
                        zip.AddEntry(namenew, s);
                    }
                    Response.Clear();
                    Response.ContentType = "application/zip";
                    if(names.Count > 1)
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + LabelCustomerName.Text + GetResource("All_Files") + ".zip");
                    else
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
                    zip.Save(Response.OutputStream);
                    Response.End();
                }
                #endregion

                #region User WebServer
                else
                {
                    string customerFoler = Server.MapPath("~/" + Constant.UPLOAD_STORAGE) + "\\" + LabelCustomerName.Text;
                    foreach(string NameNew in names)
                    {
                        filePath = string.Format("{0}\\{1}", customerFoler, NameNew);
                        if (!File.Exists(filePath))
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_FILE_DOWNLOAD_FOUND") + "');", true);
                            return;
                        }
                        if (names.Count > 1)
                            zip.AddFile(filePath, LabelCustomerName.Text + GetResource("All_Files"));
                        else
                            zip.AddFile(filePath, NameNew);
                    }
                    if (!string.IsNullOrEmpty(listName))
                    {
                        foreach (GridViewRow row in gridCustomers.Rows)
                        {
                            Email += row.Cells[1].Text + ";";
                        }
                        Email = Email.Substring(0, Email.Length - 1);
                        UserMail mailSystem = new UserMail("A", "A", Email);
                        listName = listName.Remove(listName.Length - 2);
                        mailSystem.AddParams("{FileName}", listName);
                        string mailBody = GetMailBody("Alert_mail_download.txt");
                        mailSystem.SendEmail(mailSystem, "Download Notice", mailBody);

                        Response.Clear();
                        Response.ContentType = "application/zip";
                        if(names.Count > 1)
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + LabelCustomerName.Text + GetResource("All_Files") + ".zip");
                        else
                            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
                        zip.Save(Response.OutputStream);
                        Response.End();
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert('" + GetResource("MSG_AT_LEST_ONE_FILE_DOWNLOAD") + "');", true);
                        return;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_ERROR"), ex.Message) + "\");");
                return ;
            }
        }
        public void DeleteFiles()
        {
            try
            {
                logger.Info("Begin WS DeleteFiles from Webservice");
                List<SharingInfo> listSharingInfo = new List<SharingInfo>();
                SharingInfo objSharingInfo = new SharingInfo();
                using (SqlConnection cnn = new SqlConnection(Common.GetConnectString()))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "select * from TD_SHARING_INFO where Expiration_date < getdate() and delete_flag = 0";
                    cmd.Connection = cnn;
                    cnn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            listSharingInfo.Add(objSharingInfo.CustomerIDataReader(dr));
                        }
                    }
                    cnn.Close();
                }

                if (listSharingInfo.Count > 0)
                {
                    if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                    {
                        BlobManager blobManger = new BlobManager();
                        for (int i = 0; i < listSharingInfo.Count; i++)
                        {
                            blobManger.DeleteBlobDirectory(listSharingInfo[i].customer_id);
                            UpdateSharingInfo(listSharingInfo[i].ID);
                        }
                    }
                    else
                    {
                        string hostPath = GetMapPath();
                        for (int i = 0; i < listSharingInfo.Count; i++)
                        {
                            string pathCustomerID = System.IO.Path.Combine(hostPath, Constant.UPLOAD_STORAGE + "\\" + listSharingInfo[i].customer_id);
                            if (Directory.Exists(pathCustomerID))
                                Directory.Delete(pathCustomerID, true);

                            UpdateSharingInfo(listSharingInfo[i].ID);

                        }
                    }
                }

                logger.Info("End DeleteFiles from Webservice");
            }
            catch (Exception ex)
            {
                logger.Error("Error in DeleteFiles " , ex);
                throw ex;
            }
        }
        public void DeleteDirectoryNotExistInDB()
        {
            try
            {
                if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "") //only case for has blob , manage blob
                {

                    logger.Debug("Begin DeleteDirectoryNotExistInDB ");
                    BlobManager blob = new BlobManager();
                    List<string> listDirectory = blob.GetDirectoryListInContainer();
                    string listCustomerId = "";
                    foreach (string i in listDirectory)
                    {
                        listCustomerId += string.Format("'{0}',", i);
                    }
                    if (listCustomerId.EndsWith(","))
                        listCustomerId = listCustomerId.Remove(listCustomerId.Length - 1, 1);

                    List<SharingInfo> listSharingInfo = new List<SharingInfo>();
                    using (SqlConnection cnn = new SqlConnection(Common.GetConnectString()))
                    {
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandType = System.Data.CommandType.Text;

                        cmd.CommandText = string.Format("select distinct S.customer_id from TD_SHARING_INFO as S , TD_FILE_INFO as F where S.ID = F.File_Sharing_ID and S.customer_id in ({0})", listCustomerId);
                        cmd.Connection = cnn;
                        cnn.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                        if (dr.HasRows)
                        {
                            while (dr.Read())
                            {
                                SharingInfo objSharingInfo = new SharingInfo();
                                objSharingInfo.customer_id = (dr["customer_id"] is DBNull) ? string.Empty : dr["customer_id"].ToString();

                                listSharingInfo.Add(objSharingInfo);
                            }
                        }
                        cnn.Close();
                    }

                    if (listDirectory.Count > listSharingInfo.Count)
                    {
                        foreach (string i in listDirectory)
                        {
                            SharingInfo objShare = listSharingInfo.FirstOrDefault(p => p.customer_id == i);
                            if (objShare == null)
                            {
                                logger.Debug("Delete directory = " + i);
                                blob.DeleteBlobDirectory(i);
                            }
                        }
                    }
                    logger.Debug("End DeleteDirectoryNotExistInDB ");

                }
            }
            catch (Exception ex)
            {
                logger.Error("Error in DeleteDirectoryNotExistInDB ", ex);
            }
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                string userLogin = hiddenAccount.Value;
                logger.Info("Begin btnUpload_Click userLogin = "******"0" : "1";
                DateTime expireDate = DateTime.Now.Date.AddDays(Convert.ToInt32(dropdownTermUpload.SelectedValue));
                //1. check Customer list
                if (this.CustomerInfo.Count == 0)
                    throw new Exception(GetResource("MSG_AT_LEAST_ONE_CUSTOMER"));

                //1.2 Check At least ONE upload file
                if (panelUploadFiles.Visible == false || PostedFiles.Count == 0)
                    throw new Exception(GetResource("MSG_AT_LEST_ONE_FILE_UPLOAD"));

                //2.Update Database
                string hostPath = GetMapPath();
                List<UserMail> listMailSystem = new List<UserMail>();
                using (SqlConnection Conn = new SqlConnection(Common.GetConnectString()))
                {
                    SqlTransaction Trans = null;
                    try
                    {
                        Conn.Open();
                        UserMail accountMailLogin = null;
                        using (SqlCommand cmd = new SqlCommand("DDV_GetDDMemberEmail", Conn))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@Account", userLogin);
                            var emailAdress = cmd.ExecuteScalar();
                            if (emailAdress != null)
                                accountMailLogin = new UserMail(userLogin, userLogin, emailAdress.ToString());
                        }
                        logger.Debug("Begin Transaction for update db");
                        Trans = Conn.BeginTransaction();

                        #region Update Database , files

                        foreach (CustomerInfo customer in this.CustomerInfo)
                        {
                            customer.CustomerId = KeyGenerator.GetUniqueKey(20);
                            string customerPass = KeyGenerator.GetUniqueKey(10);
                            string fileSharingId = "";
                            using (SqlCommand cmd = new SqlCommand("DDV_InsertSharingInfo", Conn, Trans))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;
                                cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
                                cmd.Parameters.AddWithValue("@dd_member_account", userLogin);
                                cmd.Parameters.AddWithValue("@Mode_code", modeCode);
                                cmd.Parameters.AddWithValue("@customer_id", customer.CustomerId);
                                cmd.Parameters.AddWithValue("@customer_password", customerPass);
                                cmd.Parameters.AddWithValue("@expiration_date", expireDate);

                                cmd.ExecuteNonQuery();
                                fileSharingId = cmd.Parameters["@id"].Value.ToString();
                            }
                            using (SqlCommand cmd = new SqlCommand("DDV_InsertCustomerInfo", Conn, Trans))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;
                                cmd.Parameters.AddWithValue("@File_Sharing_ID", fileSharingId);
                                cmd.Parameters.AddWithValue("@Customer_name", customer.CustomerName);
                                cmd.Parameters.AddWithValue("@Customer_Email", customer.CustomerEmail);
                                cmd.ExecuteNonQuery();
                            }

                            //Case Upload File
                            string listFileName = "";
                            if (panelUploadFiles.Visible)
                            {
                                logger.Debug("Upload files in customerID =  " + customer.CustomerId);
                                if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                                {
                                    BlobManager blobManager = new BlobManager();

                                    foreach (DetailsFile objfile in PostedFiles)
                                    {
                                        string blobName = customer.CustomerId + "/" + objfile.FileName;
                                        string soureBlob = "Temp/" + hiddenAccount.Value + "/" + objfile.FileName;

                                        long contentLenght =  blobManager.CopyBlob(soureBlob, blobName);

                                        if (contentLenght > 0)
                                        {
                                            listFileName += objfile.FileName + ",";

                                            using (SqlCommand cmd = new SqlCommand("DDV_InsertFileInfo", Conn, Trans))
                                            {
                                                cmd.CommandType = CommandType.StoredProcedure;
                                                cmd.Parameters.AddWithValue("@File_Sharing_ID", fileSharingId);
                                                cmd.Parameters.AddWithValue("@File_Name", Path.GetFileName(objfile.FileName));
                                                cmd.Parameters.AddWithValue("@File_Size", objfile.ContentLength);
                                                cmd.Parameters.AddWithValue("@Upload_Date", DateTime.Now.Date);
                                                cmd.ExecuteNonQuery();
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    string pathCustomerID = CreateUploadCustomerID(hostPath, customer.CustomerId);
                                    foreach (DetailsFile postedFile in PostedFiles)
                                    {

                                        listFileName += postedFile.FileName + "\n";
                                        using (SqlCommand cmd = new SqlCommand("DDV_InsertFileInfo", Conn, Trans))
                                        {
                                            cmd.CommandType = CommandType.StoredProcedure;
                                            cmd.Parameters.AddWithValue("@File_Sharing_ID", fileSharingId);
                                            cmd.Parameters.AddWithValue("@File_Name", postedFile.FileName);
                                            cmd.Parameters.AddWithValue("@File_Size", postedFile.ContentLength);
                                            cmd.Parameters.AddWithValue("@Upload_Date", DateTime.Now.Date);
                                            cmd.ExecuteNonQuery();
                                        }
                                    }
                                }
                            }
                            //Add Mail System
                            UserMail mailSystem = new UserMail(customer.CustomerName, customer.CustomerName, customer.CustomerEmail);
                            mailSystem.AddParams("{DD_MEMBER_NAME}", userLogin);
                            mailSystem.AddParams("{customer_id}", customer.CustomerId);
                            mailSystem.AddParams("{customer_Password}", customerPass);
                            mailSystem.AddParams("{TD_FILE_SHARING_INFORATION.ID}", fileSharingId);
                            mailSystem.AddParams("{TD_FILE_SHARING_INFORMATION.Expiration_date}", expireDate.ToShortDateString());
                            mailSystem.AddParams("{UrlPortal}", Common.AppSettingKey(Constant.PORTAL_URL));
                            if (listFileName.Length > 0)
                                mailSystem.AddParams("{File_Name}", listFileName.Remove(listFileName.Length - 1, 1));
                            listMailSystem.Add(mailSystem);
                        }

                        Trans.Commit();
                        Conn.Close();
                        PostedFiles = null;
                        #endregion

                        #region SendMail
                        logger.Debug("Begin send Email ");
                        string mailBody = "";
                        string subject = "";
                        if (panelUploadFiles.Visible)
                        {
                            mailBody = GetMailBody(hostPath, "Invitation_mail_body_download.txt");
                            subject = Common.GetResourceString("MAIL_DownloadSubject");
                        }
                        else
                        {
                            mailBody = GetMailBody(hostPath, "Invitation_mail_body_upload.txt");
                            subject = Common.GetResourceString("MAIL_InvitationSubject");
                        }
                        foreach (UserMail mail in listMailSystem)
                        {
                            mail.SendEmail(accountMailLogin, mail, subject, mailBody);
                        }
                        #endregion

                    }
                    catch (Exception ex)
                    {
                        Trans.Rollback();
                        Conn.Close();
                        try
                        {
                            if (Common.AppSettingKey(Constant.STORAGE_CONNECT_STRING) != "")
                            {
                                BlobManager blobManager = new BlobManager();
                                foreach (CustomerInfo customer in this.CustomerInfo)
                                {
                                    blobManager.DeleteBlobDirectory(customer.CustomerId);
                                }
                            }
                            else
                            {
                                foreach (CustomerInfo customer in this.CustomerInfo)
                                {
                                    string pathCustomerID = System.IO.Path.Combine(hostPath, Constant.UPLOAD_STORAGE + "\\" + customer.CustomerId);
                                    if (Directory.Exists(pathCustomerID))
                                        Directory.Delete(pathCustomerID, true);
                                }
                            }
                        }
                        catch { logger.Error("Error when try to delete storage", ex); }
                        throw ex;
                    }

                }

                logger.Debug("End btnUpload_Click , loadData()");

                ScriptManager.RegisterStartupScript(this, typeof(Page), "Redirect", "alert(\"" + GetJSMessage(GetResource("TITLE_SUCESS"), GetResource("MSG_UPLOAD_SUCESS")) + "\");window.location='Upload.aspx';", true);
            }
            catch (Exception ex)
            {
                ButtonUpload.Enabled = true;
                logger.Error("Error btnUpload_Click", ex);
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_ERROR"), ex.Message) + "\");");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                hiddenAccount.Value = "";
                if (Session["user"] == null)
                    Server.Transfer("LoginMember.aspx");

                hiddenAccount.Value = Session["user"].ToString();

                if (PostedFiles == null)
                    PostedFiles = new List<DetailsFile>();
                #region Sava file to temp folder
                foreach (string filename in Request.Files)
                {
                    HttpPostedFile file = Request.Files.Get(filename);

                    if (file != null && file.ContentLength > 0)
                    {
                        DetailsFile objFile = new DetailsFile();
                        objFile.FileName = file.FileName;
                        objFile.ContentLength = file.ContentLength;
                        PostedFiles.Add(objFile);
                        string blobName = "Temp/" + hiddenAccount.Value + "/" + file.FileName;

                        BlobManager blob = new BlobManager();
                        blob.UploadFromStream(file.InputStream, blobName);
                    }
                }
                #endregion

                #region IsPostback
                if (!Page.IsPostBack)
                {

                    BindGridView();
                    InitLanguage();

                    SetLabelText(LabelCustomerInfo, LabelCustomerName, LabelEmailAddress, LabelCustomerList, LabelTermUpload, LabelbUploadfilelist, LabelDay, lblDropdrag);
                    SetButtonText(ButtonAddCustomer, ButtonUpload, ButtonCancel);
                    requiredName.ToolTip = requiredName.ErrorMessage = string.Format(GetResource("MSG_REQUIRED_INPUT_FIELD"), LabelCustomerName.Text);
                    requiredEmail.ToolTip = requiredEmail.ErrorMessage = string.Format(GetResource("MSG_REQUIRED_INPUT_FIELD"), LabelEmailAddress.Text);
                    validateEmail.ToolTip = validateEmail.ErrorMessage = GetResource("MSG_VALID_EMAIL");
                    //requiredDetailsFile.ToolTip = requiredDetailsFile.ErrorMessage = GetResource("MSG_SELECTED_FILE_NOT_EXIST");
                    for (int i = 1; i <= 10; i++)
                        dropdownTermUpload.Items.Add(i.ToString());

                    string mode = Request.QueryString["mode"]; // mode=2 Invitation Upload
                    if (mode != null)
                    {
                        panelUploadFiles.Visible = false;
                        ButtonUpload.Text = GetResource("ButtonInviteUpload");
                    }
                    else
                    {
                        ButtonUpload.Text = GetResource("ButtonUploadSend");
                    }
                    this.ButtonUpload.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(ButtonUpload, "").ToString());

                #endregion
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error Page_Load ", ex);
                RegisterStartupScript("alert(\"" + GetJSMessage(GetResource("TITLE_INFO"), ex.Message) + "\");");
            }
        }