Make ReSharper reformat code according to StyleCop rule SA1206: The 'static' keyword must come before the 'other' keyword in the element declaration - resharper

I suspect I should create a pattern in ReSharper / Options / Languages / C# / Formatting Style / Type Membership Layout for this. I am currently using the default pattern and I would like some help from someone who is good at them.
I want this to be WRONG:
public new static Age Empty {
get {
return empty;
}
set {
empty = value;
}
}
And this to be right:
public static new Age Empty {
get {
return empty;
}
set {
empty = value;
}
}
In other words, I want static to come before other keywords, like new. Currently ReSharper 5.1 does it the "wrong" way.

ReSharper now has the possibility to configure the arrangement of modifiers.
Open the ReSharper options and go to Code Editing | C# | Code Style. In the Modifiers section Modifiers order you can reorder the arrangement according to your needs (see ReSharper online help: Arranging Modifiers).
To satisfy StyleCop's rule SA1206 move the static modifier above the new modifier:

It is impossible.

Related

Is it possible to change keyword for cross referencing between grammar rules/objects in Xtext?

When I want to make cross referencing between grammar rules in Xtext work, I need to use keyword name for that. E.g.:
Constant:
name=NAME_TERMINAL "=" number=Number;
ConstUsage:
constant=[Constant | NAME_TERMINAL];
Is it possible to change this word to another one (e.g. id) ? I need it e.g. in case when I have rule, which uses parameter name for something else.
you can use a custom implementation of IQualifiedNameProvider e.g. by subclassing DefaultDeclarativeQualifiedNameProvider.
public class MyDslQNP extends DefaultDeclarativeQualifiedNameProvider{
QualifiedName qualifiedName(Element e) {
Package p = (Package) e.eContainer();
return QualifiedName.create(p.getName(), e.getId());
}
}
see https://dietrich-it.de/xtext/2011/07/16/iqualifiednameproviders-in-xtext-2-0.html for the complete example

How to programmatically update .rgs files to reflect changes made in IDL files?

Is there any tool to update .rgs files to reflect change made in the IDL ?
rgs files are created by the ATL control wizzard but I can't find a way to refresh thoses files.
When we change the uuid of an interface (within the .IDL file), we are forced to changed by hand the "hard copy" values in those .rgs files. This is quiet prone to error.
I found this interesting project that intend to fill this gap but, accordingly the last comments, it didn't works any more since VC2005.
ATL CAtlModule implementation offers virtual CAtlModule::AddCommonRGSReplacements which you can override and add substitutions to remove hardcoded RGS values.
For example, my typical ATL code looks like this:
class CFooModule :
public CAtlDllModuleT<CFooModule>
{
[...]
// CAtlModule
HRESULT AddCommonRGSReplacements(IRegistrarBase* pRegistrar)
{
// Error handling omitted for code brevity
__super::AddCommonRGSReplacements(pRegistrar);
ATLASSERT(m_libid != GUID_NULL);
pRegistrar->AddReplacement(L"LIBID", _PersistHelper::StringFromIdentifier(m_libid));
pRegistrar->AddReplacement(L"FILENAME", CStringW(PathFindFileName(GetModulePath())));
pRegistrar->AddReplacement(L"DESCRIPTION", CStringW(AtlLoadString(IDS_PROJNAME)));
return S_OK;
}
In COM classes I override UpdateRegistry method to add tokens with third parameter of standard call _pAtlModule->UpdateRegistryFromResource.
As a result, many .RGS are shared between COM classes because hardcoded values are replaced with tokens. Specifically, there are no GUIDs in RGS files, e.g.:
HKCR
{
NoRemove CLSID
{
ForceRemove %CLSID% = s '%DESCRIPTION%'
{
InprocServer32 = s '%MODULE%'
{
val ThreadingModel = s 'Both'
}
val AppID = s '%APPID%'
TypeLib = s '%LIBID%'
}
}
}
I'm not able to understand how %CLSID% is replaced with the COM class CLSID in roman-r's answer. There seem to be something missing in the answer.
Alternative solution from CodeProject: Registry Map for RGS files.
This solution introduces a custom registrymap.hpp header with a DECLARE_REGISTRY_RESOURCEID_EX extension that allows you to add RGS substitution macros to your COM classes. Example:
BEGIN_REGISTRY_MAP(CClassName)
REGMAP_ENTRY("PROGID", "MyLibrary.ClassName")
REGMAP_ENTRY("VERSION", "1")
REGMAP_ENTRY("DESCRIPTION", "ClassName Class")
REGMAP_UUID ("CLSID", CLSID_ClassName)
REGMAP_UUID ("LIBID", LIBID_MyLibraryLib)
REGMAP_ENTRY("THREADING", "Apartment")
END_REGISTRY_MAP()

Adding detectable Nullable values to CsvHelper

I was wondering if CsvHelper by Josh Close has anything in the configuration I am missing to translate values to null. I am a huge fan of this library, but I always thought there should be some sort of configuration to let it know what values represent NULL in your file. An example would be a column with the value "NA", "EMPTY", "NULL", etc. I am sure I could create my own TypeConverter, but I was hoping there would be an easier option to set somewhere in a config as this tends to be fairly common with files I encounter.
Is there a configuration setting to do this relatively easily?
I found the TypeConversion in the CsvHelper.TypeConversion namespace but am not sure where to apply something like this or an example of the correct usage:
new NullableConverter(typeof(string)).ConvertFromString(new TypeConverterOptions(), "NA")
I am also using the latest version 2.2.2
Thank you!
I think some time in the last seven years and thirteen versions since this question was asked the options for doing this without a custom type map class expanded, e.g.:
csvReader.Context.TypeConverterOptionsCache.GetOptions<string>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<DateTime?>().NullValues.AddRange(new[] { "NULL", "0" });
csvReader.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.Add("0");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("1");
CsvHelper can absolutely handle nullable types. You do not need to roll your own TypeConverter if a blank column is considered null. For my examples I am assuming you are using user-defined fluent mappings.
The first thing you need to do is construct a CsvHelper.TypeConverter object for your Nullable types. Note that I'm going to use int since strings allow null values by default.
public class MyClassMap : CsvClassMap<MyClass>
{
public override CreateMap()
{
CsvHelper.TypeConversion.NullableConverter intNullableConverter = new CsvHelper.TypeConversion.NullableConverter(typeof(int?));
Map(m => m.number).Index(2).TypeConverter(intNullableConverter);
}
}
Next is setting the attribute on your CsvReader object to allow blank columns & auto-trim your fields. Personally like to do this by creating a CsvConfiguration object with all of my settings prior to constructing my CsvReader object.
CsvConfiguration csvConfig = new CsvConfiguration();
csvConfig.RegisterClassMap<MyClassMap>();
csvConfig.WillThrowOnMissingField = false;
csvConfig.TrimFields = true;
Then you can call myReader = new CsvReader(stream, csvConfig) to build the CsvReader object.
IF you need to have defined values for null such as "NA" == null then you will need to roll your own CsvHelper.TypeConversion class. I recommend that you extend the NullableConverter class to do this and override both the constructor and ConvertFromString method. Using blank values as null is really your best bet though.
I used "ConvertUsing"...
public class RecordMap : CsvHelper.Configuration.ClassMap<Record>
{
public RecordMap()
{
AutoMap();
Map(m => m.TransactionDate).ConvertUsing( NullDateTimeParser );
Map(m => m.DepositDate).ConvertUsing( NullDateTimeParser );
}
public DateTime? NullDateTimeParser(IReaderRow row)
{
//"CurrentIndex" is a bit of a misnomer here - it's the index of the LAST GetField call so we need to +1
//https://github.com/JoshClose/CsvHelper/issues/1168
var rawValue = row.GetField(row.Context.CurrentIndex+1);
if (rawValue == "NULL")
return null;
else
return DateTime.Parse(rawValue);
}
}

Resharper Code Pattern for IDisposable not inside using

I'd like to know how to build a Resharper (6.1) code pattern to search and replace the following issues:
var cmd = new SqlCommand();
cmd.ExecuteNonQuery();
and turn it into this:
using (var cmd = new SqlCommand())
{
cmd.ExecuteNotQuery();
}
and:
StreamReader reader = new StreamReader("myfile.txt");
string line = reader.Read();
Console.WriteLine(line);
becomes:
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
EDIT: Thanks for the answers, but I'm looking for anything that implements IDisposable
Search pattern:
var $cmd$ = $sqlcommand$;
$cmd$.ExecuteNonQuery();
Replace pattern:
using (var $cmd$ = $sqlcommand$)
{
$cmd$.ExecuteNonQuery();
}
where cmd = identifier
and sqlcommand = expression of type System.Data.SqlClient.SqlCommand
It looks like what you're really after is an inspection mechanism that goes off looking for IDisposable objects and ensures they are disposed. If that's the case, I doubt custom patterns would be the right approach - after all, what if you do call Dispose() a few lines later?
One way to implement this is by using the ReSharper SDK. In fact, one of the examples the SDK comes with is a PowerToy which implements IDisposable on a particular class, so you could take that code as a foundation for possible analysis of usage.
Use the Search with Pattern tool under the ReSharper | Find menu.
In the Search pattern make sure you have C# selected and enter the code you're searching for in the box. Click the Replace button in the top-right, and enter the code you want to replace it with in the Replace pattern box.
You can save the search and replace pattern and R# will use it for subsequent code analysis should you so desire. You can also add additional patterns in R# Options under Code Inspection | Custom Patterns.

Can I change the way ReSharper generates properties?

Is it possible to change the way that Resharper formats properties?
I don't like:
public string Foo
{
get
{
return bar;
}
set
{
bar = value;
}
}
I like:
public string Foo
{
get { return bar; }
set { bar = value; }
}
You sure can, just go to Resharper > Options > Languages > C# > Formatting Style
and tick "place simple property/indexer/event declaration on a single line"
Updated for Resharper 8.2:
Resharper > Options > Code Editing > C# > Formatting Style > Line Breaks and Wrapping > Other > Place simple property/indexer/event declaration on single line
If you're using the code expansion template to produce a property, you can update the template in the ReSharper Settings at: ReSharper >> Live Templates >> Predefined Templates >> C# >> prop.
If you're referring to the code produced by refactoring commands, I don't believe it's configurable. However, you may be able to run Code Cleanup and have it reformat.

Resources