C# attribute formatting conventions - c#

Lately I've seen attribute tags formatted into two ways in C# (even in the official microsoft guide):
[foo]
public class bar {...}
and
[foo] public datatype bar;
Is there any advantage to where the tag is placed? Should the tag be placed in a certain position based on whether it is over a class or a datatype?

it's personal preference, it's not going to make any difference to the compiler, pick one and be consistent.
That said, I prefer the 1st format in both cases because it's possible to have multiple attributes on both classes and datatypes - and I find it easier to read spread out.
it would get messy quickly if you did that in-line.
take the following sample code for a class for example:
[Author("P. Ackerman", version = 1.1)]
[Author("R. Koch", version = 1.2)]
class SampleClass
{
// P. Ackerman's code goes here...
// R. Koch's code goes here...
}
putting it inline just makes it unreadable.

Related

Bond: How to change field and class names during code generation

I have a bond file with a struct like this:
struct Foo
{
0: float myField1;
1: float myField2;
}
I am using this file to generate code for C++ and also for C#. But in the C# code, I want the field names to be capitalized: MyField1, MyField2.
Is there any way to do this?
Similarly, I might want Foo to be named Bar in my C# code (in order to be backward compatible with my pre-bond clients). But I don't see any documentation on how this can be done.
There is no way to rename types/fields when using the Bond code generator, gbc. The features simply don't exist.
If you want, you can write a C# class by hand and annotate it with Bond's attributes. This will get you a highly compatible struct. You do lose much of the benefit of having one, central location to describe the structs in the .bond file with this approach. That might be the right trade off to interface with your pre-Bond clients by annotating the existing classes.
An example of how you'd do this based on the structs in the question:
[Bond.Schema]
class Bar
{
[Bond.Id(0)]
public float MyField1;
[Bond.Id(1)]
public float MyField2;
}
This has some caveats:
You'll have to manually keep it in sync with the .bond file when you make changes.
The full schemas of these Foo and Bar structs differ slightly. The fields have different names ("myField1" vs. "MyField2"), which you'll be able to detect if you look at the SchemaDef of each struct. When using binary protocols, the field names don't matter: only the IDs do. When using the text-based protocols, the names do matter.

What does the syntax seen when decompiling c# dynamic operations actually mean?

I've recently had to make a forray into decompiling a colleague's code while they're away, and found that most of it looks surprisingly nice (thanks ILSpy), with the notable exception of a couple of places where we needed to use dynamic - these got mangled into several parts:
A call site container - i.e. what resembles a class in definition, but let's say the method in which dynamic was used was DoStuff, would have a declaration along the lines of public /* static? I forget */ class <DoStuff>CallSiteContainer_Plus_Some_Weirdness { /* bunch of CallSite fields */ }
A lot of code that checks whether various CallSites within the container have been assigned and assigns them before usage as required using approaches I really don't get yet.
My question is regarding the syntax of the class declaration in the 1st point. It looks like a generic class, but it clearly isn't. Can anyone explain what's going on there?
Please note, I'm not looking for help in working out the original code - I've already managed to do that by judicious use of find and replace, and breaking out the autogenerated code from everything else. But I'd like to understand how the CallSite container syntax is a valid class name!
Here's an example of such auto-generated class:
private static class <>o__0
{
public static CallSite<Action<CallSite, Type, object>> <>p__0;
}
If you are worried about the <>o__0 class name and the <>p__0 field name, then you are right, those are not valid C# names but this doesn't mean that they are not valid IL names which is what the compiler generates. The reason why it uses such special symbols is to ensure that they will never conflict with class names that you as a developer might have written.

How to format my class? With toString, in the GUI or in other way?

I have some classes in a library that are representing analysis and validation results of some files.
These classes contains enums, Lists of invalid properties, etc.
I wrote a GUI application that uses the library, and wrote some functions for writing those classes in readable form in a rich text box.
It just occured to me, that I may have to write this formatting in a ToString overriding of the class.
However, all this formatting is very long, includes inserting tabs and new lines, includes several iteration over the lists, extracting enum description etc.
So I was wondering - what is the standart for toString size and complexity? Am I suppose to write difficult formatting in the toString? Or maybe I should provide some other common interface- is there any common interface for a formatted printable output of a class? Or shall I do it in the GUI application?
Thanks!
Stuff like UI formatting shouldn't be baked into any library except UI libraries.
Instead what you could do is provide a UI agnostic set of classes that can format your entities, as in, can do the complex code necessary to produce a format with the expectation of being displayed in a UI.
These could use a simple interface, something like:
public interface IEntityFormatter<T>
{
string GetFormattedValue(T myEntity);
}
public class Customer
{
public string FullName {get;set;}
}
public class CustomerFormatter : IEntityFormatter<Customer>
{
public string GetFormattedValue(Customer myEntity)
{
return myEntity.FullName;
}
}
Generally, ToString should not be very complex, otherwise, it may slow down debugging (note that it's often called automatically by the debugger). Adding your own interface also allows you to add more customization. On the other hand, if you don't need any settings for the formatting then ToString might be a good place to implement it.

In C#, what is a good way to exclude a class when outputting code from textfile

What I want to do may seem like a weird scenario. Please keep in mind that I need to do this for a Demo project, where I output c# code to the user to teach them how certain controls are coded.
I am given a .cs file and I need to output the contents. There is at least one class in the file, and at most...a lot. I need to output the whole file, EXCEPT one type of class. The specific type of class that I want to prevent being outputted all inherit a certain base class, so they should be easy to distinguish.
Here is an example:
public abstract class A{}
public class B{]
public class C{}
Assume these are the base-types that some of my classes may inherit. I want to prevent outputting all classes that inherit from A. A is probably going to be the only abstract base class so if that can help in anyway, that would be awesome.
Let's say I'm given a file, example.cs:
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
And the output should be
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
The only way I have thought of is brute-force string manipulation. I can't, however, use whitespace as a separator between classes because there is no guarantee if there will even be white space between classes. I will need to keep track of open and closed curly brackets to discover where one class begins and another end. I also need to test for the base class of each class by testing the string tokens before the first {} pair.
Also I need to prevent the attributes of AA from outputted too.
Since there are many brighter minds out there, I am here to ask if there is another simpler/cleaner method for doing what I need.
Thanks for reading!
Edit after YetAnotherUser's answer: The output should be exactly the same as the file, which includes all comments.
Another edit: Instead of answering with certain software or libraries that could do this, I would more prefer algorithms. Maybe regular expressions? I am not good with them so I do not know the extend that they can be used for.
Could you wrap everything you need to exclude with:
#region ExcludeRegion
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
#endregion
See the #region documentation
This should be relatively easy to scan for and exclude. It also gives you the added benefit of showing what you're hiding in the IDE.
You can try to use open-source lib NRefactory. It supports parsing the code into AST which you can modify afterwards and generate output code. It also can retain your comments as shown on their wiki page.
Found it here: An alternative for "CSharpCodeProvider.Parse"
Update: Apparently there's no implementation of CodeDomProvider that supports parsing. Hence this is invalid - I'll keep this post to ensure this is highlighted to someone thinking on same lines.
You can parse the code using CodeDomProvider and then remove the required classes and regenerate the code file.
If it is for educational purpose, this might not exactly fit your needs as generated file might not exactly match with the original source file.
See -
System.CodeDom Namespace
Using the CodeDOM
Microsoft .NET CodeDom Technology - Part 1

How to parse C# code to find the derived class and interfaces of a class

I am looking for an approach for finding the code between the base class identifier colon and the opening curly brace of a class that's been that's been stored into a string literal.
By this I mean that I have a class
public class Class : BaseClass
{
}
That's been stored as a string
string classString = "public class Class : BaseClass{}\r\n"
The class will most certainly be more detailed with the potential for strongly-typed, fully qualified base class and interfaces, but I need an approach for sniffing out the code between the colon and opening curly bracket.
Assuming that the class is not a generic that defines derivation constraint
i.e.
public class LinkedList<K,T> : BaseClass
**where K : IComparable**
{
}
Then it might be safe to assume that there would on be one colon in the class definition and it would fairly easy to find the derivation colon and the opening curly brace.
If that's the case I could do
string baseClassString = classString.Substring(derivationColonIndex + 1, (openCurlyBraceIndex - (derivationColonIndex + 1)))
Can anyone think of a better approach that would GUARANTEE the I get a string for the baseClass and any interfaces that might exist between the colon and opening curly brace.
Background for why I'm needing this : Classes are being generated base on data coming from a database, if the certain data in the db changes, then potentially, I have the need to change the inheritance in the class string. Thus, I would replace the existing substring of the base class and interfaces.
Man, you really should be using CodeDOM:
http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx
The CodeDOM provides types that
represent many common types of source
code elements. You can design a
program that builds a source code
model using CodeDOM elements to
assemble an object graph. This object
graph can be rendered as source code
using a CodeDOM code generator for a
supported programming language. The
CodeDOM can also be used to compile
source code into a binary assembly.
I'd like to draw your attention to the object graph. Using the object graph, you should be able to do what you need to do.
EDIT: Sorry for the misdirection, actually what you're trying to accomplish is the reverse of what I suggested - my bad! You may want to look at the following projects, which offer the capability to build an object graph from the code, rather than generate code from an object graph:
http://csparser.codeplex.com/
http://wiki.sharpdevelop.net/Default.aspx?Page=NRefactory&NS=&AspxAutoDetectCookieSupport=1
You are going down into a pretty deep rabbit hole. Writing your own C# language parser is a task that can keep you occupied for a long time, with a pay-off that enhances your skill as a programmer but doesn't turn the boss' frown upside-down.
You are re-inventing a wheel. The DataSet designer built into Visual Studio already does what you're trying to do. It could be argued that it is the wrong wheel, the fans of NHibernate will certainly think so. They generate the dbase schema from the C# class declarations.
Rescue your plan by considering that modifying an existing C# class that models the dbase is not necessary. Just re-generate the class from scratch every time you compile. It normally only takes a fraction of a second. The compiler will dutifully warn you when there's a breaking change. That's how the Settings designer and the Resource designer work.
If you're willing to spend some time learning it, SharpDevelop contains a C# parser named NRefactory. It returns an abstract syntax tree from a source string. It could catch errors and handle other language elements like comments, attributes, etc.
Obviously it's not a quick fix, but if you have the time it's an interesting tool.
There's an ANTLR grammar for C#. Maybe you can use that?

Categories

Resources