HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/TDijk1/erp-apps.eu/wwwroot/ERPApps/ERPWebParts/Documents/NewsForm.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using CMS.PortalControls;
using CMS.GlobalHelper;
using CMS.SettingsProvider;
using CMS.FormEngine;
using CMS.CMSHelper;
using CMS.EventLog;
using CMS.TreeEngine;
using CMS.WorkflowEngine;
using CMS.DocumentEngine;
using CMS.ExtendedControls;
using CMS.Helpers;
using CMS.Membership;
using CMS.PortalEngine;
using CMS.SiteProvider;
using CMS.DataEngine;
using ERP.News;
using CMS.FormControls;

/// <summary>
/// Form for inserting and editing application.
/// </summary>
public partial class ERPApps_ERPWebParts_Documents_NewsForm : CMSAbstractWebPart
{
    #region "Layout properties"

    /// <summary>
    /// Full alternative form name ('classname.formname') for usersettingsinfo.
    /// Default value is cms.user.RegistrationForm
    /// </summary>
    public string AlternativeForm
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("AlternativeForm"), "cms.user.RegistrationForm");
        }
        set
        {
            this.SetValue("AlternativeForm", value);
        }
    }

    /// <summary>
    /// Document type for applications.
    /// Default is ERPConfig.DOCTYPE_NEWS.
    /// </summary>
    public string ApplicationDocumentType
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("NewsDocumentType"), ERPConfig.DOCTYPE_NEWS);
        }
        set
        {
            this.SetValue("NewsDocumentType", value);
        }
    }

    /// <summary>
    /// Target node alias path for the application`s document.
    /// </summary>
    public string ApplicationTargetPath
    {
        get
        {
            //return ValidationHelper.GetString(this.GetValue("NewsTargetPath"), ERPConfig.APP_NEWS_DIR_NAME);
            return ValidationHelper.GetString(this.GetValue("NewsTargetPath"), String.Empty);
        }
        set
        {
            this.SetValue("NewsTargetPath", value);
        }
    }

    /// <summary>
    /// Text of "Save" button
    /// </summary>
    public string ButtonText
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("ButtonText"), "Create application");
        }
        set
        {
            this.SetValue("ButtonText", value);
        }
    }

    /// <summary>
    /// Redirect URL to redirect to after saving the application
    /// </summary>
    public string TargetURL
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("TargetURL"), String.Empty);
        }
        set
        {
            this.SetValue("TargetURL", value);
        }
    }

    /// <summary>
    /// Application`s node ID in case of editing the app.
    /// </summary>
    public int EditNodeID
    {
        get
        {
            return ValidationHelper.GetInteger(this.GetValue("EditNodeID"), 0);
        }
        set
        {
            this.SetValue("EditNodeID", value);
        }
    }

    /// <summary>
    /// Content displayed after saving the application.
    /// </summary>
    public string SuccessText
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("SuccessText"), "");
        }
        set
        {
            this.SetValue("SuccessText", value);
        }
    }

    /// <summary>
    /// Content displayed in case contact information is detected in application`s description.
    /// Macros $$type$$ and $$value$$ can be used to display type of contact and it`s value (found in the description).
    /// </summary>
    public string ContactErrorText
    {
        get
        {
            return ValidationHelper.GetString(this.GetValue("ContactErrorText"), "It looks like there is $$type$$ contact ($$value$$) in your description. If you would like to provide contact, please use our commercial profile.");
        }
        set
        {
            this.SetValue("ContactErrorText", value);
        }
    }

    #endregion

    #region "Webpart properties"
    private bool IsEditing
    {
        get;
        set;
    }

    TreeNode mNode;
    private bool mFormLoaded;

    private TreeNode Node
    {
        get
        {
            if (mNode == null)
            {
                mNode = TreeHelper.SelectSingleNode(EditNodeID);
            }

            return mNode;
        }

        set
        {
            mNode = value;
        }
    }
    #endregion

    #region "On events"
    /// <summary>
    /// Content loaded event handler
    /// </summary>
    //public override void OnContentLoaded()
    //{
    //    base.OnContentLoaded();

    //    SetupControl();
    //}
    #endregion

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        // Reload data
        ReloadData(false);
    }

    private void ReloadData(bool forceReload)
    {
        if (EditNodeID != 0)
        {
            // load existing node
            if (Node == null || Node.GetIntegerValue("NodeOwner", 0) != MembershipContext.AuthenticatedUser.UserID)
            {
                // insufficient rights
                if (PortalContext.ViewMode == CMS.PortalEngine.ViewModeEnum.LiveSite)
                {
                    ERPDataHelper.Redirect404(true);
                }

                Node = null;
            }
            else
            {
                //panelTerms.Visible = false;
            }
        }
        else
        {
            // requires accepting terms and conditions
            //panelTerms.Visible = true;
        }
        if (!mFormLoaded || forceReload)
        {
            TreeNode parent = formElem.TreeProvider.SelectSingleNode(SiteContext.CurrentSiteName, ApplicationTargetPath, DocumentContext.CurrentPageInfo.DocumentCulture);
            if (parent == null)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "NewsForm", "PARENTNODE", null, "Parent node for target path " + ApplicationTargetPath + " is null!");

                ShowError("Application could not be created. Please try again later.");

                return;
            }
            var dataClass = DataClassInfoProvider.GetDataClassInfo(ApplicationDocumentType);
            formElem.ParentNodeID = parent.NodeID;

            if (EditNodeID ==0)
            {
                DocumentManager.Mode = FormModeEnum.Insert;
                DocumentManager.ParentNodeID = parent.NodeID;
                DocumentManager.NewNodeClassID = dataClass.ClassID;
                DocumentManager.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
                DocumentManager.SiteName = SiteContext.CurrentSiteName;
            }
            else
            {
                DocumentManager.Mode = FormModeEnum.Update;
                DocumentManager.NodeID = EditNodeID;
                DocumentManager.SiteName = SiteContext.CurrentSiteName;
                DocumentManager.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
            }
            TreeProvider provider = new TreeProvider(MembershipContext.AuthenticatedUser);
            formElem.ParentNodeID = parent.NodeID;
            formElem.Visible = true;
            formElem.TreeProvider = provider;
            formElem.NodeID = Node == null ? 0 : Node.NodeID;
            formElem.FormName = ApplicationDocumentType + ".default";
            formElem.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
            formElem.AlternativeFormFullName = AlternativeForm;
            formElem.LoadForm(true);
            formElem.FormMode = Node == null ? FormModeEnum.Insert : FormModeEnum.Update;
            mFormLoaded = true;
        }
    }

    #region "Initialization"

    private void SetupControl()
    {
        TreeProvider provider = new TreeProvider(MembershipContext.AuthenticatedUser);

        if (EditNodeID != 0)
        {
            // load existing node
            if (Node == null || Node.GetIntegerValue("NodeOwner", 0) != MembershipContext.AuthenticatedUser.UserID)
            {
                // insufficient rights
                if (PortalContext.ViewMode == CMS.PortalEngine.ViewModeEnum.LiveSite)
                {
                    ERPDataHelper.Redirect404(true);
                }

                Node = null;
            }
            else
            {
                //panelTerms.Visible = false;
            }
        }
        else
        {
            // requires accepting terms and conditions
            //panelTerms.Visible = true;
        }


        TreeNode parent = formElem.TreeProvider.SelectSingleNode(SiteContext.CurrentSiteName, ApplicationTargetPath, DocumentContext.CurrentPageInfo.DocumentCulture);
        if (parent == null)
        {
            EventLogProvider.LogEvent(EventType.ERROR, "NewsForm", "PARENTNODE", null, "Parent node for target path " + ApplicationTargetPath + " is null!");

            ShowError("Application could not be created. Please try again later.");

            return;
        }

        formElem.ParentNodeID = parent.NodeID;


        formElem.Visible = true;
        formElem.TreeProvider = provider;
        formElem.NodeID = Node == null ? 0 : Node.NodeID;
        formElem.FormName = ApplicationDocumentType + ".default";
        formElem.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
        formElem.AlternativeFormFullName = AlternativeForm;
        formElem.LoadForm(true);
        formElem.FormMode = Node == null ? FormModeEnum.Insert : FormModeEnum.Update;
    }

    #endregion

    #region "Events"

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!formElem.ValidateData() && (formElem.FieldControls["NewsTeaser"].FindControl(formElem.FieldControls["NewsTeaser"].InputControlID) as AttachmentsControl).InnerAttachmentGUID != Guid.Empty)
        {
            return;
        }

        //formElem.BasicForm.Data["AppDateUpdated"] = DateTime.Now;

        if (SaveNews())
        {
            // send notification to admin
            ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.App", formElem.EditedObject as TreeNode);

            if (!DataHelper.IsEmpty(TargetURL))
            {
                URLHelper.Redirect(URLHelper.ResolveUrl(TargetURL));
            }

            lblInfo.Visible = true;
            lblInfo.Text = SuccessText;
        }
        else
        {
            TreeNode node = formElem.EditedObject as TreeNode;

            EventLogProvider.LogEvent(EventType.ERROR, "NewsForm", "SAVINGFAILED", null, "Saving failed. Data: " + (node != null ? node.ToJSON("data", false) : "NULL"));

            ShowError("Application could not be created. Please try again later.");
        }

    }

    private bool SaveNews()
    {
        DocumentManager.SaveDocument();

        //TreeNode parent = formElem.TreeProvider.SelectSingleNode(SiteContext.CurrentSiteName, ApplicationTargetPath, DocumentContext.CurrentPageInfo.DocumentCulture);
        //NewsTreeNode newsTreeNode;
        //if (EditNodeID > 0)
        //{
        //    newsTreeNode = NewsTreeNodeProvider.GetNews(EditNodeID, CurrentDocument.DocumentCulture, SiteContext.CurrentSiteName);
        //}
        //else
        //{
        //    newsTreeNode = new NewsTreeNode();
        //}
        //newsTreeNode.NewsTitle = ValidationHelper.GetString(formElem.FieldEditingControls["NewsTitle"].Value, "");
        //newsTreeNode.NewsReleaseDate = ValidationHelper.GetDateTime(formElem.FieldEditingControls["NewsReleaseDate"].Value, DateTimeHelper.ZERO_TIME);
        //newsTreeNode.NewsSummary = ValidationHelper.GetString(formElem.FieldEditingControls["NewsSummary"].Value, "");
        //newsTreeNode.NewsText = ValidationHelper.GetString(formElem.FieldEditingControls["NewsText"].Value, "");
        //newsTreeNode.NodeOwner = MembershipContext.AuthenticatedUser.UserID;
        //if (EditNodeID > 0)
        //{
        //    newsTreeNode.Update();
        //}
        //else
        //{
        //    newsTreeNode.Insert(parent);
        //}
        //ProcessFileField(newsTreeNode, "NewsTeaser");
        //newsTreeNode.Update();
        return true;
    }

    private void ProcessFileField(NewsTreeNode treeNode, string fieldName)
    {
        SiteInfo siteInfo = SiteInfoProvider.GetSiteInfo(treeNode.NodeSiteID);
        if (siteInfo == null)
        {
            throw new Exception("[CMSForm.ProcessFiles]: Site doesn't exist.");
        }
        var fieldFileControl = formElem.FieldControls[fieldName];
        var uploader = fieldFileControl.FindControl(fieldFileControl.InputControlID) as AttachmentsControl;
        AttachmentInfo attachmentInfo = null;
        int documentCheckedOutVersionHistoryID = treeNode.DocumentCheckedOutVersionHistoryID;
        attachmentInfo = (documentCheckedOutVersionHistoryID == 0 ? AttachmentInfoProvider.GetAttachmentInfo(uploader.InnerAttachmentGUID, siteInfo.SiteName) : DocumentHelper.GetAttachment(uploader.InnerAttachmentGUID, documentCheckedOutVersionHistoryID, null, false));
        attachmentInfo = DocumentHelper.AddAttachment(treeNode, fieldName, uploader.InnerAttachmentGUID, Guid.Empty, attachmentInfo, treeNode.TreeProvider, uploader.ResizeToWidth, uploader.ResizeToHeight, uploader.ResizeToMaxSideSize);
        if (attachmentInfo == null)
        {
            return;
        }
        uploader.Value = attachmentInfo.AttachmentGUID;
    }

    #endregion

    void ShowError(string message)
    {
        lblInfo.Visible = true;
        lblInfo.Text = "<span class='ErrorLabel'>" + message + "</span>";
    }
}