I don't know, if StackOverflow is the right place to ask about Performance issues, but I haven't found any better community for this issue yet.
Basically we have two sample programs, one is an addin and one is a winforms program referencing the Word interop.
Both have implemented the same method called GetTabsFromParagraph:
public class SlowExample
{
public static void GetTabsFromParagraph(Paragraph para, Style style, List<Tabulator> tabList, bool getTabsForCase = false)
{
foreach (TabStop tab in para.TabStops)
{
if (tab.CustomTab)
{
bool showTab = true;
foreach (TabStop ts in style.ParagraphFormat.TabStops)
{
if (Math.Abs(ts.Position - tab.Position) < 0.001 &&
ts.Alignment == tab.Alignment)
{
showTab = false;
break;
}
}
if (showTab || getTabsForCase)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung =
tab.Alignment == WdTabAlignment.wdAlignTabLeft
? TabulatorAusrichtung.Links
: TabulatorAusrichtung.Rechts,
Tabulatorart = TabulatorArt.Tabulator,
Position = tab.Position
};
tabList.Add(t);
}
}
}
if (!getTabsForCase)
{
foreach (TabStop ts in style.ParagraphFormat.TabStops)
{
if (ts.CustomTab)
{
bool showTab = true;
foreach (TabStop tab in para.TabStops)
{
if (Math.Abs(tab.Position - ts.Position) > 0.0001 || tab.Alignment != ts.Alignment)
{
showTab = false;
break;
}
}
if (showTab)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung = TabulatorAusrichtung.Geloescht,
Tabulatorart = TabulatorArt.Tabulator,
Position = ts.Position
};
tabList.Add(t);
}
}
}
}
if (Math.Abs(para.LeftIndent - style.ParagraphFormat.LeftIndent) > 0.001 || getTabsForCase)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung = TabulatorAusrichtung.Links,
Tabulatorart = TabulatorArt.Einzug,
Position = para.LeftIndent
};
tabList.Add(t);
}
if (Math.Abs(para.RightIndent - style.ParagraphFormat.RightIndent) > 0.001 || getTabsForCase)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung = TabulatorAusrichtung.Rechts,
Tabulatorart = TabulatorArt.Einzug,
Position = para.RightIndent
};
tabList.Add(t);
}
if (Math.Abs(para.FirstLineIndent - style.ParagraphFormat.FirstLineIndent) > 0.001 || getTabsForCase)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung = TabulatorAusrichtung.ErstzeilenEinzug,
Tabulatorart = TabulatorArt.Einzug,
Position = para.FirstLineIndent
};
tabList.Add(t);
}
}
public class Tabulator
{
private TabulatorArt m_Tabulatorart;
private TabulatorAusrichtung m_Tabulatorausrichtung;
private float m_Position;
private bool m_UebernahmeInFolgedokument = false;
public float Position
{
get { return m_Position; }
set { m_Position = value; }
}
public float PositionOrg
{
get;
set;
}
public float PositionInCm
{
get
{
return (m_Position / 28.35F);
}
set
{
m_Position = value * 28.35F;
}
}
public TabulatorArt Tabulatorart
{
get { return m_Tabulatorart; }
set { m_Tabulatorart = value; }
}
public TabulatorAusrichtung Tabulatorausrichtung
{
get { return m_Tabulatorausrichtung; }
set { m_Tabulatorausrichtung = value; }
}
public TabulatorAusrichtung TabulatorausrichtungOrg
{
get;
set;
}
public bool UebernahmeInFolgedokument
{
get { return m_UebernahmeInFolgedokument; }
set { m_UebernahmeInFolgedokument = value; }
}
}
public enum TabulatorArt
{
Invalid = 0,
Tabulator = 1,
Einzug = 2
}
public enum TabulatorAusrichtung
{
Invalid = 0,
Links = 1,
Rechts = 2,
ErstzeilenEinzug = 3,
Geloescht = 4,
}
}
In each of the both programs, I load up a Application, open up a document with a few paragraphs and tabs and run this method for each paragraph like this:
private void TestSlowMethod(Word.Document document)
{
Word.Paragraphs documentParagraphs = document.Paragraphs;
List<Tabulator> tabList = new List<Tabulator>();
long swElapsedMilliseconds = 0;
foreach (Word.Paragraph documentParagraph in documentParagraphs)
{
Word.Style style = documentParagraph.get_Style();
Stopwatch sw = new Stopwatch();
sw.Start();
SlowExample.GetTabsFromParagraph(documentParagraph, style, tabList, true);
sw.Stop();
swElapsedMilliseconds += sw.ElapsedMilliseconds;
Debug.WriteLine(sw.ElapsedMilliseconds + "\r\n");
}
MessageBox.Show("Total ms: " + swElapsedMilliseconds);
Debug.WriteLine("Done...");
}
What I found out is the addin is running throw all of this 10-20 times faster.
Addin: 20-30 ms per call
WinForms tool: 200-300 ms per call
Why is that? My assumption would be, that the addin runs in the same context / process than the word application. But is that the real reason?
And can we fix that? Our software moved from addin to WPF + Interop-Word.
Thanks in advance!
Some performance fixes:
Check getTabsForCase sooner here:
if (tab.CustomTab)
{
bool showTab = true;
if (getTabsForCase) //insert this here, no need to run if getTabsForCase.
foreach (TabStop ts in style.ParagraphFormat.TabStops)
{
if (Math.Abs(ts.Position - tab.Position) < 0.001 &&
ts.Alignment == tab.Alignment)
{
showTab = false;
break;
}
}
if (showTab || getTabsForCase)
{
Tabulator t = new Tabulator
{
Tabulatorausrichtung =
tab.Alignment == WdTabAlignment.wdAlignTabLeft
? TabulatorAusrichtung.Links
: TabulatorAusrichtung.Rechts,
Tabulatorart = TabulatorArt.Tabulator,
Position = tab.Position
};
tabList.Add(t);
}
}
Similarly, put the check on getTabsForCase before all calculations in if statements:
//see getTabsForCase goes first
if (getTabsForCase || Math.Abs(para.LeftIndent - style.ParagraphFormat.LeftIndent) > 0.001)
Fix all of those conditionals to have getTabsForCase first - then the rest of the statement won't need to evaluate.
Related
I am gridding around an object but I need the grid to align in the local space of the pivot object
the code that i have
private void createColum()
{
for (int i =0; i<gridGame.Count;i++)
{
if(gridGame[i] == gridGame[0])
{
gridGame[i].localPosition = gridGame[0].localPosition;
}
if(gridGame[i]!= gridGame[0])
{
gridGame[i].localPosition = new Vector3(gridGame[i-1].localPosition.x + distX,gridGame[0].localPosition.y, gridGame[0].localPosition.z);
}
if(i +1 > limiteFila)
{
if(i%limiteFila==0)
{
gridGame[i].localPosition = new Vector3(gridGame[0].position.x, gridGame[0].position.y , gridGame[i-Mathf.RoundToInt(limiteFila)].position.z + distY);
}else
{
gridGame[i].position = new Vector3(gridGame[i-1].position.x + distX, gridGame[0].position.y , gridGame[i-1].position.z);
}
}
gridGame[i].rotation = gridGame[0].rotation;
}
}
with this the grid of objects is formed but only in taking the world space
picture of how you are at this moment
I'm not sure if this will help, but you can turn the grid into a child object and leave the worldPositionStays as false, to do so use the SetParent(Transform parent, bool worldPositionStays). For example as a reference for your script.
private void createColum()
{
for (int i =0; i<gridGame.Count;i++)
{
if(gridGame[i] == gridGame[0])
{
gridGame[i].localPosition = gridGame[0].localPosition;
gridGame[i].transform.SetParent(this.transform, false);
}
if(gridGame[i]!= gridGame[0])
{
gridGame[i].localPosition = new Vector3(gridGame[i-1].localPosition.x + distX,gridGame[0].localPosition.y, gridGame[0].localPosition.z);
}
if(i +1 > limiteFila)
{
if(i%limiteFila==0)
{
gridGame[i].localPosition = new Vector3(gridGame[0].position.x, gridGame[0].position.y , gridGame[i-Mathf.RoundToInt(limiteFila)].position.z + distY);
}else
{
gridGame[i].position = new Vector3(gridGame[i-1].position.x + distX, gridGame[0].position.y , gridGame[i-1].position.z);
}
}
gridGame[i].rotation = gridGame[0].rotation;
}
}
I have a User Control with a DataGrid.Every thing was fine since the DataGride Pagenation Function within the User Control Class.I Desided to move the pagenation functions into a class instead.This is my Code
{
private static DataTable _dt ;
private static TextBlock _PageInformation;
private static ComboBox _NumberOfRecords;
private static Button _btnPrev;
private static Button _BtnFirst;
private static Button _BtnNext;
private static Button _BtnLast;
internal static AssetsManagement equipmentManage
{
get { return equipmentMng; }
set { equipmentMng = value; }
}
private static DataGrid _datagridObject;
public static TextBlock PageInformation { get => _PageInformation; set => _PageInformation = value; }
public static DataTable dt { get => _dt; set => _dt = value; }
public static ComboBox NumberOfRecords { get => _NumberOfRecords; set => _NumberOfRecords = value; }
public static DataGrid DatagridObject { get => _datagridObject; set => _datagridObject = value; }
public static Button BtnPrev { get => _btnPrev; set => _btnPrev = value; }
public static Button BtnFirst { get => _BtnFirst; set => _BtnFirst = value; }
public static Button BtnNext { get => _BtnNext; set => _BtnNext = value; }
public static Button BtnLast { get => _BtnLast; set => _BtnLast = value; }
int pageIndex = 1;
public static int numberOfRecPerPage;
//To check the paging direction according to use selection.
private enum PagingMode
{ First = 1, Next = 2, Previous = 3, Last = 4, PageCountChange = 5 };
public Pagenation(DataGrid UCDatagrid,ComboBox NumberOfRecordsComboBox,TextBlock PageInfo,DataTable Data,Button Prev, Button First, Button Next, Button Last)
{
DatagridObject = UCDatagrid;
dt = Data.Copy();
if (Data == null)
{
MessageBox.Show(Data.Rows.Count.ToString());
}
PageInformation = PageInfo;
NumberOfRecords = NumberOfRecordsComboBox;
Prev = BtnPrev;
First = BtnFirst;
Next= BtnNext;
Last= BtnLast;
NumberOfRecordsComboBox.Items.Add("5");
NumberOfRecordsComboBox.Items.Add("10");
NumberOfRecordsComboBox.Items.Add("15");
NumberOfRecordsComboBox.Items.Add("20");
NumberOfRecordsComboBox.Items.Add("25");
RefreshDataGrid(dt);
}
public void BtnFirst_Click(object sender, RoutedEventArgs e)
{
Navigate((int)PagingMode.First);
}
public void BtnNext_Click()
{
Navigate((int)PagingMode.Next);
}
public void BtnPrev_Click(object sender, RoutedEventArgs e)
{
Navigate((int)PagingMode.Previous);
}
public void BtnLast_Click(object sender, RoutedEventArgs e)
{
Navigate((int)PagingMode.Last);
}
public void CbNumberOfRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Navigate((int)PagingMode.PageCountChange);
}
private void Navigate(int mode)
{
int count;
switch (mode)
{
case (int)PagingMode.Next:
BtnPrev.IsEnabled = true;
BtnFirst.IsEnabled = true;
if (dt.Rows.Count >= (pageIndex * numberOfRecPerPage))
{
if (dt.AsEnumerable().Skip(pageIndex *
numberOfRecPerPage).Take(numberOfRecPerPage).Count() == 0)
{
DatagridObject.ItemsSource = null;
DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip((pageIndex *
numberOfRecPerPage) - numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
count = (pageIndex * numberOfRecPerPage) +
(dt.AsEnumerable().Skip(pageIndex *
numberOfRecPerPage).Take(numberOfRecPerPage)).Count();
}
else
{
DatagridObject.ItemsSource = null;
DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip(pageIndex *
numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
count = (pageIndex * numberOfRecPerPage) +
(dt.AsEnumerable().Skip(pageIndex * numberOfRecPerPage).Take(numberOfRecPerPage)).Count();
pageIndex++;
}
PageInformation.Text = count + " of " + dt.Rows.Count;
}
else
{
BtnNext.IsEnabled = false;
BtnLast.IsEnabled = false;
}
break;
case (int)PagingMode.Previous:
BtnNext.IsEnabled = true;
BtnLast.IsEnabled = true;
if (pageIndex > 1)
{
pageIndex -= 1;
DatagridObject.ItemsSource = null;
if (pageIndex == 1)
{
DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
count = dt.AsEnumerable().Take(numberOfRecPerPage).Count();
PageInformation.Text = count + " of " + dt.Rows.Count;
}
else
{
DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip
(pageIndex * numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
count = Math.Min(pageIndex * numberOfRecPerPage, dt.Rows.Count);
PageInformation.Text = count + " of " + dt.Rows.Count;
}
}
else
{
BtnPrev.IsEnabled = false;
BtnFirst.IsEnabled = false;
}
break;
case (int)PagingMode.First:
pageIndex = 2;
Navigate((int)PagingMode.Previous);
break;
case (int)PagingMode.Last:
pageIndex = (dt.Rows.Count / numberOfRecPerPage);
Navigate((int)PagingMode.Next);
break;
case (int)PagingMode.PageCountChange:
numberOfRecPerPage = Convert.ToInt32(NumberOfRecords.SelectedItem);
DatagridObject.ItemsSource = null;
DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
count = (dt.AsEnumerable().Take(numberOfRecPerPage)).Count();
PageInformation.Text = count + " of " + dt.Rows.Count;
BtnNext.IsEnabled = true;
BtnLast.IsEnabled = true;
BtnPrev.IsEnabled = true;
BtnFirst.IsEnabled = true;
break;
}
}
public static void RefreshDataGrid(DataTable dte)
{
MessageBox.Show(dte.Rows.Count.ToString());
dt = dte.Copy();
MessageBox.Show(dt.Rows.Count.ToString());
DatagridObject.ItemsSource = null;
DatagridObject.ItemsSource = dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
int count = dt.AsEnumerable().Take(numberOfRecPerPage).Count();
PageInformation.Text = count + " of " + dt.Rows.Count;
}
}}
and in the Class of the UserControl I instantaite an object of the Pagenation Class with the constructor that takes all the needed varaible for pagenation.
public PartsUC()
{
InitializeComponent();
PartsDataTable = PartMng.GetAllEquipments();
MessageBox.Show(PartsDataTable.Rows.Count.ToString());
PageInformation = lblpageInformation;
Partsdatagrid = this.PartsDataGrid;
CbNumberOfRecords = this.cbNumberOfRecords;//the interface XAMAL Combobox
Pagenation pagenation = new Pagenation(Partsdatagrid, cbNumberOfRecords, PageInformation, PartsDataTable, btnPrev, btnFirst, btnNext, btnLast);
//Pagenation.RefreshDataGrid(PartsDataTable);}
The problem is that i still getting this error message!
The source contains no DataRows
and the error points to the refreshDataGrid method in this line
DatagridObject.ItemsSource = dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
Note that the messege box in the function refreshDataGrid shows that i have 50 rows.
Solved it,The thing that caused the error was the function Take() since it takes the number from the combobox that let you choose how many rows to display.I put Fixed number and It Worked.
DatagridObject.ItemsSource = dt.AsEnumerable().Take(15).CopyToDataTable().DefaultView;
I am new in coding and I am having the following issue. When I run the select if there are no rows I receive the following error
but in that case, i want to make an insert
how can I do this? This is my entire code:
private DataRow verifica_pontajul()
{
string query = String.Format("select PR_ID,WORKER_Name,PR_Come,PR_Go, CURRENT_TIMESTAMP from `ppresence` {0}",
(Functii.marca == "admin" ? "" :
String.Format("WHERE PR_WorkerPTR='{0}' ORDER BY PR_ID DESC LIMIT 1 ", this.marca)
));
return conn.dt(query,0).Rows[0];
}
public class liniepontaj
{
public long idlinie = 0;
private string angajat = "";
public DateTime DataIntrare = new DateTime();
private DateTime DataIesire = new DateTime();
public DateTime DataReferinta = new DateTime();
private bool isIntrare = false;
public bool facintrare = false;
public bool faciesire = false;
public liniepontaj() { }
public liniepontaj(DataRow rand)
{
this.idlinie = long.Parse(rand.ItemArray[0].ToString());
this.angajat = rand.ItemArray[1].ToString();
this.DataIntrare = (DateTime)rand.ItemArray[2];
try {
this.DataIesire = (DateTime)rand.ItemArray[3];
}
catch (Exception) { this.DataIesire = new DateTime(1, 1, 1, 0, 0, 0); }
this.DataReferinta = (DateTime)rand.ItemArray[4];
if (this.DataIesire == null || this.DataIesire != new DateTime(1, 1, 1, 0, 0, 0)) { isIntrare = true; } else { isIntrare = false; }
TimeSpan t1 = DataReferinta - DataIntrare;
TimeSpan t2 = DataReferinta - DataIesire;
if ((t1.TotalMinutes < 15 && !this.isIntrare))
{
faciesire = false;
facintrare = false;
}
else if (t2.TotalMinutes < 15 && this.isIntrare)
{
faciesire = false;
facintrare = false;
}
else
{
facintrare = isIntrare;
faciesire = !isIntrare;
}
}
}
Where should i modify? To have the properly insert functional?
Basically, you just need to validate if there is any data inside Rows.
var dt = conn.dt(query, 0);
if (dt.Rows.Count == 0) return null;
else return dt.Rows[0];
Check for rowcount and if greater than or equal to 1 and then proceed else insert
The program uses two threads: one for collecting the data from USB, and the other writes/displays the data. It seems to work as expected, however, as soon as I minimize/restore any windows on the PC, or press any buttons on the Form, it stops working properly (it stops receiving data). I use link list to keep the data streaming in order. I suspect that maybe the link is lost somewhere because of improper variable declaration. Is there an obvious mistake in my code that could be causing this?
namespace Streamer
{
public class Form1 : System.Windows.Forms.Form
{
Thread tListen;
Thread tDisplay;
public class MY_DATA_BUFFER
{
public byte[] buffer;
public int length;
public MY_DATA_BUFFER nextBuff;
}
private Object thisLock = new Object();
MY_DATA_BUFFER pHead = null;
private static AutoResetEvent DataQueueEvent = new AutoResetEvent(false);
public Form1()
{
// some settings;
}
public unsafe void dataDisplayThread()
{
MY_DATA_BUFFER pWorkingSet = pHead;
if (pWorkingSet == null)
{
// Make sure link list head is initialized...........
do {DataQueueEvent.WaitOne();} while (pHead == null);
// Wait till the two datas are available to write.
if (pHead.nextBuff == null){ DataQueueEvent.WaitOne(); }
if (pWorkingSet == null) { pWorkingSet = pHead; }
}
// Let's start the data write loop
while (bRunning || (pWorkingSet != null))
{
// copy small array to a bigger array
for (int i = 0; i < pWorkingSet.length; i++)
{
pixelValues[pixptr] = pWorkingSet.buffer[i];
pixptr++;
}
if (pixptr >= imWidth * imHeight)
{
pixptr = 0;
// show data in pixelValues
}
// Traverse through the link list data structure.
if (pWorkingSet.nextBuff == null)
{
do
{
if (pWorkingSet.nextBuff == null DataQueueEvent.WaitOne();
lock (thisLock)
{
if (pWorkingSet.nextBuff == null && !bRunning)
break;
}
} while (pWorkingSet.nextBuff == null);
}
// We are good to loop for the next operation
lock (thisLock)
{
pHead = pHead.nextBuff;
pWorkingSet = pHead;
}
}
// All write operation is at completion
pHead = null;
}
public unsafe void XferData(...)
{
MY_DATA_BUFFER tempBuff = null;
for (; bRunning; )
{
// .... do something
// push the data to a link list for
lock (thisLock)
{
MY_DATA_BUFFER newBuff = new MY_DATA_BUFFER();
newBuff.nextBuff = null;
newBuff.buffer = xBufs[k];
newBuff.length = len;
if (tempBuff == null) tempBuff = newBuff;
else
{
tempBuff.nextBuff = newBuff;
tempBuff = newBuff;
}
if (pHead == null) pHead = newBuff;
else
{
DataQueueEvent.Set();
}
}
///////////////////Link List Population completes///////////
Thread.Sleep(0);
} // End infinite loop
}
private void StartBtn_Click(object sender, System.EventArgs e)
{
if (StartBtn.Text.Equals("Start"))
{
// ...
pHead = null;
bRunning = true;
tListen = new Thread(new ThreadStart(XferThread));
tListen.IsBackground = true;
tListen.Priority = ThreadPriority.Highest;
tListen.Start();
tDisplay = new Thread(new ThreadStart(dataDisplayThread));
tDisplay.IsBackground = true;
tDisplay.Priority = ThreadPriority.Highest;
tDisplay.Start();
}
else
{
if (tListen.IsAlive)
{
// ...
bRunning = false;
if (tListen.Join(5000) == false )
tListen.Abort();
tListen = null;
}
if (tDisplay.IsAlive)
{
if (tDisplay.Join(5000) == false )
tDisplay.Abort();
Display = null;
}
}
}
}
}
I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init