How to recognize code generated by Visual Studio's GUI designer? - c#

Visual Studio is kind enough to generate a lot of code for us when we create and design Windows.Forms controls. It also surrounds most of it with a #region statement.
In newer versions it also uses a partial class to separate generated from manually created code.
Developers are supposed to edit code only in certain areas.
But nothing prevents us from violating this in whatever way we please.
I'm fine with manual edits that could just as well have been made from the designer, or manual edits in areas the designer doesn't touch. But I'd like to flag any other kind of edit.
Does anyone know a utility that can do this? StyleCop rules perhaps?
I mostly need it for the combination of C#, Windows.Forms, and Visual Studio 2003, 2005, and 2008.

These days, designer code should end up in a .Designer.cs file. It should be very rare that developers need to touch that. Unfortunately, I don't know any way of verifying that the code was genuinely generated by the designer. It would be handy if it included some sort of hash, but it doesn't as far as I'm aware...
Given how easy it is now to just say "don't edit designer files" do you really need another system though? It's not like you need to stay away from specific regions - it's the whole file which is out of bounds.

Why should developers not be allowed to change this code? If they are able to write code that works, they should be allowed to do it. If they are not able to write code that works, lets say they should be trained or fired.
You just have to extend the meaning of "it works" to "it works at runtime as well as in the designer". So what's wrong about that?
Todays gui designers are not very restrictive and are doing a good job in "understanding" code that had been written by a human.
There is also real generated code around, for instance code generated by some xml specification, resources etc. This code is generated when building, so when it had been changed, these changes are undone whenever the application is built.
Designers are not real code generators of this kind. They are a kind of "coding helpers", helping the developer to write code faster then by typing it in. But it should actually be possible to write the same kind of code manually although limiting one self to the designers capabilities is a reasonable maintainability decision.

Related

TFS: Keeping history while formatting document

Currently, the developers of my team format their source code (C++, C+, stored in MS's TFS 2012) manually. We are now considering to use Visual Studio's auto formatting option (probably with Uncrustify as the pretty print engine). The idea would be to make sure that nobody has any outgoing changes, and then to format the whole code base and to commit the result. From then on, we would integrate automatic formatting into our workflow.
However, our fear is that we will afterwards not be able to easily find out who has done the last changes on a particular line of code using Source Control/Annotate (that information is often quite useful, e.g. for asking the according developer about that code).
So here are my two questions:
a) Does anybody have experience with introducing auto-formatting into a team's workflow (given an already existing and quite large code base)? Are there any best practices for this?
b) In particular: Is there any way to format our complete code base without loosing the history information? I could e.g. imagine a tool which would keep track of where each line has gone after formatting, and to adjust TFS's history such that that information is preserved. However, I haven't found anything like that by now.
Annotation will indeed be 'screwed up' by pretty-printing the whole project. There are no tools that I know of that can work around that.
A way to get the least amount of history issues is to have each developer prettify a method when he is making changes to it to add functionality or solve a bug, this will take time to propagate the whole code base, but it's the only way I know of.

When I use WinForms (C#) designer in VS2010, it still generates code that StyleCop complains about

Some problems that I recall (there may be more):
Includes regions
Does not use this. prefix for member variables and methods
Includes comments like the one below ( having // by itself catches the eye of StyleCop)
//
// fileNameTextBox
//
If I make a change to the text, and then open the designer again, and screws up my previously perfected fruits of hard labor. How did / would you solve this problem?
I heard but did not personally experience a similar problem with WPF. How did / would you fix that?
Thanks.
There are several ways to make StyleCop ignore generated code:
StyleCop: How To Ignore Generated Code
As I recall it, ignoring generated code is the default setting (at least, it ignores my VS 2008 generated code with the standard settings).
I don't use VS 2010, so I don't know if they changed the designer generated files somehow so that StyleCop doesn't recognize them as generated anymore.
Maybe the link helps you to figure that out in your code.
StyleCop can be instructed to ignore generated source files. I don't know why designer-generated files have to adhere to any arbitrary coding standard – the only thing that should ever read or write them is an automated tool, not the developer.
Code styles are mainly there to help developers. Code generators certainly couldn't care less.

If it is possible to auto-format code before and after a source control commit, checkout, diff, etc. does a company really need a standard code style?

If it is possible to auto-format code before and after a source control commit, checkout, diff, etc. does a company really need a standard code style?
It feels like standard coding style debates that have been raging since programming began like "put the bracket on the following line" or "properly indent your (" are no longer essential.
I realize in languages where white space matters the diff will have to consider it but for languages where the style is a personal preference is there really a need to worry about it anymore?
Auto-format can really only address whitespace.
It wont address developers giving variables bizarre nonsensical names.
It won't address some developers having functions return null on an error vs throwing an exception.
I'm sure others can think of more examples.
This is what we do at my work:
We all use Eclipse. We don't have a policy for using Eclipse but somehow none of us is an IDEA/IntelliJ guy. We also think our code should be written with legacy in mind. This means our code has to be readable in a certain way even years after (#1) no matter who wrote it and if that person even is in the company anymore.
Eclipse has couple handy features, automatic format on save and a specific Formatter tool. As you can see from the linked screenshot, it can be configured with XML. Thus there's a bunch of premade XML:s available for every worker in our company so that when a new guy comes in, we walk him through of the whole process and configure their Eclipse for them (yes, it's slightly evil thing to do) so that it actually uses those formatting XML:s we have provided. We do not enforce automatic format on save, we don't want to be completely intrusive, we just want to push all our developers into the right directions. For even increased compatability, we mostly use rules defined in JCC.
Next comes the important part, the actual builds. We are those who embrace automatic builds and for that we use Hudson Continuous Integration Server. There's two important parts in our configurations beyond this:
We use CVS loginfo to trigger builds whenever something is committed.
We utilize several plugins available for Hudson, including Continuous Integration Game in conjuction with the most important one, Checkstyle.
The Checkstyle Plugin is the magician in our code style enforcement guide line:
After commiting code to CVS, Hudson build is triggered
After build has been completed succesfully (all unit tests pass etc.), Checkstyle inspects the actual source files
Checkstyle ranks the code based rules we have defined for it
Continuous Integration Game sees the result of Checkstyle and awards/takes away points for the person who has the ownership for the relevant part of the code
Leaderboard shows total points for every commiter in system
Basically this means that when anyone commits ugly code into our CVS, our build server automatically reduces that person's points.
This means that eventually any one of us can be ranked on the Leaderboard based on the general code quality in both look and OO principles such as Law of Demeter, Cyclomatic complexity etc. etc. Naturally this isn't a completely serious statistic, but it's a good indication you're doing something wrong when causing a build to be initiated in our CI won't reduce your points - most of our commits are worth between 1 and 5 points.
And is it working? Sort of, I don't think anyone of us at my work writes ugly or unmaintainable code and personally I love to hunt all kinds of scores so it's definitely motivating me to make code that looks nice and follows all the OO paradigms I know of.
And do we as a company really need it? I think we do as you should see from reading this entire answer, it can be considered a good practice for the advancements it brings.
#1: in a related note, I refactored legacy code from 2002 today which used those standards, didn't look "bad" at all even in its original form and certainly not worse in its new form
No, not really.
If you can actually get it to work consistently and not make it flag code has changed due to a different style of laying the code out.
However, this is just a small part of coding standards. It won't cover multiple return statements, the use or not of ternary operators, etc.
It is always nice if the coding style that the shop uses is the same one that is also followed by the development tools.
Otherwise, if there is a large body of code that already follows a shop standard which is NOT the same as that of the tools you have two choices:
Modify all of the code to follow the tool standard, or
Maintain the existing shop standard.
Many shops do the latter. Regardless, there does need to be some kind of standard, and it does need to be followed.
Some development tools allow you to tweak their standard. In some cases you may be able to bring the tools in alignment with the shop standard.
It probably doesn't matter that much anymore if you can ensure that everybody in the team sees the source code "correctly" formatted, whatever they think it is. However I've not seen a system that can do that - you can do parts of it (say, reformat before and after checkin/checkout) but these days you also have to consider web interfaces into the version control, external code review systems that interact directly with the version control system etc.
The main purpose of a standard code style is (IMHO) to ensure that you can read other team members' code easily without having to start reverse engineering it because all the code is written using the same sort of guiding principles. Indenting and parentheses placement seem to be a major hangup on this but they are only a very small and in my opinion, somewhat overblown and not very important part of the need to make code consistent.
Unfortunately I'm not aware of any tools that can automatically apply consistent coding principles to source code...
Yes, coding styles are needed if there is a desire to have a homogeneous code base. Such a code base can be useful in preventing individual ownership of parts of the code base, which can cause problems when people leave the team. If you can't imagine having wildly different styles and problems understanding all of it, just look at all the different ways English text can be organized in various communications, all written but quite different such as tweets, e-mail, text messages, IM, message board posts, etc. and changes in fonts, capitalization, decorations, etc.

Simple & Practical C# code generation (VS 2008 or 2010)

I've put off using generated code as part of the build process for fear of the complexity it introduces into the build process.
Is there a simple way to integrate build-time generated code into an app?
The kind of code I'm thinking of is similar to the resource and settings file code generation that Visual studio performs:
Having intellisense here is valuable
There are a lot of properties and links between properties that are trivial to describe, but impossible to implement tersely in C#.
The underlying resource is be modifiable and the code is automatically regenerated without needing any user interaction and without any need to understand the internals of the generator.
For (a non-real-world) example consider a precompiler that generated accessor to the named capture groups of a Regex via similarly named C# properties (or methods). This is typical of the kinds of things I'd like to generate: long snippets of boilerplate wrappers whose primary function is to enable compile time checking for errors (in the above; accessing non-existant capturing groups or writing and invalid regex) and no less importantly, intellisense for these properties. Finally, this setup should be trivially usable by others on the team with only the bare minimum of learning curve. I.e., it's absolutely not acceptable to require manual intervention to regenerate the code, nor acceptable to commit the generated code into source control. At worst, everyone should just need to install some extension; ideally the extension should be installable into the source-tree so that anyone that checks out the tree can build the project without any introduction.
For that to work well, it's critical that the IDE integration be excellent: Updating the underlying "resource" definition file should trigger a regeneration of the code without any user interaction, and ideally the generator itself would be easy to maintain for other developers later on (i.e. some amount of generator debug-ability is a plus).
Finally, an XSLT-like approach where the same template can be applied to various input resources is ideal; both because this means that you don't even need to look at the actual generator code if all you want to do is is update the resource, and because it makes template reuse trivial.
I've looked at T4, but from what I've seen this has a less handy ASP-like approach where template and resource aren't cleanly split (i.e, the generator is responsible for finding the resource - which makes template reuse less easy).
Is there a better (cleaner) solution or some way of running T4 such that the same template is can be trivially reused and (much like .NET settings files) that any update of the resource automatically triggers a regeneration of the implemented code?
Summary:
I'm looking for a code-gen approach that can
Regenerate code automatically without dev intervention when the underlying resource (not the template!) changes.
Be somewhat simple to maintain
Be able to share the same generator template between several resources (which, with point #1 probably implies the resource should refer to the generator and not vice-versa).
You can use T4ScriptFileGenerator from T4 Toolbox. Change "Custom Tool" property for your "resource" file to T4ScriptFileGenerator and save changes. The custom tool will generate a new, empty T4 script (.tt file). Place your code generation logic in this .tt file. Any time you modify (and save) the resource file, the T4ScriptFileGenerator will use the .tt file to generate the output code. For an example of how this works, see "LINQ to SQL Model" generator in the T4 Toolbox, which uses a .dbml file as the "resource". In the .tt file created by this generator, you will see that all of the code generation logic resides in separate .tt files and is reused with the help of include directives.
You may want to keep an eye on ABSE (http://www.abse.info). ABSE is a code-generation and model-driven software development methodology that is completely agnostic in terms of platform and language, so you wouldn't have any trouble creating your own generators for C# and anything else you wish. The big plus is that you can generate code exactly the way you want. The downside is that you may have more work to do at first to build your templates.
ABSE allows you to capture your domain knowledge into "Atoms", which are basically fragments of larger models you can build. ABSE is both declarative and executable. The model is able to generate code by your specification and incorporate custom code at the model level.
Unfortunately, ABSE is still work in progress and an Integrated Development Environment (named AtomWeaver) is still in the making. Anyway a CTP release of the generator is scheduled for January 2010, so we're already close to it.

C# - what are the benefits of "partial" classes?

I'm asking this because I find it quite a dangerous feature to distribute the class definition so that you can't really be sure if you know all about it. Even if I find three partial definitions, how do I know that there's not a fourth somewhere?
I'm new to C# but have spent 10 years with C++, maybe that's why I'm shaken up?
Anyway, the "partial" concept must have some great benefit, which I'm obviously missing. I would love to learn more about the philosophy behind it.
EDIT: Sorry, missed this duplicate when searching for existing posts.
Partial classes are handy when using code generation. If you want to modify a generated class (rather than inheriting from it) then you run the risk of losing your changes when the code is regenerated. If you are able to define your extra methods etc in a separate file, the generated parts of the class can be re-created without nuking your hand-crafted code.
The great benefit is to hide computer generated code (by the designer).
Eric Lippert has a recent blog post about the partial-keyword in general.
Another usage could be to give nested classes their own file.
An other point is, that when a class implements multiple interfaces, you can split the interface implementations on diffrent files.
So every code file has only the code that belongs to the interface implementation. It´s according to separation of concerns concept.
Two people editing the same class, and autogenerated designer code are the two immediate features I can see that were solved by partial classes and methods.
Having designer generated code in a separate file is a lot easier to work with compared to 1.1, where you code could often be mangled by Visual Studio (in windows forms).
Visual Studio still makes a mess of syncing the designer file, code behind and design file with ASP.NET.
If you have some kind of absurdly large class that for some reason are unable or not allowed to logically break apart into smaller classes then you can at least physically break them into multiple files in order to work with it more effectively. Essentially, you can view small chunks at a time avoiding scrolling up and down.
This might apply to legacy code that perhaps due to some arcane policy are not allowed to mess with the existing API because of numerous and entrenched dependencies.
Not necessarily the best use of partial classes, but certainly gives you an alternate option to organize code you might not be able to otherwise modify.
maybe its too late but please let me to add my 2 cents too:
*.When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
*.You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code

Categories

Resources