VS 2008 Code Snippet Indentation - visual-studio

In VS 2008, there are XML code snippets that seem to be pretty awesome :) However, it seems that the snippets we created do not indent properly. For example if we have the following code:
{
...
{
...
{
InsertSnippet here.
We get something like:
{
...
{
...
{
FirstLineofSnippet
SecondLineOfSnippet
ThirdLineOfSnippet
Is there any way to make it so that all lines keep the same indentation?

This usually indicates that the code you are inserting is semantically incorrect - at the time of insert, not when you filled in the snippet values.
To prevent this you can use default values in your snippet to make the snipped syntactivaly correct. E.g. to declare an argument list for a function:
<Literal Editable="true">
<ID>methodArguments</ID>
<ToolTip>methodArguments</ToolTip>
<Default>params object[] args</Default>
<Function>
</Function>
</Literal>
The <Default> Element provides the declaration. So using this in a snippet declaring a funciton will lead to this:
public void FunctionName(params object[] args) { }
And it then lets you replace params object[] args with whatever argument declarations you need.

paste the first line without indentation, then select the block and tab until you get the whole block to the indentation you want. AFAIK what you see is the standard behavior and it happens because the location you paste from wasn't indented as far as you wanted.

My unit test snippet appears to be indenting correctly. It may be due to the fact that the code is wrapped in a CDATA block. VisualStudio also tends to auto-format the block as soon as it is added to the code. Does your snippet have as many open braces as closing ones? If the two match up, and the snippet is inserted in a valid/compilable location, it should auto-format.

It seems that Visual Studio does an auto-format on the inserted lines. My snippet wasn't correctly formatted (i.e. indented) either, neither by snippet insertion, nor by manual format (Ctrl-K-F). It contained "delegate{...}", maybe the formatter cannot handle this.

Try swithing from Insert spaces to Keep tabs in Tools > Options > TextEditor > C# > Tabs, it worked for me.

Related

Where are Freemarker Functions set?

I have not used Freemarker before and inherited some templates that won't compile. I have narrowed down the line that is causing problems to:
${text('Text and {0}', 'More Text')}
Where does this text() function come from? I understand that its trying to return the second string injected into the first like: "Text and More Text".
Here is the error:
FreeMarker template error:
For "...(...)" callee: Expected a method, but this has evaluated to an extended_hash (wrapper: f.t.SimpleHash):
modernizr-2.6.2.js is the only javascript imported.
Any ideas why this line is causing problems and where this function should be declared??
It can come from a few places:
From the data-model (one of the parameters you pass to Template.process)
From a shared variable, which is added to the Configuration singleton.
From an #include-d template (or from the template you are in), via #function text or #assign text = ... (or #global text = ...)
From an #import-ed template via #global text = ... (highly unlikely...)
But one potentially interesting thing is that the error says that text does exist, but it's a hash (a Map-like thing), not a callable thing. Maybe something that's also called text shadows the good text? What does ${.data_model.text('Text and {0}', 'More Text')} say?
You mention a JavaScript file. FreeMarker has nothing to do with JavaScript (and it runs on the server, inside the JVM).

Does Sublime Text 2 have the ability to region code similar to Visual Studio?

In Visual Studio you can minimize huge chunks of code using regions; they essentially just surround the code and minimize it in the window.
Does Sublime have a feature similar to this?
By default, you can select some code the go to Edit > Code Folding > Fold. There are tons of plugins that leverage the code-folding api for more options.
There's a request on the official site to "ask for features" here.
But apparently:
FYI, Jon has stated that this is not possible in the current
implementation of the editor control. Looks like we're waiting till V3
guys.
Jon being the programmer behind Sublime Text 2.
There might be a way to fake it by creating a plugin that looks for markers and removes the code region in between the markers, but it probably wouldn't look good. With the current API, it's probably your best bet!
By the way, there is some code folding in Sublime Text, if you hover your mouse next to the line number, you will see some arrows appearing when you can fold / unfold.
I ended up using custom comment tags, indented one level less than the code I want to fold. It doesn't look best, though it serves its purpose.
class Foobar {
// ...some code
// <fold
function foo() {
}
function bar() {
}
// </fold
// more code...
}
This (at the moment) folds to:
class Foobar {
// ...some code
// <fold[...]
// </fold
// more code...
}
Having a native ST2 support for this would be nice.
This looks what you are looking for. You can define tags for #region and #endregion for each language, or a generic tag for all of them.
If you are obsessed with intendation, this solution may make you uncomfortable but here it is, once upon a time while I had been writing a semi-complex jQuery plugin I've had constants, variables, private and public functions sections and foldings like so;
;(function($, undefined, window) {...
/* Consts */
var FOO = "BAR";
/* Variables */
var m_Foo = "bar";
/* Functions */
/* Public Functions */
function foo() {...}
function bar() {...}
/* Private Functions */
function _foo() {...}
function _bar() {...}
})(jQuery, window);
As you can see it is all about intendation. Sections can be folded; Consts, Variables, Functions. And also inside Functions section, Public Functions and Private Functions are both can be folded.
You can also use one line comment (//) to name your fold. So the idea underneath that is simple; ST2 thinks that the more intended lines belongs to first less-intended comment above them, like C/C++ compilers how handle brackets as own unique code blocks.
To fold the code select the code and press
ctrl + shift + [
To unfold the code put the cursor there and press
ctrl + shift + ]
I think that like myself, the OP has come to appreciate a little-known feature in VS called regions that many equate to code-folding, but is FAR more powerful and above, Dio Phung provided the answer that I wanted, and I suspect the OP wanted, but he didn't share as an answer so here it is.
The difference between "code-folding" as it's provided in Sublime Text is that it's based on code/compiler syntax while "regions" and what this plugin does, allow you infinitely more freedom, though it's a freedom that's more or less dependant on the code you're working with to begin with (deeply nested, or properly modularized).
If you are on Sublime Text 3, here is a plugin that can do it :
github.com/jamalsenouci/sublimetext-syntaxfold – Dio Phung
In languages which support 3 types of comments (e.g. PHP) I use the hashtag comment for regions, as shown in the other answers. It's also good for keeping track of what's being done
# default options
$a = 3;
$b = 'bob';
$old_code = 1;
# bugfix #130
$result = magic_function($data);
fix_stuff($result);
$old_code = $result;
Otherwise use triple slash ///, or //# etc.
In sublime text, it works like this, it shades the lines you want to collapse and presses (Control + Shift +?)
I have the most recent version of sublimetext.

VS2010 save array/collection data to a file while debugging

Is there some way to save array/list/collection data to a file while debugging in VS2010?
For example, in this code:
var addressGraphs = from a in context.Addresses
where a.CountryRegion == "Canada"
select new { a, a.Contact };
foreach(var ag in addressGraphs) {
Console.WriteLine("LastName: {0}, Addresses: {1}", ag.Contact.LastName.Trim(),
ag.Contact.Addresses.Count());
foreach(var Address in ag.Contact.Addresses) {
Console.WriteLine("...{0} {1}", Address.Street1, Address.City);
}
}
I'd like to set a breakpoint on the first 'foreach' line and then save the data in 'addressGraph' to a file.
where 'a' contains fields such as:
int addressID
string Street1
string City
<Ect.>
and 'Contact' contains fields such as:
string FirstName
string LastName
int contactID
<Ect.>
I'd like the file to contain the values of each of the fields for each item in the collection.
I don't see an obvious way to do this. Is it possible?
When your breakpoint is hit, open up the Immediate window and use Tools.LogCommandWindowOutput to dump the output to a file:
>Tools.LogCommandWindowOutput c:\temp\temp.log
?addressGraphs
>Tools.LogCommandWindowOutput /off
Note: You can use Log which is an alias for Tools.LogCommandWindowOutput
Update:
The > character is important. Also, the log alias is case sensitive.
See screenshot:
I also encoutered such a question, but in VS2013. I have to save a content of array while debugging.
For example, I need to save a content of double array named "trimmedInput". I do so:
Open QuickWatch Window from Debug menu (Ctrl+D, Q).
Put your variable in Expression and push Recalculate Button
You'll see all the values. Now you could select them all (Ctrl+A) and copy (Ctrl+C).
Paste (Ctrl+V) them in your favorite editor. Notepad, for example. And use them.
That's the simples way that I know. Without additional efforts. Hope that my description helps you!
P.S. Sorry for non English interface on screenshots. All necessary information are written in the text.
Something similar is possible with this method:
I built an extension method that I use in all of my projects that is a general and more powerful ToString() method that shows the content of any object.
I included the source code in this link:
https://rapidshare.com/files/1791655092/FormatExtensions.cs
UPDATE:
You just have to put FormatExtensions.cs in your project and change the Namespace of FormatExtensions to coincide to the base Namespace of your project. So when you are in your breakpoint you can type in your watch window:
myCustomCollection.ToStringExtended()
And copy the output wherever you want
On Visual studio Gallery search for: Object Exporter Extension.
be aware: as far as I worked with, it has a bug that block you from exporting object once in a while.
You can also call methods in the Immediate Window, and so I think your best bet would be to use an ObjectDumper object, like the one in the LINQ samples or this one, and then write something like this in the Immediate Window:
File.WriteAllText("myFileName.txt", ObjectDumper.Dump(addressGraph));
Depending on which ObjectDumper you decide to use, you may be able to customize it to suit your needs, and to be able to tell it how many levels deep you want it to dig into your object when it's dumping it.
Here's a solution that takes care of collections. It's a VS visualizer that will display the collection values in a grid while debugging as well as save to the clipboard and csv, xml and text files. I'm using it in VS2010 Ultimate. While I haven't tested it extensively, I have tried it on List and Dictionary.
http://tinyurl.com/87sf6l7
It handles the following collections:
•System.Collections classes
◦System.Collections.ArrayList
◦System.Collections.BitArray
◦System.Collections.HashTable
◦System.Collections.Queue
◦System.Collections.SortedList
◦System.Collections.Stack
◦All classes derived from System.Collections.CollectionBase
•System.Collections.Specialized classes
◦System.Collections.Specialized.HybridDictionary
◦System.Collections.Specialized.ListDictionary
◦System.Collections.Specialized.NameValueCollection
◦System.Collections.Specialized.OrderedDictionary
◦System.Collections.Specialized.StringCollection
◦System.Collections.Specialized.StringDictionary
◦All classes derived from System.Collections.Specialized.NameObjectCollectionBase
•System.Collections.Generic classes
◦System.Collections.Generic.Dictionary
◦System.Collections.Generic.List
◦System.Collections.Generic.LinkedList
◦System.Collections.Generic.Queue
◦System.Collections.Generic.SortedDictionary
◦System.Collections.Generic.SortedList
◦System.Collections.Generic.Stack
•IIS classes, as used by
◦System.Web.HttpRequest.Cookies
◦System.Web.HttpRequest.Files
◦System.Web.HttpRequest.Form
◦System.Web.HttpRequest.Headers
◦System.Web.HttpRequest.Params
◦System.Web.HttpRequest.QueryString
◦System.Web.HttpRequest.ServerVariables
◦System.Web.HttpResponse.Cookies
As well as a couple of VB6-compatible collections
In "Immediate Window" print following to get the binary dump:
byte[] myArray = { 02,01,81,00,05,F6,05,02,01,01,00,BA };
myArray
.Select(b => string.Format("{0:X2}", b))
.Aggregate((s1, s2) => s1 + s2)
This will print something like:
0201810005F60502010100BA
Change the '.Aggregate(...)' call to add blanks between bytes, or what ever you like.

VS 2010 Is possible to turn off collapsing JS code?

in VS 2010 Ultimate if You type a JS code an then press Enter, You'll notice that the 1st bracket is in the same line as e.g function header. How to turn it off ? It is very annoying for me
after pressed enter... =>
function a() {
}
I want it as:
function a()
{
}
Using braces on the same line as the function declaration is proper JavaScript coding style (see Crockford). Using braces on the same line as the opening block is recommended due to the way JavaScript inserts semicolons wherever possible. Take, for example, this code:
return
{
hello: "world"
};
JavaScript parsers will rewrite this as:
return;
{
hello: "world"
};
This has a substantially different meaning, and there is no warning to the developer that this has happened, other than incorrect behavior from their script. While function declarations are ok, since function foo(); is not valid JavaScript, and parsers will therefore not insert a semicolon there, such formatting is still strongly discouraged.
If you still want to do this, you can alter this setting: Tools - Options - Text Editor - JScript - Formatting - Place open brace on new line for functions.
Code convention aside, the option is there in Visual Studio 2010 (Premium in my case)
Tools > Options > Text Editor > JScript > Formatting > Place open brace on new line for functions [check]

Is there a shortcut to swap/reorder parameters in visual studio IDE?

I have a common issue when working with code in the IDE:
string.Concat("foo", "bar");
and I need to change it to:
string.Concat("bar", "foo");
Often I have several of these that need to be swapped at once. I would like to avoid all the typing. Is there a way to automate this? Either a shortcut or some sort of macro would be great if I knew where to start.
Edit: changed to string.Concat to show that you can't always modify the method signature. I am only looking to change the order of the params in the method call, and nothing else.
<Ctrl> + <Shift> + <t> will transpose two words, so it would work in your case. Unfortunately I don't see this working (without multiple presses) for functions with larger parameter lists...
I had a lot of code with this function:
SetInt(comboBox1.Value + 1, "paramName", ...
SetInt(comboBoxOther.Value, "paramName", ...
And I needed to swap only the first two parameters;
I ended up using some text editor with regular expression management (like Scite), and using this one saved me hours:
Find: SetInt(\([.a-z0-9]+[ + 1]*\), \("[a-z0-9]+"\)
Replace: SetInt(\2, \1

Resources