File: D:/HostingSpaces/TDijk1/erp-apps.eu/wwwroot/ERPApps/ERPWebParts/Documents/AdNewForm.ascx.cs.bak
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;
/// <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);
}
}
#endregion
#region "Events"
void btnSave_Click(object sender, EventArgs e)
{
formElem.OnAfterSave += new EventHandler(formElem_OnAfterSave);
TreeNode node = CreateAd();
}
void formElem_OnAfterSave(object sender, EventArgs e)
{
ShowDonePanel(false);
}
/// <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.BasicForm.FieldEditingControls["DocumentName"] as EditingFormControl );
EventLogProvider ev = new EventLogProvider();
if ( formElem.BasicForm.ValidateData() && chckTerms.Checked )
{
TreeNode vendorNode = CMSContext.CurrentUser.GetValue("VendorNode") as TreeNode;
if ( vendorNode == null )
{
ShowError(null);
ev.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "AdNewForm", "VENDORNODE", null, "Vendor node for user " + CMSContext.CurrentUser.UserID + " is null!");
return null;
}
// get target path
int locationID = ValidationHelper.GetInteger(drpAdLocation.SelectedValue, 0);
int periodID = ValidationHelper.GetInteger(drpPeriod.SelectedValue, 0);
string targetPath = GetTargetPath(locationID);
if ( targetPath == null )
{
ShowError(null);
ev.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "AdNewForm", "TARGETPATH", null, "Target path for location ID " + locationID + " is null!");
return null;
}
if ( periodID == 0 )
{
ShowError("Please select a period.");
return null;
}
// create new ad -> initialize with special fields
string name = ValidationHelper.GetString(editName.Text, "[missing]");
formElem.BasicForm.Data["AdName"] = name;
// create document name from ad name and vendor name
if ( documentNameControl != null )
{
documentNameControl.Value = TreePathUtils.EnsureMaxNodeNameLength(vendorNode.GetValue("VendorName") + ": " + name);
}
else
{
formElem.BasicForm.Data["DocumentName"] = name;
}
// load location code from ID
CustomTableItemProvider cp = new CustomTableItemProvider();
CustomTableItem locationItem = cp.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
formElem.BasicForm.Data["AdVendorID"] = CMSContext.CurrentUser.GetValue("UserVendorID");
formElem.BasicForm.Data["AdLocation"] = drpAdLocation.SelectedValue;
formElem.BasicForm.Data["AdSolutionType"] = drpSolutionType.SelectedValue;
switch ( locationItem["ItemCode"].ToString() )
{
case "industry":
formElem.BasicForm.Data["AdIndustrySector"] = drpAdIndustry.SelectedValue;
break;
case "process":
formElem.BasicForm.Data["AdProcessGroup"] = drpAdProcess.SelectedValue;
break;
case "platform":
formElem.BasicForm.Data["AdPlatformType"] = drpAdPlatform.SelectedValue;
break;
}
formElem.BasicForm.Data["AdIsPublished"] = 0;
formElem.BasicForm.Data["AdStartDate"] = DateTime.Now;
formElem.BasicForm.Data["AdEndDate"] = DateTime.Now;
formElem.BasicForm.Data["AdPeriod"] = periodID;
formElem.OwnerID = CMSContext.CurrentUser.UserID;
// create a new tree node
TreeNode parent = formElem.TreeProvider.SelectSingleNode(CMSContext.CurrentSiteName, targetPath, CMSContext.CurrentPageInfo.DocumentCulture);
if ( parent == null )
{
//ShowError(null);
ev.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "AdNewForm", "TARGETPATHNODE", null, "Node for target path " + targetPath + " is null!");
return null;
}
formElem.NodeId = parent.NodeID;
// save node
formElem.OnSaveFailed += new EventHandler(formElem_OnSaveFailed);
return formElem.Save();
}
lblTermsRequired.Visible = !chckTerms.Checked;
return null;
}
void formElem_OnSaveFailed(object sender, EventArgs e)
{
// send notification to admin
ERPNotifications.SendNotificationToAdmin("ERP.AdminNotification.Ad", formElem.BasicForm.EditedObject as TreeNode);
TreeNode node = formElem.BasicForm.EditedObject as TreeNode;
EventLogProvider ev = new EventLogProvider();
ev.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "AdNewForm", "SAVINGFAILED", null, "Saving failed, data " + (node != null ? node.ToJSON("data", false) : "NULL") + "!");
}
/// <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 = CreateAd();
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);
CMS.GlobalHelper.ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", CMS.GlobalHelper.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(CMSContext.CurrentUser);
formElem.Visible = true;
formElem.TreeProvider = provider;
formElem.NodeId = 0;
formElem.FormName = ERPConfig.DOCTYPE_AD + ".default";
formElem.CultureCode = CMSContext.CurrentPageInfo.DocumentCulture;
formElem.AlternativeFormFullName = AlternativeFormFullName;
formElem.FormMode = FormModeEnum.Insert;
}
/// <summary>
/// Initializes dropdown for selecting period.
/// Values are selected from custom table.
/// </summary>
/// <param name="tp"></param>
protected void InitPeriodDropdown(CustomTableItemProvider tp)
{
DataSet ds = tp.GetItems(ERPConfig.CUSTOM_TABLE_ADS_PERIOD, "ItemIsPublished = 1", "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(CustomTableItemProvider tp)
{
DataSet ds = tp.GetItems(ERPConfig.CUSTOM_TABLE_SOLUTION_TYPE, "", "ItemOrder");
InitDropdown(drpSolutionType, ds);
}
/// <summary>
/// Initializes dropdown for location types.
/// Values are selected from custom table.
/// </summary>
/// <param name="tp"></param>
protected void InitLocationTypeDropdown(CustomTableItemProvider tp)
{
DataSet ds = tp.GetItems(ERPConfig.CUSTOM_TABLE_ADS_LOCATION, "", "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()
{
CustomTableItemProvider tp = new CustomTableItemProvider(CMSContext.CurrentUser);
if ( drpAdLocation.Items.Count == 0 )
{
// init dropdown menus
InitLocationTypeDropdown(tp);
InitPeriodDropdown(tp);
InitSolutionTypeDropdown(tp);
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)
{
CustomTableItemProvider tp = new CustomTableItemProvider(CMSContext.CurrentUser);
DataSet ds = tp.GetItems("ERP.ListAdsLocation", "[ItemID] = " + adLocationID, "");
if ( !DataHelper.DataSourceIsEmpty(ds) )
{
return ValidationHelper.GetString(ds.Tables[0].Rows[0]["ItemTargetPath"], null);
}
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
}