Has anyone created any cool rules for FxCop/StyleCop? - code-analysis

I'm just looking for some inspiration. Especially in the area of performance and security, naming conventions are important but not as 'cool' ;)
Even if your rule was only applicable to your domain/project but demonstrates how powerful a rule can be, please let me know.
I work with C#, but I'm interested in rules for any language.

In my experience, the developers that have started out creating custom rule sets for FxCop, usually give up after pulling out much hair. It seems like a great idea, but the pain is just not worth the effort.

An alternative to the mess of writing FxCop custom rules would be to use the commercial tool NDepend. With this tool one can write Code Rule over LINQ Queries (namely CQLinq). Disclaimer: I am one of the developers of the tool
More than 200 code rules are proposed by default, these include naming conventions, design, architecture, code quality, code evolution, dead code, .NET Fx usage...
CQLinq is dedicated to write code rules that can be verified live in Visual Studio, or that can be verified during build process and reported in an HTML/javascript report.
The strength of CQLinq over FxCop API or other tools, is that it is straightforward to write a code rule, and get immediately results. Facilities are proposed to browse matched code elements. Concretely this looks like that:

I've got a nice functioning base with 2 rules so far at breusable.codeplex.com under the fxcop directory
ConfigKeyExistsInConfig (make sure that any references to ConfigurationManager with a magic string key actually exists in the config file.
NoUnderscoresInProperties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FxCop.Sdk;
namespace RulesByImaginaryDevelopment
{
public class NoUnderscoresInProperties : BaseRule
{
public NoUnderscoresInProperties() : base("NoUnderscoresInProperties") { }
public override ProblemCollection Check(Member member)
{
var prop = member as PropertyNode;
if(prop==null)
return Problems;
if(prop.Name.Name.Contains("_"))
{
Problems.Add(new Problem(new Resolution("Remove any '_' from name "+prop.Name.Name)));
}
return Problems;
}
}
}
Also http://msdn.microsoft.com/en-us/magazine/cc163930.aspx

Related

Dynamically register a language

I'm writing a vscode extension and I'd like to register languages dynamically, based on user configuration. The extension would then instantiate LSP clients to talk to servers derived from user configuration as well.
This would allow for people writing custom and toy languages to get an extension "for free" and experiment with editor features without necessarily having to implement and publish the vscode part of it.
I've dug a bit in the vscode sources, and found an interface that seem like it could help : "ILanguageService", but I'm unsure as to whether this is something that's accessible from the extension API.
Any idea how I could go at it ? Is it even possible ?
Alright, so my question stemmed from a misunderstanding of how LSP clients work. They don't necessarily need to be tied to a language, and can work on a glob-pattern basis, something like
const filter: DocumentFilter = {
scheme: 'file',
pattern: `**/*.${myLanguage.extension}`
};
const clientOptions: LanguageClientOptions = {
documentSelector: [filter]
};
This seems to be sufficient for vscode to understand which LSP it should be calling

Any alternative to shim feature provided in Microsoft fake framework?

I am wondering is there any alternative lib to the shim feature provided in Microsoft fake framework since it is only supported in ultimate version?
There are three frameworks to my knowledge that allow you to mock non virtual methods and sealed classes like Fakes' Shims. There are
Microsofts' Moles or Fakes
Teleriks JustMock
TypeMocks
They are all commercial because they use the Profiling API, which is very hairy and poorly documented, so coding them is a real pain.
And for the record I'm all for fakes. Most code that people are working on is legacy code. One of the Pragmatic Programmer's rules of refactoring is make sure that you have unit test coverage before any refactorings to avoid regression. This makes Fakes and similar frameworks super useful, especially when the legacy code was not written for test-ability.
Prig hasn't been updated to work with VS 2017, but Pose does, and works really well for what I needed it for (basic shimming of Environment.UserName, and DateTime.Now and similar), and has a really nice interface:
// Create shims. They only apply within this isolate block.
var dateTimeShim = Shim.Replace(() => DateTime.Now)
.With(() => new DateTime(2010, 1, 1));
var usernameShim = Shim.Replace(() => Environment.UserName)
.With(() => "john.wick");
// Shims are only active within an Isolate block - and you
// have to pass all shims you want to be active.
PoseContext.Isolate(() =>
{
// Run your test - shims are active at this point.
RunTest();
}, dateTimeShim, usernameShim);
EDIT
I should note that I get lots of errors when doing fairly basic tests - really scary errors like "Common Language Runtime detected an invalid program.", and "JIT Compiler encountered an internal limitation." so caveat emptor.
An open source alternative is Prig. MIT licenced and still active - but slightly behind with VS IDE

NSGA-II implementation

I have studied about Non dominating sorting algorithtm (NSGA-II).
I want to use this multi objective optimization algorithm.
could anybody help me by addressing any free implementation of NSGA-II in java or matlab.
Thanks in advance
MOEA Framework is a a free and open source Java framework for Multiobjective Optimization. It has the largest collection of MOEAs of any library, including NSGA-I, NSGA-II, and NSGA-III.
I personally used it to implement and solve a Multi Objective Problem (MOP) for my Master's thesis and found it far superior to PyGMO (for python) and jMetal (in Java).
The following code demonstrates how to use the MOEA Framework API to run NSGA-II to solve the ZDT1 multiobjective problem:
import java.util.List;
import org.moeaframework.Executor;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.Solution;
public class NSGAIIExample {
public static void main(String[] args) {
// configure and run this experiment
NondominatedPopulation result = new Executor()
.withProblem("ZDT1")
.withAlgorithm("NSGAII")
.withMaxEvaluations(1000)
.distributeOnAllCores()
.run();
List<NondominatedPopulation> multiRuns = new Executor()
.withProblem("ZDT1")
.withAlgorithm("NSGAII")
.withMaxEvaluations(1000)
.distributeOnAllCores()
.runSeeds(3);
System.out.format("Obj1 Obj2%n");
for (Solution solution : result) {
System.out.format("%.5f\t%.5f%n", solution.getObjective(0),
solution.getObjective(1));
}
}
}
jMetal is the Java framework of MOEA, which NSGA-II is included in. The website is here.
This looks like what you want from Matlab
http://www.mathworks.co.uk/matlabcentral/fileexchange/10429-nsga-ii-a-multi-objective-optimization-algorithm
And here's one for Java:
http://ia-2008.googlecode.com/svn/trunk/TrabajoPracticoFinal/Implementacion/NSGA/src/jmetal/metaheuristics/nsgaII/NSGAII.java
Since it hasn't been mentioned so far: Jenetics
Jenetics is an advanced Genetic Algorithm, Evolutionary Algorithm and Genetic Programming library, respectively, written in modern day Java.
As of version 4.1.0 the jenetics.ext module offers classes for multi-objective problems. It also offers a NSGA2Selector, but (taken from the manual v4.3.0, p. 92):
Since the MOO classes are an extensions to the existing evolution Engine, the implementation doesn't exactly follow an established algorithm, like NSGA2 or SPEA2. The results and performance, described in the relevant papers, are therefore not directly comparable.
Nonetheless, this might reasonable alternative.
Have quickly read this thread and I haven't seen a mention of platEMO. Which is a matlab based optimisation platform that I have used a lot recently. The documentation and installation information can be found at:
https://github.com/BIMK/PlatEMO
It has a large amount of problems and algorithms (including NSGA-II) as standard.

Precompile protobuf-net Type Model for compact framework

I am deserializing thousands of objects on compact framework (3.5) and it is slow. Taking the devices 20+ seconds to finish. I found that it's done by reflection, instead of compile-and-run like non compact counterpart.
So I thought, could I pre-compile and generate a type model dll first?
So I did the following:
Extract all the Contract class to a smart device dll (it references Protobuf-net CF3.5 Dll)
Create a desktop 3.5 console application, referencing Protobuf-net "Desktop" Dll and the Contract Dll created above.
class Program
{
static void Main(string[] args)
{
var bb = TypeModel.Create();
foreach (var t in Assembly.GetAssembly(typeof(My.ContractX)).GetTypes())
{
var contract = t.GetCustomAttributes(typeof (ProtoBuf.ProtoContractAttribute), false);
if (contract.Length > 0)
{
bb.Add(t, true);
}
}
bb.Compile("My.TypeModel", "My.Serialization.dll");
}
}
Back to the device project, reference the Contract DLL, the generated My.Serialization.dll, and Protobuf-net CF3.5 Dll.
Instead of using the default model, modified it to deserialize with the model constructed by "new TypeModel()"
It actually compiles correctly. I look at the generated dll in the Reflector, it's as expected.
Except that upon running, it throws MissingMethodException. However exactly what is missing is missing because compact framework doesn't report that.
My bet is because the generated My.Serialization.dll actually refers to the "Desktop" dll, but some method is missing.
So back to my question, how could I achieve type model pre-generation to be used in compact framework? Or could I get performance boost by doing something else?
Good news, I suspect. I've spent quite insane amounts of time working on the issue of cross-compilation (ok, I've been mainly driven by people asking about WP7 and WinRT), culminating in a brand new cross-platform precompiler.
This already does what your code does, i.e. it looks for all the [ProtoContract] types in the input assembly/assemblies. I honestly haven't tried it for CF, but I'm very hopeful. I would genuinely love to hear how you get on. The only reason I haven't tested it against CF is that my external drive with my VS2008 VM died-a-death.
Usage:
precompile {some path}\YourCFDto.dll –o:MySerializer.dll –t:MySerializer
Note: at the moment you would need to build "precompile" from source, but if this is an issue, I can get around to publishing it.
If you have any problems whatsoever, please let me know.

how to get knowing more about a class behaviour without looking at its manual?(a fundamental question about how to dive more into OOP)

I'm practicing OOP for 2 years (for real) and I know how to consume objects and packages and I'm developing stuffs mostly using C# .
but I have a problem with consuming unknown objects and packages as an instance :
for now I am working on an enterprise like website and for part of our job we need to consume RSS. I decided to use "System.Xml.Xpath"
and my real problem is:
for using system.xml.xpath I should look at manual and read it carefully and I don't want to do that every time.A plain example of that is like following code :
XPathDocument xp = new XPathDocument(sites[2]);
XPathNavigator nav = xp.CreateNavigator();
XPathNodeIterator it = nav.Select(xpath3);
foreach (XPathNavigator n in it)
{
//get elements here
}
//another way of iterating elements is
while(it.movenext())
{
//it.current.Value;
}
for the "foreeach" part I got it from MSDN manual and I guess I could get this simple fact by looking at class structure.
but I don't know which structure I should look.
I know how to read tooltips and I'm familiar with things like : [] / collection / enum /generic / Ienumerable / Idisposable etc...
but I think there is something about reading class behaviors and I'm missing that part.
for make it more lucid :
I know whenever we have a class that inherited from IEnumerable so we can use foreach statement against that class to iterate it through
my real problem is I think classes are self described enough to not to look at manuals all the time but I don't know how/where to read those descriptions of classes so I need your advice to get more familiar with how to reading classes without looking at manuals.
best regards.
Classes can (and should) be documented with source code comments, and in many languages you can generate API documentation from these comments (in HTML, XML or other format). In Java it is called Javadoc; I don't know the C# term. If this is what you call "manual", then this is your primary source of information. Other than reading the source code comments and the code itself (which you often don't have access to, especially in the MS universe). If you don't find enough information in the API documentation, you can always try googling for more explanation, tutorials or usage examples.
Hope this helps; I am not entirely sure I understood your question though. If this is not the answer you are looking for, please clarify.