Unreachable Code Detected? - c#

I am getting this rediculous error "unreachablecode detected" and clearly everything in in proper visibiliity...
Here is the code ..
int lastAppNum = 0;
//load the xml document
XmlDocument xdoc = new XmlDocument();
xdoc.Load(GlobalVars.strXMLPath);
//add a app node
XmlNode newApp = xdoc.CreateNode(XmlNodeType.Element, "app", null);
//add the app number - this will be used in order to easily identify the app details (used for overwriting/saving)
XmlAttribute newNum = xdoc.CreateAttribute("num");
//in order to create a new number - search the last num and add one to it
foreach (XmlNode xmlAppChild in xdoc.ChildNodes)
{
//if there are existing child nodes
if (true)
{
//get the last childs num attribute
lastAppNum = Convert.ToInt32(xmlAppChild.LastChild.Attributes["num"].Value);
//add +1 to the last app num
lastAppNum++;
//add the new value to the attribute
newNum.InnerText = lastAppNum.ToString();
break;
}else{
//if there isnt an existing child node - set the num to 1
lastAppNum = 1; <<where the error happens
newNum.InnerText = lastAppNum.ToString();
break;
}
}
Does anyone have an idea of whats going on ? I thought perhaps it was the lack of a "break" so i threw two in here (i saw on a form thats what a solution was) but either way it doesnt matter and the error is still happening. Any suggestions would be great.

You have if (true) - was there some condition you actually wanted to test here?
if (true)
{
// this code will always run
}
else
{
// this code will never run
}

else condition will never run since you have if (true)
i think based on your comments, you need to change the implimentation as below
if(xdoc.HasChildNodes)
{
foreach (XmlNode xmlAppChild in xdoc.ChildNodes)
{
//if there are existing child nodes
//get the last childs num attribute
lastAppNum = Convert.ToInt32(xmlAppChild.LastChild.Attributes["num"].Value);
//add +1 to the last app num
lastAppNum++;
//add the new value to the attribute
newNum.InnerText = lastAppNum.ToString();
}
}else
{
//if there isnt an existing child node - set the num to 1
lastAppNum = 1;
newNum.InnerText = lastAppNum.ToString();
}

the code
if (true)
will always be executed and there is no chance to else condition be executed.

Related

Unable to iterate to next ListNode, since the current node is getting overridden with the listnode.next value

This is a leetcode problem.
I saw the solution however while trying to use my own logic, I cannot iterate over to the next node.
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
try
{
string l1NodeData = null;
string l2NodeData = null;
do
{
l1NodeData = l1NodeData + l1.val;
l1 = l1.next;
} while (l1 != null);
do
{
l2NodeData = l2NodeData + l2.val;
l2 = l2.next;
} while (l2 != null);
int sum = Convert.ToInt32(l1NodeData) + Convert.ToInt32(l2NodeData);
var sumInChar = sum.ToString().ToArray();
ListNode dummyhead = new ListNode(0);
ListNode ans = dummyhead;
for (int i = sumInChar.Length - 1; i > 0; i--)
{
ans.val = Convert.ToInt32(sumInChar[i].ToString());
ListNode tempListNode = new ListNode(Convert.ToInt32(sumInChar[i - 1].ToString()));
ans.next = tempListNode;
ans = ans.next;
//here(ans = ans.next) after assigning the next node, the data of the current node is getting overridden.
}
return ans;
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
In the above solution where I am assigning ans = ans.next, there the current node is overridden with the next node, however, I just want to move to the next node in order to iterate.
Could someone please help me on this?
In the above solution where I am assigning ans = ans.next, there the current node is overridden with the next node, however, I just want to move to the next node in order to iterate.
The assignment is to a variable. That never mutates your linked list. This way of assigning to a variable is exactly what you need to traverse a linked list. It does not modify it. In order to mutate it, you will always need to assign to a member (property) of a node, like its next property.
In the code comments you wrote:
the data of the current node is getting overridden.
No, it looks like that because you return the reference to the last node that was created in the loop. Instead you should return dummyHead.next; This way you return the first node that was created in the loop.
In comments you wrote:
...I have not made any assignment to dummyhead right, then how does data reside in that variable?
You have referenced ans to the same node as dummyHead, and you did assign to ans.next, which in the first iteration of the loop is synonymous to dummyHead.next. With those assignments to ans.next the nodes get linked to eachother.
Note that dummyHead is an extra node that is created to ease the code in the loop -- not having to make a special case for creating the real head node. After the loop that dummyHead is then ignored (it served its purpose), and the real head (that is sitting right after it) is returned.

trying to identify text nodes with htmlagility pack

I am trying to identify text nodes from an HTML text having a format like as below
sample text 1 : <strong>[Hot Water][Steam][Electric]</strong> Preheating Coil
sample text 2 : <b><span>[Steam] [Natural Gas Fired] [Electric] [Steam to steam]</span></b><span> Humidifier</span><br>
using the below code
public static string IdentifyHTMLTagsAndRemove(string htmlText)
{
_ = htmlText ?? throw new ArgumentNullException(nameof(htmlText));
var document = new HtmlDocument();
document.LoadHtml(htmlText);
var rootNode = document.DocumentNode;
// get first and last text nodes
var nonEmptyTextNodes = rootNode.SelectNodes("//text()[not(self::text())]") ?? new HtmlNodeCollection(null);
//if (nonEmptyTextNodes.Count == 0)
//{
// return rootNode.OuterHtml;
//}
if (nonEmptyTextNodes.Count > 0)
{
var firstTextNode = nonEmptyTextNodes[0];
var lastTextNode = nonEmptyTextNodes[^1];
// get all br nodes in html string,
var breakNodes = rootNode.SelectNodes("//br") ?? new HtmlNodeCollection(null);
var lastTextNodeLengthIndex = lastTextNode.OuterStartIndex + lastTextNode.OuterLength;
foreach (var breakNode in breakNodes)
{
if (breakNode == null)
continue;
// check index of br nodes against first and last text nodes
// and remove br nodes that sit outside text nodes
if (breakNode.OuterStartIndex <= firstTextNode.OuterStartIndex
|| breakNode.OuterStartIndex >= lastTextNodeLengthIndex)
{
breakNode.Remove();
}
}
}
return rootNode.OuterHtml;
}
But it is constantly failing here
var nonEmptyTextNodes =
rootNode.SelectNodes("//text()[not(self::text())]") ?? new
HtmlNodeCollection(null);
and nonEmptyTextNodes giving count as zero, I am unsure where I am doing wrong with the above code.
Could anyone please point me in the right direction? Many thanks in advance.
In addition to Siebe's answer, I'd also like to point out an inefficiency in the code that trims start/end BR tags. If you look at the HtmlAgilityPack code for HtmlNode operations, you'll see that whenever nodes are removed, the SetChanged() method is called on the parent (and its parent, all the way up). The next time you check the start/end indexes of anything in the tree, they need to be recalculated. So this code could be made to run much faster if you instead just create a temporary list of all the nodes to be removed, then remove them after they've all been identified.
var lastTextNodeLengthIndex = lastTextNode.OuterStartIndex + lastTextNode.OuterLength;
var breakNodesToRemove = rootNode.SelectNodes("//br")?.Where(node => node.OuterStartIndex <= firstTextNode.OuterStartIndex || node.OuterStartIndex >= lastTextNodeLengthIndex).ToList();
breakNodesToRemove?.ForEach(a => a.Remove());
reference: https://github.com/zzzprojects/html-agility-pack/blob/master/src/HtmlAgilityPack.Shared/HtmlNode.cs
Not sure what you are trying to achieve with
//text()[not(self::text())]
It tries to select text()-nodes that are not text()-nodes. So nothing will be found. If you just use
//text()
Will select all text()-nodes

C# strange issue - unable to assign value from right to left variable

I have a list Rows which holds 10 different records. I am looping this list in C# console app and inserting values to another list but it only picks first record and inserts it 10 times to new list.
When I debug, unique values are shown in the loop but they are not being assigned to left variable.
List<Job> jobList=new List<Job>();
foreach (var row in rows)
{
Job job = new Job();
job.Title = row.SelectSingleNode("//h2[#class='jobtitle']").ChildNodes[1].Attributes["title"].Value;
job.summary = row.SelectSingleNode("//span[#class='summary']").InnerText
jobList.add(job);
}
Any idea, what is happening?
I also used garbage collector but still no improvement:
job = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Here is updated code after #Andrew suggestion but it didn't work. Right side holds updated values but they are not being assigned to left side variables.
foreach (var row in rows)
{
try
{
var job = new Job();
var title = row.SelectSingleNode("//h2[#class='jobtitle']").ChildNodes[1].Attributes["title"].Value;
var company = row.SelectSingleNode("//span[#class='company']").InnerText.Replace("\n", "").Replace("\r", "");
var location = row.SelectSingleNode("//span[#class='location']").InnerText.Replace("\n", "").Replace("\r", "");
var summary = row.SelectSingleNode("//span[#class='summary']").InnerText.Replace("\n", "").Replace("\r", "");
job.Title = title;
job.Company = company;
job.Location = location;
job.Summary = summary;
jobList.Add(job);
job = null;
GC.Collect();
GC.WaitForPendingFinalizers();
counter++;
Status("Page# " + pageNumber.ToString() + " : Record# " + counter + " extracted");
}
catch (Exception)
{
AppendRecords(jobList);
jobList.Clear();
}
//save file
}
Hi You don't tell us what the rows variable relates to, but I assume these are nodes in a single XmlDocument. The XPath expressions you are using to extract values from these nodes is incorrect, because they will always navigate to the same node in the document irrespective of the current row node.
Here's a simple example that demonstrates the problem:-
static void Main(string[] args)
{
XmlDocument x = new XmlDocument();
x.LoadXml(#"<rows> <row><bla><h2>bob1</h2></bla></row> <row><bla><h2>bob2</h2></bla></row> </rows>");
var rows = x.GetElementsByTagName("row");
foreach (XmlNode row in rows)
{
var h2 = row.SelectSingleNode("//h2").ChildNodes[0].Value;
Console.WriteLine(h2);
}
}
The output from this will be
bob1
bob1
Not what you were expecting? Have a play with the example in Dot Net Fiddle. Take another look at your XPath expression. Your current expression //h2 is saying "give me all h2 elements in the document irrespective of the current node". Whereas .//h2 would give you the h2 elements that are descendants of the current row node, which is probably what you need.

Adding elements to an ordered list

I want to add an element to a linked list so that the list remains sorted. I wrote this function. He's got a place that should be included, but I do not know how to insert the element.
public void AddSorted(int num)
{
Node n = new Node(num);
Node curr = _first;
Node curr1 = _first.Link;
while (curr1.Data < n.Data && curr1 != null)
{
curr = curr.link;
curr1= curr1.link;
}
// how to add element ???
}
You have provided absolutely no context regarding your LinkedList class, so I can only make an educated guess.
Given what I understand from the above code, after traversing to the location you want to insert the new Node, you will need to set the link of Node curr1 (which is the last Node) to the new node object.
Node temp = curr1.Link; // store next Node in temporary object
curr1.Link = n; // Insert new Node
Remember that you need to set the link of the new node to the next node in the LinkedList in order to continue the LinkedList (if the newly inserted Node is not the last):
n.Link = temp;
Please let me know if I made a mistake understanding your code, I can then change my answer accordingly.
With the help of my dear friends.
I could write this function.
Below you can see the code :
public void AddSorted(int num)
{
Node n = new Node(num);
Node curr = _first;
if (_first == null || _first.Data >= n.Data)
{
n.Link = _first;
_first = n;
}
else
{
while (curr.Link != null && curr.Link.Data < n.Data)
{
curr = curr.Link;
}
n.Link = curr.Link;
curr.Link = n;
}

Cant resolve infinite recursion

Ive recently started coding on populating a treeview control from a list and this is where i am starting.
http://msmvps.com/blogs/deborahk/archive/2009/11/09/populating-a-treeview-control-from-a-list.aspx
I am currently trying to retrieve registry paths and storing them to a list. From that list, I am trying to add it as parent nodes to the treeview control. Then I traverse every level in the registry and add them as nodes eventually creating a tree-like replica of it. I am retrieving registry information through a separate process and I shy away from using the Registry API within c#. I incorporated all of the code in the link above to my current code and now i am experiencing an infinite recursion error everytime i compile.
This is the current code I am working on.
private void registry()
{
string hivelist_output = process.StandardOutput.ReadToEnd();
string[] hivelist_lines = Regex.Split(hivelist_output, "\r\n");
string[] registry_paths = new string[hivelist_lines.Length];
List<string> registry_path_list = new List<string>();
for (i = 0; i < hivelist_lines.Length; i++)
{
registry_paths[i] = hivelist_lines[i].Substring(22);
registry_path_list.Add(registry_paths[i].Trim());
}
for (i = 0; i < registry_path_list.Count; i++)
{
treeViewList.Add(new TreeViewItem()
{
ParentID = 0,
ID = i,
Text = registry_path_list[i]
});
}
PopulateTreeView(0, null);
treeView1.ExpandAll();
}
private void PopulateTreeView(int parentId, TreeNode parentNode)
{
var filteredItems = treeViewList.Where(item => item.ParentID == parentId);
TreeNode childNode = new TreeNode();
foreach (var i in filteredItems.ToList())
{
if (parentNode == null)
childNode = treeView1.Nodes.Add(i.Text);
else
childNode = parentNode.Nodes.Add(i.Text);
PopulateTreeView(i.ID, childNode);
}
}
The error of infinite recursion points me to this line of code and I dont understand why.
childNode = parentNode.Nodes.Add(i.Text);
I appreciate your great advice on this matter. Thanks in advance!
-------------------------------------SOLVED-------------------------------------------
Moving forward, now my next problem is to add the subkeys below each parent node (registry path) and as well as the subkeys below each of the previously retrieved subkeys and key values and data types. Since the registry is quite deep, how could i make it so that I plot all possible values without using too much nested loops? Thanks!
*structure of what I would like to achieve
registry path
- subkey1
- subkeys of subkey1
- subkeys of subkey1.1
- data types & values
-subkey 2
.
.
.
-subkey 3
.
.
.
-subkey n
- data types & values
so and so forth
You are adding TreeViewItems always with ID = 0. Therefore, your PopulateTreeView always calls itself recursively with ID 0.
You need to fix your setup method:
for (i = 0; i < registry_path_list.Count; i++)
{
treeViewList.Add(new TreeViewItem()
{
ParentID = 0,
ID = 0,
Text = registry_path_list[i]
});
}
and use the corresponding IDs.

Categories