Is it possible to run extra lines of code during debugging - debugging

I want to execute extra lines of code during debugging in Visual Studio 2012.
Is it possible to make it.
One application would be to execute some WRITE(,) statements, or evaluate some expressions.

If you're using F77 with the Intel Compiler, have a look at the /D-lines option. You can write code like
if (x.gt.10) then
x = 0
D print *, 'x reset'
end if
It will only compile the lines with D in column 1 if the /D-lines option is present, otherwise it is treated as a comment. I've only ever used this on F77. I don't know if it works on F90 etc.
Reference http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/composerxe/compiler/fortran-lin/GUID-E356B0E3-F847-40A9-A932-77B4D8EEF53B.htm
The Intel compiler also supports preprocessing. You could use either
the C type macros with #if etc http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/composerxe/compiler/fortran-mac/GUID-4A598AC5-1C5F-48F2-BA42-DA8F38D46CB3.htm
the original Microsoft/DEC macros with !DEC$ http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/composerxe/compiler/fortran-mac/GUID-0E1D6C34-2565-4331-864F-5970EF452E27.htm
If you're using Silverfrost, have a look at the CIF-CELSE-CENDIF /VPARAM /SPARAM options.

You can use the #if to do this within Visual Studio.
#if DEBUG
Console.WriteLine("Debug version");
#endif
http://msdn.microsoft.com/en-us/library/4y6tbswk(v=vs.110).aspx

Related

Nim checks:off vs -d:release

I'd like to know what's the difference between both options. At first i thought they would produce the same output, but i have profiled a code using first {.checks:off.} and later -d:release and the difference is notable (release being more faster).
The code in this case is a hot loop with some float operations, one if and array get/set.
Here's what release does: https://github.com/nim-lang/Nim/blob/devel/config/nim.cfg#L50-L66
#if release or quick:
obj_checks:off
field_checks:off
range_checks:off
bound_checks:off
overflow_checks:off
assertions:off
stacktrace:off
linetrace:off
debugger:off
line_dir:off
dead_code_elim:on
#end
#if release:
opt:speed
#end
opt:speed then tells your C compiler to optimize the output for speed, for example:
gcc.options.speed = "-O3 -fno-strict-aliasing"
-d:release also enables the optimiser (which does some extras such as removing asserts) which will be causing some speed increases on its behalf. The flags are descibed here.

Stringify Endpoint for Xcode LLVM Processor Macros

In the "Apple LLVM 7.0 - Preprocessing" section under the "Build Settings" tab, I've defined a Preprocessor Macros as:
STR(arg)=#arg
HUBNAME=STR("myhub")
HUBLISTENACCESS=STR("Endpoint=sb://abc-xyz.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=JKLMNOP=")
In my code, I'm trying to refer to the value of HUBLISTENACCESS as a string:
SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:#HUBLISTENACCESS notificationHubPath:#HUBNAME];
But I'm getting errors from Xcode for the initialization of "hub":
Expected ';' at end of declaration
Unterminated function-like macro invocation
Unexpected '#' in program
I suspect that the definition of HUBLISTENACCESS in the Preprocessor Macros needs to be properly escaped but I've tried a few things and can't seem to get it right. Can somebody help me understand what I'm doing wrong?
There's one very obvious reason why you were trying to do failed: you use // in the HUBLISTENACCESS. As in C, things after // were commented out so in the aspect of the compiler, the last line of yours is actually:
HUBLISTENACCESS=STR("Endpoint=sb:
To test it, just remove one slash and it will work again. What you were doing like trying to define things as such:
#define FOO //
which I don't think it's possible. I honestly have no idea how you can do that within the Build Settings, but there are other ways to do it globally via a PCH file (prefix header).
A simple line within the PCH will will save all those troubles:
#define HUBLISTENACCESS #"Endpoint=sb://abc-xyz.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=JKLMNOP="
Then use it as below: (no more # needed!)
NSLog(#"%#", HUBLISTENACCESS);

Visual Studio 9.0 Error C2051 Case Expression Not Constant

When I try to compile this code, I get a Case Expression Not Constant error. I can't figure out why.
while ((*datalen) == 0)
crReturn(NULL); //error here
st->len = (st->len << 8) + **data;
The function crReturn() is defined as following.
#define crReturn(z) \
do {\
*crLine =__LINE__; return (z); case __LINE__:;\
} while (0)
The problem is that MSVC++ does something nonstandard (and contrary to its own documentation) when it's configured to generate debug information for its "edit and continue" feature, and that this nonstandard breaks the way that __LINE__ is used in Simon Tatham's coroutine macros.
Here's what the comments in the PuTTY source code say about this:
In particular, if you are getting `case expression not constant'
errors when building with MS Visual Studio, this is because MS's
Edit and Continue debugging feature causes their compiler to
violate ANSI C. To disable Edit and Continue debugging:
- right-click ssh.c in the FileView
- click Settings
- select the C/C++ tab and the General category
- under `Debug info:', select anything _other_ than `Program
Database for Edit and Continue'.
So you should probably do that. (In fact, I know that you already did, because we discussed this in comments before I posted this answer :-).)

How do you count the lines of code in a Visual Studio solution?

Is it possible to find the number of lines of code in an entire solution? I've heard of MZ-Tools, but is there an open source equivalent?
I've found powershell useful for this. I consider LoC to be a pretty bogus metric anyway, so I don't believe anything more formal should be required.
From a smallish solution's directory:
PS C:\Path> (gci -include *.cs,*.xaml -recurse | select-string .).Count
8396
PS C:\Path>
That will count the non-blank lines in all the solution's .cs and .xaml files. For a larger project, I just used a different extension list:
PS C:\Other> (gci -include *.cs,*.cpp,*.h,*.idl,*.asmx -recurse | select-string .).Count
909402
PS C:\Other>
Why use an entire app when a single command-line will do it? :)
Visual Studio has built-in code metrics, including lines of code:
Analyze → Calculate Code Metrics
I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).
An open source line counter for VS2005, 2003 and 2002 is available here:
http://www.wndtabs.com/
There is also discussion of creating a line counting VS addin, complete with code on Codeproject, here
http://www.codeproject.com/KB/macros/LineCounterAddin.aspx
Also Slick Edit Gadgets have a nice line-counter, here:
http://www.slickedit.com/products/slickedit
and Microsoft Visual Studio Team System 2008 includes a good line counter.
Just remember though:
Measuring programming progress by lines of code is like measuring aircraft building progress by weight.
Bill Gates
Here's an update for Visual Studio 2012/2013/2015 for those who want to do the "Find" option (which I find to be the easiest): This RegEx will find all non-blank lines with several exclusions to give the most accurate results.
Enter the following RegEx into the "Find" box. Please make sure to select the "Use Regular Expressions" option. Change the search option to either "Current Project" or "Entire Solution" depending on your needs. Now select "Find All". At the bottom of the Find Results window, you will see "Matching Lines" which is the lines of code count.
^(?!(\s*\*))(?!(\s*\-\-\>))(?!(\s*\<\!\-\-))(?!(\s*\n))(?!(\s*\*\/))(?!(\s*\/\*))(?!(\s*\/\/\/))(?!(\s*\/\/))(?!(\s*\}))(?!(\s*\{))(?!(\s(using))).*$
This RegEx excludes the following items:
Comments
// This is a comment
Multi-Line comments (assuming the lines are correctly commented with a * in front of each line)
/* I am a
* multi-line
* comment */
XML for Intellisense
/// <summary>
/// I'm a class description for Intellisense
/// </summary>
HTML Comments:
<!-- I am a HTML Comment -->
Using statements:
using System;
using System.Web;
Opening curly braces:
{
Closing curly braces:
}
Note: anything between the braces would be included in the search, but in this example only 4 lines of code would count, instead of 18 actual non-blank lines:
public class Test
{
/// <summary>
/// Do Stuff
/// </summary>
public Test()
{
TestMe();
}
public void TestMe()
{
//Do Stuff Here
/* And
* Do
* Stuff
* Here */
}
}
I created this to give me a much more accurate LOC count than some previous options, and figured I would share. The bosses love LOC counts, so I'm stuck with it for a while. I hope someone else can find this helpful, let me know if you have any questions or need help getting it to work.
Found this tip:
LOC with VS Find and replace
Not a plugin though if thats what you are looking for.
cloc is an excellent commandline, Perl-based, Windows-executable which will break down the blank lines, commented lines, and source lines of code, grouped by file-formats.
Now it won't specifically run on a VS solution file, but it can recurse through directories, and you can set up filename filters as you see fit.
Here's the sample output from their web page:
prompt> cloc perl-5.10.0.tar.gz
4076 text files.
3883 unique files.
1521 files ignored.
http://cloc.sourceforge.net v 1.07 T=10.0 s (251.0 files/s, 84566.5 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code scale 3rd gen. equiv
-------------------------------------------------------------------------------
Perl 2052 110356 112521 309778 x 4.00 = 1239112.00
C 135 18718 22862 140483 x 0.77 = 108171.91
C/C++ Header 147 7650 12093 44042 x 1.00 = 44042.00
Bourne Shell 116 3402 5789 36882 x 3.81 = 140520.42
Lisp 1 684 2242 7515 x 1.25 = 9393.75
make 7 498 473 2044 x 2.50 = 5110.00
C++ 10 312 277 2000 x 1.51 = 3020.00
XML 26 231 0 1972 x 1.90 = 3746.80
yacc 2 128 97 1549 x 1.51 = 2338.99
YAML 2 2 0 489 x 0.90 = 440.10
DOS Batch 11 85 50 322 x 0.63 = 202.86
HTML 1 19 2 98 x 1.90 = 186.20
-------------------------------------------------------------------------------
SUM: 2510 142085 156406 547174 x 2.84 = 1556285.03
-------------------------------------------------------------------------------
The third generation equivalent scale is a rough estimate of how much code it would take in a third generation language. Not terribly useful, but interesting anyway.
Answers here are a little bit out of date, may be from vs 2008 time. Because in newer Visual Studio versions 2010/2012, this feature is already built-in. Thus there are no reason to use any extension or tools for it.
Feature to count lines of code - Calculate Metrics. With it you can calculate your metrics (LOC, Maintaince index, Cyclomatic index, Depth of inheritence) for each project or solution.
Just right click on solution or project in Solution Explorer,
and select "Calculate metrics"
Later data for analysis and aggregation could be imported to Excel. Also in Excel you can filter out generated classes, or other noise from your metrics. These metrics including Lines of code LOC could be gathered also during build process, and included in build report
Regular expressions have changed between VS2010 and 2012, so most of the regular expression solutions here no longer work
(^(?!(\s*//.+)))+(^(?!(#.+)))+(^(?!(\s*\{.+)))+(^(?!(\s*\}.+)))+(^(?!(\s*\r?$)))+
Will find all lines that are not blank, are not just a single bracket ( '{' or '}' ) and not just a #include or other preprocessor.
Use Ctrl-shift-f and make sure regular expressions are enabled.
The corresponding regular expression for VS 2010 and older is
^~(:Wh#//.+)~(:Wh#\{:Wh#)~(:Wh#\}:Wh#)~(:Wh#/#).+
In Visual Studio Team System 2008 you can do from the menu Analyze--> 'Calculate Code Metrics for Solution' and it will give you a line count of your entire solution (among other things g)
For future readers I'd like to advise the DPack extension for Visual Studio 2010.
It's got a load of utilities built in including a line counter which says how many lines are blank, code, and etc.
A simple solution is to search in all files. Type in "*" while using wildcards. Which would match all lines. At the end of the find results window you should see a line of the sort:
Matching lines: 563 Matching files: 17 Total files searched: 17
Of course this is not very good for large projects, since all lines are mached and loaded into memory to be dispayed at the find results window.
Reference:
Advanced Example
In Visual Studio 2019, from the top menu you need to select:
'Analyze' -> 'Calculate Code Metrics' -> 'For Solution'
This works in both Visual Studio 2019 Professional and Enterprise.
You could use:
SCLOCCount http://www.dwheeler.com/sloccount/- Open source
loc metrics, http://www.locmetrics.com/ - not open source, but easy to use
I prefer OxyProject Metrics VS Addin.
Obviously tools are easier, but I feel cool doing this in powershell:)
This script finds all the .csproj references in the .sln file, and then within each csproj file it locates files included for compilation. For each file that is included for compilation it creates an object with properties: Solution, Project, File, Lines. It stores all these objects in a list, and then groups and projects the data as needed.
#path to the solution file e.g. "D:\Code\Test.sln"
$slnFile = "D:\Code\Test.sln"
#results
$results = #()
#iterate through .csproj references in solution file
foreach($projLines in get-item $slnFile | Get-Content | Select-String '".*csproj')
{
$projFile = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($slnFile), [regex]::Match($projLines,'[^"]*csproj').Value)
$projFolder = [System.IO.Path]::GetDirectoryName($projFile)
#from csproj file: get lines for files to compile <Compile Include="..."/>
$includeLines = get-item $projFile | Get-Content | Select-String '<Compile Include'
#count of all files lines in project
$linesInProject = 0;
foreach($fileLine in $includeLines)
{
$includedFilePath = [System.IO.Path]::Combine($projFolder, [Regex]::Match($fileLine, '"(?<file>.*)"').Groups["file"].Value)
$lineCountInFile = (Get-Content $includedFilePath).Count
$results+=New-Object PSObject -Property #{ Solution=$slnFile ;Project=$projFile; File=$includedFilePath; Lines=$lineCountInFile }
}
}
#filter out any files we dont need
$results = $results | ?{!($_.File -match "Designer")}
#print out:
"---------------lines per solution--------------"
$results | group Solution | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
"---------------lines per peoject--------------"
$results | group Project | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip
Use Menu-> Analyse - > Calculate Code Metrics option in Visual Studio 2010 Ultimate.
You can use the Visual Studio Code Metrics PowerTool 10.0. It's a command-line utility that calculates a few metrics on managed code for you (including lines of code). You can get a VS 2010 plugin that brings the tool into Visual Studio, and makes it as quick as selecting the menu item and clicking "Analyze Solution."
Agree with Ali Parr. The WndTab Line Counter addin is a such tool.
http://www.codeproject.com/KB/macros/linecount.aspx
It's also a good idea to search from download site to find some related tool.
http://www.cnet.com/1770-5_1-0.html?query=code+counter&tag=srch
Here is the Trick.. It counts the Js file also.
http://www.spoiledtechie.com/post/2011/11/22/How-To-Count-Lines-of-Code-in-Visual-Studio.aspx
You can use free tool SourceMonitor
Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth
Has graphical outputs via charts
You can use the Project Line Counter add-in in Visual Studio 2010. Normally it doesn't work with Visual Studio 2010, but it does with a helpful .reg file from here: http://www.onemanmmo.com/index.php?cmd=newsitem&comment=news.1.41.0
I came up with a quick and dirty powershell script for counting lines in a folder structure. It's not nearly as full featured as some of the other tools referenced in other answers, but I think it's good enough to provide a rough comparison of the size of code files relative to one another in a project or solution.
The script can be found here:
https://gist.github.com/1674457
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".
Try neptuner. It also gives you stuff like spaces, tabs, Lines of comments in addition to LoC.
http://neptuner.googlecode.com/files/neptuner_0_30_windows.zip

Invert assignment direction in Visual Studio [duplicate]

This question already has answers here:
How can I reverse code around an equal sign in Visual Studio?
(6 answers)
Closed 4 years ago.
I have a bunch of assignment operations in Visual Studio, and I want to reverse them:
i.e
i = j;
would become
j = i;
i.e. replacing everything before the equals with what's after the equals, and vice versa
Is there any easy way to do this, say something in the regular expression engine?
Select the lines you want to swap, Ctrl+H, then replace:
{:i}:b*=:b*{:i};
with:
\2 = \1;
with "Look in:" set to "Selection"
That only handles C/C++ style identifiers, though (via the ":i"). Replace that with:
{.*}:b*=:b*{.*};
to replace anything on either side of the "=".
Also, since you mentioned in a comment you use ReSharper, you can just highlight the "=", Alt+Enter, and "Reverse assignment".
Just a slight improvement on Chris's answer...
Ctrl+H, then replace:
{:b*}{[^:b]*}:b*=:b*{[^:b]*}:b*;
with:
\1\3 = \2;
(better handling of whitespace, esp. at beginning of line)
EDIT:
For Visual Studio 2012 and higher (I tried it on 2015):
Replace
(\s*)([^\s]+)\s*=\s*([^\s]+)\s*;
with:
$1$3 = $2;
In Visual Studio 2015+ after selecting code block press Ctrl + H (Find & Replace window) and check "Use Regular Expression" option, then:
Find: (\w+.\w+) = (\w+);
Replace: $2 = $1;
For example:
entity.CreateDate = CreateDate;
changes to:
CreateDate = entity.CreateDate;
Thank you #Nagesh and Revious, mentioned details added.
The robust way to do this is to use a refactoring tool. They know the syntax of the language, so they understand the concept of "assignment statement" and can correctly select the entire expression on either side of the assignment operator rather than be limited to a single identifier, which is what I think all the regular expressions so far have covered. Refactoring tools treat your code as structured code instead of just text. I found mention two Visual Studio add-ins that can do it:
ReSharper
MZ-Tools
(Inverting assignment isn't technically refactoring since it changes the behavior of the program, but most refactoring tools extend the meaning to include other generic code modifications like that.)
Please see this question: Is there a method to swap the left and right hand sides of a set of expressions in Visual Studio?
My answer to that question has a macro that you can use to swap the assignments for a block of code.
I've improved the expression a little.
Replace
(\t+)(\s*)(\S*) = (\S*);
with
$1$2$4 = $3;
The reason is, it will look for lines starting with tab (\t). It will skip the lines starting with definition. E.g.:
TestClass tc = new TestClass();
int a = 75;
int b = 76;
int c = 77;
a = tc.a;
b = tc.b;
a = tc.c;
Would ignore the int a, int b and int c and swap only the assignments.
what about replace all (CTRL-H)
you can replace for example "i = j;" by "j = i;"
you can use regular expressions in that dialog. I'm not so sure about how you should pop-up help about them however. In that dialog, press F1, then search that page for more information on regular expressions.
I like this dialog because it allows you to go through each replacement. Because the chance of breaking something is high, I think this is a more secure solution
You can do search and replace with regular expressions in Visual Studio, but it would be safer to just do a normal search and replace for each assignment you want to change rather than a bulk change.
Unfortunatly I don't have Visual Studio, so I can't try in the target environment, but if it uses standard regexps, you could probably do it like this:
Search for "(:Al) = (:Al);", and replace with "\2 = \1". (\1 and \2 are references to the first and second capture groups, in this case the parenthesises around the \w:s)
EDIT
Ok, not \w... But according to MSDN, we can instead use :Al. Edited above to use that instead.
Also, from the MSDN page I gather that it should work, as the references seem to work as usual.

Resources