How to increase the speed of finding elements? - c#

This code performs extremely long time and in the end, doesn't accomplish its goal - combine element's parameters inside of a schedule. It clearly happens due to a large number of elements of the category "Pipe Fitting" in the project. How to increase the speed? Is it through selecting elements using some scheduled class?
Win Forms GUI is used.
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"GP_Description",
"GP_Model",
"GP_Angle"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting);
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element duct in ducts)
{
Parameter parameter1 = duct.LookupParameter(comboBox1.Text);
Parameter parameter2 = duct.LookupParameter(comboBox2.Text);
Parameter parameter3 = duct.LookupParameter(comboBox3.Text);
List<string> parameterValues = new List<string>();
if (parameter1 != null)
{
string parameterValue1 = parameter1.AsString();
if (parameterValue1 != "") parameterValues.Add(parameterValue1);
}
if (parameter2 != null)
{
string parameterValue2 = parameter2.AsString();
if (parameterValue2 != "") parameterValues.Add(parameterValue2);
}
if (parameter3 != null)
{
string parameterValue3 = parameter3.AsString();
if (parameterValue3 != "") parameterValues.Add(parameterValue3);
}
if (parameterValues.Count > 0)
{
string newValue = String.Join(" ,", parameterValues);
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("Outcome").Set(newValue);
t.Commit();
}

This is untested. The biggest item is the location of the Transaction. I suggest wrapping the foreach loop with the Transaction.
public void Process(Document doc, string text1, string text2, string text3)
{
FilteredElementCollector collector =
new FilteredElementCollector(doc)
.OfCategory(BuiltInCategory.OST_PipeFitting)
.WhereElementIsNotElementType();
using (Transaction t = new Transaction(doc))
{
if (t.Start("Set Parameter Names") == TransactionStatus.Started)
{
foreach (Element elem in collector)
{
string newValue = string.Empty;
Parameter outcomeParam = elem.LookupParameter("Outcome");
if (outcomeParam == null)
{
continue;
}
newValue += this.GetParameterValue(elem, text1);
newValue += this.GetParameterValue(elem, text2);
newValue += this.GetParameterValue(elem, text3);
newValue.TrimEnd(',', ' ');
outcomeParam.Set(newValue);
}
t.Commit();
}
}
}
public string GetParameterValue(Element elem, string parameterName)
{
Parameter param = elem.LookupParameter(parameterName);
return param == null ? string.Empty : param.AsString() + ", ";
}

Related

Some problems about JSON data to C# Winforms TreeView

Firstly, I read heaps of topics about JSON to TreeView on the Stackoverflow. After this, I create a JSON data like this:
{
"Cars": {
"Audi": [{
"A6 2.0 TDI quatro 2018 Red": ["S-Line", "17 inch rim", "Full sport packet"],
"A5 1.6 TFSI 2018 Blue": ["Desing packet", "Sunroof"]
}],
"Mercedes-Benz": [{
"E220d AMG 2018 white": ["Glass ceiling", "Vacuum doors", "Navigation"],
"E220d Exclusive Black 2018 Blue": ["Power seats", "Start & Stop"]
}]
}
}
Here is the C# code content:
private void Form1_Load(object sender, EventArgs e)
{
try
{
treeView1.Nodes.Clear();
var json = File.ReadAllText(Uz.path + #"cars.json");
var obj = JObject.Parse(json);
var parent = Json2Tree(obj);
treeView1.Nodes.Add(parent);
treeView1.ExpandAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, #"ERROR");
}
}
private static TreeNode Json2Tree(JObject obj)
{
//create the parent node
var parent = new TreeNode();
//loop through the obj. all token should be pair<key, value>
foreach (var token in obj)
{
//change the display Content of the parent
parent.Text = token.Key;
//create the child node
var child = new TreeNode();
child.Text = token.Key;
//check if the value is of type obj recall the method
if (token.Value.Type.ToString() == "Object")
{
// child.Text = token.Key.ToString();
//create a new JObject using the the Token.value
var o = (JObject)token.Value;
//recall the method
child = Json2Tree(o);
//add the child to the parentNode
parent.Nodes.Add(child);
}
//if type is of array
else if (token.Value.Type.ToString() == "Array")
{
int ix = -1;
// child.Text = token.Key.ToString();
//loop though the array
foreach (var itm in token.Value)
{
//check if value is an Array of objects
if (itm.Type.ToString() == "Object")
{
//child.Text = token.Key.ToString();
//call back the method
ix++;
var o = (JObject)itm;
var objTN = Json2Tree(o);
//objTN.Text = token.Key + "[" + ix + "]";
child.Nodes.Add(objTN);
//parent.Nodes.Add(child);
}
//regular array string, int, etc
else if (itm.Type.ToString() == "Array")
{
ix++;
var dataArray = new TreeNode();
foreach (var data in itm)
{
//dataArray.Text = token.Key + "[" + ix + "]";
dataArray.Nodes.Add(data.ToString());
}
child.Nodes.Add(dataArray);
}
else
{
child.Nodes.Add(itm.ToString());
}
}
parent.Nodes.Add(child);
}
else
{
//if token.Value is not nested
// child.Text = token.Key.ToString();
//change the value into N/A if value == null or an empty string
child.Nodes.Add(token.Value.ToString() == "" ? "N/A" : token.Value.ToString());
parent.Nodes.Add(child);
}
}
return parent;
}
when I run the code, the screenshot looks like this:
But marked as 1, 2 and 3 are should not be shown. It must be like this:
Although I worked 3 days, I did not succeed.
In JsonTreeView project, it show like this:
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
namespace JsonTreeView
{
public static class JsonToTreeView
{
public static void Json2Tree(this TreeView treeView, string json, string group_name)
{
if (string.IsNullOrWhiteSpace(json))
{
return;
}
var obj = JObject.Parse(json);
AddObjectNodes(obj, group_name, treeView.Nodes);
}
public static void AddObjectNodes(JObject obj, string name, TreeNodeCollection parent)
{
var node = new TreeNode(name);
parent.Add(node);
foreach (var property in obj.Properties())
{
AddTokenNodes(property.Value, property.Name, node.Nodes);
}
}
private static void AddArrayNodes(JArray array, string name, TreeNodeCollection parent)
{
var node = new TreeNode(name);
parent.Add(node);
for (var i = 0; i < array.Count; i++)
{
AddTokenNodes(array[i], $"[{i}]", node.Nodes);
}
}
private static void AddTokenNodes(JToken token, string name, TreeNodeCollection parent)
{
switch (token)
{
case JValue _:
parent.Add(new TreeNode($"{((JValue) token).Value}"));
break;
case JArray _:
AddArrayNodes((JArray)token, name, parent);
break;
case JObject _:
AddObjectNodes((JObject)token, name, parent);
break;
}
}
}
}

Select 1 item from the filter in a pivot table

I'm generating an excel in a server that doesn't have the excel application installed, so I used EPPlus to generate the Excel and in the excel there are many pivot tables. By default, all items in a filter of the pivot table are selected but I need specific filters to have only one item selected.Is there a way to do that using EPPlus?
If there isn't, is there another library that could do that? I need a something that could search all pivot tables, search the filters for a filter with a specific name and make only 1 item selected in the filters with that specific name for every pivot table.
If it's not possible in C#, is there another way to make a program that does it without having Excel installed?If there is, I could just run that program when the excel is done.
For example, I have a filter with 13 months :
Jan/2017
Feb/2017
Mar/2017
Apr/2017
May/2017
Jun/2017
Jul/2017
Aug/2017
Sep/2017
Oct/2017
Nov/2017
Dec/2017
Jan/2018
In the filter, by default all of them are selected, I want the newest one to be selected(in this example Jan/2018).
This is the class that I created to build pivot tables :
public class PivotTableFactory
{
private ExcelPivotTable _pivotTable;
public void CreatePivotTable (Worksheet baseSheet, Worksheet targetSheet, string startRange, string tableName)
{
// Selecting All Range of the base Sheet
String baseAddress = "A1:" + baseSheet.EPPlusSheet.Dimension.End.Address;
ExcelRange baseRange = baseSheet.EPPlusSheet.Cells[baseAddress];
ExcelAddress startAddress = targetSheet.EPPlusSheet.Cells[startRange];
// Creating Pivot Table
_pivotTable = targetSheet.EPPlusSheet.PivotTables.Add (startAddress, baseRange, tableName);
_pivotTable.UseAutoFormatting = false;
}
public void AddFilterField(string columnName, string fieldName, eSortType sortType = eSortType.None)
{
ExcelPivotTableField dataField = _pivotTable.PageFields.Add (_pivotTable.Fields[columnName]);
dataField.Name = fieldName;
dataField.Sort = sortType;
if (columnName.Equals("MES_REFERENCIA")) selectFilterValue("MÊS", 10);
}
public void AddRowField(string columnName, string fieldName, eSortType sortType = eSortType.None)
{
ExcelPivotTableField rowField = _pivotTable.RowFields.Add (_pivotTable.Fields[columnName]);
rowField.Name = fieldName;
rowField.Sort = sortType;
}
public void AddColumnField (string columnName, string fieldName, eSortType sortType = eSortType.None)
{
ExcelPivotTableField rowField = _pivotTable.ColumnFields.Add (_pivotTable.Fields[columnName]);
rowField.Name = fieldName;
rowField.Sort = sortType;
}
public void AddValueField (string columnName, string fieldName, DataFieldFunctions func = DataFieldFunctions.Sum, string format = "")
{
ExcelPivotTableDataField dataField = _pivotTable.DataFields.Add (_pivotTable.Fields[columnName]);
dataField.Name = fieldName;
dataField.Function = func;
dataField.Format = format;
}
public void SetStyle (TableStyles style)
{
_pivotTable.TableStyle = style;
}
public void SetDataOnRows (bool dataOnRow)
{
_pivotTable.DataOnRows = dataOnRow;
}
public void SetDataCaption(string name)
{
_pivotTable.DataCaption = name;
}
public void setAutoFormating(bool value)
{
_pivotTable.UseAutoFormatting = value;
}
public void printPivotXml()
{
_pivotTable.PivotTableXml.Save("pivotsXmls\\pivotFinal.xml");
}
private int getFieldIndex(string name)
{
for (int i = 0;i < _pivotTable.Fields.Count; i++)
{
if (_pivotTable.Fields[i].Name.Equals(name)) return i;
}
return -1;
}
public void selectFilterValue(string name, int valueIndex)
{
int fieldIndex = getFieldIndex(name);
if (fieldIndex < 0) return;
XmlDocument xDoc = _pivotTable.PivotTableXml;
XmlAttribute attr = xDoc.CreateAttribute("item");
attr.Value = valueIndex.ToString();
XmlNode currentDoc = null;
foreach (XmlNode node in xDoc.ChildNodes)
{
if (node.Name.Equals("pivotTableDefinition"))
{
currentDoc = node;
break;
}
}
foreach (XmlNode node in currentDoc.ChildNodes)
{
if (node.Name.Equals("pageFields"))
{
currentDoc = node;
}
if (node.Name.Equals("pivotFields"))
{
foreach (XmlNode field in node.ChildNodes)
{
if (field.Attributes["name"] == null) continue;
if (field.Attributes["name"].Value.Equals(name))
{
XmlNode itemsNode = field.ChildNodes[0];
itemsNode.InnerXml = "";
List<string> items = new List<string>();
// Add item tags
for(int i = 0; i < 13; i++){
XmlNode createdNode = xDoc.CreateNode(XmlNodeType.Element, "item" , currentDoc.NamespaceURI);
XmlAttribute tempAttr = xDoc.CreateAttribute("x");
tempAttr.Value = i.ToString();
createdNode.Attributes.Append(tempAttr);
itemsNode.AppendChild(createdNode);
}
XmlNode createdNodeDefault = xDoc.CreateNode(XmlNodeType.Element, "item", currentDoc.NamespaceURI);
XmlAttribute tempAttrDefault = xDoc.CreateAttribute("t");
tempAttrDefault.Value = "default";
createdNodeDefault.Attributes.Append(tempAttrDefault);
itemsNode.AppendChild(createdNodeDefault);
itemsNode.Attributes["count"].Value = "14";
}
}
}
}
foreach (XmlNode node in currentDoc.ChildNodes)
{
if (node.Attributes["fld"].Value.Equals(fieldIndex.ToString()))
{
node.Attributes.InsertAfter(attr, node.Attributes["fld"]);
}
}
}
}
I created the function "selectFilterValue" that tries to select the value of the filter using XML but it didn't work.Please ignore the extremely rough way of selecting the XML nodes...

how to append a cookie for shopping cart details in asp.net in c#

here i want to append the product id of new product in the cookie name cart so can anyone help me with it
protected void lnkAddToCart_Click(object sender, EventArgs e)
{
HttpCookie CartCookie=Request.Cookies["cart"];
if (CartCookie != null)
{
string str = CartCookie.ToString();
str= str + ";"+ _ProductID.ToString();
Response.Cookies["cart"].Value = str;
}
else
{
CartCookie = new HttpCookie("cart");
CartCookie["Cart"] = _ProductID.ToString();
CartCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(CartCookie);
}
}
To Set Cookie
public void AddToCartCookie(List<string> listCookie)
{
string objCartListString = string.Join(",", listCookie);
if (Request.Cookies["CartCookie"] == null)
Response.Cookies["CartCookie"].Value = objCartListString;
else
Response.Cookies["CartCookie"].Value = Request.Cookies["CartCookie"].Value + "|" + objCartListString;
Response.Cookies["CartCookie"].Expires = DateTime.Now.AddYears(30);
}
Here listCookie is list of string like
string productName, quantity, price etc;
Then retrieve it by splitting like
if (Request.Cookies["CartCookie"] != null)
{
string objCartListString = Request.Cookies["CartCookie"].Value.ToString();
string[] objCartListStringSplit = objCartListString.Split('|');
foreach(string s in objCartListStringSplit)
{
string[] ss = s.Split(',');
productName = ss[0];
quantity = Convert.ToDouble(ss[1]);
price = Convert.ToDecimal(ss[3]);
.........
}
}

How to remove a word that already exist in errorList

I have a method that runs spellcheck in a word, but what i want here is that if the word already exist in my errorlist it should not be add as error. below is my code.
public void CheckSpelling()
{
int lineno = 0;
bool start = false;
foreach (string line in _contentList)
{
lineno++;
if (line.Contains("<text>"))
{
start = true;
}
if (start)
{
foreach (Match match in Regex.Matches(line, "<.*?>[^<]+</(.*?)>", RegexOptions.IgnoreCase))
{
List<string> customdiclist = new List<string>(File.ReadAllLines(Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["customdic"])));
string[] strArray = Regex.Replace(match.Value, "</?[^>]+>", string.Empty).Split(' ');
foreach (string word in strArray)
{
if ((word.Trim() != string.Empty) && ((word.Substring(0, 1) != word.Substring(0, 1).ToUpper()) && !_helper.CheckSpelling(Regex.Match(word, "[a-zA-Z]+").Value) && !customdiclist.Contains(word)))
{
ErrorModel errorModel = new ErrorModel()
{
LineNumber = lineno,
ErrorMessage = "Please Check Misspelled words",
Text = word
};
ErrorList.Add(errorModel);
}
}
}
}
}
}
_helper.CheckSpelling
class Helper
{
private static readonly string DictPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["dictionary"]);
private readonly Hunspell _splCheck = new Hunspell(DictPath + #"\nl_NL.aff", DictPath + #"\nl_NL.dic");
public bool CheckSpelling(string strWord)
{
if(!_splCheck.Spell(strWord.Trim()))
{
return false;
}
return true;
}
}
Can some one help, I dont want any duplicate word in my errorlist.
You can use LINQ to check if your ErrorList already contains an ErrorModel object with a Text property which has the value of the word you are checking.
Using FirstOrDefault you can check to see if it returns a null. If an item cannot be found in the list, a null will be returned as the default value because your list is a collection of class objects (whose default value is null).
If the FirstOrDefault returns null then the word has not been added to the ErrorList.
For more information see When to use .First and when to use .FirstOrDefault with LINQ?.
foreach (string word in strArray)
{
if ((word.Trim() != string.Empty) && ((word.Substring(0, 1) != word.Substring(0, 1).ToUpper()) && !_helper.CheckSpelling(Regex.Match(word, "[a-zA-Z]+").Value) && !customdiclist.Contains(word)))
{
if (ErrorList.FirstOrDefault(e => e.Text == word) == null)
{
ErrorModel errorModel = new ErrorModel()
{
LineNumber = lineno,
ErrorMessage = "Please Check Misspelled words",
Text = word
};
ErrorList.Add(errorModel);
}
}
}

display items inside a session variable inside a repeater?

I am trying to get the items stored in a sessions variable into a repeater for users to see. However, I am not entirely sure how to do it (I'm new to session variables). Basically, when users enter in quantities for items on once page the hit submit, they are taken to an "order summary" page, which will display what they plan to purchase. I have successfully set up a session variable to contain the sku and quantity of each product the user selects, but I do not know how to get the information out.
I've stored the information in the session variable as [sku],[quantity];[sku],[quantity];[sku],[quantity] and so on. I figure I must do a split or something based on the commas and semicolons but I am not sure how to do so with a session variable.
The code for the product listing page that contains the information to be stored in the session variable:
public partial class GojoptproductlistSublayout : System.Web.UI.UserControl
{
private void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoProductList']");
if (ProductGroup != null)
{
Item[] LocationList = ProductGroup.Axes.SelectItems(#"child::*[##templatename='gojoProductLocation' and #Active = '1']");
if (LocationList != null)
{
DataSet ds = new DataSet();
DataTable locations = ds.Tables.Add("locations");
locations.Columns.Add("LocationName", Type.GetType("System.String"));
locations.Columns.Add("LocationID", Type.GetType("System.String"));
foreach (Item LocationItem in LocationList)
{
DataRow dr = locations.NewRow();
dr["LocationName"] = LocationItem.Fields["Header"].Value;
dr["LocationID"] = LocationItem.ID.ToString();
locations.Rows.Add(dr);
}
locationRepeater.DataSource = ds;
locationRepeater.DataMember = "locations";
locationRepeater.DataBind();
}
}
}
}
}
protected void SetInner(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType != ListItemType.Footer) & (e.Item.ItemType != ListItemType.Header))
{
Label refID = (Label)e.Item.FindControl("refID");
Label test = (Label)e.Item.FindControl("test");
Repeater areaRepeater = (Repeater)e.Item.FindControl("areaRepeater");
Database db = Sitecore.Context.Database;
Item LocationAreaItem = db.Items[refID.Text];
if (LocationAreaItem != null)
{
Item[] AreaList = LocationAreaItem.Axes.SelectItems(#"child::*[##templatename='gojoProductLocationArea' and #Active = '1']");
if (AreaList != null)
{
DataSet dset = new DataSet();
DataTable areas = dset.Tables.Add("areas");
areas.Columns.Add("AreaName", Type.GetType("System.String"));
areas.Columns.Add("Sku", Type.GetType("System.String"));
areas.Columns.Add("ProductName", Type.GetType("System.String"));
areas.Columns.Add("masterSku", Type.GetType("System.String"));
areas.Columns.Add("masterName", Type.GetType("System.String"));
areas.Columns.Add("Size", Type.GetType("System.String"));
areas.Columns.Add("SkuID", Type.GetType("System.String"));
areas.Columns.Add("AreaID",Type.GetType("System.String"));
areas.Columns.Add("productID", Type.GetType("System.String"));
foreach (Item AreaItem in AreaList)
{
DataRow drow = areas.NewRow();
drow["AreaName"] = AreaItem.Fields["Header"].Value;
drow["AreaID"] = AreaItem.ID.ToString();
areas.Rows.Add(drow);
Item[] SkuList = AreaItem.Axes.SelectItems(#"child::*[(##templatename='gojoPTRefill' or ##templatename = 'gojoPTAccessories' or ##templatename = 'gojoPTDispenser' or ##templatename = 'gojoPTSelfDispensed') and #Active = '1']");
foreach (Item ChildItem in SkuList)
{
Item MarketProduct = db.Items[ChildItem.Fields["Reference SKU"].Value];
drow["productID"] = ChildItem.ID.ToString();
if (MarketProduct != null)
{
Item MasterProduct = db.Items[MarketProduct.Fields["Master Product"].Value];
if (MasterProduct != null)
{
DataRow newRow = areas.NewRow();
if(MasterProduct.TemplateName == "gojoSKUSelfDispensed" || MasterProduct.TemplateName == "gojoSKURefill")
{
newRow["Size"] = MasterProduct.Fields["Size"].Value;
}
else
{
newRow["Size"] = "-";
}
newRow["Sku"] = MasterProduct.Fields["SKU"].Value;
newRow["productID"] = MasterProduct.ID.ToString();
Item MasterProductName = db.Items[MasterProduct.Fields["Complete Product Name"].Value];
if (MasterProductName != null)
{
newRow["ProductName"] = MasterProductName.Fields["Complete Name"].Value;
}
areas.Rows.Add(newRow);
}
}
}
}
areaRepeater.DataSource = dset;
areaRepeater.DataMember = "areas";
areaRepeater.DataBind();
}
}
}
}
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is TextBox)
{
TextBox lineQty = (TextBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Text != "")
{
try
{
int.Parse(lineQty.Text);
productID = prodID.Text;
qty = int.Parse(lineQty.Text);
if (qty > 0)
{
noItemMsg.Visible = false;
noItemMsgTop.Visible = false;
ItemCnt++; //only count items with valid qty values
LinesToOrder.Add(new LineItem(productID, qty));
}
else
{//Qty is 0 or less error
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
catch
{//NaN - display error msg
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
}
}
}
}
}
}
}
}
return validQtys;
}
class LineItem
{//This class will store the product information
public string SKUID;
public int Qty;
public LineItem(string InSKUID, int InQty)
{
this.SKUID = InSKUID;
this.Qty = InQty;
}
}
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt,ref LinesToOrder))
{
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
}
Here is the designer code with the repeater that is meant to hold the order summary:
<asp:Repeater ID="orderRepeater" runat="server" >
<headertemplate>
<tr>
<th>SKU</th>
<th>Quantity</th>
</tr>
</headertemplate>
<itemtemplate>
<tr>
<td><%#Eval("sku") %></td>
<td><%#Eval("qty") %></td>
</tr>
</itemtemplate>
</asp:Repeater>
And here is the code behind:
private void Page_Load(object sender, EventArgs e)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
if (ProductGroup != null)
{
//this is where I am confused on how to proceed
}
}
}
}
Everything is working and I did a Response.Write test on the session variable to make sure it had the correct information and it did.
Thanks in advance!
Before I try to address your question, lets take a look at some basics. A Session can hold an object, not just a string object. I would change:
if (Session["orderComplete"] != "")
to
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
if you don't, and Session["orderComplete"] is null, Session["orderComplete"] != "" will throw an error object not set to an instance of an object
And now to your question. Setting your session variable to [sku],[quantity];[sku],[quantity];[sku],[quantity], is not a good idea. For one, its not object oriented and 2, its not going to bind to any repeater or data source. You should create an object and bind a list of those objects to your control:
pseudo code:
class Program
{
static void Main(string[] args)
{
List<Order> orders = new List<Order>();
orders.Add(new Order { Sku = "ABC", Qty = 10});
}
}
public class Order {
public String Sku { get; set; }
public int Qty { get; set; }
}
Then you can bind orders to your repeater. For example:
if (Session["orderComplete"] != null && Session["orderComplete"] != ""){
List<Order> orders = Session["orderComplete"] as List<Order>;
myRepeater.DataSource = orders;
myRepeater.DataBind();
}

Categories

Resources