C# rule for public fields - c#

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.

Related

Sergen : syntax erros despite rebuilt

For one of my internship mission, I need to use a C# app-builder, serenity.is with Visual Studio 2015. I'm following this official tutorial.
More precisely, I followed the begin of the tutorial p 43. (I'm just adapting it to what I do, I join the code at the end of the post).
Nothing is going wrong till p 49. The code generator of the app-builder, sergen.exe, is creating some code (I don't have the detail of what he creates but it doesn't seem to be important).
They ask me to "rebuild all", what I did, and everything should work smoothly.
As project is modified, Visual Studio will ask if you want to reload changes, click Reload All.
REBUILD the Solution and then press F5 to launch application.(tutoriel)
Nevertheless, when i compile and execute my code, I've got a bunch of syntax error which shouldn't happen.
You can find the code of my migration file below, but I don't think it is the problem.
using FluentMigrator;
using System;
using FluentMigrator.Infrastructure;
namespace Serene3.Migrations.DefaultDB
{
[Migration(20170802070000)]
public class DefaultDB_20170802_070000_TcpDump : Migration
{
public override void Up()
{
Create.Schema("tcpdump");
Create.Table("TCPDump").InSchema("tcpdump")
.WithColumn("TimeStp").AsString(16).Nullable()
.WithColumn("IdTransmission").AsInt32().Identity().PrimaryKey().NotNullable()
.WithColumn("IdSource").AsString(32).Nullable()
.WithColumn("IdDestination").AsString(32).Nullable()
.WithColumn("PortSource").AsString(16).Nullable()
.WithColumn("PortDestination").AsString(16).Nullable()
.WithColumn("-->").AsInt32().NotNullable()
.WithColumn("<--").AsInt32().NotNullable();
}
public override void Down()
{
}
}
}
I tried to stay as close as the tutorial as possible. I probably forgot to do something, but I can't find what.
Is there any Serenity user which could help?
Feel free to ask any other details
Make sure that all column names are supported by the tool. Column names like "-->" and "<--" would need special syntax in SQL and can't be used as property names in generated code files.
Use property-ready names without special characters or spaces. If you need special names, consult the tools documentation and make sure to use supported techniques.

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

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.

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)

what will be the Regular Expression to get all the property and variables names of a class in c#?

What will be the Regular Expression to get all the property and variables names of any class in c#, I want to parse the *.cs file. that is i want to select any *.cs file as input and it should get the property name of that selected class, as an output.
can any one help!!!....would appreciate for any help i tried very much but not got the actual result every time class name is coming instead of property.
thanks
Jack
There's no way you're going to be able to get exactly what you want with a regular expression because you need semantic context, not just string parsing.
For example, a good first attempt at finding all of the field and property definitions in a C# file might go something like this
^\s*(?:(?:private|public|protected|internal)\s+)?(?:static\s+)?(?:readonly\s+)?(\w+)\s+(\w+)\s*[^(]
That will match properties (public int Foo {...}) and fields (private int foo;) but not methods (protected void Bar()).
The problem is that a regex engine has no concept of the context within which those tokens appear. It will match both foo and bar in this code:
int foo;
void Stuff()
{
int bar;
}
If you happen to know that your code file follows some coding standards, you may have more luck. For example, if you enforce a style rule that all class members must have access specifiers, then you can make the private/public/etc part of that regex non-optional; since those are only permitted at the class level, it will filter out local variables.
There are other options, none of them too attractive at first glance. There is persistent talk from the C# dev team about exposing the C# compiler as a service in some future version of .NET, which would be perfect here, but I wouldn't expect that any time soon. You could purchase a third-party C# parser/analyzer like this one (caveat: I have zero experience with that, it's just the first Google hit). You could try compiling the .cs file using csc and examining the IL, but you'd need to know all of the third-party references.

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