Remove empty line after Replace in Visual Studio - c#

I have many classes and these classes have properties with attribute [WordColumn("Xxx", 1, typeof(string))]. E.g:
[JsonObject("Сотрудник")]
public class Person
{
[JsonProperty("firstName")]
[WordColumn("Имя", 1, typeof(string))]
public string FirstName { get; set; }
[JsonProperty("lastName")]
[WordColumn("Фамилия", 1)]
public string LastName { get; set; }
// ... other properties are omitted for the brevity
}
What I want is a regular expression that can delete all text that starts from [WordColumn and ends with )] and delete empty line which can be left after deletion.
I've tried to write the following regex and it finds all WordColumn:
\[WordColumn.*?\]
However, when I use it in Visual Studio with Find and Replace, then Replace in Files, tick Use Regular Expression, I leave Replace empty. Then after it leaves empty spaces after Replaces:
[JsonObject("Сотрудник")]
public class Person
{
[JsonProperty("firstName")]
// <- here the empty line remains
public string FirstName { get; set; }
[JsonProperty("lastName")]
// <- here the empty line remains
public string LastName { get; set; }
}
I am doing this in Visual Studio 2019 with Replace button.
Is it possible to remove this empty lines after [WordColumn...] was replaced?

Use the regex from #AndersonPimentel comment but with a small change (add ^[\t ]* to remove spaces)
^[\t ]*\[WordColumn.*?\]\r?\n

The proper regular expression for both, Visual Studio for Windows and for Mac, would be
\[WordColumn.*?\]\s*

Related

Editorconfig indent C# record properties

I am trying to use editorconfig + ReSharper/cleanupcode.exe to format my C# code (using this cool precommit hook)
The problem I am having is that cleanupcode refuses to indent properties in a record
namespace MyNameSpace
{
public record MyRecord
{
// I would like these to be indented
public int Property1 { get; init; }
public int Property2 { get; init; }
}
public class MyClass
{
public int Property1 { get; init; }
public int Property2 { get; init; }
}
}
Here is my editorconfig file
root = true
# top-most EditorConfig file
# Don't use tabs for indentation.
[*]
indent_style = space
# ReSharper properties
resharper_place_accessor_attribute_on_same_line = true
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
csharp_indent_block_contents = true
csharp_max_line_length = 150
Does anyone know what setting/rule I need to set to make editorconfig/ReSharper indent these record properties?
I only tested your settings in Rider and the properties are getting highlighted as you'd like to.
The mentioned tool is pretty old (v2019.3.1, see here) - at that time, records didn't even exist in C#.
Try it with a newer version: https://www.jetbrains.com/help/resharper/CleanupCode.html

Get the value of the property of the object whose name begins with a number

I'm fetching data from website that returns me an object in a string like this:
{
index: 1,
commentNumber: 20,
feedComments: {
3465665: {
text: "I do not agree",
likeRatio: 0
},
6169801: {
text: "Hello",
likeRatio: 12
},
7206201: {
text: "Great job!",
likeRatio: 5
}
}
}
I want to work with this as an object, that's pretty easy to do, I'll just do this:
string objectString = GetData(); // Artificial GetData() method
dynamic data = JObject.Parse(objectString);
And now I can easily get all properties I want from this object using dynamic
The problem is pretty obvious now, I want to get properties, whose name starts with number (the object data structure I fetch is just designed that way). But property/field names you get from object cannot begin with a number.
int commentNumber = data.commentNumber; // Works fine
string commentText = data.feedComments.3465665.text; // Obviously won't compile
Is there any way to do this?
Note that I want to work with data I fetch as it was an object, I know I get get the comment text right from the string that GetData() method returns using some regex or something, but that's something I want to avoid.
You should really be parsing the JSON into concrete C# classes. Dynamic is slow and vulnerable to runtime errors that are hard to detect.
The comments will go into a Dictionary. For example:
public class Root
{
public int Index { get; set; }
public int CommentNumber { get; set; }
public Dictionary<long, FeedComment> FeedComments { get; set; }
}
public class FeedComment
{
public string Text { get; set; }
public int LikeRatio { get; set; }
}
And deserialise like this:
var result = JsonConvert.DeserializeObject<Root>(objectString);
Now you can access the comments very easily:
var commentText = result.FeedComments[3465665].Text

How to find all class properties that start with a lower case letter

In Visual Studio 2019, how do I Find (Ctrl + F, using Regular Expressions option) all class properties that start with a lower case?
public decimal FirstName { get; set; }
public decimal lastName { get; set; }
In sample above, I would only want lastName to be highlighted
The following selects everything except what I'm looking for...
public .*?\s[a-z]?
Not really how I want to solve it though.
Based just on the code snippet you provided, you may try:
public \S+ [a-z]\w+ \{.*?\}
If the content inside the brackets might span multiple lines, then you can enable dot all mode.
Demo
try this one :
(\b[a-z]\w+\b)(?=\s{.*})
demo

XML special character escape not working

I'm trying to use the "!" special character in my C# class but my xml doesn't result in this "!MovieName" instead it results in " _x0021_MovieName "
I have tried to &#x21 ; and also use CDATA but they dont work. They turn into a string of more x0021 (an example) types for each special character.
public class Movie
{
[XmlElement("!MovieName")]
public string Title
{ get; set; }
[XmlElement("MovieRating")]
public float Rating
{ get; set; }
[XmlElement("MovieReleaseDate")]
public DateTime ReleaseDate
{ get; set; }
}
An XML element name cannot begin with a ! which is why it's being replaced.
You should be able to start with:
Any letter
Underscore _
Colon :
See the XML Spec for more information, or more specifically the section on NameStartChar.
It's illegal to have a ! as the opening character of a tag in XML. You'll just have to use a different naming strategy.

String comparison assertion failing when it looks like it should pass

I have a test for checking that an item is serialized correctly
public interface IMyJsIdentity
{
string Forename { get; }
string Surname { get; }
string Guid { get; }
}
public class MyIdentity : IMyJsIdentity
{
public string Forename { get; set; }
public string Surname { get; set; }
public string Guid { get; set; }
public int Id { get; set; }
}
[Fact]
public void SerialiseCorrectly()
{
// Arrange
MyIdentity identity = new MyIdentity()
{
Forename = "forename",
Surname = "surname",
Guid = "abcdefghijk"
};
// Act
string result = JsonConvert.SerializeObject(
identity,
new JsonSerializerSettings()
{
ContractResolver = new InterfaceContractResolver(typeof(IMyJsIdentity))
});
// Assert
result.Should().Be(
"{{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}}"
);
}
However I get the following error on the test failure
Xunit.Sdk.AssertException: Expected string to be
"{{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}}" with a length of 66, but
"{{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}}" has a length of 64.
There's clearly something special that Json.net is doing to the string but I can't figure out what.
Weirdly this passes
result.Should().Be(
String.Format("{{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}}")
);
I guess it's not a big deal but I'd like to know why.
I just tested and the value of result is:
{"Forename":"forename","Surname":"surname","Guid":"abcdefghijk","Id":0}
Which will naturally fail against your expected string of:
"{{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}}"
Using double curly braces is an escape sequence only for format strings used in the String.Format method so that you may include a single brace. From the Composite Formatting MSDN page:
Opening and closing braces are interpreted as starting and ending a
format item. Consequently, you must use an escape sequence to display
a literal opening brace or closing brace. Specify two opening braces
("{{") in the fixed text to display one opening brace ("{"), or two
closing braces ("}}") to display one closing brace ("}").
If you aren't using String.Format, then the double brace will be interpreted literally as two braces as per the C# Specification 2.4.4.5 since it is not an escape character for string literals.
The resultant error message is confusing. I'm not sure if this is because how the debugger is reporting it to the GUI, or an error with how they are formatting their error message (perhaps they are overly aggressive escaping braces for output), or what.
If you change your test to be:
result.Should().Be(
"{\"Forename\":\"forename\",\"Surname\":\"surname\",\"Guid\":\"abcdefghijk\"}"
);
Then it will pass I suspect. This is backed up by your additional test using the String.Format call which changes your double braces to single braces. Now, if you intended to have double wrapping braces around your JSON, that's another issue entirely, but I suspect that that isn't your intent.

Categories

Resources