Windows Workflow Foundation 4.0 Break Out of ForEach<T> Activity - windows

I'm using Visual Studio 2010 Beta 2 to get a head start on learning to use WF4. I'm working in the designer to create a xaml file. I've added a ForEach activity, and inside that ForEach activity have a flowchart that does some conditional processing. I want to be able to break out of the ForEach if one of the conditions is true, but can't figure out how to do so. In a C# code behind file that would just be to issue a break; , but in the xaml workflow designer, I don't see any mechanism for breaking from a loop. Any suggestions?

There is no break equivalent in WF4. So either you need to start adding conditional logic to skip the next loops or throw an exception and catch that outside of the ForEach and continue.
And I agree that neither is a very nice option :-(

Using a While or DoWhile activity in place of a ForEach may be the best option for the activity's limitations on iteration control. It's a little uglier but works just as you're wanting your iteration to.
The conditional could check a bool, such as Broken, and a counter variable to compare it against the collections length. I'm not sure if this is the best for your scenario or for the collection your looping but seems like a viable option.

Related

Visual Studio - Discover if method is called by another method at some point

I was wondering, does visual studio have a feature such that I gave it a 2 method names and it then works out if at somewhere along the call stack the first method is called by the second (statically, without having to debug).
e.g.
Say I have a method FireBullet, and I want to see if IsOutsideWestBoundary can be invoked at some point
FireBullet()->HitTest()->CheckBoundaries()->IsOutsiteWestBoundary()
You can see that FireBullet can eventually cause IsOutsideWestBoundary to be invoked at some point.
I understand this can potentially become a very large problem, especially with deep call stacks and multiple methods called at each level, but still, for relatively small call stacks depths, this could be very useful.
Surely something like this must exist?
Thanks
Thomas
The Visual Studio extension NDepend can do that. It lets write code rules and code queries through C# LINQ queries. The following LINQ code query, executed live in Visual Studio, answers your need:
from m in Methods
where m.Name == "FireBullet()"
let depth0 = m.DepthOfIsUsing("MyNamespace.Program.IsOutsiteWestBoundary()")
where depth0 >= 0 orderby depth0
select new { m, depth0 }
Notice that the code query result also provides the depth of call. It can be stored in your NDepend project, and it can be transformed into a rule by adding the prefix warnif count > 0.
This query gets inspired from the query generated by NDepend when right clicking a method and Select Methods ... that call me (directly or indirectly).
If you click the button Export to Graph you get such call graph (more info on this here):
A 14-day full featured trial is available here.
Disclaimer: I work for NDepend.

Can I have VS 2013 ignore certain syntax errors until I build?

For example, I could pretty much always do without the "not all code paths return a value" error squiggly. This generally means I'm in the process of writing the method. I don't need to be told it doesn't return a value. If I forget to add a return value, VS can tell me that when it builds. But I never want that while I'm working; it's annoying and usually tells me something I already know.
For another example, I could do without the errors that show up while I'm in the process of writing a switch statement, such as the one that tells me I don't have a break statement yet, as I'm still working on whatever case.
You can try to disable "Show live semantic errors",
http://www.devcurry.com/2011/01/disable-squiggly-or-wavy-lines-in.html

How to get Resharper to convert back to a foreach loop

Resharper 5 can convert my foreachloops to Linq queries. Which I like. But linq is way way way harder to debug than a foreachloop.
When I convert my foreach statement to a linq query, I don't see any option to go back the other way.
Does any one know how to do this? Is it even possible?
We are working on LINQ2Foreach (and some other) functionality for ReSharper vNext
I do not believe this is possible. Certainly, it's not listed in the examples of Quick Fixes, where loop-to-LINQ-expression is shown.
What you should be able to do is use the Context Action 'Convert LINQ to methods chain' to go from the 'fluent' style to the 'methods' style, and then selectively use 'Introduce variable' to pull the expression to pieces.

Performing expression evaluation/reduction in Visual Studio 2008

Is it possible to get Visual Studio to do mathematical expression evaluation/reduction?
For example if I type '-0.005 + -0.345' how do I get Visual Studio to reduce that (i.e. replace it with the reduction)? Do I have to write a macro? If so, are there any pre-existing macros to do this type of expression reduction?
Just to be clear, I want to be able to highlight an expression and have it replaced with the reduced result. Many are suggesting the immediate window but I fail to see how that will suffice?
Edit I should point out that this is while editing not running or debugging. The immediate window is of little to no use. I also consider this a language neutral question. I would certainly be interested in seeing alternative macros to the one I had posted.
Edit Going Once... Going Twice... (i.e. any other suggestions before I consider accepting my own answer?)
Thank you for the above answers.
There probably are better ways, but here's a quick and dirty macro that does what I need.
References to the System.Data and System.XML namespaces need to be added.
Highlight the expression you want to evaluate and run the macro (it uses the calculated column in the DataTable to evaluate the expression.) It will replace the expression with the reduced result.
Edit - Updated code below. It worked extremely well for reducing a large number of expressions. As pointed out by others there is the immediate window but this will not work for editing purposes. This macro is a language independent solution for basic expressions "(), +, -, *, /".
Sub Eval()
Dim ts As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Using dt As New DataTable()
dt.Columns.Add("Expression", GetType(Double), ts.Text)
dt.Rows.Add(dt.NewRow)
ts.Text = CDbl(dt.Rows(0).Item("Expression"))
End Using
End Sub
Visual Studio by default will not do any mathematical expression evaluation / reduction. I'm not sure if you can get support for that via items like ReSharper, but if it is available it will be in an add-in.
Also, it would be helpful to know the language you are working in?
Some languages may be helpful in this area. F# for instance makes it easy to evaluate expressions in the IDE via the interactive window and will display out the result. This could easily be added back into your code but it doesn't appear to be exactly what you're looking for.
Here's an answer: Yes, it is possible using the following steps. (While technically performing what you're asking for, I'm not sure it will be extremely useful. :-)
Set a breakpoint in your program that's likely to get hit when you debug the program.
Then, run your program under the Visual Studio debugger.
When the breakpoint is hit, open the Watch window.
In the Watch window, add a new watch by clicking in the Name column.
Enter your expression '-0.005 + -0.345' (without the quotes) then hit [Enter].
... You should see the Value column get populated with -0.35.
Of course, that isn't in the context of the editor window ... which is, presumably, where you'd want to perform the reduction. So again, not very useful, I imagine. An add-in is the likely way to do that in the editor window.
You could just go to the immediate window and type "?<yourExpression>"

How to debug a LINQ Statement

I have a Linq to objects statement
var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
select l;
The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?
EDIT When I said I know for a fact that there are no null objects it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'
LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool
Yes it is indeed possible to pause execution midway through a linq query.
Convert your linq to query style using lambda expressions and insert a Select statement that returns itself somewhere after the point in the linq that you want to debug. Some sample code will make it clearer -
var query = dataset.Tables[0].AsEnumerable()
.Where (i=> i.Field<string>("Project").Contains("070932.01"))
// .Select(i =>
// {return i;}
// )
.Select (i=>i.Field<string>("City"));
Then uncomment the commented lines. Make sure the {return i;} is on its own line and insert a debug point there. You can put this select at any point in your long, complicated linq query.
I'm not sure if it's possible to debug from VS, but I find LINQPad to be quite useful. It'll let you dump the results of each part of the LINQ query.
You should be able to set a breakpoint on the expression in the where clause of your LINQ statement.
In this example, put the cursor anywhere in the following section of code:
(l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
Then press F9 or use the menu or context menu to add the breakpoint.
When set correctly, only the above code should have the breakpoint formatting in the editor rather than the entire LINQ statement. You can also look in the breakpoints window to see.
If you've set it correctly, you will stop each time at the function that implements the above part of the query.
I wrote a comprehensive article addressing this very question published on Simple-Talk.com (LINQ Secrets Revealed: Chaining and Debugging) back in 2010:
I talk about LINQPad (as mentioned earlier by OwenP) as a great tool external to Visual Studio. Pay particular attention to its extraordinary Dump() method. You can inject this at one or more points in a LINQ chain to see your data visualized in an amazingly clean and clear fashion. Though very useful, LINQPad is external to Visual Studio. So I also present several techniques available for use within Visual Studio because sometimes it is just not practical to migrate a chunk of code over to LINQPad:
(1) Inject calls to the Dump() extension method I present in my article to allow logging. I started with Bart De Smet's Watch() method in his informative article LINQ to Objects – Debugging and added some labeling and colorization to enhance the visualization, though still it pales in comparison to LINQPad's Dump output.
(2) Bring LINQPad's visualization right into Visual Studio with Robert Ivanc's LINQPad Visualizer add-in. Not sure if it was through my prodding :-), but the couple inconveniences present when I was writing my article have now all been admirably addressed in the latest release. It has full VS2010 support and lets you examine any object you like when debugging.
(3) Embed nop statements in the middle of your LINQ chain so you can set breakpoints, as described earlier by Amazing Pete.
2016.12.01 Update
And I just wrote the sequel to the above article, titled simply LINQ Debugging and Visualization, which reveals that true LINQ debugging capability has finally arrived in Visual Studio 2015 with the about-to-be-released new feature in OzCode. #Dror's answer to this question shows a tiny glimpse of it, but I encourage you to read my new article for an in-depth "how to". (And I do not work for OzCode.:-)
[Disclaimer: I work at OzCode]
The problem with LINQ is that it's hard to impossible to debug - even when dealing simple queries a developer is forced to refactor his/her query to a bunch of foreach loops, or use logging.
LINQ debugging is supported in a soon-to-be-released version of OzCode (currently available as an Early Access Preview) and it helps developers drill into their LINQ code as well and pinpoint those hard to catch exceptions inside queries
This is what your query would look like in OzCode:
It is possible to step inside the LINQ expression without setting any temporary breakpoints. You need to step into the function which evaluates the LINQ expression, e.g.:
var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber)
|| (l.LineNumber == endline.LineNumber)
select l;
confirm.ToArray(); // Press F11 ("Step into") when you reach this statement
foreach(var o in q) // Press F11 when "in" keyword is highlighted as "next statement"
// ...
Check the exception stack trace and see the last bit of your code that executed.
From the looks of the error I would suggest you take a look at line.Lines and make sure its enumerator is implemented properly. I think it's returning a null when it shouldn't.
Oh and just make sure the line and line.Lines objects aren't null or returning nulls as well.
While it isn't a way of debugging, I'd suggest using the following:
using (var db = new AppContext())
{
db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
// Rest of code
}
You can then check the output window when debugging to see the SQL generated from your LINQ query.
To step through the LINQ statement just put a breakpoint on linq statement and then when it starts to debug that line then
Right click on it
click on Run To Cursor option
It will start to execute code line by line as we do normally.

Resources