File: D:/HostingSpaces/TDijk1/erp-apps.eu/wwwroot/ERPApps/ERPWebParts/Documents/ApplicationForm.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.SiteProvider;
using CMS.PortalEngine;
using CMS.DataEngine;
using CMS.Membership;
using ERP.Application;
using ERP.Vendor;
/// <summary>
/// Form for inserting and editing application.
/// </summary>
public partial class ERPApps_ERPWebParts_Documents_ApplicationForm : 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_APPLICATION.
/// </summary>
public string ApplicationDocumentType
{
get
{
return ValidationHelper.GetString(this.GetValue("ApplicationDocumentType"), ApplicationTreeNode.CLASS_NAME);
}
set
{
this.SetValue("ApplicationDocumentType", value);
}
}
/// <summary>
/// Force invitation
/// If True, the form can only be edited if a valid invitation is provided
/// </summary>
public bool ForceInvitation
{
get
{
return ValidationHelper.GetBoolean(this.GetValue("ForceInvitation"), false);
}
set
{
this.SetValue("ForceInvitation", value);
}
}
private int _VendorID;
/// <summary>
/// Vendor of the application.
/// </summary>
public int VendorID
{
get
{
if (_VendorID == 0)
{
_VendorID = ValidationHelper.GetInteger(this.GetValue("VendorID"), 0);
if (_VendorID == 0 && EditInvitationGuid != Guid.Empty)
{
var application = ApplicationTreeNodeProvider.GetApplications()
.WhereLike("NodeAliasPath", "/%")
.CombineWithDefaultCulture()
.WhereEquals("AppLastInvitationToEditToken", EditInvitationGuid)
.FirstObject;
if (application != null)
{
var expiration = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".ERPExpirationInterval");
if (application.AppLastInvitationToEditSendWhen > DateTime.Now.AddDays(-expiration))
{
EditNodeID = application.NodeID;
VendorID = ValidationHelper.GetInteger(application.GetValue("AppVendorID"), 0);
}
else
{
URLHelper.Redirect(URLHelper.ResolveUrl(ExpiredInvitationURL));
}
}
}
}
return _VendorID;
}
set
{
_VendorID = value;
this.SetValue("VendorID", value);
}
}
/// <summary>
/// Target node alias path for the application`s document.
/// </summary>
public string ApplicationTargetPath
{
get
{
return ValidationHelper.GetString(this.GetValue("ApplicationTargetPath"), String.Empty);
}
set
{
this.SetValue("ApplicationTargetPath", 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 ExpiredInvitationURL
{
get
{
return ValidationHelper.GetString(this.GetValue("ExpiredInvitationURL"), String.Empty);
}
set
{
this.SetValue("ExpiredInvitationURL", value);
}
}
private int _EditNodeID;
/// <summary>
/// Application`s node ID in case of editing the app.
/// </summary>
public int EditNodeID
{
get
{
if (_EditNodeID == 0)
{
_EditNodeID = ValidationHelper.GetInteger(this.GetValue("EditNodeID"), 0);
if (_EditNodeID == -1 && EditInvitationGuid != Guid.Empty)
{
var application = ApplicationTreeNodeProvider.GetApplications()
.WhereLike("NodeAliasPath", "/%")
.CombineWithDefaultCulture()
.WhereEquals("AppLastInvitationToEditToken", EditInvitationGuid)
.FirstObject;
if (application != null)
{
var expiration = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".ERPExpirationInterval");
if (application.AppLastInvitationToEditSendWhen > DateTime.Now.AddDays(-expiration))
{
EditNodeID = application.NodeID;
VendorID = application.AppVendorID;
}
else
{
URLHelper.Redirect(URLHelper.ResolveUrl(ExpiredInvitationURL));
}
}
}
}
return _EditNodeID;
}
set
{
_EditNodeID = value;
this.SetValue("EditNodeID", value);
}
}
/// <summary>
/// Application`s invitationNodeGuid
/// </summary>
public Guid EditInvitationGuid
{
get
{
return ValidationHelper.GetGuid(this.GetValue("EditInvitationGuid"), Guid.Empty);
}
set
{
this.SetValue("EditInvitationGuid", 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);
}
}
protected bool ShouldRedirect { get; set; }
#endregion
#region "Webpart properties"
private bool IsEditing;
ApplicationTreeNode _Application;
private ApplicationTreeNode Application
{
get
{
if (_Application == null)
{
_Application = ApplicationTreeNodeProvider.GetApplication(EditNodeID, CurrentDocument.DocumentCulture, CurrentSiteName);
}
return _Application;
}
set
{
_Application = value;
}
}
private int OriginalSolutionTypeID { get; set; }
#endregion
#region "On events"
/// <summary>
/// Content loaded event handler
/// </summary>
public override void OnContentLoaded()
{
base.OnContentLoaded();
SetupControl();
}
#endregion
#region "Initialization"
private void SetupControl()
{
TreeProvider provider = new TreeProvider(MembershipContext.AuthenticatedUser);
if (ForceInvitation)
{
if (!IsInvitationValid())
{
plcContent.Visible = false;
return;
}
}
if (EditNodeID != 0)
{
// load existing node
if (Application == null || Application.AppVendorID != VendorID)
{
// insufficient rights
if (PortalContext.ViewMode == CMS.PortalEngine.ViewModeEnum.LiveSite)
{
ERPDataHelper.Redirect404(true);
}
Application = null;
}
else
{
panelTerms.Visible = false;
OriginalSolutionTypeID = ValidationHelper.GetInteger(Application.AppSolutionType, 0);
}
}
else
{
// requires accepting terms and conditions
//panelTerms.Visible = true;
}
formElem.Visible = true;
formElem.TreeProvider = provider;
formElem.NodeID = Application == null ? 0 : Application.NodeID;
formElem.FormName = ApplicationDocumentType + ".default";
formElem.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
formElem.AlternativeFormFullName = AlternativeForm;
formElem.FormMode = Application == null ? FormModeEnum.Insert : FormModeEnum.Update;
}
private bool IsInvitationValid()
{
if (EditInvitationGuid.Equals(Guid.Empty))
{
ShowError(ResHelper.GetString("ERPApps.ApplicationInvitation.NotValid"));
return false;
}
else
{
var application = ApplicationTreeNodeProvider.GetApplications()
.WhereLike("NodeAliasPath", "/%")
.CombineWithDefaultCulture()
.WhereEquals("AppLastInvitationToEditToken", EditInvitationGuid)
.FirstObject;
if (application == null)
{
ShowError(ResHelper.GetString("ERPApps.ApplicationInvitation.NotValid"));
return false;
}
else
{
var expiration = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".ERPExpirationInterval");
if (application.AppLastInvitationToEditSendWhen <= DateTime.Now.AddDays(-expiration))
{
ShowError(ResHelper.GetString("ERPApps.ApplicationInvitation.Expired"));
return false;
}
}
}
return true;
}
#endregion
#region "Events"
protected void Page_PreRender(object sender, EventArgs e)
{
var updatedAppID = ValidationHelper.GetInteger(Session["UpdatedAppID"], 0);
if (updatedAppID != 0)
{
lblInfo.Visible = true;
lblInfo.Text = SuccessText;
Session.Remove("UpdatedAppID");
}
else
{
lblInfo.Visible = false;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!formElem.ValidateData())
{
return;
}
if (panelTerms.Visible && !chckTerms.Checked)
{
// not agreed to terms and conditions
lblTermsRequired.Visible = true;
return;
}
// validate contact details inside description
CMS.FormControls.EditingFormControl descriptionControl = formElem.FieldEditingControls["AppDescription"] as CMS.FormControls.EditingFormControl;
if (descriptionControl != null)
{
KeyValuePair<string, string> contactValidation = ERPDataHelper.ContainsContacts(descriptionControl.Value.ToString());
if (contactValidation.Key != null)
{
// error found
ShowError(ContactErrorText.Replace("$$type$$", contactValidation.Key).Replace("$$value$$", HTMLHelper.HTMLEncode(contactValidation.Value)));
return;
}
}
if (Application == null)
{
// insert new application
formElem.Data["AppVendorID"] = VendorID;
// create new app -> initialize with special fields
formElem.Data["AppName"] = TreePathUtils.EnsureMaxNodeNameLength(ValidationHelper.GetString(formElem.GetFieldValue("AppName"), "[missing]"), TreeNode.OBJECT_TYPE);
formElem.Data["AppDateAdded"] = DateTime.Now;
formElem.OwnerID = MembershipContext.AuthenticatedUser.UserID;
// create a new tree node
TreeNode parent = formElem.TreeProvider.SelectSingleNode(SiteContext.CurrentSiteName, ApplicationTargetPath, DocumentContext.CurrentPageInfo.DocumentCulture);
if (parent == null)
{
EventLogProvider.LogEvent(EventType.ERROR, "AppForm", "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.Data["AppDateUpdated"] = DateTime.Now;
formElem.OnSaveFailed += new EventHandler(formElem_OnSaveFailed);
SaveApplication();
}
private void SaveApplication()
{
var application = (formElem.EditedObject as ApplicationTreeNode);
application.AppName = ValidationHelper.GetString(formElem.FieldEditingControls["AppName"].Value, "");
application.AppSolutionType = ValidationHelper.GetString(formElem.FieldEditingControls["AppSolutionType"].Value, "");
application.AppSolutionExtension = ValidationHelper.GetString(formElem.FieldEditingControls["AppSolutionExtension"].Value, "");
application.AppShortDescription = ValidationHelper.GetString(formElem.FieldEditingControls["AppShortDescription"].Value, "");
application.AppDescription = ValidationHelper.GetString(formElem.FieldEditingControls["AppDescription"].Value, "");
application.AppFeatures = ValidationHelper.GetString(formElem.FieldEditingControls["AppFeatures"].Value, "");
application.AppAddedValue = ValidationHelper.GetString(formElem.FieldEditingControls["AppAddedValue"].Value, "");
application.AppIndustrySectors = ValidationHelper.GetString(formElem.FieldEditingControls["AppIndustrySectors"].Value, "");
application.AppProcessGroups = ValidationHelper.GetString(formElem.FieldEditingControls["AppProcessGroups"].Value, "");
application.AppPlatformTypes = ValidationHelper.GetString(formElem.FieldEditingControls["AppPlatformTypes"].Value, "");
application.AppCertifications = ValidationHelper.GetString(formElem.FieldEditingControls["AppCertifications"].Value, "");
application.AppTechnology = ValidationHelper.GetString(formElem.FieldEditingControls["AppTechnology"].Value, "");
application.AppImplementationCount = ValidationHelper.GetInteger(formElem.FieldEditingControls["AppImplementationCount"].Value, 0);
application.AppBrochureURL = ValidationHelper.GetString(formElem.FieldEditingControls["AppBrochureURL"].Value, "");
application.AppOnlinePresentationURL = ValidationHelper.GetString(formElem.FieldEditingControls["AppOnlinePresentationURL"].Value, "");
application.AppLastInvitationToEditSendWhen = ValidationHelper.GetDateTime(formElem.FieldEditingControls["AppLastInvitationToEditSendWhen"].Value, DateTimeHelper.ZERO_TIME);
application.AppInvitationsToEditSentOn = ValidationHelper.GetString(formElem.FieldEditingControls["AppInvitationsToEditSentOn"].Value, "");
application.AppLastInvitationToEditToken = ValidationHelper.GetString(formElem.FieldEditingControls["AppLastInvitationToEditToken"].Value, "");
application.AppLastInvitationEditedWhen = ValidationHelper.GetDateTime(formElem.FieldEditingControls["AppLastInvitationEditedWhen"].Value, DateTimeHelper.ZERO_TIME);
if ((formElem.EditedObject as ApplicationTreeNode).NodeID == 0)
{
var vendor = VendorTreeNodeProvider.GetVendors().WhereEquals("VendorID", VendorID);
application.Insert(vendor);
ProcessFileField(application, "AppIcon");
(formElem.FieldControls["AppIndustrySectors"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
(formElem.FieldControls["AppProcessGroups"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
(formElem.FieldControls["AppPlatformTypes"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
}
else
{
ProcessFileField(application, "AppIcon");
application.Update();
(formElem.FieldControls["AppIndustrySectors"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
(formElem.FieldControls["AppProcessGroups"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
(formElem.FieldControls["AppPlatformTypes"] as ERPApps_ERPWebParts_ManyToManySelector).Form_OnAfterSave(this, new EventArgs());
}
// send notification to admin
TreeNode treeNode = formElem.EditedObject as TreeNode;
ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.App", treeNode);
treeNode.SetValue("AppLastInvitationEditedWhen", DateTime.Now);
treeNode.Update();
if (OriginalSolutionTypeID > 0 && ValidationHelper.GetInteger(formElem.Data["AppSolutionType"], OriginalSolutionTypeID) != OriginalSolutionTypeID)
{
// solution type was changed, inform administrator
ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.AppSolutionTypeChanged", treeNode);
}
if (treeNode != null)
{
// clear cache
CacheHelper.TouchKey("nodeid|" + treeNode.NodeID);
CacheHelper.TouchKey("homepagelist");
Session["UpdatedAppID"] = treeNode.NodeID;
URLHelper.Redirect(URLHelper.ResolveUrl(URLHelper.AddParameterToUrl("~/account/vendor/my-apps/edit", "ID", treeNode.NodeID.ToString())));
}
}
private void ProcessFileField(ApplicationTreeNode application, string fieldName)
{
var appIconFileControl = formElem.FieldControls[fieldName];
var upload = appIconFileControl.FindControl(appIconFileControl.InputControlID) as Uploader;
if (upload.PostedFile != null)
{
AttachmentInfo attachmentInfo1 = DocumentHelper.AddAttachment(application, fieldName, upload.PostedFile, formElem.TreeProvider, upload.ResizeToWidth, upload.ResizeToHeight, upload.ResizeToMaxSideSize);
}
}
/// <summary>
/// In case of saving failed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void formElem_OnSaveFailed(object sender, EventArgs e)
{
TreeNode node = formElem.EditedObject as TreeNode;
EventLogProvider.LogEvent(EventType.ERROR, "AppForm", "SAVINGFAILED", null, "Saving failed. Data: " + (node != null ? node.ToJSON("data", false) : "NULL"));
ShowError("Application could not be created. Please try again later.");
}
#endregion
void ShowError(string message)
{
lblInfo.Visible = true;
lblInfo.Text = "<span class='ErrorLabel'>" + message + "</span>";
}
}