C# Visual Studio 2013 suppress 'Class is never instantiated' - c#

I have a web api project which accepts HttpPost communications.
The controller's methods always accepting a single validated object.
For example:
public sealed class NumbersRequest
{
[NumberOne]
public string Number1 { get; set; }
[NumberTwo]
public string Number2 { get; set; }
}
Since I never declare NumbersRequest req = new NumbersRequest() and they only serve as a request object, Im getting the
class is never instantiated
How can I suppress the warning? (its more like a green underline..)
Maybe something with annontations?
Thanks.

This looks like a ReSharper warning and as such you can ask ReSharper to be silent about these things.
You can either configure ReSharper to stop complaining about this overall, you do this simply by hitting Alt+Enter on the squiggly in question and use the bottom menu item that usually allows you to configure the inspection severity.
You can opt to save this in your global settings, which means it will affect every project you open from now on, or you can save it to a team-shared settings file which you can then check into source control alongside your project, to make it only count for this one solution.
Now, if you want to keep the warning overall but ask it to stop complaining about one or more particular types, methods, properties or the likes, you can use the attributes that ReSharper provides.
You have several ways of bringing these attributes into your project:
Add a reference to the Nuget package "JetBrains ReSharper annotations"
Use the options dialog for ReSharper and find the page where it allows you to grab a copy of the source for those attributes onto the clipboard, then simply paste this into a file in your project.
Define just the one or two attributes you want, even in your own namespace (which you then have to tell ReSharper about)
The recommended way is option 1, use the nuget package.
Assuming you now have the attributes available you can use either PublicAPIAttribute or the UsedImplicitlyAttribute.
Either one should suffice but they may have different connotations. Since you're flagging objects being transferred to or from clients I would go with the PublicAPIAttribute first.
Since you say in a comment that the PublicAPIAttribute didn't work but UsedImplicitlyAttribute did then I guess they do have different meanings.

Related

C# attributes used for information or to import extern functions?

I'm a bit confused about C#'s use of attributes. At first I thought it was simply used to give program code additional information through the use of the [Obsolete] attribute. Now I find that [Dllimport] can be used to import a dynamic linked library and its functions. Can attributes import .exe files and other kind of files?
A last question, for programmers working in C# every day, how much do you use attributes, and do you use it for anything else than extending information and importing dll's?
Simply said, attributes are just metadata attached to classes or methods, at the very base.
The compiler, however, reads through your code, and runs specific actions for specific attributes it encounters while doing so, hardcoded into it. E.g., when it finds a DllImportAttribute on a method, it will resolve it to an external symbol (again, this is a very simplified explanation).
When it finds an ObsoleteAttribute, it emits a warning of deprecation.
Your own attributes (which you can create with a class inheriting from the Attribute base class) will not have an effect on the default compiler. But you (or other libraries) can also scan for them at runtime, opening up many possibilities and leading to your second question:
I typically use them to do meta programming. For example, imagine a custom network server handling packets of a specific format, implemented in different classes. Each packet format is recognized by reading an integer value. Now I need to find the correct class to instantiate for that integer.
I could do that with a switch..case or dictionary mapping integer -> packet which I extend every time I add a packet, but that is ugly since I have to touch code possibly far away from the actual Packet class whenever I add or delete a packet. I may not even know about the switch or dictionary in case the server is implemented in another assembly than my packets (modularity / extensibility)!
Instead, I create a custom PacketAttribute, storing an integer property set via the attribute, and decorate all my Packet classes with it. The server only has to scan through my assembly types at startup (via reflection) and build a dictionary of integer -> packet pairs automatically. Of course I could scan my assembly every time I need a packet, but that's probably a bit slow performance-wise.
There are APIs which are much more attribute heavy, like controllers in ASP.NET Core: You map full request URLs to methods in handler classes with them, which then execute the server code. Even URL parameters are mapped to parameters in that way.
Debuggers can also make use of attributes. For example, decorating a class with the DebuggerDisplayAttribute lets you provide a custom string displayed for the instances of the class when inspecting them in Visual Studio, which has a specific format and can directly show the values of important members.
You can see, attributes can be very powerful if utilized nicely. The comments give some more references! :)
To answer the second part of your questions, they are also used, for example, in setting validation and display attributes for both client and server side use in a web application. For example:
[Display(Name = "Person's age")]
[Required(ErrorMessage = "Persons's age is required")]
[RangeCheck(13, 59, ErrorMessage = "The age must be between 13 and 59")]
public int? PersonsAgeAtBooking { get; set; }
Or to decorate enums for use in display
public enum YesNoOnlyEnum
{
[Description("Yes")]
Yes = 1,
[Description("No")]
No = 2
}
There are many other uses.

C# rule for public fields

I have problem with public fields, which I use from time to time in my code. I keep forgeting to change them to private and create properties for them- especialy when Im testing some new part of code (and Im used to create public field for testing at first).
I was thinking that it would be fine to see some sort of "warning" if I use public field in my code.
I have found out, that I can create a ruleset (Im using Visual Studio Community 2013) and choose any of the rule I need. I searched for the rules relative to public fields and found these 2: CA2211: Non-constant fields should not be visible and CA1051: Do not declare visible instance fields. I checked these in the ruleset, tried to Run code analysis on whole solution but I cant see any warnings in the outcome.
I even tried to add something like public int i; in one of my classes but still nothing.
Do you know if I have the right rules or whether there is something else I should do to get the warning? Thank you.

How to specify order of debugger visualizers in Visual Studio

I've been working on a debugger visualizer for Visual Studio for some time and while the actual visualizer works fine. The problem is that it always places itself at the top of the visualizer list when examining a variable which really annoys some of the users who rather have Text as the top one (since the top one is also default when opening VS).
I can't find any support for this on DialogDebuggerVisualizer or DebuggerVisualizerAttribute which were my first thoughts so I've been scouring SO/MSDN/Google for information on how to affect the sort order of the visualizers (preferably to put mine last in the list) but to no avail.
Below is how I register my visualizer, it then just shows a form based on the value that is being visualized.
using Microsoft.VisualStudio.DebuggerVisualizers;
[assembly: System.Diagnostics.DebuggerVisualizer(
typeof(Shorthand.VSAddins.JsonVisualizer.JsonVisualizer),
typeof(VisualizerObjectSource),
Target = typeof(string),
Description = "Json Visualizer")]
namespace Shorthand.VSAddins.JsonVisualizer
{
public class JsonVisualizer : DialogDebuggerVisualizer
{
protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
{
var json = objectProvider.GetObject() as string;
var form = new VisualizerForm { Json = json };
windowService.ShowDialog(form);
}
}
}
Does anyone know if it is possible to affect the order of the visualizers or should I just let it be?
I don't think there is a solution. But there is a workaround:
Define your own Text Visualizer and put appropriate DebuggerVisualizer attribute before the attribute of your JsonVisualizer. The result will be that string will be readable by default and Json Visualizer can be chosen. A window with a multi-line textbox is not too much work.
It is probably not even necessary to write visualizer. It should be possible to use internal one but I don't know its name (Which class is used for "Text Visualizer"?).
It will always appear first, by design. The under the hood cast has found the best match for the variable it is reflecting on.
however, you could do either of two things. You could make the visualizer only appear when the sting contains ':'
Or you could use reflection to reorder the visualisers by adding them to the end of the collection in the order you want, then removing the originals from the collection.
For the latter you will most likely have to change the collection from readonly to writable. Via reflection.
There is no reliable source to draw on other than your will to succeed.
I guess that VS 'under the hood' can distinguish between type of string and type of xml quite easily, but Xml is just a string too, so a key question here would be, how does VS tell the difference between the two?
Could you dissect the VS XML visualizer to see how it works (even if you have to use reflector on the DLL to do it, you might get to see the method that works it out)

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!

C#: Attrbute for intellisense to show method only outside of assembly

Basically what I'm hoping for is something that would work like how the Obsolete attribute works with Intellisense and strikes the method text when typing out the name. What I'm looking for is an attribute that blocks the method from being seen with the assembly it's defined. Kind of like an reverse internal. Using 3.5 by the by.
Yeah sounds odd but if you need the reason why, here it is:
My current solution for lazy loading in entity framework involves having the generated many to one or one to one properties be internal and have a facade? property that is public and basically loads the internal property's value:
public ChatRoom ParentRoom
{
get
{
if(!ParentRoomInnerReference.IsLoaded)
{
ParentRoomInnerReference.Load();
}
return ParentRoomInner;
}
set
{
ParentRoomInner = value;
}
}
Problem with this is if someone tries to use the ParentRoom property in a query:
context.ChatItem.Where(item => item.ParentRoom.Id = someId)
This will blow up since it doesn't know what to do with the facade property when evaluating the expression. This isn't a huge problem since the ParentRoomInner property can be used and queries are only in the entity assembly. (IE no selects and such in the UI assembly) The only situation comes in the entity assembly since it can see both properties and it's possible that someone might forget and use the above query and blow up at runtime.
So it would be nice if there were an attribute or some way to stop the entity assembly from seeing (ie blocked by intellisense) the outward facing properties.
Basically inside the assembly see ParentRoomInner. Outside the assembly see ParentRoom. Going to guess this isn't possible but worth a try.
I do see that there is an attribute
for stopping methods from being
viewable
(System.ComponentModel.EditorBrowsable)
but it's choices are rather slim and
don't really help.
You can use the EditorBrowsableAttribute for this:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void MyMethod() {}
One thing to know, though: In c#, you will still get intellisense on the method if it is in the same assembly as the one you are working in. Someone referencing your assembly (or your project, for a project reference) will not see it though. You can also pass EditorBrowsableState.Advanced, and then you will only get intellisense if c# if you clear the HideAdvancedMembers option in Tools Options.
I haven't heard of a good way to do this in plain .NET. But, here are some ideas. Maybe one of them will work, or set you off in a direction that will be helpful.
Use FxCop, probably writing your own rule to make sure ParentRoom isn't called from the asslembly that defined it.
Look into the various post-processing projects for .NET (link design-by-contract).
Write some code inside your ParentRoom getter which will check the stack (using "new Stack()" or "new StackFrame(1)" to figure out whether the caller was from the same assembly. If so, either throw an exception or simply return ParentRoomInner.

Categories

Resources