Resharper Intellisense Auto Import - c#

There is a neat little feature in the Resharper Intellisense where it suggests items which are in a namespace you haven't imported yet.
e.g. if you type in StreamReader the Intellisense is showing me the item StreamReader (in System.IO) and if I press enter it is importing the namespace and everything is fine.
But it seems like this feature is just working for System types and not types you have written yourself.
consider the following example:
namespace Test
{
internal class Program
{
internal static void Main()
{
}
}
}
namespace Test.Util
{
internal class Helper
{
}
}
Let's say you want to use your Helper-class in the Main-method. While you are writing Helper you won't get an entry in the intellisense drop down menu like in the StreamReader example. When you exit the intellisense drop down you will get the import message Import 'Test.Util.Helper' and all other references in the file where you can import all missing references.
Is there any way to extend this 'auto import'-feature to show my self-written classes in the intellisense drop down or is this just something I'll have to live with

You can always use import-completion mode when ordinary completion doesn't suggest import items for some reason. It's invoked by Ctrl+Alt+Space.
In your sample, if you write "Hel" and invoke Ctrl+Alt+Space, the item will be auto-imported.

Jetbrains support:
We fixed such issue in ReSharper 9.1 branch and the fix will be
available after ReSharper 9.1 release. Unfortunately, we do not have
exact date of the release.

Related

C# code expansion/injection in compile time

I'm looking for a way to expand/inject code at compile time,
something like templates/macros/snippets...
Let's say I wrote this code in a lot of places in my application:
[JsonObject("MyProperty")]
private string MyPropertyJson { get; set; }
public object MyProperty { get; set; }
The MyPropertyJson property is used for EF mapping purposes only so I save the value is a JSON string in DB but for class users, they only know about MyProperty property.
What I want to do is, at compile time, MyPropertyJson to be expanded to this:
private string MyPropertyJson
{
get
{
return JsonConvert.SerializeObject(MyProperty);
}
set
{
MyProperty = JsonConvert.DeserializeObject(value);
}
}
I want this to be done in the output binaries only without affecting the source code.
I know about Unity, PostSharp, Aspect-Injector, etc.. but they don't achieve what I want because by using them, I have to use some reflection to find & manipulate MyProperty but I want to expand it exactly like it's been written in the same class with access to all class internals.
It's exactly like code snippets but to be expanded during compilation phase.
A solution that doesn't cost anything extra and is supported within Visual Studio is T4 aka Text Templates. However, it does require you install the VS SDK (eg, 2015) and Modeling SDK (eg, 2015) of the version of VS that you use.
For my base class libraries, I end up dedicating an assembly for utils to use in the T4 code I write in production code. I use it in places like rolling out read/writes for primitives in IO code (eg, .TT and .CS). Although you don't have to do this if you don't need much/complex compile time code gen.
I was able to achieve my requirement by writing a BeforeBuild msbuild target to call an external console app which I've developed to:
Copy source files that will be rewritten to a temp folder
Rewrite the source code in the temp files
Added conditional Compile tag to the .csproj file to include manipulated source files instead of the original ones
It works like a charm :)
I'm working on a generic engine for this task and will commit it to github once finished.
The is a way to kind of get what you want.
Using implicit operators
That would need to create your own json object class for example, then add these:
class JsonObject {
public object obj;
public static implicit operator string(JsonObject target) {
return Json.SerializeObject(target.obj);
}
}
But that won't really do what you really wanted. Almost the same as creating a new class and add functions.

How do I make my own method similar to String.Format using Composite Formatting in C#

I like how String.Format uses arguments to inject variables in to the string it is formatting. This is called Composite Formating and is discussed by MSDN here.
I want this functionality with my logging facade:
string foo = "fancy";
string bar = "message";
log.Debug("My {0} log {1}.", foo, bar)
My ILoggerFacade has the following method signature:
void Debug<T>(T message, params Object[] args);
And, I know I can implement this quite simply:
ILog m_Log = \\some logging implementation
public void Debug<T>(T message, params Object[] args)
{
m_Log.Debug(String.Format(message, args));
}
However, in Visual Studio I don't get the fancy highlighting of the {0}, {1}, ... arguments:
I guess it is ReSharper who is resposible for them, and it seems like it is just ignoring the formatting arguments and giving no "intellisense" help. This isn't good since the other developers who will be using the facade will be expecting this.
How do I get argument highlighting and "intellisense" for custom formatted methods similar to how these work:
Console.WriteLine(...)
String.Format(...)
etc...
Any help would be appreciated.
Check out ReSharpers External Annotations. Specifically, you want to use StringFormatMethodAttribute for this.
To use the External Annotations there are actually 3 methods. Two that it spells out, and one that you have to read between the lines to see.
Reference "JetBrains.Annotations.dll". I would recommend against this one. I don't like the idea of copying the DLL, or having to reference the ReSharper install directory. This could cause issues if you upgrade or re-install.
Copying and pasting attribute declarations into your solution. I'd recommend this as it gives you more control. Additionally, you can get rid of ReSharper (why would anyone do this? Stranger things have happened, I guess.), and still provide this feature to anyone that consumes your library. There are step by step instructions on how to do this in the first link.
Create an XML file, similar to what it uses for for the .NET Assemblies. I did this for the Silverlight Unit Test Framework. ReSharper does not recognize these tests by default.
To do this
Create a file name <assembly>.xml and put it in "ReSharper\vXX\Bin\ExternalAnnotations".
Add a root element "<assembly name="<assembly>">
Now add <member> elements for each member that you want to give an attribute.
I do not recommend doing this for your own code. However, if you have an assembly that you want to have this functionality, but cannot edit, this is the way to do it. This will only apply on your machine and each developer that uses the assembly will need to copy the xml file.

Most efficient way to move an inline class, interface, or enum to it's own file in Visual Studio

Sometimes when I'm developing I may prefer to quickly inline classes, interfaces and/or enums when I'm building a fresh design or from within a test fixture. However, I find it inconvenient to interrupt my thought process to create new code files, copy and paste the class/interface/enum written inline to the new file, and all the time it takes to navigate between them.
I'm looking for an extension, macro, or hidden shortcut combo that will automatically create a file for the highlighted or selected inline class/interface/enum, and, if possible, copy the using list so that it can be built (but remove & sort will clean it up later).
I'm open to extensions, macros, or hidden shortcut keys. Suggestions?
Edit #1: ReSharper looks awesome, yes, and it appears to have exactly what I need, but I would like to find a free solution, if it exists, that didn't push me back $200.
Edit #2: After your helpful input, I'm pushing for my dev team to all run the ReSharper trial, and re-evaluate in a few weeks if the value-add is worth it. We want keep our extension use consistent, so I'm hoping we all find it equally worthwhile.
Example: I want to turn this (IExample.cs):
using System.Linq;
public interface IExample
{
}
public class Example : IExample
{
}
public enum ExampleType
{
}
...into these:
IExample.cs:
using System.Linq;
public interface IExample
{
}
Example.cs
using System.Linq;
public class Example : IExample
{
}
ExampleType.cs
using System.Linq;
public enum ExampleType
{
}
The built in refactoring tools do not have a simple way to extract a class to its own file, so the simplest thing to do if you do not have a refactoring tool like Resharper or Refactor! Pro that do have it is to:
Copy the class to memory.
Add a new file with the class name.
Paste the class to the new file.
ReSharper offers the feature Move to another file to match type name, the ALT+Enter shortcut makes your work faster.
Devexpress Refactor!pro can be your solution....in example you posted, refactor! Pro shows a quick action menu at the bottom of the class name that you want to move.
In this Actionmenu there s the "Move to file" option that' s all you need....
EDIT:
Apparently, this method does move the type to its own file but still keeps the relationship with the previous class, so it won't actually change anything other than generate a seperate file. The type will still be nested in the same way.
This is a pretty old question and I just encountered the same issue.
In Visual Studio 2019 (and probably in 2017 as well, though I did not check),
you can select the entire class -> right click -> Quick Actions and Refactoring -> Move Type to its own file.
It correct all references to said type, too.
Very handy!

Using ExcludeFromCodeCoverageAttribute breaks XML Comment

Im using Visual Studio 2010 with c#.
I'm using XML documentation in my project and successfully added comments.
Successfully means there are noch compilerwarnings about missing XML comments.
Then I checked the codevoverage for my project and started to exclude some files from codecoverage calculation with System.Diagnostics.CodeAnalysis.[ExcludeFromCodeCoverageAttribute]
I did it in the following way:
...
using System.Diagnostics.CodeAnalysis;
namespace MyAppp
{
[ExcludeFromCodeCoverageAttribute]
/// <summary>My comment</summary>
public partial class FDB_PolicyGruppen : Form
{ ...
}
}
The problem is, as soon as I put [ExcludeFromCodeCoverageAttribute] before a comment, I receive the warnings
CS1591: Missing XML comment for publicly visible type or member
or
CS1587 XML comment is not placed on a valid language element.
Hmm that sounds like a bug in whatever you are using to measure code coverage or you have made a copy and paste error hwne juggling things about, i can see how positioning of the comments might affect something that is looking for comments but something measuring code coverage shouldn't even notice comments wherever they happen to be.

Can you use the same Enum in multiple entities in Linq-to-SQL?

In my persistence layer, I've declared a load of Enums to represent tables containing reference data (i.e. data never changes).
In Linq2SQL, I am able to set the type of an entity property to an enum type and all is well, but as soon as I set a second entity's property to use the same enum type, the Code Generator (MSLinqToSQLGenerator) start generating an empty code file.
I assume that MSLinqToSQLGenerator is quietly crashing. The question is why, and are there any work-arounds? Anyone else experienced this problem?
Is your enum by any chance in a file named the same as the dbml? There is a bug in 3.5 (fixed in 4.0) where conflicts cause an empty file. Oddly, usually moving the using directives (and right-click; run custom tool) fixes it.
So if you have "foo.dbml" and your own "foo.cs" (in the same folder) with:
using System;
namespace MyNamespace {
}
it will break (generate an empty foo.designer.cs). If you have:
namespace MyNamespace {
using System;
}
it will work. I'm not kidding. Likewise, renaming "foo.cs" to "bar.cs" (and right-click, run custom tool) will fix it.
Oddly, I've discovered that this behavior only occured with an Enum named "GrantType". As soon as changed the name of the enum, the generator started working again.

Categories

Resources