LINQ2SQL Stack overflow - asp.net

I am getting a stack overflow with the following code. I know what the problem is, that it executes all "GetAllPages" in the
Children = new LazyList<Page>(from p in GetAllPages(language)
where p.ParentPage == s.Id
select p)
before it adds the p.ParentPage == s.Id
private IQueryable<Page> GetAllPages(string language)
{
return from s in context.Pages
where (from c in GetAllContent()
where c.PageId == s.Id &&
c.Language.ToLower() == language.ToLower()
select c).Any()
let contents = (from c in GetAllContent()
where c.PageId == s.Id
select c)
select new Page()
{
Id = s.Id,
SiteId = s.SiteId,
Type = s.Type,
Template = s.Template,
ParentPage = s.ParentPage,
Visible = s.Visible,
Order = s.Order,
Contents = contents.ToList(),
Children = new LazyList<Page>(from p in GetAllPages(language)
where p.ParentPage == s.Id
select p)
};
}
How can i do this, correctly?
UPDATE:
The reason behind the code is that, i have a tree structured menu, where one menu item can have 0 to many child items.
The language part can be skipped, but my site support multiple languages, and with the language parameters do i only want menu items there have a content of the given language.

From the moment that you call this GetAllPages(language), and then call it again with out change the language you get 100% stack overflow.
You need to get something that is different, not the same ! and your only parameter is the language and this is not change.
private IQueryable<Page> GetAllPages(string language)
{
....
Children = new LazyList<Page>(from p in GetAllPages(language) // <-- here you
// call him self again with the same parametre.
// Your function is going to call him self asking the same think
// This is bring the stack overflow
// When you make call to the same function you need some how
// to get different results with some different parameter.

Related

Set default data in field x++ PurchCreateOrder

I want to set a default value based on curUserid() in PurchCreateOrder. How can I put data in my field on form extension ?
Is there any better option of doing this ? Fields are bound to datasource and I have different fields with differentdatasources.
My code is giving me abnormal termination error with nullreferences. XPPCompiler
[ExtensionOf(tableStr(PurchTable))]
final class PurchCreateOrderGetDefAdress_Extension
{
void initvalue(PurchaseType _purchaseType)
{
next initvalue(_purchaseType);
PurchTable purchtable;
LogisticsPostalAddress logpostadress;
UserInfoSz usrsz;
str user = curUserId();
select firstonly logpostadress where logpostadress.city == 'lub';
// select firstonly InventSiteId, InventLocationId from purchtable join usrsz where purchtable.InventSiteId == usrsz.InventSiteId && usrsz.IsDefault == true;
select firstonly InventSiteId from usrsz where usrsz.UserId == user && usrsz.IsDefault == true;
purchtable.initValue();
purchtable.deliveryname = 'asasasasas' ;//logpostadress.Address;
purchtable.inventsiteid = usrsz.InventSiteId;
purchtable.inventlocationid = usrsz.InventSiteId;
info(strFmt("%1, %2, %3", logpostadress.Address, usrsz.InventSiteId));
}
}
The error is straight forward.
Error The augmented class 'PurchTable' provides a method by this name, but this method cannot be used as a chain of command method since the parameter profile does not match the original method.
Take a look at the highlighted parameter profile and compare to yours.
Edit: Take a look at these links for more info on Chain of Command (CoC):
https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/extensibility/method-wrapping-coc
https://channel9.msdn.com/Blogs/mfp/X-Chain-Of-Command (This video is excellent)

tree implementation using linked list,with parent pointer,first chil pointer and siblings pointer in c

I want help in linked list implementation of a tree. A tree node has three child.
using pointers: Parent, Siblings and FirstChild.
I have tried making it but couldn't get it to work. I need help in inserting new nodes
void InsertFirstChild(Node newNode)
{
newNode.m_Parent = this;
newNode.m_NextSibling = m_FirstChild;
if (m_FirstChild != null)
m_FirstChild.m_PrevSibling = newNode;
else
m_LastChild = newNode;
m_FirstChild = newNode;
}

Regarding to retrieve values inside the array

Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:
int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
int g;
if (chkmark.Checked == true)
{
g = 1;
}
else
{
g = 0;
}
int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
int[] temp1 = (int[])Session["arrofchk"];
int k, no;
if (temp1 == null)
no = 0;
else
no = temp.Length;
for (k = 0; k < no; k++)
{
chkarray[k] = temp1[k];
}
chkarray[j] = g;
Personally, i would use a Dictionary<int, bool> for this.
In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.
Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.
For your example, it can work only if the positions of both arrays are the same.
Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>
// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
{
quizAnswers.Add(a[i], temp1[i] == 1);
}
}
// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
where pair.Value == true
select pair.Key).ToArray<int>();
The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.
I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..
It's something to take into consideration. Hope I could help you out.

Can't use foreach on a anonymous type

I have the code below where I am trying to go through the child questions of my qestAires anonymous type. When I get to the foreach loop i get the error:
foreach statement cannot operate on
variables of type 'Question' because
'Question' does not contain a public
definition for 'GetEnumerator'
What do I need to do differently to get around this?
var questAires = (from qs in dc.Questionnaires
from q in dc.Questions.Where(t => t.QuestionnaireId == qs.QuestionnaireID)
from r in dc.Responses.Where(qr => qr.QuestionID == q.QuestionId).DefaultIfEmpty()
where qs.QuestionnaireID == QuestionnaireId
select new
{
qs.Description,
Questions = q,
Responses = r
}).Single();
foreach(var question in questAires.Questions)
{
}
questAires.Questions will only resolve to a single question, and you will get one questAires object for each question (which will cause .Single() to throw).
I guess you want something like this:
var questAires = (from qs in dc.Questionnaires
select new {
qs.Description,
Questions = from q in dc.Questions where q.QuestionnaireId == qs.QuestionnaireID
select new {
Question = q,
Response = (from r in dc.Responses where r.QuestionID == q.QuestionId select r).DefaultIfEmpty()
}
}).Single()
q actually resolves to a single item from the enumerable dc.Questions.Where(...), so yeah, you're only going to get a single item - not an enumerable - for Questions.

Creating a TreeView Nested Structure Using Self Referencing Table

I am trying to create a TreeView nested structure with the use of self referencing table fields. Here is a simple example:
Category 1
Product 1
Toy 1
Toy 2
Product 2
Toy 3
Toy 4
more categories..
The database table has a single table called "Category". The ParentCategoryId points to the Category which is the parent. So, for the Category 1 the ParentCategoryId is null since it is parent. For Product 1 the ParentCategoryId is that of the Category 1 id and for Toy 1 the ParentCategoryId is that for the Product 1 id.
I am using the following code but it does not generate the TreeView (ASP.NET) successfully.
public void BuildTree(List<Category> categories, TreeNode treeNode)
{
if (treeNode == null) return;
TreeNode tnAdd = null;
var categoryId = Guid.NewGuid();
foreach (var category in categories)
{
if (category.IsBaseCategory)
{
tnAdd = new TreeNode();
tnAdd.Text = category.Description;
BuildTree((from c in categories
where c.ParentCategoryId == category.CategoryId
select c).ToList<Category>(), tnAdd);
}
else
{
tnAdd = new TreeNode();
tnAdd.Text = category.Description;
BuildTree((from c in categories
where c.ParentCategoryId == category.CategoryId
select c).ToList<Category>(), tnAdd);
}
if (tnAdd != null)
treeNode.ChildNodes.Add(tnAdd);
}
}
Does this require recursion!
and here is the result I get:
80W
40W
40W
Light Bulbs
Flourecent
Incedecent
60W
80W
60W
Flourecent
40W
80W
60W
Incedecent
80W
40W
60W
What isn't successful?
If its because you see nothing ... I don't see where you're ever adding the root node to the actual tree control. tnAdd needs to be added to the tree control somewhere.
If it's because your not getting everything you expect: Unless you already have recursion going on somewhere and don't realize it, I can't see how the above code is ever going to get to the toy level. You say "base", then "child" in the above code which covers two levels. You have three levels in your sample data, so at some point you need to account for adding the toys. You can write it recursively if you need to have n levels. If you only have three levels, you can just repeat yourself.
----- UPDATES FOR OP UPDATES
Looking at your code, what you have is this:
for each category {
if it is base
add its children
else if it is not base
add its children
add it to the tree
}
This means every item is hit in the first foreach and added to the tree, rather than per level.
what you want is
for each category{
if it is base
add base's children
for each child [
add child's children
add child to the tree
]
add base the tree
}
Something closer to this (I don't have time to test right now, sorry) should come close to working
public BuildTreeTop(List<Category> categories, TreeNode treeNode)
{
BuildTree((from c in categories
where c.IsBaseCategory == true
select c).ToList<Category>(), categories, tnAdd);
}
public void BuildTree(List<Category> currentLevel, List<Category> allCategories, TreeNode treeNode)
{
if (treeNode == null) return;
TreeNode tnAdd = null;
var categoryId = Guid.NewGuid();
foreach (var category in currentLevel)
{
tnAdd = new TreeNode();
tnAdd.Text = category.Description;
BuildTree((from c in allCategories
where c.ParentCategoryId == category.CategoryId
select c).ToList<Category>(), allCategories, tnAdd);
if (tnAdd != null)
treeNode.ChildNodes.Add(tnAdd);
}
}

Resources