C# List items got overwritten by last added item - c#

I am having a problem with all properties of each item in a List<ButtonTemplateModel> get values of the last added item. Does anyone know why?
public Task<IViewComponentResult> InvokeAsync(EpisodeVM EpisodeBtnConfig)
{
Dictionary<string,string> stageType = Helpers.EpisodeCommandButtonSettings.stageType;
Dictionary<string, string> actionBtnClass = Helpers.EpisodeCommandButtonSettings.actionBtnColor;
List<ButtonTemplateModel> cmdButtonVMList = new();
string rawID;
if (EpisodeBtnConfig.EpisodeID > 0)
{
rawID = EpisodeBtnConfig.PINFK;
EpisodeBtnConfig.PINFK = rawID.Substring(rawID.Length - 4, 4);
}
/* iterate 8 stage types */
foreach (KeyValuePair<string, string> entry in stageType)
{
ButtonTemplateModel cmdBtnTemplateVM = new()
{
ActionVM = EpisodeBtnConfig.ActionButtonVM,
Title = entry.Value,
Stage = entry.Key,
TextNode = entry.Key,
ActionBtnCssClass = actionBtnClass[entry.Key],
ShowThisButton = true,
DisableThisButton = false
};
switch (cmdBtnTemplateVM.Stage)
{
case "PeopleList":
cmdBtnTemplateVM.TextNode = "Back to People List";
if (EpisodeBtnConfig.ActionButtonVM.HostingPage == "Question")
{
cmdBtnTemplateVM.ActionVM.ControllerName = "PeopleList";
cmdBtnTemplateVM.ActionVM.ActionName = "Index";
cmdBtnTemplateVM.ActionVM.PeopleListID = string.Empty;
cmdBtnTemplateVM.ActionVM.EpisodeID = -1;
}
else
cmdBtnTemplateVM.ShowThisButton = false;
break;
case "Full":
cmdBtnTemplateVM.TextNode = "IRF-PAI";
break;
case "Followup":
cmdBtnTemplateVM.TextNode = "Follow Up";
break;
}
if (EpisodeBtnConfig.ActionButtonVM.EpisodeID == -1 && (cmdBtnTemplateVM.Stage != "PeopleList" && cmdBtnTemplateVM.Stage != "Base"))
cmdBtnTemplateVM.DisableThisButton = true;
if (EpisodeBtnConfig.ActionButtonVM.EpisodeID != -1 && cmdBtnTemplateVM.Stage != "New")
cmdBtnTemplateVM.Title = cmdBtnTemplateVM.Title.Replace("Create new", "Edit existing");
cmdButtonVMList.Add(cmdBtnTemplateVM);
}
string viewName = "StageCommandBtn";
return Task.FromResult<IViewComponentResult>(View(viewName, cmdButtonVMList));

Related

How to trigger TreeView NodeMouseClick and CursorChanged events with a method. I am getting error on parameter `e` due to incompatible parameters

I managed to create a TreeView method for NodeMouseClick and CursorChanged events.
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
// my action code here...
}
private void TvwPanel_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
Node_Selection_Action(sender, e);
}
However, I am getting an error on e parameter when I applied the method to the CursorChanged:
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
Node_Selection_Action(sender, e); //error on `e` here
}
I supposed this is due to the parameter EventArgs that is not compatible with my method parameter TreeNodeMouseClickEventArgs.
Is there any workaround that I could use to trigger the CursorChanged event with my method?
UPDATE 1:
As requested, here's the bunch of code for the Node_Selection_Action method:
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
TvwPanel.SelectedNode = e.Node;
if (Convert.ToString(e.Node.Tag) == "a") //profile Convert.ToInt16()
{
TsmNewPr.Enabled = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Enabled = true;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Enabled = true;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "b") //database
{
TsmNewPr.Visible = false;
TsmNewDb.Enabled = true;
// arbitrary control if database already exists. If exists disable, otherwise enable.
#region TsmNewDb.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Type" || childText.Value != "Name" || childText.Value != "Connection")
{
// enable TsmNewDb ContextMenu button if does not exists yet
TsmNewDb.Enabled = false;
}
}
// initialize the attribute tags to null
string TypeTag = null;
string NameTag = null;
string ConnTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
TypeTag = childTag.Value;
}
else if (count == 1)
{
NameTag = childTag.Value;
}
else if (count == 2)
{
ConnTag = childTag.Value;
}
count++;
}
// check if database exists
if (db.Databases_Exists(ConnTag) == true)
{
// convert the password to "*" for display purposes
string s = ConnTag;
int start = s.LastIndexOf("pwd=") + "pwd=".Length;
int end = s.IndexOf(";", start);
string result = s.Substring(start, end - start);
s = s.Replace(result, "********");
ConnTag = s;
// transfer data FrmDatabase form to main form tabcontrol panel
LblDbTypeDef.Text = TypeTag;
LblDbNameDef.Text = NameTag;
LblDbConnDef.Text = ConnTag;
// make the main tabcontrol panel visible to true
TbcMain.SelectedIndex = 0;
TbcMain.Visible = true;
}
else
{
// make the main tabcontrol panel visible to false
TbcMain.SelectedIndex = 0;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Enabled = true;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Enabled = true;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "c") //company file
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Enabled = true;
// arbitrary control if company file already exists. If exists, disable, otherwise enable.
#region TsmNewCo.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Company Name" || childText.Value != "File Path")
{
// enable TsmNewCo ContextMenu button if does not exists yet
TsmNewCo.Enabled = false;
}
}
// initialize the attribute tags to null
string CoFileTag = null;
string FilePathTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
CoFileTag = childTag.Value;
}
else if (count == 1)
{
FilePathTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (CoFileTag != null || FilePathTag != null)
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = true;
LblCompanyFileDef.Text = CoFileTag;
LblFilePathDef.Text = FilePathTag;
}
else
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Enabled = true;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Enabled = true;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "d") //tasks
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Enabled = true;
#region Enable/Disable "New" if database and company file are not saved yet
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.PrevNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
// inquire if database has child or db already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeDbSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
}
// inquire if company file has child or has file already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeCoSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
else
{
foreach (XElement enc in profNode)
{
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get company details for showing on the right panel of the main form specified below for task creation
foreach (var childTag in childrenTags)
{
if (count == 1)
{
qbFilePath = childTag.Value;
}
count++;
}
}
}
}
#endregion
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Enabled = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Enabled = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks summary
#region Extract data from Xml and show in the main form tabcontrol
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
if (Xml_Extract_Data_TaskSum(selNodeParentName, selNodeName) == true)
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = false;
}
#endregion
}
else // for the task credentials
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Enabled = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Enabled = true;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Enabled = true;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = true;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks details
#region Extract data from Xml and show in the main form tabcontrol
selNodeGrandParentName = TvwPanel.SelectedNode.Parent.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.Text;
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profileTask =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeGrandParentName
select ep;
foreach (XElement ep in profileTask)
{
IEnumerable<XElement> profNodeTask =
from en in ep.Elements("node")
where (string)en.Attribute("text") == selNodeParentName
select en;
foreach (XElement ept in profNodeTask)
{
IEnumerable<XElement> profNodeTaskCred =
from en in ept.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement eptc in profNodeTaskCred)
{
// initialize the attribute tags to null
string ActionTag = null;
string TablesTag = null;
string FiltersTag = null;
string ScheduleTag = null;
// get the attribute tags
var childrenTags = eptc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
ActionTag = childTag.Value;
}
else if (count == 1)
{
TablesTag = childTag.Value;
}
else if (count == 2)
{
FiltersTag = childTag.Value;
}
else if (count == 3)
{
ScheduleTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (ActionTag != null || FiltersTag != null || ScheduleTag != null)
{
LblActionDef.Text = ActionTag;
// TablesTag
string[] TablesTagArray = TablesTag.Split(','); //(new char[] { ',', ' ' });
LvwTables.Items.Clear();
foreach (string tt in TablesTagArray)
{
string table = tt.TrimStart();
ListViewItem lvi = new ListViewItem(table);
LvwTables.Items.Add(lvi);
}
// FiltersTag
// filter period
string filterPeriod;
int Pos1 = FiltersTag.IndexOf("Transactions: ") + "Transactions: ".Length;
int Pos2 = FiltersTag.IndexOf(" | Migration");
filterPeriod = FiltersTag.Substring(Pos1, Pos2 - Pos1);
LblFtrPeriodDef.Text = filterPeriod;
// migration type
string migrationType;
int Pos3 = FiltersTag.IndexOf("Type: ") + "Type: ".Length;
int Pos4 = FiltersTag.IndexOf(" | No");
migrationType = FiltersTag.Substring(Pos3, Pos4 - Pos3);
LblFtrMigTypeDef.Text = migrationType;
// no of record per query
string numberRecords;
int Pos5 = FiltersTag.IndexOf("Query: ") + "Query: ".Length;
numberRecords = FiltersTag.Substring(Pos5);
LblFtrRpqDef.Text = numberRecords;
// filter head
if (filterPeriod == "All" && migrationType == "Overwrite" && numberRecords == "0")
{
LblFiltersDef.Text = "Default";
}
else
{
LblFiltersDef.Text = "Custom";
}
LblSchedDef.Text = ScheduleTag;
TbcMain.SelectedIndex = 3;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 3;
TbcMain.Visible = false;
}
}
}
}
// capture the db credentials for task running
Capture_DB_Credentials_for_NodeMouseClick_And_Task_Saving(selNodeGrandParentName, selNodeDbSiblingName, selNodeCoSiblingName);
#endregion
}
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
}
In the Node_Selection_Action method, the last if statement block:
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
is the only block of code that needs the TreeNodeMouseClickEventArgs properties. If you really need to pass this type of argument to the method then create one:
// Still no idea what is the relation, however...
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
var s = sender as TreeView;
var p = s.PointToClient(Cursor.Position);
var ht = s.HitTest(p);
if (ht.Node != null)
{
var args = new TreeNodeMouseClickEventArgs(ht.Node, MouseButtons, 1, p.X, p.Y);
Node_Selection_Action(s, args);
}
}
Unless I'm missing an access to the sender param in your code, you can omit it to simplify the method signature:
private void Node_Selection_Action(TreeNodeMouseClickEventArgs e) { }
Also, you can determine which mouse button is pressed anywhere in your code through the Control.MouseButtons property. The Control.MousePosition property gets the cursor's position in screen coordinates. So, maybe these two properties are all what you need.
Maybe the mentioned above last if block is in the wrong method and moving it into a new method or elsewhere in the context could be better.
Hope that helps.

Creating Product Listing Group Tree google ads Api returning INTERNAL_ERROR

I am trying to add a listing group tree in google ads api V10 but it is returning internal error. Here is my code:
public GoogleAwApi.AdGroupCriterionReturnValue MutateProductPartitionsForAdGroupGA(GoogleAwApi.AdGroupCriterionOperation[] operations, long clientId)
{
var result = new GoogleAwApi.AdGroupCriterionReturnValue();
AdGroupCriterionServiceClient service = this.AdGroupCriterionServiceGA;
List<AdGroupCriterionOperation> operationsGA = new List<AdGroupCriterionOperation>();
List<GoogleAwApi.AdGroupCriterion> results = new List<GoogleAwApi.AdGroupCriterion>();
List<GoogleAwApi.ApiError> partialFailures = new List<GoogleAwApi.ApiError>();
foreach (var item in operations)
{
try
{
var operand = (GoogleAwApi.BiddableAdGroupCriterion)item.operand;
// Start creating the criteron...
GoogleAdsResources.AdGroupCriterion adGroupCriterion = new GoogleAdsResources.AdGroupCriterion()
{
// The resource name the criterion will be created with. This will define the ID
// for the ad group criterion.
AdGroup = ResourceNames.AdGroup(clientId, item.operand.adGroupId),
//ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id),
Status = Google.Ads.GoogleAds.V10.Enums.AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled
};
switch (operand.userStatus)
{
case GoogleAwApi.UserStatus.ENABLED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
case GoogleAwApi.UserStatus.REMOVED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Removed;
break;
case GoogleAwApi.UserStatus.PAUSED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Paused;
break;
default:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
}
string cType = item.operand.criterion.GetType().Name;
if (operand.biddingStrategyConfiguration != null)
{
var bids = operand.biddingStrategyConfiguration.bids;
var thidBid = (GoogleAwApi.CpcBid)bids[0];
adGroupCriterion.CpcBidMicros = thidBid.bid.microAmount;
adGroupCriterion.EffectiveCpcBidSource = Google.Ads.GoogleAds.V10.Enums.BiddingSourceEnum.Types.BiddingSource.AdGroup;
}
adGroupCriterion.ApprovalStatus = APIHelper.MapApprovalStatus(operand.approvalStatus);
adGroupCriterion.BidModifier = operand.bidModifier;
var criterion = (GoogleAwApi.ProductPartition)item.operand.criterion;
adGroupCriterion.CriterionId = criterion.id;
ListingGroupTypeEnum.Types.ListingGroupType lType = ListingGroupTypeEnum.Types.ListingGroupType.Unknown;
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.SUBDIVISION)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Subdivision;
adGroupCriterion.ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id);
}
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.UNIT)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Unit;
}
var casevalue = (GoogleAwApi.ProductDimension)criterion.caseValue;
var lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Unknown;
var cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Unknown;
var lValue = "";
Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo listingDimensionInfo = null;
if (casevalue != null)
{
//Get listing Group Info
switch (casevalue.ProductDimensionType)
{
case "ProductType":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("PRODUCT_TYPE_L1"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level1;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L2"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level2;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L3"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level3;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L4"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level4;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L5"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level5;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel }
};
}
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel, Value = lValue }
};
}
}
break;
case "Brand":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
//isEverythingElse
if (String.IsNullOrEmpty(lValue))
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo
{ Value = lValue }
};
}
}
break;
case "Custom":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_0"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index0;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_1"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index1;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_2"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index2;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_3"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index3;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_4"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index4;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex }
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex, Value = lValue }
};
}
}
}
break;
case "OfferId":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo
{ Value = lValue }
};
}
}
break;
default:
break;
}
}
Google.Ads.GoogleAds.V10.Common.ListingGroupInfo ListingGroup = new Google.Ads.GoogleAds.V10.Common.ListingGroupInfo()
{
Type = lType, // SubDivision OR Unit
CaseValue = listingDimensionInfo
};
if (criterion.id != -1)
ListingGroup.ParentAdGroupCriterion = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, criterion.parentCriterionId);
adGroupCriterion.ListingGroup = ListingGroup;
adGroupCriterion.CriterionId = criterion.id;
if (item.#operator == GoogleAwApi.Operator.ADD) { operationsGA.Add(new AdGroupCriterionOperation() { Create = adGroupCriterion }); }
if (item.#operator == GoogleAwApi.Operator.REMOVE) { operationsGA.Add(new AdGroupCriterionOperation() { Remove = adGroupCriterion.ResourceName }); }
if (item.#operator == GoogleAwApi.Operator.SET) { operationsGA.Add(new AdGroupCriterionOperation() { Update = adGroupCriterion }); }
}
catch (Exception ex)
{
string except = ex.Message;
}
}
try
{
// Issues a mutate request to process Ads.
MutateAdGroupCriteriaResponse retVal = service.MutateAdGroupCriteria(
new MutateAdGroupCriteriaRequest()
{
CustomerId = clientId.ToString(),
Operations = { operationsGA },
PartialFailure = true,
ValidateOnly = false,
ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.MutableResource // required to bring back a complete mutated object to report on.
});
if (retVal.Results[0].AdGroupCriterion != null)
results.Add(APIHelper.MapAdGroupCriterion(retVal.Results[0].AdGroupCriterion));
if (retVal.PartialFailureError != null)
{
var ApiError = new ApiErrorGA();
ApiError.errorString = retVal.PartialFailureError.Message;
ApiError.ApiErrorType = retVal.PartialFailureError.GetType().ToString();
partialFailures.Add(ApiError);
}
}
catch (GoogleAdsException ex)
{
string except = ex.Message;
}
result.ListReturnValueType = "AdGroupAdService";
result.value = results.ToArray();
result.partialFailureErrors = partialFailures.ToArray();
return result;
}
I need the code to be able to create new trees and also replace existing one.
I have tried a lot of different possibilities of trying to get it to work but all return internal error which really doesn't give me any pointers on what the issue is. Any help will be appreciated.

db.SaveChanges in ForEach causes 'New transaction is not allowed because there are other threads running in the session'

I have an excel file with about 21000 rows . I imported it into a temp Table in my database.
Now I want to do some conversions on my data and then put them into my main table.
When I do SaveChanges() inside a foreach I got the following error:
Microsoft.Data.SqlClient.SqlException: 'New transaction is not allowed because there are other threads running in the session
When I use it after the foreach no error occurs and the table has just 4 records inserted instead of all 21000 records that I expected.
public ActionResult FeedTempdataToMainDB()
{
var L = new Leave();
// var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT) - 1;
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
db.Leaves.Add(L);
db.SaveChangesAsync();
}
//db.SaveChanges();
return RedirectToAction("index");
You have a bug in your code. You declared and created L outside of the loop. Each time you add the same L , only with different data. In the end you have list of the same data that was created during the last foreach loop cicle.
try this:
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
db.Leaves.Add(L);
}
or this
var leaves= new List<Leave>();
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
leaves.Add(L);
}
if(leaves.Count>0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
if you want to use async save you have to make async action at first.
The raison every time that foreach execute the savechnages there is a thread that your not note controlling. Since entity framework is managing the savechanges function. You have to execute your savechnages after the foreach or use async function.
here an example for the async:
private static async Task<Student> GetStudent()
{
Student student = null;
using (var context = new SchoolDBEntities())
{
Console.WriteLine("Start GetStudent...");
student = await (context.Students.Where(s => s.StudentID == 1).FirstOrDefaultAsync<Student>());
Console.WriteLine("Finished GetStudent...");
}
return student;
}
*This Code finally worked:
public ActionResult FeedTempdataToMainDB()
{
var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
var L = new Leave();
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT);
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0 && t == false)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
leaves.Add(L);
}
if (leaves.Count > 0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
return RedirectToAction("index");
}

How to get selected value or index of a dropdownlist upon entering a page?

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

Query not updating database

Morning,
I have an issue with some of my code...
Basically i am trying to update or insert into the database. the first if statement if for when adding a new product. the else should then update any existing products.
However when i run it, it is not updating the existing products in the database. It is however setting the items ready to be updated. Any ideas?
Many thanks...
using (aboDataDataContext dc = new aboDataDataContext())
{
foreach (abcProduct p in abcProducts)
{
var match = (from t in dc.abcProducts
where t.sku == p.productcode
select t).FirstOrDefault();
if (match == null)
{
// Watch out here; there is some type conversion required for certain fields!
abcProduct prod = new abcProduct();
prod.sku = p.productcode;
prod.categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
prod.title = p.name;
prod.brand = p.manufacturer;
prod.description = p.description;
prod.abcPrice = p.price;
prod.size = decimal.TryParse(p.size.Replace("cl", ""), out size) == true ? (int?)size : null;
prod.country = p.country;
prod.region = p.region;
prod.vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null;
prod.weight = Convert.ToDecimal("1.50");
prod.strength = p.strength;
prod.bottler = p.bottler;
prod.age = int.TryParse(p.age, out age) == true ? (int?)age : null;
prod.caskType = p.casktype;
prod.series = p.series;
prod.flavour = p.flavour;
if (p.freestock <= 0) { prod.stock = 0; } //check to see if stock is 0
else { prod.stock = p.freestock; }
prod.abcUpdated = false;
prod.stockUpdated = false;
prod.priceUpdated = false;
prod.pricePublished = false;
prod.stockPublished = false;
prod.imgPublished = false;
prod.prodPublished = false;
prod.lastUpdated = DateTime.Now;
// Add the new object to the abcProducts table (only in memory here)
dc.abcProducts.InsertOnSubmit(prod);
}
else
{
// update row
match.abcUpdated = true;
//Set if an item has been updated or not.
if (match.stock == p.freestock) { match.stockUpdated = false; }
else { match.stockUpdated = true; }
if (match.abcPrice == p.price) { match.priceUpdated = false; }
else { match.priceUpdated = true;}
match.sku = p.productcode;
match.categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
match.title = p.name;
match.brand = p.manufacturer;
match.description = p.description;
match.stock = p.freestock;
match.abcPrice = p.price;
match.size = decimal.TryParse(p.size.Replace("cl", ""), out size) == true ? (int?)size : null;
match.weight = Convert.ToDecimal("1.50");
match.country = p.country;
match.region = p.region;
match.vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null;
match.strength = p.strength;
match.bottler = p.bottler;
match.age = int.TryParse(p.age, out age) == true ? (int?)age : null;
match.caskType = p.casktype;
match.series = p.series;
match.flavour = p.flavour;
if (p.freestock <= 0) { match.stock = 0; } //check to see if stock is 0
else { match.stock = p.freestock; }
match.abcUpdated = true;
match.pricePublished = false;
match.stockPublished = false;
match.imgPublished = false;
match.prodPublished = false;
match.lastUpdated = DateTime.Now;
}
}
// Finally, request Linq to perform the database updates.
dc.SubmitChanges();
}
return null;
}
The context is loosing track of the object when setting match.
At the bottom of the else statement insert
dc.abcProducts.Attach(match);
There is problem in your code, you are iterating through the product table and getting the values in the match variable. In the part of the if statement where match is not null, you are setting the object to the new values, but you are not calling the dc.SubmitChanges();, that object match is not getting stored any where in your code, and in the next iteration in the loop, it is being assigned the new values.
You need to call dc.SubmitChanges(); after update the match values.
foreach (abcProduct p in abcProducts)
{
var match = (from t in dc.abcProducts
where t.sku == p.productcode
select t).FirstOrDefault();
if (match == null)
{
//insertion code commented out
dc.abcProducts.InsertOnSubmit(prod);
}
else
{
///.... setting up all fields.
match.stockPublished = false;
match.imgPublished = false;
match.prodPublished = false;
match.lastUpdated = DateTime.Now;
dc.SubmitChanges(); //Call this otherwise you will
//loose the match values in the next iteration
}
}

Categories