Razor (.cshtml) editor code block format settings - visual-studio

I am running Visual Studio 16.8.1, when editing a Razor .cshtml file and applying a reformat (CTRL+K+D) the editor moves braces and elements in a code block starting with #
For example if I have the code:
#{
Layout = "_Layout";
ViewData["Title"] = "My Page";
}
#if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>#Model.RequestId</code>
</p>
}
And I reformat the file by pressing CTRL+K+D it will move the fist line to the same line as the #{ and move the closing brace right after the last element like:
#{ Layout = "_Layout";
ViewData["Title"] = "My Page"; }
#if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>#Model.RequestId</code>
</p>}
Is there a way to control when VS inserts or removes new lines and indenting before and after the braces so it formats like the first example? I have searched through the Options->Text Editor->{editor}->Formatting groups and can't find anything that seems to control this behavior, is this a bug in the VS editor or am I just missing the setting somewhere?

This looks like it was fixed in Visual Studio Version 16.8.2

Related

Visual Studio "Toggle Line Comment" Not Adding // To Already Commented Out Code

I want to comment out a block of Scss code with single line comments (multiline comment will not work b/c I need it to not be processed). In most editors you can select a block of code, and then use a shortcut to simply add // to the beginning of every line. The problem is that in Visual Studio 19 (version 16.7.7), the "Toggle Line Comment" (ctrl+k, ctrl+/) tries to be smart and does not add an extra // to the beginning of a line that already begins with a comment. That's a problem b/c when I toggle the comments off, it then removes comments that were originally there.
This seems really silly that it works this way. Is there some setting or way to change this behavior?
You can use the following command with my Visual Commander extension to add "//" to every selected line:
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
EnvDTE.TextDocument doc = DTE.ActiveDocument.Object("TextDocument") as EnvDTE.TextDocument;
EnvDTE.EditPoint p = doc.CreateEditPoint();
for (int i = ts.TopLine; i <= ts.BottomLine; ++i)
{
p.MoveToLineAndOffset(i, 1);
p.Insert("//");
}
}
The shortcut you need is Ctrl+Shift+/
It comments selected lines by adding // before the first character. Toggles back if pressed again.

Is there a shortcut in VS to reformat a block of code to one line?

I'd like to be able to take this code block
var uVacationLandLubbers = new UserAttribute {
Name = "Land Lubbers",
Project = pVacation,
SystemUserAttribute = context.SystemUserAttributes.Single(x => x.Name == "Yes/No")
};
and reformat it to
var uVacationLandLubbers = new UserAttribute { Name = "Land Lubbers", Project = pVacation, SystemUserAttribute = context.SystemUserAttributes.Single(x => x.Name == "Yes/No") };
Is there a VS/Resharper/Other way of doing this?
This solution would not fully satisy your requirements, but help you considerably.
In Visual Studio, navigate to Tools -> Options.
In Options window, on the left select the language of your choice, say C#. Under C#, select Formatting -> New Lines. Once you select New Lines, a set of rules would be displayed on the right side, uncheck the following rules:
Place open brace on new line for types
Place open brace on new line for anonymous methods
Place open brace on new line for anonymous types
Place open brace on new line for object initializers
Place memebers in object initializers in new line
Place memebers in anonymous types in new line
Note: While unchecking a preview of the rule would be displayed which would help you to view the changes.
Once you do these settings, use this shortcut Ctrl + K + D to format the document.
Use shortcut Ctrl + K + D to format the document code

How to indent the first line of a paragraph in CKEditor

I'm using CKEditor and I want to indent just the first line of the paragraph. What I've done before is click "Source" and edit the <p> style to include text-indent:12.7mm;, but when I click "Source" again to go back to the normal editor, my changes are gone and I have no idea why.
My preference would be to create a custom toolbar button, but I'm not sure how to do so or where to edit so that clicking a custom button would edit the <p> with the style attribute I want it to have.
Depending on which version of CKE you use, your changes most likely disappear because ether the style attribute or the text-indent style is not allowed in the content. This is due to the Allowed Content Filter feature of CKEditor, read more here: http://docs.ckeditor.com/#!/guide/dev_advanced_content_filter
Like Ervald said in the comments, you can also use CSS to do this without adding the code manually - however, your targeting options are limited. Either you have to target all paragraphs or add an id or class property to your paragraph(s) and target that. Or if you use a selector like :first-child you are restricted to always having the first element indented only (which might be what you want, I don't know :D).
To use CSS like that, you have to add the relevant code to contents.css, which is the CSS file used in the Editor contents and also you have to include it wherever you output the Editor contents.
In my opinion the best solution would indeed be making a plugin that places an icon on the toolbar and that button, when clicked, would add or remove a class like "indentMePlease" to the currently active paragraph. Developing said plugin is quite simple and well documented, see the excellent example at http://docs.ckeditor.com/#!/guide/plugin_sdk_sample_1 - if you need more info or have questions about that, ask in the comments :)
If you do do that, you again need to add the "indentMePlease" style implementation in contents.css and the output page.
I've got a way to indent the first line without using style, because I'm using iReport to generate automatic reports. Jasper does not understand styles. So I assign by jQuery an onkeydown method to the main iframe of CKEditor 4.6 and I check the TAB and Shift key to do and undo the first line indentation.
// TAB
$(document).ready(function(){
startTab();
});
function startTab() {
setTimeout(function(){
var $iframe_document;
var $iframe;
$iframe_document = $('.cke_wysiwyg_frame').contents();
$iframe = $iframe_document.find('body');
$iframe.keydown(function(e){
event_onkeydown(e);
});
},300);
}
function event_onkeydown(event){
if(event.keyCode===9) { // key tab
event.preventDefault();
setTimeout(function(){
var editor = CKEDITOR.instances['editor1'], //get your CKEDITOR instance here
range = editor.getSelection().getRanges()[0],
startNode = range.startContainer,
element = startNode.$,
parent;
if(element.parentNode.tagName != 'BODY') // If you take an inner element of the paragraph, get the parentNode (P)
parent = element.parentNode;
else // If it takes BODY as parentNode, it updates the inner element
parent = element;
if(event.shiftKey) { // reverse tab
var res = parent.innerHTML.toString().split(' ');
var aux = [];
var count_space = 0;
for(var i=0;i<res.length;i++) {
// console.log(res[i]);
if(res[i] == "")
count_space++;
if(count_space > 8 || res[i] != "") {
if(!count_space > 8)
count_space = 9;
aux.push(res[i]);
}
}
parent.innerHTML = aux.join(' ');
}
else { // tab
var spaces = " ";
parent.innerHTML = spaces + parent.innerHTML;
}
},200);
}
}

Using in Visual Studio 10 ASP.NET MVC3

I am using Visual Studio 2010 Professional edition for developing an application in ASP.NET MVC3 framework.
I have come across a situation where I need to have a literal space character, usually accomplished by adding (something similar) in HTML.
However, program gives a run-time error.
How do I overcome this?
Code:
<div class="week">
#for (int i = 0; i < 7; i++)
{
<div class="day">
#weekStartDay.ToString().Substring(0, 3)
</div>
weekStartDay = (DayOfWeek)(((int)weekStartDay + 1) % 7);
}
</div>
Error:
c:***\Documents\Visual Studio 2010\Projects\MvcApplication2\MvcApplication2\Views\Home\Calendar.cshtml(22): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Change your code to
<div class="week">
#for (int i = 0; i < 7; i++)
{
<div class="day">
#weekStartDay.ToString().Substring(0, 3)
</div>
#:
weekStartDay = (DayOfWeek)(((int)weekStartDay + 1) % 7);
}
</div>
#: tells the Razor view engine is plain text
If you look at this code in Visual Studio 2012 you will see the exact same error message. The is underlined and the tooltip shows this message.
The problem is that you are inside a code block: #{ }. If you want to output plain text you have to wrap it inside an HTML element like this:
<span> </span>
or you have to use
#:
simply use add #: before &nbsp
for every list item in your dropdown list you have to replace your list item value by .Replace(" ", "\u00A0")
eg:
in your controller
var Listval =(from u in yourtablename select u.YourColumnName.Replace(" ", "\u00A0")).Distinct().ToList();
ViewBag.DDlVals= new SelectList(Listval);
in your View page
#Html.DropDownListFor(model => model.YourColumnName, (SelectList)ViewBag.DDlVals, "--Select--", new { #class = "form-control" })

Bizarre hidden character in MVC3 Razor loop

I have a loop
<ul id="news-list" class="thumbobs-list">
#foreach (var item in Model.News) {
#Html.Partial("RenderNews/" + item.TypeString, item)
}
</ul>
that uses partials like this
#model Web.Models.DataModel.NewsItem
#{ Layout = null; }
<li class="news-item #Model.TypeString.ToLower()" id="id-#Model.Id">
<h3 class="headline">
Example News headline.
</h3>
<p class="timestamp">#Model.TimeString</p>
</li>
that works great
but when i went to style with css i encountered a hidden whitespace character that is causing an issue
in front of each partial a space, a U+FEFF, and another space causing issues with the design.
has anyone ever seen this?
You have discovered the BOM, Byte Order Mark. It's stored as the first bytes in text files to indicate the encoding.
http://en.wikipedia.org/wiki/Byte_order_mark
[EDIT]
You can open a file with Notepad and "Save As..." as ANSI. This removes the BOM (and the encoding).
// reading a text file as binary will include the BOM flag
FileStream FS = new FileStream(MapPath(#"~\Text\TestUTF8.txt"), FileMode.Open);
byte[] Data = new byte[100];
FS.Read(Data, 0, 100); // BOM is in the data
FS.Close();
// get rid of the BOM
String String1 = System.Text.Encoding.UTF8.GetString(Data);
// reading a text file as text will automatically handle it.
String String2 = File.ReadAllText(MapPath(#"~\Text\TestUTF8.txt"));
Try copying the text out and create a new partial view. Paste it into notepad and rebuild your partial to rule out this character being hidden in your partial or simply load it on the vs binary editor and look for that character. Right click and open with... Then choose binary editor.

Resources