using framework_business; using framework_library; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class controls_admin_fileUploader : System.Web.UI.UserControl, ISurfaceControlBase { private enum FileExtension { pdf, doc, docx, xls, xlsx, txt, jpg, jpeg, png, gif,htm,html } #region override /// /// Reload Control /// /// /// /// public void ReloadControl(oSurfaceFieldData controlFieldData, bool alternateView = false, bool readOnly = false) { try { try { // Add ValidationGroup="Properties" to btnAddGalleryVideo button ISurfaceBase parent = (ISurfaceBase)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent; string parentName = parent.AppRelativeVirtualPath; int iLastIndex = parentName.LastIndexOf("/") + 1; string validate = parentName.Substring(iLastIndex).Replace("_form.ascx", ""); btnOpenUploadModal.ValidationGroup = validate; } catch { } FileUploadDocumentId = controlFieldData.surfaceId; SurfaceFileUploadDocumentItemId = controlFieldData.surfaceItemId; foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "recId", controlFieldData.surfaceFieldID.ToString())) { SurfaceFileUploadDocumentFieldId = field.recId; //lblVideoGalleryTitle.Text = field.surfaceFieldDisplay; } if (alternateView) RecordLimit = 3; //BindVideoGallery(); } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } public void SaveControlData(ref oSurfaceFieldData _surfaceFieldData) { //throw new NotImplementedException(); } #endregion #region Methods /// /// Bind Uploader Grid Repeater /// private void BindFileUploaderGrid() { if (SurfaceFileUploadDocumentItemId > 0) { //typeID = 1 and moduleId = 54 DataTable dtTable = xData.GetDynamicByCriteriaSpecific("recId", typeof(oAttachment), "moduleId, entityId, isActive, typeId", pNums.Module.FileUploader.GetHashCode() + "," + SurfaceFileUploadDocumentItemId + ",1," + pNums.AttachmentType.Document.GetHashCode(), "sequence"); if (dtTable.TableIsValid()) { rptFileUploader.DataSource = dtTable; rptFileUploader.DataBind(); } else { StringBuilder uploadedFiles = new StringBuilder(); uploadedFiles.Append($"No documents uploaded"); //Literal literal = (Literal)Page.FindControl("ltSurfaceFileUploader"); //literal.Text = uploadedFiles.ToString(); } } } /// /// Remove Document /// /// private void DeleteUploadedDocument(int documentId) { try { xData.DeleteTyped("recId", documentId.ToString(), typeof(oAttachment)); } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["attachment"]); Response.Redirect("/error", false); } } #endregion #region events /// /// Page Load Event /// /// /// protected void Page_Load(object sender, EventArgs e) { BindFileUploaderGrid(); } /// /// Te button to open up the modal dialog /// /// /// protected void btnOpenUploadModal_Click(object sender, EventArgs e) { try { ISurfaceBase parent = (ISurfaceBase)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent; if (SurfaceFileUploadDocumentItemId == 0) { // If this is a new property, we need to save the gallery top down (Parent => Gallery) parent.SaveControl(false, false, false); } radUploadSurfaceDocument.UploadedFiles.Clear(); txtDocumentDescription.Text = ""; txtDocumentVersion.Text = ""; //chkPrimaryImage.Checked = false; //setup attachments Session["moduleId"] = pNums.Module.FileUploader.GetHashCode(); Session["entityId"] = SurfaceFileUploadDocumentItemId; string fieldName = String.Empty; if (utils.verifySession("fieldNameNote")) fieldName = Session["fieldNameNote"].ToString(); Session["fieldNameFile"] = SurfaceFileUploadDocumentFieldId; //dynamic attachments = (IControlBase)Page.Master.FindControl("attachments"); //attachments.ReloadControl(); rowFileUploadRow.Visible = true; btnUploadFile.Visible = true; btnSaveFile.Visible = false; sfFileUploader.Update(); string scriptVar = "$('#" + pnlFileUploaderModalDocuments.ClientID + "').closest('div').find('.modalUploadFileDocuments').modal();"; ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySurfaceFileUploaderModal", scriptVar, true); } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Item Created Event /// /// /// protected void rptFileUploader_ItemCreated(object sender, RepeaterItemEventArgs e) { try { ScriptManager scriptMan = ScriptManager.GetCurrent(this.Page); Repeater rpt = (Repeater)sender; RepeaterItem item = e.Item; LinkButton lnkDownloadFile = item.FindControl("lnkDownloadFile") as LinkButton; if (lnkDownloadFile != null) { lnkDownloadFile.Click += lnkDownloadFile_Click; scriptMan.RegisterPostBackControl(lnkDownloadFile); } } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Item Databound event /// /// /// protected void rptFileUploader_ItemDataBound(object sender, RepeaterItemEventArgs e) { Label lblFileVersion = e.Item.FindControl("lblFileVersion") as Label; Label lblUploader = e.Item.FindControl("lblUploader") as Label; Label lblFileSize = e.Item.FindControl("lblFileSize") as Label; LinkButton lnkDownloadFile = e.Item.FindControl("lnkDownloadFile") as LinkButton; if (lblFileVersion != null) { List lstItems = ((DataRowView)e.Item.DataItem).Row.ItemArray.Select(c => c.ToString()).ToList(); string recordID = lstItems[0]; string display = lstItems[5]; string folderName = lstItems[3]; string fileName = lstItems[6]; string dateSaved = lstItems[7]; string userUploaded = lstItems[11]; string jsonString = lstItems[16]; dateSaved = utils.formatDateToString(Convert.ToDateTime(dateSaved)); UploadFileMetadata meta = JsonConvert.DeserializeObject(jsonString); string fileVersion = (meta.IsNull()) ? "" : meta.FileVersion; lblFileVersion.Text = fileVersion; string uploadUser = (meta.IsNull()) ? "" : meta.UploadUser; lblUploader.Text = uploadUser; string fileSize_MB = (meta.IsNull()) ? "" : meta.FileSize_MB; lblFileSize.Text = fileSize_MB; string fileType = (meta.IsNull()) ? "txt" : meta.FileType; string fileClass = ""; switch (fileType.ToLower()) { case nameof(FileExtension.jpg): fileClass = "fa fa-file-picture-o palette-back"; break; case nameof(FileExtension.jpeg): fileClass = "fa fa-file-picture-o palette-back"; break; case nameof(FileExtension.gif): fileClass = "fa fa-file-picture-o palette-back"; break; case nameof(FileExtension.png): fileClass = "fa fa-file-picture-o palette-back"; break; case nameof(FileExtension.doc): fileClass = "fa fa-file-word-o palette-add"; break; case nameof(FileExtension.docx): fileClass = "fa fa-file-word-o palette-add"; break; case nameof(FileExtension.xls): fileClass = "fa fa-file-excel-o palette-edit"; break; case nameof(FileExtension.xlsx): fileClass = "fa fa-file-excel-o palette-edit"; break; case nameof(FileExtension.pdf): fileClass = "fa fa-file-pdf-o palette-remove"; break; case nameof(FileExtension.txt): fileClass = "fa fa-file-text-o palette-default"; break; case nameof(FileExtension.htm): fileClass = "fa fa-html5 palette-default"; break; case nameof(FileExtension.html): fileClass = "fa fa-html5 palette-default"; break; default: fileClass = "fa fa-file-text-o palette-add"; break; } lnkDownloadFile.CssClass = fileClass; //lnkDownloadFile.Text = "\"""; } } protected void rptFileUploader_ItemDataBoundBak(object sender, RepeaterItemEventArgs e) { StringBuilder uploadedFiles = new StringBuilder(); List lstItems = ((DataRowView)e.Item.DataItem).Row.ItemArray.Select(c => c.ToString()).ToList(); string recordID = lstItems[0]; string display = lstItems[5]; string folderName = lstItems[3]; string fileName = lstItems[6]; string dateSaved = lstItems[7]; string userUploaded = lstItems[11]; string jsonString = lstItems[16]; dateSaved = Convert.ToDateTime(dateSaved).ToString("dd/MM/yyyy"); UploadFileMetadata meta = JsonConvert.DeserializeObject(jsonString); Label lblFileName = new Label(); lblFileName.Text = display; lblFileName.ID = $"lblFileName_{recordID}"; uploadedFiles.Append($"{lblFileName.Text}"); string fileVersion = (meta.IsNull()) ? "" : meta.FileVersion; uploadedFiles.Append($"{fileVersion}"); string uploadUser = (meta.IsNull()) ? "" : meta.UploadUser; uploadedFiles.Append($"{uploadUser}"); uploadedFiles.Append($"{dateSaved}"); string fileSize_MB = (meta.IsNull()) ? "" : meta.FileSize_MB; uploadedFiles.Append($"{fileSize_MB}"); string fileType = (meta.IsNull()) ? "txt" : meta.FileType; string imageFile = ""; switch (fileType) { case nameof(FileExtension.doc): imageFile = nameof(FileExtension.doc); break; case nameof(FileExtension.docx): imageFile = nameof(FileExtension.doc); break; case nameof(FileExtension.xls): imageFile = nameof(FileExtension.xls); break; case nameof(FileExtension.xlsx): imageFile = nameof(FileExtension.xls); break; case nameof(FileExtension.pdf): imageFile = nameof(FileExtension.pdf); break; case nameof(FileExtension.txt): imageFile = nameof(FileExtension.txt); break; default: imageFile = nameof(FileExtension.txt); break; } StringBuilder sb = new StringBuilder(); sb.Append($""); sb.Append($"\"{display}\""); sb.Append(""); uploadedFiles.Append($"{sb.ToString()}"); LinkButton lnkEditFile = new LinkButton(); lnkEditFile.ID = $"lnkEditFile_{recordID}"; lnkEditFile.PostBackUrl = ""; lnkEditFile.Text = "Edit"; uploadedFiles.Append($"{lnkEditFile.Text}"); LinkButton lnkDeleteFile = new LinkButton(); lnkDeleteFile.ID = $"lnkDeleteFile_{recordID}"; lnkDeleteFile.Text = "delete"; lnkDeleteFile.CssClass = "glyphicon glyphicon-ok palette-remove"; lnkDeleteFile.CommandArgument = recordID; lnkDeleteFile.PostBackUrl = ""; uploadedFiles.Append($"{lnkDeleteFile.Text}"); Literal literal = (Literal)e.Item.FindControl("ltSurfaceFileUploader"); literal.Text = uploadedFiles.ToString(); } /// /// The button on the Modal to save the file to the server /// /// /// protected void btnUploadFile_Click(object sender, EventArgs e) { try { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySurfaceFileUploaderModalClose", "TaskFileUploadCancel(); $('#" + pnlFileUploaderModalDocuments.ClientID + "').closest('div').find('.modalUploadFileDocuments').modal('hide');$('body').removeClass('modal-open');", true); } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } finally { txtDocumentDescription.Text = ""; if (SurfaceFileUploadDocumentItemId == 0) { // If this is a new property, we need to save the gallery top down (Parent => Gallery) ISurfaceBase parent = (ISurfaceBase)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent; parent.SaveControl(false, false, false); } BindFileUploaderGrid(); } } /// /// File Uploaded Event /// /// /// protected void radUploadSurfaceDocument_FileUploaded(object sender, Telerik.Web.UI.FileUploadedEventArgs e) { FileUploadDocumentAttachment = new oAttachment(); try { oUser user = handler.ReturnUser(); FileUploadDocumentAttachment.entityId = SurfaceFileUploadDocumentItemId; FileUploadDocumentAttachment.fieldName = SurfaceFileUploadDocumentFieldId.ToString(); FileUploadDocumentAttachment.moduleId = (int)pNums.Module.FileUploader; FileUploadDocumentAttachment.isActive = true; FileUploadDocumentAttachment.typeId = (int)pNums.AttachmentType.Document; string taskFolderName = "surface/"; taskFolderName += SurfaceFileUploadDocumentItemId.ToString(); FileUploadDocumentAttachment.folderName = taskFolderName; int userId = user.recId; FileUploadDocumentAttachment.userIdSaved = userId; FileUploadDocumentAttachment.dateSaved = DateTime.Now; if (txtDocumentDescription.Text.Length > 0) { FileUploadDocumentAttachment.display = txtDocumentDescription.Text; } else FileUploadDocumentAttachment.display = e.File.FileName.Remove(e.File.FileName.LastIndexOf(".")); string randomFileName = utils.RandomString(9, true) + e.File.FileName.Substring(e.File.FileName.LastIndexOf(".")); string friendlyDocumentName = FileUploadDocumentAttachment.display; foreach (var c in Path.GetInvalidFileNameChars()) { friendlyDocumentName = friendlyDocumentName.Replace(c.ToString(), ""); } FileUploadDocumentAttachment.fileName = $"{friendlyDocumentName}_{FileUploadDocumentAttachment.entityId}_{randomFileName}"; string filePath = Server.MapPath("~/upload/" + FileUploadDocumentAttachment.folderName + "/file/"); utils.validateFolder(filePath); FileUploadDocumentAttachment.sourcePath = System.Configuration.ConfigurationManager.AppSettings["WebAddy"]; string fileExtension = ""; //upload file fileExtension = Path.GetExtension(filePath + FileUploadDocumentAttachment.fileName); e.File.SaveAs(filePath + FileUploadDocumentAttachment.fileName); UploadFileMetadata metaData = new UploadFileMetadata(); metaData.FileSize_InBytes = e.File.ContentLength; metaData.FileType = fileExtension.Replace(".", ""); metaData.FileVersion = txtDocumentVersion.Text; metaData.UploadUser = user.userDisplay; string jsonString = JsonConvert.SerializeObject(metaData, Formatting.Indented); FileUploadDocumentAttachment.fileMetadata = jsonString; xData.SaveTyped("recId", typeof(oAttachment), FileUploadDocumentAttachment); //GR redundant code //List lstParms = FileUploadDocumentAttachment.GetType().GetProperties().ToList().ToDynamicParamList(FileUploadDocumentAttachment); //int atIdentity = xData.SaveTypedByProc("recId", typeof(oAttachment), null, "sproc_PROP1_FileUploader_AddUpdate", lstParms); //string SQL = $"UPDATE pal_Attachment SET fileMetadata = '{jsonString}' WHERE recId = {atIdentity}"; //xData.RunCustomQuery(SQL); } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["attachment"]); Response.Redirect("/error", false); } } /// /// Download File /// /// /// protected void lnkDownloadFile_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { int documentId = int.Parse(((LinkButton)sender).CommandArgument); Response.Clear(); foreach (oAttachment file in xData.GetTypedByCriteriaSpecific("recId", typeof(oAttachment), "recId", documentId.ToString())) { string fileType = file.fileName.Substring(file.fileName.IndexOf(".")); switch (fileType.ToLower()) { case ".doc": Response.ContentType = "Application/msword"; break; case ".docx": Response.ContentType = "Application/msword"; break; case ".rtf": Response.ContentType = "Application/msword"; break; case ".txt": Response.ContentType = "text/plain"; break; case ".htm": Response.ContentType = "text/HTML"; break; case ".html": Response.ContentType = "text/HTML"; break; case ".xlsx": Response.ContentType = "Application/x-msexcel"; break; case ".xls": Response.ContentType = "Application/x-msexcel"; break; case ".jpg": Response.ContentType = "image/jpeg"; break; case ".jpeg": Response.ContentType = "image/jpeg"; break; case ".png": Response.ContentType = "image/PNG"; break; case ".gif": Response.ContentType = "image/GIF"; break; case ".pdf": Response.ContentType = "application/pdf"; break; } Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.fileName + ""); Response.TransmitFile(Server.MapPath("~/upload/" + file.folderName + "/file/" + file.fileName)); Response.Flush(); Response.SuppressContent = true; ApplicationInstance.CompleteRequest(); } } } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Edit File /// /// /// protected void lnkEditFile_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { int documentId = int.Parse(((LinkButton)sender).CommandArgument); foreach (oAttachment file in xData.GetTypedByCriteriaSpecific("recId", typeof(oAttachment), "recId", documentId.ToString())) { FileUploadDocumentAttachment = file; txtDocumentDescription.Text = file.display; UploadFileMetadata meta = JsonConvert.DeserializeObject(file.fileMetadata); string fileVersion = (meta.IsNull()) ? "" : meta.FileVersion; string uploadUser = (meta.IsNull()) ? "" : meta.UploadUser; string fileType = (meta.IsNull()) ? "txt" : meta.FileType; txtDocumentVersion.Text = fileVersion; rowFileUploadRow.Visible = false; btnUploadFile.Visible = false; btnSaveFile.Visible = true; sfFileUploader.Update(); string scriptVar = "$('#" + pnlFileUploaderModalDocuments.ClientID + "').closest('div').find('.modalUploadFileDocuments').modal();"; ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "mySurfaceFileUploaderModalEdit", scriptVar, true); } } } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Delete File /// /// /// protected void lnkDeleteFile_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { int documentId = int.Parse(((LinkButton)sender).CommandArgument); DeleteUploadedDocument(documentId); BindFileUploaderGrid(); sfFileUploader.Update(); } } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Save changes /// /// /// protected void btnSaveFile_Click(object sender, EventArgs e) { try { if (FileUploadDocumentAttachment.recId > 0) { FileUploadDocumentAttachment.display = txtDocumentDescription.Text; UploadFileMetadata meta = JsonConvert.DeserializeObject(FileUploadDocumentAttachment.fileMetadata); string fileVersion = (meta.IsNull()) ? "" : meta.FileVersion; string uploadUser = (meta.IsNull()) ? "" : meta.UploadUser; string fileSize_MB = (meta.IsNull()) ? "" : meta.FileSize_MB; string fileType = (meta.IsNull()) ? "txt" : meta.FileType; UploadFileMetadata metaData = new UploadFileMetadata(); metaData.FileSize_InBytes = (meta.IsNull()) ? 0 : meta.FileSize_InBytes; metaData.FileType = fileType; metaData.FileVersion = txtDocumentVersion.Text; metaData.UploadUser = uploadUser; string jsonString = JsonConvert.SerializeObject(metaData, Formatting.Indented); FileUploadDocumentAttachment.fileMetadata = jsonString; xData.UpdateTyped("recId", FileUploadDocumentAttachment.recId.ToString(), typeof(oAttachment), FileUploadDocumentAttachment); BindFileUploaderGrid(); sfFileUploader.Update(); } } catch (Exception ex) { exception.HandleException("fileUploader:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } #endregion #region Properties private DataTable SurfaceFileUploadDocument { get { if (ViewState["surfaceFileUploadDocument"] != null) { return (DataTable)ViewState["surfaceFileUploadDocument"]; } else { return null; } } set { ViewState["surfaceFileUploadDocument"] = value; } } private int SurfaceFileUploadDocumentItemId { get { if (ViewState["surfaceFileUploadDocumentItemId"] != null) return (int)ViewState["surfaceFileUploadDocumentItemId"]; else return 0; } set { ViewState["surfaceFileUploadDocumentItemId"] = value; } } private int SurfaceFileUploadDocumentFieldId { get { if (ViewState["surfaceFileUploadDocumentFieldId"] != null) return Convert.ToInt32(ViewState["surfaceFileUploadDocumentFieldId"]); else return 0; } set { ViewState["surfaceFileUploadDocumentFieldId"] = value; } } private int SurfaceFileUploadDocumentId { get { if (ViewState["surfaceFileUploadDocumentId"] != null) return Convert.ToInt32(ViewState["surfaceFileUploadDocumentId"]); else return 0; } set { ViewState["surfaceFileUploadDocumentId"] = value; } } private int RecordLimit { get { if (ViewState["recordLimit"] == null) return 0; else return (int)ViewState["recordLimit"]; } set { ViewState["recordLimit"] = value; } } private int FileUploadDocumentId { get { if (ViewState["fileUploadDocumentId"] != null) return (int)ViewState["fileUploadDocumentId"]; else return 0; } set { ViewState["fileUploadDocumentId"] = value; } } private oAttachment FileUploadDocumentAttachment { get { if (ViewState["attachment"] != null) return (oAttachment)ViewState["attachment"]; else return null; } set { ViewState["attachment"] = value; } } #endregion }