Roslyn Analyzer analyze Namespaces - c#

We have some guidelines, how we want to use our namespaces and there are also access restrictions on them. Because developers are doing this wrong sometimes, we need to analyze these rules. Currently we are doing this with nDepend, which is working good. But the process that someone have to overwatch this, go to the guy who violated these rules and force him to fix it, is very time consuming. So it would be very nice to get instant notice while developing, or at least after building the current changes. This should be a job for a roslyn analyzer.
I've introduced myself into roslyn the past 3 hours, but I'm a bit overwhelmed with the feature list and how they work. Maybe you can give me a hint, how I could achieve what I want.
We are talking about a solution with >1m lines of code and nearly 35000 types. So peformance does matter a lot.
What I want to do:
get the current class
get the namespace of the current class
get all used types with their full name
If I'm able to do this, the rest would be relatively easy. I've played arround with it and maybe I need the current project of the opened class and the compilation. But opening this is very time consuming and therefore the performance would be very ugly.

A Roslyn analyzer can register a bunch of different code actions, eg. on the "whole file" level, the method, every single syntax node, or symbol. Depending on what you're exactly are trying to analyze, any of those might be applicable for you. Especially, as you indicate, you're concerned about performance. See the AnalysisContext.Register*Action() methods, for possible "hooks" you can add.
To get the things that you want:
1 Get the current class
Basically, with any of those, you should be able to get the current class (if registering syntax node or symbol action), or all declared classes (for example, with registering a compilation action, or syntax tree action). But the most simple option is to register a syntax node analysis for class nodes, you can do that like this:
context.RegisterSyntaxNodeAction(AnalyzeClassNode, SyntaxKind.ClassDeclaration);
Where AnalyzeClassNode is an action to analyze the class declaration. That will receive an additional context (a SyntaxNodeAnalysisContext), which contains the class declaration syntax node.
2 Get the namespace of the current class
For this, you need the semantic model. Let's say you used the RegisterSyntaxNodeAction method, and declared a method AnalyzeClassNode, then in the body, you can do this:
var classNode = context.Node;
var model = context.SemanticModel;
var classSymbol = model.GetDeclaredSymbol(classNode);
And you get the namespace symbol with:
var #namespace = classSymbol.ContainingNamespace;
And .MetadataName will give you the namespace as string.
3 Get all used types with their full name
That's something much more complex, and really depends on what you're trying to achieve here. To really get to something like "all dependent types, or imports". You should traverse the entire class node, get the symbol for every useful node (I have no idea what that would entail), and checking it's namespace, or full metadata name.
Maybe, you can elaborate a little bit more on this, to find out if this is the right approach.
By the way, check out "Learn Roslyn Now", a site with a bunch of tutorials for Roslyn. Specifically, you want to checkout part 3 (for syntax nodes), 7 (for symbols), and 10 (intro to analyzers).

Related

What's the easiest way to create a managed visualiser in C#?

I have a background in C++ and recently I started working in C#.
I have written following pieces of code (in Visual Studio):
var list_Loads = database.GetData<Load>().ToList();
var test_list = list_Loads.Where(o => (o.Name.Substring(0, 3) == "123")).ToList();
When I run the program and I move my mouse over both lists, first I get the count, which is very useful, but when I ask for the entries, this is what I get:
0 : namespace.Load
1 : namespace.Load
2 : namespace.Load
...
Not very useful, as you can imagine :-)
So my question: how can I show the Name attributes of those objects?
I thought: no problem. I have a background in native visualisers, so it should be rather easy to turn this into useful information, but then it comes:
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Then I found another solution, which comes down to: "Write an entire C# project, debug, test and install it and it might work" (see documentation on "Custom visualisers of data" on the Microsoft website).
I almost choked in my coffee: writing an entire project, just for altering the view of an object??? (While, in C++, you just create a simple .natvis file, mention the classname and some configuration, launch .nvload and that's it.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
By the way, when I try to load a natvis file in Visual Studio immediate window, this is what I get:
.nvload "C:\Temp_Folder\test.natvis"
error CS1525: Invalid expression term '.'
What am I doing wrong?
Thanks in advance
OP (my emphasis):
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
If you just want to specify [DebuggerDisplay] on a type, you don't have to have access to the source code. You can make use of [assembly:DebuggerDisplay()] and control how a type appears in the debugger. The only downside is that [assembly:DebuggerDisplay()] naturally only affects the current assembly whose code your mouse is hovering over. If you wish to use the customised display in other assemblies that you own, then you must repeat the [assembly:DebuggerDisplay()] definition.
Here's an easy before-and-after example with DateTime. I picked DateTime because we generally don't have access to the source code and it has some interesting properties:
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
...which on my machine defaults to:
Maybe I'm fussy and I just want to see:
Day of the week and
Day of the year
...I can do that via:
using System.Diagnostics;
[assembly: DebuggerDisplay("{DayOfWeek} {DayOfYear}", Target = typeof(DateTime))]
...which results in:
Example:
namespace DebuggerDisplayTests
{
public class DebuggerDisplayTests
{
public DebuggerDisplayTests()
{
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
}
}
.
.
.
}
Overrides
[assembly:DebuggerDisplay()] can also be used as a means to override pre-existing [DebuggerDisplay] on a 3-rd party type. Don't like what style they have chosen? Is the type showing far too much information? Change it with [assembly:DebuggerDisplay()].

Get an `SBObject` instance's real type

(This question is tagged c# because I'll be doing this from Xamarin, but this is more of a framework question; the language shouldn't matter.)
I'm trying to interact with Music (née iTunes) using Scripting Bridge. To that end, I can get the SBApplication and ask it for properties; for example, playerState will get me whether it's currently playing, and sources will basically get me the entire library, hierarchically.
But that's fairly low-level, so I dug into sdef and sdp to generate some XML and a header file, in order to write some matching wrapper classes that match those described.
The part where I get stuck is basically inheritance. The playlists property can contain different kinds of playlists (such as MusicPlaylist, MusicFolderPlaylist, etc., all of which inherit from MusicPlaylist), and I'm only interested in MusicUserPlaylist instances.
But I'm confused how to even ask an instance its type at all, much less efficiently. I see that debugDescription answer this, for example:
<SBObject #0x6000008bf180: <class 'cUsP'> id 28712
of <class 'cSrc'> id 63 of application "Music" (8034)>
And I can see from the sdef that cUsP is what I'm looking for:
<class name="user playlist" code="cUsP"
description="custom playlists created by the user"
inherits="playlist" plural="user playlists">
…
</class>
But… am I really supposed to parse description for this? Surely there's a nicer way? I see that the constructor always takes an elementCode:
- (instancetype) initWithElementCode:(DescType)code
properties:(nullable NSDictionary<NSString *, id> *)properties data:(nullable id)data;
(I'm actually not a 100% on whether DescType is the same thing as e.g. class 'cUsP'?)
And yet, there doesn't appear to be a way to get that element code back?
TL;DR: given an SBElementArray that can contain various subclasses, how do I verify that an instance's dynamic scripting bridge type is a certain class?

How do I find out if an enum value is used at Runtime?

We are using a quasi dynamic method to create enums from sql lookup tables using t4 templates. The template generates an enum for every table that conforms to the lookup patter. Several of these enums are not being used in code, but any could be.
This has been fine and dandy, but now we have been asked to create a lookup management interface so that users can add new values, edit descriptions, etc.
They don't want to modify any items that are currently being used in code as an enum value, so is there a simple (or not so simple) way to query our assemblies to find out if an enum value is used?
We have a lot of code similar to this made-up example:
public Role GetAdminRole
{
using (myContext ctx = new myContext()
{
return ctx.Roles.Where(i=> i.RoleId == (int)RoleEnum.Admin).SingleOrDefault();;
}
}
Is there a way to use the Type.FindMembers() and build a filter that can query the internals of a method?
I've looked at the System.Reflection.Emit namespace, which seemed promising based on the EnumBuilder class, but couldn't figure out how to hook up a builder to an existing assembly. The System.Diagnostics.CodeAnalysis namespace sounds interesting, but it only contains two attributes (for suppressing warnings and excluding code from coverage).
EDIT: While poking through ILSpy I discovered that I knew, but didn't put together, that enum values in methods get converted to their integer value when used in the above manner when compiled.
If you insist on checking at runtime you could use the GetILAsByteArray method on the MethodBody class to get the IL and parse that, searching for places where your enumerations are used.
As you can imagine, this is going to be very painful, as you have to go through all of the methods in all of the types in all of the modules, in all of the assemblies.
I strongly recommend that you use some sort of static analysis on the code; ReSharper, for example, can tell you whether or not members are used.
If you want to code an in-house solution, you can take a look at Roslyn to analyse your code (warning, it's a CTP as of this writing); you can parse the code in your project and do the analysis yourself.
That said, you're best off finding a tool that's going to an analysis of the code and not of the final, output assembly.

Building a string representation of an object using a "mask" or user supplied Format String

I'm not really sure what tags should be on this sort of question so feel free to give me some suggestions if you think some others are more suited.
I have a dynamic object with an unknown number or properties on it, it's from a sort of dynamic self describing data model that lets the user build the data model at runtime. However because all of the fields holding relevant information to the user are in dynamic properties, it's difficult to determine what should be the human readable identifier, so it's left up to the administrator. (Don't think it matters but this is an ASP.NET MVC3 Application). To help during debugging I had started decorating some classes with DebuggerDisplayAttribute to make it easier to debug. This allow me to do things like
[DebuggerDisplay(#"\{Description = {Description}}")]
public class Group
to get a better picture of what a specific instance of an object is. And this sort of setup would be perfect but I can't seem to find the implementation of this flexibility. This is especially useful on my dynamic objects because the string value of the DebuggerDisplayAttribute is resolved by the .NET framework and I have implementations of TryGetMember on my base object class to handle the dynamic aspect. But this only makes it easier for development. So I've added a field on what part of my object is still strongly typed and called it Title, and I'd like to let the administer set the implementation using their own format, so to speak. So for example they might build out a very simplistic rental tracking system to show rentals and they might specify a format string along the lines of
"{MovieTitle} (Due: {DueDate})"
I would like that when they save the record to add some logic to first update the Title property by resolving the format string to substitute each place holder with the value of the appropriate property on the dynamic object. So this might resolve to a title of
"Inception (Due: May 21, 2011)", or a more realistic scenario of a format string of
"{LastName}, {FirstName}"
I don't want the user to have to update the title of a record when they change the first name field or the last name field. I fully realize this will likely use reflection but I'm hoping some one out there can give me some pointers or even a working example to handle complex format strings that could be a mix if literal text and placeholders.
I've not had much luck looking for an implementation on the net that will do what I want since I'm not really sure what keywords would give me the most relevant search results?
You need two things:
1) A syntax for formatting strings
You have already described a syntax where variables are surrounded by bracers, and if you want to use that you need to build a parser that can parse that. Perhaps you also want to add ways to specify say a date or a number format.
2) Rules for resolving variables
If there is a single context object you can use reflection and match variable names to properties but if your object model is more complex you can add conventions for searching say a hierarchy of objects.
If you are planning to base your model objects on dynamic chances are that you will find the Clay library on CodePlex interesting.

.NET refactoring, DRY. dual inheritance, data access and separation of concerns

Back story:
So I've been stuck on an architecture problem for the past couple of nights on a refactor I've been toying with. Nothing important, but it's been bothering me. It's actually an exercise in DRY, and an attempt to take it to such an extreme as the DAL architecture is completely DRY. It's a completely philosophical/theoretical exercise.
The code is based in part on one of #JohnMacIntyre's refactorings which I recently convinced him to blog about at http://whileicompile.wordpress.com/2010/08/24/my-clean-code-experience-no-1/. I've modified the code slightly, as I tend to, in order to take the code one level further - usually, just to see what extra mileage I can get out of a concept... anyway, my reasons are largely irrelevant.
Part of my data access layer is based on the following architecture:
abstract public class AppCommandBase : IDisposable { }
This contains basic stuff, like creation of a command object and cleanup after the AppCommand is disposed of. All of my command base objects derive from this.
abstract public class ReadCommandBase<T, ResultT> : AppCommandBase
This contains basic stuff that affects all read-commands - specifically in this case, reading data from tables and views. No editing, no updating, no saving.
abstract public class ReadItemCommandBase<T, FilterT> : ReadCommandBase<T, T> { }
This contains some more basic generic stuff - like definition of methods that will be required to read a single item from a table in the database, where the table name, key field name and field list names are defined as required abstract properties (to be defined by the derived class.
public class MyTableReadItemCommand : ReadItemCommandBase<MyTableClass, Int?> { }
This contains specific properties that define my table name, the list of fields from the table or view, the name of the key field, a method to parse the data out of the IDataReader row into my business object and a method that initiates the whole process.
Now, I also have this structure for my ReadList...
abstract public ReadListCommandBase<T> : ReadCommandBase<T, IEnumerable<T>> { }
public class MyTableReadListCommand : ReadListCommandBase<MyTableClass> { }
The difference being that the List classes contain properties that pertain to list generation (i.e. PageStart, PageSize, Sort and returns an IEnumerable) vs. return of a single DataObject (which just requires a filter that identifies a unique record).
Problem:
I'm hating that I've got a bunch of properties in my MyTableReadListCommand class that are identical in my MyTableReadItemCommand class. I've thought about moving them to a helper class, but while that may centralize the member contents in one place, I'll still have identical members in each of the classes, that instead point to the helper class, which I still dislike.
My first thought was dual inheritance would solve this nicely, even though I agree that dual inheritance is usually a code smell - but it would solve this issue very elegantly. So, given that .NET doesn't support dual inheritance, where do I go from here?
Perhaps a different refactor would be more suitable... but I'm having trouble wrapping my head around how to sidestep this problem.
If anyone needs a full code base to see what I'm harping on about, I've got a prototype solution on my DropBox at http://dl.dropbox.com/u/3029830/Prototypes/Prototype%20-%20DAL%20Refactor.zip. The code in question is in the DataAccessLayer project.
P.S. This isn't part of an ongoing active project, it's more a refactor puzzle for my own amusement.
Thanks in advance folks, I appreciate it.
Separate the result processing from the data retrieval. Your inheritance hierarchy is already more than deep enough at ReadCommandBase.
Define an interface IDatabaseResultParser. Implement ItemDatabaseResultParser and ListDatabaseResultParser, both with a constructor parameter of type ReadCommandBase ( and maybe convert that to an interface too ).
When you call IDatabaseResultParser.Value() it executes the command, parses the results and returns a result of type T.
Your commands focus on retrieving the data from the database and returning them as tuples of some description ( actual Tuples or and array of arrays etc etc ), your parser focuses on converting the tuples into objects of whatever type you need. See NHibernates IResultTransformer for an idea of how this can work (and it's probably a better name than IDatabaseResultParser too).
Favor composition over inheritance.
Having looked at the sample I'll go even further...
Throw away AppCommandBase - it adds no value to your inheritance hierarchy as all it does is check that the connection is not null and open and creates a command.
Separate query building from query execution and result parsing - now you can greatly simplify the query execution implementation as it is either a read operation that returns an enumeration of tuples or a write operation that returns the number of rows affected.
Your query builder could all be wrapped up in one class to include paging / sorting / filtering, however it may be easier to build some form of limited structure around these so you can separate paging and sorting and filtering. If I was doing this I wouldn't bother building the queries, I would simply write the sql inside an object that allowed me to pass in some parameters ( effectively stored procedures in c# ).
So now you have IDatabaseQuery / IDatabaseCommand / IResultTransformer and almost no inheritance =)
I think the short answer is that, in a system where multiple inheritance has been outlawed "for your protection", strategy/delegation is the direct substitute. Yes, you still end up with some parallel structure, such as the property for the delegate object. But it is minimized as much as possible within the confines of the language.
But lets step back from the simple answer and take a wide view....
Another big alternative is to refactor the larger design structure such that you inherently avoid this situation where a given class consists of the composite of behaviors of multiple "sibling" or "cousin" classes above it in the inheritance tree. To put it more concisely, refactor to an inheritance chain rather than an inheritance tree. This is easier said than done. It usually requires abstracting very different pieces of functionality.
The challenge you'll have in taking this tack that I'm recommending is that you've already made a concession in your design: You're optimizing for different SQL in the "item" and "list" cases. Preserving this as is will get in your way no matter what, because you've given them equal billing, so they must by necessity be siblings. So I would say that your first step in trying to get out of this "local maximum" of design elegance would be to roll back that optimization and treat the single item as what it truly is: a special case of a list, with just one element. You can always try to re-introduce an optimization for single items again later. But wait till you've addressed the elegance issue that is vexing you at the moment.
But you have to acknowledge that any optimization for anything other than the elegance of your C# code is going to put a roadblock in the way of design elegance for the C# code. This trade-off, just like the "memory-space" conjugate of algorithm design, is fundamental to the very nature of programming.
As is mentioned by Kirk, this is the delegation pattern. When I do this, I usually construct an interface that is implemented by the delegator and the delegated class. This reduces the perceived code smell, at least for me.
I think the simple answer is... Since .NET doesn't support Multiple Inheritence, there is always going to be some repetition when creating objects of a similar type. .NET simply does not give you the tools to re-use some classes in a way that would facilitate perfect DRY.
The not-so-simple answer is that you could use code generation tools, instrumentation, code dom, and other techniques to inject the objects you want into the classes you want. It still creates duplication in memory, but it would simplify the source code (at the cost of added complexity in your code injection framework).
This may seem unsatisfying like the other solutions, however if you think about it, that's really what languages that support MI are doing behind the scenes, hooking up delegation systems that you can't see in source code.
The question comes down to, how much effort are you willing to put into making your source code simple. Think about that, it's rather profound.
I haven't looked deeply at your scenario, but I have some thoughs on the dual-hierarchy problem in C#. To share code in a dual-hierarchy, we need a different construct in the language: either a mixin, a trait (pdf) (C# research -pdf) or a role (as in perl 6). C# makes it very easy to share code with inheritance (which is not the right operator for code-reuse), and very laborious to share code via composition (you know, you have to write all that delegation code by hand).
There are ways to get a kind of mixin in C#, but it's not ideal.
The Oxygene (download) language (an Object Pascal for .NET) also has an interesting feature for interface delegation that can be used to create all that delegating code for you.

Categories