In my project I am using custom controls instead of normal ASP.NET controls. We have build an architecture on .NET and are using its controls.
Now I need to write a custom rule to check for if some of windows controls are being used. Reason being, my team needs to be limited to only my custom controls that were designed to replace the windows controls.
Example: I need to search and if they are using System.Windows.Controls.Textbox.....I need it to be an error.
Can anyone please help me out with code?
I hope the problem is clear ..... in case of any further clarifications needed please let me know.
The logic for this sort of rule is fairly simple:
Check method bodies, visiting each constructor invocation to see if
the target class inherits from the base Control class.
If it does, verify that the target class is in your namespace or assembly (or however you can best identify it as "yours").
This is relatively simple. A much bigger problem is that the relevant contructors will usually be invoked in designer-generated code, which most folks tend to prefer ignoring when executing FxCop. To get your rule to work, you will need to include designer-generated code in your analyses.
The tool NDepend let's write custom code rules on .NET code much more easily than with FxCop. Disclaimer: I am one of the developer of the tool
With this tool you can write custom code rules over LINQ queries (what is named CQLinq). For example, the query you are asking for can be written this way with CQLinq:
// <Name>Don't use system controls</Name>
warnif count > 0
let systemControls = ThirdParty.Types.Where(
t => t.DeriveFrom("System.Windows.Forms.Control".AllowNoMatch()))
where systemControls.Count() > 0
from t in systemControls
let methodsThatCreateT = t.TypesUsingMe.ChildMethods().Where(m => m.CreateA(t))
select new { t, methodsThatCreateT }
While editing such code rule, instantly a browsable result is shown (in 3 milliseconds here). Double clicking any type or method in this result, jumps to its declaration in source code in Visual Studio:
200 default code rules are proposed. The tool is 100% integrated in Visual Studio 2012, 2010, and 2008. Default or custom code rules can be validated inside Visual Studio, and/or at Build Process time, in a generated HTML+javascript report.
Related
I am using Visual Stuido 2022 to code my C# project.
Is there a way to configure VS using (.editorconfig file) where a new line is added before and after the namespace?
So my class will look like this
using System;
namespace ProjectName.Tests;
public class Test
{
}
instead of
using System;
namespace ProjectName.Tests;
public class Test
{
}
I'm not sure there is a Visual Studio native way of doing this.
There is definitely not a way to do this in .editorconfig with Visual Studio alone (meaning no plugins). About halfway down Namespace declaration preferences, it talks about csharp_style_namespace_declarations, and the code formatting sample when that value is file_scoped looks like
// csharp_style_namespace_declarations = file_scoped
using System;
namespace Convention;
class C
{
}
which appears to get you part of the way there (blank line after using). When you look at the supported formatting rules, the list is pretty brief.
If you have ReSharper there is a way. These settings in .editorconfig will do what you want:
resharper_blank_lines_after_file_scoped_namespace_directive = 1
resharper_blank_lines_after_imports = 1
If ReSharper is not an option, here are 3 possible paths to take, none all that great. They certainly aren't simple solutions.
try to find something in the Visual Studio Marketplace
write a .NET Analyzer that is configured via .editorconfig (ref. this page)
raise an issue on Developer Community, and hope they get to it.
Like the other guy said,
No, not with editor config (out of the box).
Resharper can do this; you can build a custom format for your code and tell it, for example, where you want certain sections like imports below the class for some weird reason ;) ...of course, with that spacing around those sections.
But now you have to get ReSharper licenses for all your devs. The Resharper devs are very cool, and Jetbrains has been building quality software for a few decades. Maybe I'm sentimental.
Well, there is another option if you don't want to pay...
In DevOps roles of the past, I've used Roslyn to build extensions for custom formatting.
Build a custom Rosyln analyzer.
https://learn.microsoft.com/en-us/visualstudio/code-quality/roslyn-analyzers-overview?view=vs-2022#severity-levels-of-analyzers
You can build a custom code suggestion with this of configurable severity.
It's pretty easy, too, thanks to Rosyln, but you must think a little backward. Let me know if I can help more.
StyleCop.Analyzers has a bunch of formatting related rules that you can enforce and, in some cases, automatically fix across your codebase.
Unfortunately it looks as though there is not yet support for file-scoped namespace formatting in the way you want. There's a PR to add it here, so if you really wanted to have this you could get that PR across the finish line, or make your own build:
https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3512
This issue might also be worth a look:
https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3578
... especially in the case of Non-Dialog Containers?
Hi folks,
I want to use ActiveX controls that are created in a view, not in a Dialog container, as described in http://msdn.microsoft.com/library/191es2w5%28v=vs.100%29.aspx . But in that article, the existence of the wrapper class is already supposed / not mentioned how to generate it. In the project that was handed me over, i found such generated classes.
For Dialog-Containers, the generator runs when I add a control varaible for the embedded activeX control, (again: not mentioned in msdn doc http://msdn.microsoft.com/library/w98bewhf%28v=vs.100%29.aspx ). Workaorunds are possible (eg. creating a useless dialog just for that purpose), but there must be a "clean" way in Visual Studio!? I am a little bit disappointed by the MS-Documentation I found. If somebody could give me a hint, you could make me happy...
Custom Compiler Warnings and
C#: Create custom warning in Visual Studio if certain method is used in source code
haven't helped as they deal with code that is under the author's control.
We are using a 3rd party suite of UI controls (DevExpress) in our software and I want to generate a warning when someone uses MessageBox.Show("blah"); instead of XtraMessageBox.Show("blah");
Is there a way to do that?
This sort of thing can be addressed relatively easily via a custom rule for FxCop/Visual Studio Code Analysis. If you are using Visual Studio Developer Edition, you will even see the rule failures displayed along-side your compilation warnings and errors in the IDE.
While there's no way you can do real custom compile-time error in .NET, there's a number of third-party tools (both free and commercial) that can inject their validation logic into the build process, usually after the compilation.
Here are three ways I know of to solve you problem:
Resharper 5.0($) will support custom rules / warnings.
In PostSharp(free) you can define OnMethodBoundary aspect, overwrite its CompileTimeValidate method and emit a [post]compile-time error from it.
NDepend can be integrated with your build process ($) to enforce coding policies like that
No there is no direct way. If you think about it you are looking for a compiler warning for some code that you don't even compile.
If you really want this you could use Reflection methods on YOUR compiled assembly to check if any methods/assemblies you don't want have been called. Cecil has a lot of the functionality you need. You could then make this part of your build process.
Last year I wrote a Language Service for Visual Studio which added syntax highlighting for NHaml files: http://github.com/snappycode/hamleditor.
To clarify, NHaml is a html template language that can mix in code elements like an aspx file can. This plugin adds support to the IDE for editing NHaml files, but basically only adds syntax highlighting.
I was wondering if anyone knows how to add inline c# intellisense to the service like you get now in an aspx file. I'm hoping that would be possible without doing the whole c# grammar myself specific for the plugin.
Has anyone written a language service that mixes languages?
UPDATE:
It looks like the spark view engine guys have made some inroads here, I am investigating their implementation
I checked the Spark View Engine, and they seem to have made a generic ATL stuff (called SparkLanguagePackageLib), that in fact seems to be not containiag anything Spark specific. It seems to be just a generic C# intellisense library that needs the following:
The original code
The C# source that gets generated from the original code
The position mappings between the two (for example the code on line 2 pos 5 gets mapped in the output to line 4 pos 10, etc.)
Some other things, like Paintings(?)
And after that you can call:
events.OnGenerated(
primaryText, // original source code
entry.SourceCode, // generated sourcecode
cMappings, // mappings between the two
ref mappings[0], // ?
cPaints, // ?
ref paints[0]); // ?
I've tried to find Spark-specific stuff in that C++ library, but I couldn't find anything: everythig spark-related is split to a separate C# code file. I think this is good, because:
You don't need to edit the C++ files
If the spark view engine's intellisense support is installed it can be used by other view engines too
You only need to create a class, that maps between the original nhaml file and it's generated C# counterpart.
Btw. Are you still working on this NHaml Intellisense library? If not I'll try to patch their implementation in hope it can be converted to NHaml easily.
this looks like it might help
http://www.codeproject.com/KB/recipes/VSLanguageService.aspx
I finally managed to modify the code to support NHaml. It wasn't that hard at all. Unfortunately the original NHaml library doesn't support everything that was needed, so I had to create a new parser for NHaml. It doesn't support all of the constructs, but it supports most of them (enough to make NHaml programming easier)
Download: http://github.com/sztupy/nhamlsense
Screencast: http://www.youtube.com/watch?v=8jTZ2zC9eYc
You can easily add keywords by creating or modifying a usertype.dat file. Check here for some directions on attaching to specific file extentions. That might get you at least part of the way, without redoing the complete c# syntax.
(In fact, I'm not sure what you mean exactly by 'syntax highlighting' in this context. I'm sure, for instance, you get brace-match highlighting for free in the editor).
FxCops is something new to me, but as always I would like to get to know the new things..
From what I've read, FxCops is already included in VS2008. I guess it's the "Code Analysis" function. Whenever I try to run it though, it seems to start a rebuild and end in the "Finished Rebuilding" state.
I checked the output window and there are a bunch of warnings there. But if I'm not mistaking, there should be more of a GUI for this then the wall of text in my output window, right?
Am I missing a window that should have popped up? Can I open it somewhere? Or is there anything else I'm missing?
Yes, Code Analysis is the nice friendly name for FxCop. However, I'm not aware of a friendly window beyond the errors / warning list where they should appear, prefixed CA.
On the project properties screen there is a Code analysis tab where you can treat warnings as errors to enforce the rules you care about.
Just so everyone knows, because it took me a long time to figure this out.... Code Analysis / FxCop is only included in Team System and Team Suite versions of VS 2008, not in the Professional Edition.
You're not missing anything - there isn't a pop-up window.
The list of issues in the output window is pretty much all you'd get in FxCop. It's just that FxCop is a standalone application.
Here's a decent article on FxCop and Code Analysis:
Link
An alternative to FxCop would be to use the tool NDepend that lets write Code Rules over C# LINQ Queries (namely CQLinq). NDepend is integrated in VS 2012, 2010 and 2008. Disclaimer: I am one of the developers of the tool
More than 200 code rules are proposed by default. Customizing existing rules or creating your own rules is straightforward thanks to the well-known C# LINQ syntax.
NDepend code rules can be verified live in Visual Studio and at build process time, in a generated HTML+javascript report.
You seems concerned by the number of false-positive. To keep the number of false-positives low, CQLinq offers the unique capabilities to define what is the set JustMyCode through special code queries prefixed with notmycode. More explanations about this feature can be found here. Here are for example two notmycode default queries:
Discard generated and designer Methods from JustMyCode
Discard generated Types from JustMyCode
To keep the number of false-positives low, with CQLinq you can also focus rules result only on code added or code refactored, since a defined baseline in the past. See the following rule, that detect methods too complex added or refactored since the baseline:
warnif count > 0
from m in Methods
where m.CyclomaticComplexity > 20 &&
m.WasAdded() || m.CodeWasChanged()
select new { m, m.CyclomaticComplexity }