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
Related
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*
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
i need a config file for my applications and i've looked through internet without really finding what I want, I want to set my config to a var and use it like config.somethingInTheConfig.
I tried some things but it didn't work,
the config file :
{
"id": 00,
"somethings": true,
"yes": "idkjustsomething"
}
the Config class :
class Config
{
public static int id { get; set; }
public static bool somethings { get; set; }
public static string yes { get; set; }
}
Code to read it
using (StreamReader streamReader = new StreamReader("config.json"))
{
string json = streamReader.ReadToEnd();
Config config = JsonConvert.DeserializeObject<Config>(json);
Console.WriteLine(config.id);
}
I want it to show the id in the config in the console but it doesn't work nd gives me an error, anyone could help ?
The properties are marked static.
JsonConvert will not be able to read values into the static properties.
And since you are not defining values for them at design time, the properties will be set to their default values unless you manually change them.
I have an ASP.NET Core project using ASP.NET Identity. Some classes cannot be exported since their properties contain attributes from System.ComponentModel.DataAnnotations. If I ignore such properties, everything works fine.
Example class:
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Since I don't want to strip out these attributes, what is the recommended course of action?
[assembly: TsGlobal(
CamelCaseForMethods = true,
CamelCaseForProperties = true,
GenerateDocumentation = true,
UseModules = true,
DiscardNamespacesWhenUsingModules = true)]
namespace X
{
public static class ReinforcedTypingsConfiguration
{
public static void Configure(ConfigurationBuilder builder)
{
builder
.ExportAsInterface<LoginViewModel>()
.AutoI(false)
.WithProperty(x => x.RememberMe)
;
}
}
}
Other than that, it seems that UseModules does the opposite of what I want it to do. When set to true, the generated ts file doesn't contain any modules. When set to false, I get module in my ts files.
Also, when dividing types among files, I get strange folder names on mac that contain \ for every . in my namespace. Can I just flatten out the structure? And completely ignore backend namespaces?
In the above configuration (and I use file splitting) I get the annoying error message error MSB3552: Resource file "**/*.resx" cannot be found..
Upgrade to 1.4.2 to fix this issue.
From Microsoft MVC doc, related to Authoring Tag Helpers, I can read this:
using System;
namespace AuthoringTagHelpers.Models
{
public class WebsiteContext
{
public Version Version { get; set; }
public int CopyrightYear { get; set; }
public bool Approved { get; set; }
public int TagsToShow { get; set; }
}
}
and this:
using System;
using AuthoringTagHelpers.Models;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AuthoringTagHelpers.TagHelpers
{
public class WebsiteInformationTagHelper : TagHelper
{
public WebsiteContext Info { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetHtmlContent(
$#"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
}
}
I never saw this kind of code before, where public WebsiteContext Info { get; set; } can automagically instantiate an object???
How it works? Is there any documentation on it?
The answer is in the document you linked:
Note
In the Razor markup shown below:
<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1638,
Approved = true,
TagsToShow = 131 }" />
Razor knows the info attribute is a class, not a string, and you want to write C# code. Any non-string tag helper attribute should be written without the # character.
The tag helper itself doesn't know how to instantiate the instance. You have to do it manually in the Razor markup or set it to a default value in the property declaration or class constructor in order for it to be non-null. Here is an example of setting the instance in the property declaration.
public WebsiteContext { get; set; } = new WebSiteContext
{
Version = new Version(1, 3),
CopyrightYear = 1638,
Approved = true,
TagsToShow = 131
};
public WebsiteContext Info { get; set; } is not instantiating anything here. If you call the following code:
var websiteInformationTagHelper = new WebsiteInformationTagHelper();
then websiteInformationTagHelper.Info will be equal to null
Note, that it is now possible in c# to assign default values like the following which is a little bit different than what you are wondering about:
public WebsiteContext Info { get; set; } = new WebsiteContext()
Not automatically, but yes. The get and set keywords are shorthand for methods that are called after the property is accessed (get) or assigned to (set). You can add a body with a regular code block:
get { return _backingField; }
set { _backingField = value; }
The value keyword represents the value being assigned to the property and you can do most things in those blocks, same as any method, including instantiating an object.
Microsoft documentation - Auto implemented properties:
learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
If you're referring to instantiating the parent object, that I don't believe makes sense.