locked
Copying an ASP.NET Page to a new Tab RRS feed

  • Question

  • User769474054 posted

    Hi, I have a large form with user controls and text boxes that the user inputs and saves to the database. Since its a large form, the user wants to have a copy mechanism where he can copy the page to a new tab and submit instead of re entering all the data again.

    There's is an attachment control in the page where it lists the attachments for the request, the list of attachments are shown in a list box and when user clicks view, it downloads the file to user machine.

    I am able to copy all other attributes from the page except the attachments info. Since its a user control and it uses some view states to store the list of attachments, deleted and new attachment info.

    I am not sure how do we copy the state of the User control or the user control in general to the new request. The user also wants to copy the attachments info from the previous copied request into the new target request.

    Here's is my attachment user control code.

     public partial class AttachmentControl : RequestBaseUserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack && this.CurrentRequestId != 0)
                {
                    List<AttachmentItem> attachments = BLRequest.GetAttachmentInfo(this.CurrentRequestId); 
                    foreach (AttachmentItem ai in attachments)
                    {
                        ListItem li = new ListItem();
                        li.Text = ai.fileName + ai.fileExtension;
                        if (!this.Attachments.ContainsKey(li.Text))
                        {
                            this.Attachments.Add(li.Text, ai);
                            this.lbAttachments.Items.Add(li);
                        }
                    }
                    if (LibraryNameConst.GICL.Equals(this.CurrentLibrary))
                    {
                        IsLibrarian = IsCurrentUserALibrarian();
    
                    }
                }                    
            }
            private bool IsCurrentUserALibrarian()
            {
                bool isLib = false;
                foreach (string str in this.MasterPage.UserRolesinCurLib)
                    if (str.ToLower().Equals(BusinessLogic.ChecklistUserRoles.STRLIB.ToLower()))
                        isLib = true;
                return isLib;
            }
    
            #region Properties
            public Dictionary<string, AttachmentItem> Attachments
            {
                get
                {
                    if (ViewState["Attachments"] == null)
                        ViewState["Attachments"] = new Dictionary<string, AttachmentItem>();
                    return ViewState["Attachments"] as Dictionary<string, AttachmentItem>;
                }
            }
            private Boolean IsLibrarian
            {
                get
                {
                    if (ViewState["IsLibrarian"] == null)
                        return false;
                    return Convert.ToBoolean(ViewState["IsLibrarian"]);
                }
                set
                {
                    ViewState["IsLibrarian"] = value;
                }
            }
            public List<AttachmentItem> DeletedAttachments
            {
                get
                {
                    if (ViewState["DeletedAttachments"] == null)
                        ViewState["DeletedAttachments"] = new List<AttachmentItem>();
                    return ViewState["DeletedAttachments"] as List<AttachmentItem>;
                }
            }
    
            public List<AttachmentItem> NewAttachments
            {
                get
                {
                    if (ViewState["NewAttachments"] == null)
                        ViewState["NewAttachments"] = new List<AttachmentItem>();
                    return ViewState["NewAttachments"] as List<AttachmentItem>;
                }
            }
            #endregion
            private string ValidateFileName(string fileName)
            {
                StringBuilder result = new StringBuilder();
                if (!string.IsNullOrEmpty(fileName))
                {
                    List<char> invalidPathChars = Path.GetInvalidFileNameChars().ToList<char>();
                    if (!invalidPathChars.Contains('#')) // there are issues with # as well
                        invalidPathChars.Add('#');
    
                    if (!invalidPathChars.Contains('?')) // there are issues with ? as well
                        invalidPathChars.Add('?');
    
                    if (!invalidPathChars.Contains('&')) // there are issues with & as well with QueryStrings
                        invalidPathChars.Add('&');
    
                    foreach (char ch in fileName.ToCharArray())
                        if (!invalidPathChars.Contains(ch))
                            result.Append(ch);
                        else
                            result.Append('_');
                }
                return result.ToString();
            }
            #region Event Handlers
            protected void btnAttach_Click(object sender, EventArgs e)
            {
                if (!(this.MasterPage.UserRolesinCurLib.Contains(LibraryUserRoles.VISITOR) && this.MasterPage.UserRolesinCurLib.Count == 1))
                {
                    string fileName = ValidateFileName(this.FileUpload1.FileName);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        string internalFileName = this.UploadAttachment(fileName, this.FileUpload1.FileBytes);
                        if (!string.IsNullOrEmpty(internalFileName))
                        {
                            this.lbAttachments.Items.Add(fileName);
                            AttachmentItem ai = new AttachmentItem();
                            ai.id = 0;
                            ai.fileDesc = this.tbAttachmetnDesc.Text;
                            ai.fileExtension = Path.GetExtension(fileName);
                            ai.fileName = Path.GetFileNameWithoutExtension(fileName);
                            ai.internalFileName = internalFileName;
                            ai.dateAttached = DateTime.Now.ToString();
                            ai.dateUTCAttached = DateTime.UtcNow;
                            if (!this.Attachments.ContainsKey(fileName))
                                this.Attachments.Add(fileName, ai);
                            this.NewAttachments.Add(ai);
                            LogHistory(true, fileName);
                        }
                        else { throw new Exception("Can't Upload Attachment to server...."); }
    
                    }
                }
                else
                {
                    UpdatePanel updatePanel = UIUtils.FindControlRecursive(this.Parent.Page.Master, "ValidatorPanel") as UpdatePanel;
                    this.ErrorMessage = "you can't add any attachments to the request. ";
                    if (updatePanel != null)
                    {
                        updatePanel.Update();
                    }
                    return;
                }
            }
    
            protected void btnView_Click(object sender, EventArgs e)
            {
                List<AttachmentItem> downloadFiles = new List<AttachmentItem>();
                foreach (ListItem li in this.lbAttachments.Items)
                {
                    if (li.Selected && li.Value != string.Empty)
                    {
                        AttachmentItem selectedAttachment = this.Attachments[li.Value];
                        
                        downloadFiles.Add(selectedAttachment);
                    }
                }
                Session["downloadfiles"] = downloadFiles;
                Response.Redirect(UIUtils.GetRootUrlPath() + "UI/FileDownloadPage.aspx?requestID="+this.CurrentRequestId);
            }
    
            protected void lbAttachments_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (this.Attachments.ContainsKey(this.lbAttachments.SelectedValue))
                {
                    AttachmentItem selectedAttachment = this.Attachments[this.lbAttachments.SelectedValue];
                    this.lblDescValue.Text = selectedAttachment.fileDesc;
                    this.lblDateAttachedValue.Text = selectedAttachment.dateAttached;
                }
            }
    
    
    
            protected void btnRemove_Click(object sender, EventArgs e)
            {
                bool isEligibleRoletoDelete = (this.MasterPage.IsCurrentUserALibrarian || this.MasterPage.IsCurrentUserAnAdmin);
                if (!isEligibleRoletoDelete && this.lbAttachments.SelectedValue != string.Empty)
                {
                    UpdatePanel updatePanel = UIUtils.FindControlRecursive(this.Parent.Page.Master, "ValidatorPanel") as UpdatePanel;
                    this.ErrorMessage = "Only librarians/Administrators can delete attachments";
                    if (updatePanel != null)
                    {
                        updatePanel.Update();
                    }
                    return;
                }
                if (this.lbAttachments.SelectedValue != string.Empty && this.Attachments.ContainsKey(this.lbAttachments.SelectedValue))
                {
                    AttachmentItem selectedAttachment = this.Attachments[this.lbAttachments.SelectedValue];
                    if (this.Attachments.ContainsKey(this.lbAttachments.SelectedValue))
                        this.Attachments.Remove(this.lbAttachments.SelectedValue);
                    LogHistory(false, selectedAttachment.fileName);
                    this.lbAttachments.Items.RemoveAt(this.lbAttachments.SelectedIndex);
                    if (selectedAttachment.id != 0)
                    {
                        //Add to the list of deleted attachments to be updated in server
                        this.DeletedAttachments.Add(selectedAttachment);
                    }
                }
            }
    
            #endregion
    
            #region Helper Methods
            private string UploadAttachment(string fileName, byte[] contents)
            {
                string intFileName = "";
                WindowsImpersonationContext impersonationContext;
    
                if (BLSecurity.ImpersonateFacelessAccount(out impersonationContext))
                {
                    string tempPath = "";
                    try
                    {
                        //Save to temp directory with the GUID name instead
                        //This causes an issue when you want to view the file though
                        string sAppDataPath = ProfileBroker.ProfileFilePath.Remove(ProfileBroker.ProfileFilePath.IndexOf("\\app.profile"));
                        string uploadPath = ProfileBroker.GetProfileValue(AppProfileConst.UPLOAD_SERVER_TEMPPATH);
                        intFileName = System.Guid.NewGuid().ToString();
                        tempPath = System.IO.Path.Combine(uploadPath, intFileName);
                        File.WriteAllBytes(tempPath, contents);
                        File.Move(tempPath, Path.Combine(uploadPath, intFileName));
                        SecurityUtils.UndoImpersonation(impersonationContext);
                    }
                    catch (Exception ex)
                    {
                        BLUtils.WebApplicationError();
                        intFileName = "";
                    }
                    finally
                    {
                       
                    }
                }
                else
                {
                    //Your impersonation failed. Therefore, include a fail-safe mechanism here.
                    //StatusLabelTxt = "Insufficient permissions granted to save the file, please contact tool support";
                }
                return intFileName;
            }
    
            private void LogHistory(bool action, string fileName)
            {
                //Log into the History of the Request
                if (this.CurrentRequestId != 0)
                {
                    using (DAL.LibMgmtDataClassesDataContext dCtx = DAL.LibMgmtDataClassesDataContext.GetDataContext(null))
                    {
                        DAL.Request request = (from r in dCtx.Requests
                                               where r.RequestID == this.CurrentRequestId && r.LibID == this.CurrentLibraryId
                                               select r).FirstOrDefault<DAL.Request>();
                        if (request != null)
                        {
                            request.ModifiedDate = DateTime.Now;
                            request.ModifiedByID = CurrentUser.UID;
                            string history = request.History;
                            string desc = string.Empty;
    
                            if (action)
                                desc = DateTime.Now
                                + ", " + CurrentUser.Name + " : Added Attachment\n"
                                + fileName + " : to Request.\n"
                                + "....................................................\n";
    
                            else
                                desc = DateTime.Now
                                + ", " + CurrentUser.Name + " : Deleted Attachment\n"
                                + fileName + " : from Request.\n"
                                + "....................................................\n";
                            request.History = desc + history;
                            dCtx.SubmitChanges();
                        }
                    }
    
                }
            }
            #endregion
        }

    Any inputs would be useful

    Thanks,

    Tuesday, December 26, 2017 8:46 PM

All replies