File: D:/HostingSpaces/TDijk1/erp-apps.eu/wwwroot/ERPApps/ERPWebParts/Documents/AdNewForm.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using CMS.PortalControls;
using CMS.Ecommerce;
using CMS.CMSHelper;
using CMS.GlobalHelper;
using System.Data;
using CMS.SiteProvider;
using CMS.DataEngine;
using CMS.SettingsProvider;
using CMS.FormEngine;
using CMS.TreeEngine;
using CMS.EventLog;
using CMS.FormControls;
using CMS.DocumentEngine;
using CMS.ExtendedControls;
using CMS.CustomTables;
using CMS.Membership;
using CMS.Helpers;
using ERP.Ad;
using ERP.Vendor;
/// <summary>
/// Wizard for creating new ad.
/// </summary>
public partial class ERPApps_ERPWebParts_Documents_AdNewForm : CMSAbstractWebPart
{
private DataSet periodsDataSet = null;
#region "Properties"
/// <summary>
/// Product SKU ID
/// </summary>
public int SKUID
{
get
{
return ValidationHelper.GetInteger(this.GetValue("SKUID"), 0);
}
set
{
this.SetValue("SKUID", value);
}
}
/// <summary>
/// Alternative form full name. Default is ""
/// </summary>
public string AlternativeFormFullName
{
get
{
return ValidationHelper.GetString(this.GetValue("AlternativeFormFullName"), "");
}
set
{
this.SetValue("AlternativeFormFullName", value);
}
}
/// <summary>
/// Shopping cart URL
/// </summary>
public string ShoppingCartURL
{
get
{
return ValidationHelper.GetString(this.GetValue("ShoppingCartURL"), "");
}
set
{
this.SetValue("ShoppingCartURL", value);
}
}
/// <summary>
/// Custom description of step 1
/// </summary>
public string Step1Description
{
get
{
return ValidationHelper.GetString(this.GetValue("Step1Description"), "");
}
set
{
this.SetValue("Step1Description", value);
}
}
/// <summary>
/// Custom description of step 2
/// </summary>
public string Step2Description
{
get
{
return ValidationHelper.GetString(this.GetValue("Step2Description"), "");
}
set
{
this.SetValue("Step2Description", value);
}
}
/// <summary>
/// Custom description of step 3
/// </summary>
public string Step3Description
{
get
{
return ValidationHelper.GetString(this.GetValue("Step3Description"), "");
}
set
{
this.SetValue("Step3Description", value);
}
}
/// <summary>
/// Custom description of step 4
/// </summary>
public string Step4Description
{
get
{
return ValidationHelper.GetString(this.GetValue("Step4Description"), "");
}
set
{
this.SetValue("Step4Description", value);
}
}
/// <summary>
/// Custom description of step 5
/// </summary>
public string Step5Description
{
get
{
return ValidationHelper.GetString(this.GetValue("Step5Description"), "");
}
set
{
this.SetValue("Step5Description", value);
}
}
/// <summary>
/// Custom description of not available combination
/// </summary>
public string TextNotAvailable
{
get
{
return ValidationHelper.GetString(this.GetValue("TextNotAvailable"), "");
}
set
{
this.SetValue("TextNotAvailable", value);
}
}
/// <summary>
/// Custom description of available combination with price.
/// Macro %%price%% can be used in the text to display found price.
/// </summary>
public string TextPrice
{
get
{
return ValidationHelper.GetString(this.GetValue("TextPrice"), "");
}
set
{
this.SetValue("TextPrice", value);
}
}
/// <summary>
/// Custom description after the item has been added to the shopping cart.
/// </summary>
public string TextAddedToCart
{
get
{
return ValidationHelper.GetString(this.GetValue("TextAddedToCart"), "");
}
set
{
this.SetValue("TextAddedToCart", value);
}
}
/// <summary>
/// Custom description after the item has been created but not added to the shopping cart.
/// </summary>
public string TextCreated
{
get
{
return ValidationHelper.GetString(this.GetValue("TextCreated"), "");
}
set
{
this.SetValue("TextCreated", value);
}
}
protected string TargetPath
{
get
{
int locationID = ValidationHelper.GetInteger(drpAdLocation.SelectedValue, 0);
return GetTargetPath(locationID);
}
}
protected TreeNode ParentTreeNode
{
get
{
return TreeHelper.SelectSingleNode(TargetPath);
}
}
#endregion
#region "Events"
void btnSave_Click(object sender, EventArgs e)
{
try
{
TreeNode node = CreateAd();
}
catch (Exception ex)
{
// send notification to admin
ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.Ad", formElem.EditedObject as TreeNode);
TreeNode node = formElem.EditedObject as TreeNode;
EventLogProvider.LogException(EventType.ERROR, "AdNewForm",ex);
EventLogProvider.LogEvent(EventType.ERROR, "AdNewForm", "SAVINGFAILED", null, "Saving failed, data " + (node != null ? node.ToJSON("data", false) : "NULL") + "!");
}
}
/// <summary>
/// Calculates and displays price based on selected category and period.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnPrice_Click(object sender, EventArgs e)
{
// find price based on selected values (options)
double? price = ERPDataHelper.GetAdPrice(ValidationHelper.GetInteger(drpAdLocation.SelectedValue, 0), ValidationHelper.GetInteger(drpSolutionType.SelectedValue, 0), ValidationHelper.GetInteger(drpPeriod.SelectedValue, 0));
if ( price == null )
{
notAvailablePanel.Visible = true;
orderPanel.Visible = false;
lblNotAvailable.Text = TextNotAvailable;
}
else
{
lblPrice.Text = TextPrice.Replace("%%price%%", ValidationHelper.GetString(price, "unknown"));
orderPanel.Visible = true;
notAvailablePanel.Visible = false;
}
}
/// <summary>
/// Creates ad.
/// </summary>
/// <returns></returns>
private TreeNode CreateAd()
{
EditingFormControl documentNameControl = ( formElem.FieldEditingControls["DocumentName"] as EditingFormControl );
EventLogProvider ev = new EventLogProvider();
if ( formElem.ValidateData() && chckTerms.Checked )
{
VendorTreeNode vendorNode = VendorTreeNodeProvider.GetVendors().WhereEquals("VendorID", (MembershipContext.AuthenticatedUser.GetValue("UserVendorID"))).FirstObject;
if ( vendorNode == null )
{
ShowError(null);
EventLogProvider.LogEvent(EventType.ERROR, "AdNewForm", "VENDORNODE", null, "Vendor node for user " + MembershipContext.AuthenticatedUser.UserID + " is null!");
return null;
}
// get target path
int locationID = ValidationHelper.GetInteger(drpAdLocation.SelectedValue, 0);
int periodID = ValidationHelper.GetInteger(drpPeriod.SelectedValue, 0);
string targetPath = TargetPath;
if ( targetPath == null )
{
ShowError(null);
EventLogProvider.LogEvent(EventType.ERROR, "AdNewForm", "TARGETPATH", null, "Target path for location ID " + locationID + " is null!");
return null;
}
if ( periodID == 0 )
{
ShowError("Please select a period.");
return null;
}
var newAdTreeNode = new AdTreeNode();
// create new ad -> initialize with special fields
string name = ValidationHelper.GetString(editName.Text, "[missing]");
newAdTreeNode.AdName = name;
// create document name from ad name and vendor name
if ( documentNameControl != null )
{
newAdTreeNode.DocumentName = TreePathUtils.EnsureMaxNodeNameLength(vendorNode.GetValue("VendorName") + ": " + name,"erp.Vendor");
}
else
{
newAdTreeNode.DocumentName = name;
}
// load location code from ID
CustomTableItem locationItem = CustomTableItemProvider.GetItem(ValidationHelper.GetInteger(drpAdLocation.SelectedValue, 0), ERPConfig.CUSTOM_TABLE_ADS_LOCATION);
if ( locationItem == null )
{
lblError.Text = "Location can not be found.";
return null;
}
// extend data by generated values
newAdTreeNode.AdVendorID = MembershipContext.AuthenticatedUser.GetIntegerValue("UserVendorID",0);
newAdTreeNode.AdLocation = drpAdLocation.SelectedValue;
newAdTreeNode.AdSolutionType = drpSolutionType.SelectedValue;
switch ( locationItem["ItemCode"].ToString() )
{
case "industry":
newAdTreeNode.AdIndustrySector = ValidationHelper.GetInteger(drpAdIndustry.SelectedValue,0);
break;
case "process":
newAdTreeNode.AdProcessGroup = ValidationHelper.GetInteger(drpAdProcess.SelectedValue, 0);
break;
case "platform":
newAdTreeNode.AdPlatformType = ValidationHelper.GetInteger(drpAdPlatform.SelectedValue, 0);
break;
}
newAdTreeNode.AdIsPublished = false;
newAdTreeNode.AdStartDate = DateTime.Now;
newAdTreeNode.AdEndDate = DateTime.Now;
newAdTreeNode.AdPeriod = periodID;
// create a new tree node
TreeNode parent = ParentTreeNode;
if ( parent == null )
{
//ShowError(null);
EventLogProvider.LogEvent(EventType.ERROR, "AdNewForm", "TARGETPATHNODE", null, "Node for target path " + targetPath + " is null!");
return null;
}
formElem.ParentNodeID = parent.NodeID;
newAdTreeNode.Insert(parent);
ProcessFileField(newAdTreeNode, "AdBanner");
newAdTreeNode.Update();
ShowDonePanel(false);
return formElem.Node;
}
lblTermsRequired.Visible = !chckTerms.Checked;
return null;
}
private void ProcessFileField(AdTreeNode newAdTreeNode, string fieldName)
{
var appIconFileControl = formElem.FieldControls[fieldName];
var upload = appIconFileControl.FindControl(appIconFileControl.InputControlID) as Uploader;
if (upload.PostedFile != null)
{
AttachmentInfo attachmentInfo1 = DocumentHelper.AddAttachment(newAdTreeNode, fieldName, upload.PostedFile, formElem.TreeProvider, upload.ResizeToWidth, upload.ResizeToHeight, upload.ResizeToMaxSideSize);
}
}
/// <summary>
/// Displays error message
/// </summary>
/// <param name="message"></param>
void ShowError(string message)
{
if ( message == null )
{
message = "Unfortunately the ad can not be created. Please contact us for more details.";
}
lblError.Visible = true;
lblError.Text = "<span class='ErrorLabel'>" + message + "</span>";
}
/// <summary>
/// Creates the ad and adds it to the shopping cart
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnAddToCart_Click(object sender, EventArgs e)
{
TreeNode node;
try
{
node = CreateAd();
}
catch (Exception ex)
{
// send notification to admin
ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.Ad", formElem.EditedObject as TreeNode);
node = formElem.EditedObject as TreeNode;
EventLogProvider.LogException("AdNewForm", "SAVINGFAILED", ex);
EventLogProvider.LogEvent(EventType.ERROR, "AdNewForm", "SAVINGFAILED", null, "Saving failed, data " + (node != null ? node.ToJSON("data", false) : "NULL") + "!");
}
if (node == null)
{
return;
}
SKUInfo SKU = SKUInfoProvider.GetSKUInfo(this.SKUID);
if ( SKU != null )
{
string result;
try
{
result = ERPShoppingCartInfoProvider.AddAdToShoppingCart(SKU, node);
// Get product added message
string message = String.Format(this.GetString("com.productadded"), SKU.SKUName);
// Add inventory check message
if ( !String.IsNullOrEmpty(result) )
{
message += "\n\n" + result;
}
// Register the call of JS handler informing about added product
ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
if ( !DataHelper.IsEmpty(ShoppingCartURL) )
{
// redirect to specific URL
URLHelper.Redirect(URLHelper.ResolveUrl(ShoppingCartURL));
}
else
{
ShowDonePanel(true);
}
}
catch ( ERPShoppingCartInfoProviderException ex )
{
string error = String.Format(this.GetString(ex.Message), SKU.SKUName);
ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
}
}
}
/// <summary>
/// Displays confirmation message and hides the form.
/// </summary>
/// <param name="addedToCart"></param>
private void ShowDonePanel(bool addedToCart)
{
donePanel.Visible = true;
calculatePanel.Visible = false;
notAvailablePanel.Visible = false;
orderPanel.Visible = false;
if ( addedToCart )
{
lblDone.Text = TextAddedToCart;
}
else
{
lblDone.Text = TextCreated;
}
}
#endregion
#region "Initialization"
void InitForm()
{
if ( this.StopProcessing )
{
return;
}
//TreeProvider provider = new TreeProvider(MembershipContext.AuthenticatedUser);
TreeProvider provider = new TreeProvider(MembershipContext.AuthenticatedUser);
TreeNode parent = ParentTreeNode;
formElem.Visible = true;
formElem.TreeProvider = provider;
formElem.NodeID = 0; //parent != null ? parent.NodeID : 0;
formElem.FormName = ERPConfig.DOCTYPE_AD + ".default";
formElem.CultureCode = DocumentContext.CurrentPageInfo.DocumentCulture;
formElem.AlternativeFormFullName = AlternativeFormFullName;
formElem.SiteName = SiteContext.CurrentSiteName;
formElem.FormMode = FormModeEnum.Insert;
formElem.IsLiveSite = true;
}
/// <summary>
/// Initializes dropdown for selecting period.
/// Values are selected from custom table.
/// </summary>
/// <param name="tp"></param>
protected void InitPeriodDropdown()
{
ObjectQuery<CustomTableItem> ds = CustomTableItemProvider.GetItems(ERPConfig.CUSTOM_TABLE_ADS_PERIOD).WhereEquals("ItemIsPublished",1).OrderBy("ItemOrder");
InitDropdown(drpPeriod, ds);
periodsDataSet = ds;
}
/// <summary>
/// Initializes dropdown for solution types.
/// Values are selected from custom table.
/// </summary>
/// <param name="tp"></param>
protected void InitSolutionTypeDropdown()
{
ObjectQuery<CustomTableItem> ds = CustomTableItemProvider.GetItems(ERPConfig.CUSTOM_TABLE_SOLUTION_TYPE).OrderBy("ItemOrder");
InitDropdown(drpSolutionType, ds);
}
/// <summary>
/// Initializes dropdown for location types.
/// Values are selected from custom table.
/// </summary>
/// <param name="tp"></param>
protected void InitLocationTypeDropdown()
{
ObjectQuery<CustomTableItem> ds = CustomTableItemProvider.GetItems(ERPConfig.CUSTOM_TABLE_ADS_LOCATION).OrderBy("ItemOrder");
InitDropdown(drpAdLocation, ds);
}
/// <summary>
/// Initializes dropdown with given values.
/// </summary>
/// <param name="control"></param>
/// <param name="ds"></param>
protected void InitDropdown(System.Web.UI.WebControls.DropDownList control, DataSet ds)
{
control.Items.Clear();
if ( !DataHelper.DataSourceIsEmpty(ds) )
{
foreach ( DataRow item in ds.Tables[0].Rows )
{
control.Items.Add(new System.Web.UI.WebControls.ListItem(ValidationHelper.GetString(item["ItemName"], ""), ValidationHelper.GetString(item["ItemID"], "")));
}
}
}
/// <summary>
/// Initializes dropdown with values found in content tree.
/// </summary>
/// <param name="control"></param>
/// <param name="type">Document type to use as a source</param>
/// <param name="key">Column name used as key value</param>
/// <param name="value">Column name used as value</param>
protected void InitDropdownFromContentTree(System.Web.UI.WebControls.DropDownList control, string type, string key, string value)
{
LinkedList<KeyValuePair<string, string>> values = null;
values = ERPDataHelper.GetOptionsFromContentTree(type, key, value);
// populate dropdown
if ( values != null && values.Count > 0 )
{
foreach ( var item in values )
{
control.Items.Add(new System.Web.UI.WebControls.ListItem(item.Value, item.Key));
}
}
}
protected void InitIndustriesDropdown()
{
InitDropdownFromContentTree(drpAdIndustry, ERPConfig.DOCTYPE_INDUSTRY, "IndustryPageSector", "DocumentName");
}
protected void InitProcessesDropdown()
{
InitDropdownFromContentTree(drpAdProcess, ERPConfig.DOCTYPE_PROCESS, "ProcessPageGroup", "DocumentName");
}
protected void InitPlatformsDropdown()
{
InitDropdownFromContentTree(drpAdPlatform, ERPConfig.DOCTYPE_PLATFORM, "PlatformPageType", "DocumentName");
}
protected void SetupControl()
{
if ( drpAdLocation.Items.Count == 0 )
{
// init dropdown menus
InitLocationTypeDropdown();
InitPeriodDropdown();
InitSolutionTypeDropdown();
InitIndustriesDropdown();
InitProcessesDropdown();
InitPlatformsDropdown();
}
// init form
InitForm();
// set custom descriptions
lblStep1.Text = Step1Description;
lblStep2.Text = Step2Description;
lblStep3.Text = Step3Description;
lblStep4.Text = Step4Description;
lblStep5.Text = Step5Description;
}
#endregion
/// <summary>
/// Based on ad type returns the correct node alias path used as a parent document to create the ad under.
/// The target location is selected from custom table.
/// </summary>
/// <param name="adLocationID"></param>
/// <returns></returns>
protected string GetTargetPath(int adLocationID)
{
CustomTableItem ds = CustomTableItemProvider.GetItems("ERP.ListAdsLocation").WhereEquals("[ItemID]", adLocationID).FirstObject;
if ( ds!=null )
{
return ds.GetStringValue("ItemTargetPath",string.Empty);
}
return null;
}
#region "On events"
public override void OnContentLoaded()
{
base.OnContentLoaded();
SetupControl();
btnSave.Click += new EventHandler(btnSave_Click);
btnAddToCart.Click += new EventHandler(btnAddToCart_Click);
btnPrice.Click += new EventHandler(btnPrice_Click);
}
#endregion
}