What controls XML serialization order of C# partial classes? - c#

As discussed in Does the order of fields in C# matter?, the order of serializable properties affects, among other things, XmlSerializer output.
But if fields are in 2 files (using partial classes), does anyone know what in fact controls the resulting order? That is, which file's properties comes first?
(Background: I ask this because I've run into a scenario where one of the 2 files is auto-generated from xsd, and the other is manually edited. The test output is different on developer boxes vs. our scripted build box. Presumably this is a side effect of the several differences in the timing and history of the xsd->C# step in the 2 environments. Various ways to fix, but I'd like to understand the compilation process a little better if possible.)

Nothing is guaranteed per C# spec.

I've found that using the 'easy' approach to making an object by marking it [Serializable] is usually only good enough for very simple implementations.
I would recommend that you implement the IXmlSerializable interface which is pretty easy to do and gives you all the control you need.

Here is what we found out through the fix of a nasty bug:
We had exactly the same problem, our serialization order has changed after a release without modifying any of the serialization related classes.
We had one half of a class generated from xsd-s, and the other half was hand-made. The order attributes were effect-less. What we saw was that before the release, the hand-made partial parts were serialized first, and after it the order changed.
The solution was in the order of the files in project file, that contained the two classes. It turned out, that after an MSBuild (on our build server) build, the serializer will put the elements of the earlier (in the csproj) ".cs" file first in the serialized XML. Changing the order of the ".cs" files in the csproj swapped the order and the generated parts were up front as needed in the XML.
This is is aligned with the answer and observation of Eric Hirst above, as renaming the file reorders the csproj's items (they are generally in alphabetical order). Watch out for editing the csproj by hand for this reason too.

Related

Is altering my namespace a nicety, or a necessity?

I added two custom classes to my project, namely "AutoSizeGrid" and "AutoSizeGridEditable"
Both derive from DataGridView, but that's probably neither here nor there.
But where they are is seemingly somewhat of a conundrum.
My project builds and runs fine; however, when inspecting it with Resharper, it gives me a "Constraints Violation" for both of these, saying: "Namespace does not correspond to file location, should be: ''
Do I need to change them like so, from, e.g.:
class AutoSizeGrid : DataGridView
...to:
class <Name of my Solution>.AutoSizeGrid : DataGridView
?
I'd rather not, as I don't know if this would force me to delete the prior DGV-derived components from my forms and replace them with the recompiled versions; that would be a pain in the donkey.
As ElVieejo says, it is not necessary to change it if the code compiles. ReSharper (and other code quality tools) recommend you keep namespaces in sync with file paths because that is the Microsoft convention. Namespaces are extremely helpful for keeping code organized, especially as projects/applications get larger, so it's good to have some clear rules and follow them, but they are for readability and separation of concerns, not syntactical correctness.

Arranging solution files

My C# .NET solution files are a mess and I am trying to find a way of getting things in order.
I tried to put all close files together in the same folder I am creating for that purpose. For example, I put interfaces, abstract classes, and all their inherited classes at the same folder. By the way - when I do that, I need to write a "using" statement pointing to that folder so I can use those classes in other files (also a mess I guess).
Is there an elegant way of doing things more clean, and not a list of files that I find very confusing?
Is it a good idea to (let's say) open a abstract class file and add nested classes for all the classes derived from it?
Is there a way of telling the solution to automatically set the folder "using" statements above every class I create?
The best way is when your solution file system structure reflects your program architecture and not your code architecture.
For example: if you define an abstract class and after have entities that implement it: put them into the same "basket" (solution folder) if they make a part of the same software architectual unit.
In this case one by looking on your solution tree can see what is your architecture about (more or less) from very top view.
There are different ways to enforce the architecture vision, understanding and felling of the code file system. For example if you use some known frameworks, like NHibernate, or (say) ASP.NET MVC tend to call the things in the name the technolgy calls them, in this way one who is familiar with that technology can easily find itself in your architecture.
For example WPF force you define in code things in some way, but also you need to define byb the way Model, ModelView, View.. which you will do intuitively in seprate files. The technology enforcce you to define your file system in way it was thought.
By the way the topic you're asking for, is broad known dilema/question, not resolved, cuase the code is just characters sequence and nothing else.
Good luck.
It sounds like you're hitting the point where you actually need to break things up a bit, but you're resisting this because more files seems like more complexity. That's true to a point. But there's also a point where files just become big and unmanageable, which is where you might end up if you try to do nested classes.
Keeping code in different namespaces is actually a good thing--that's the "issue" you're running into with the folders and having to add using statements at the top of your files. Namespacing allows you to logically divide your code, and even occasionally reuse a class name, without stepping on other parts of your code base.
What version of Visual Studio are you using? One little known feature of Visual Studio is that it can automatically create the using directive when you type a class name. That would eliminate one pain point.
If I was in your shoes, I'd start looking for logical places to segment my code into different projects. You can definitely go overboard here as well, but it's pretty common to have:
A "core" project that contains your business logic and business objects.
UI projects for the different user interfaces you build, such as a website or Windows Forms app.
A datalayer project that handles all interactions with the database. Your business logic talks to the datalayer instead of directly to the database, which makes it easier to make changes to your database setup down the road.
As your code base grows, a tool like ReSharper starts to become really important. I work on a code base that has ~1 million lines and 10 or so projects in the solution, and I couldn't live without ReSharper's go-to-file navigation feature. It lets you hit a keyboard shortcut and start typing a file name and just jump to it when it finds a match. It's sort of like using Google to find information instead of trying to bookmark every interesting link you come across. Once I made this mental shift, navigating through the code base became so much easier.
Try using multiple projects in the same solution to bring order. Seperate projects for web, entity, data access, setup, testing, etc.
IF the files are in the same namespace you won't need a using statement. If you're breaking your code into multiple projects you'll need to reference the other projects with using statements.
Its up to you. Break things apart logically. Use subfolders where you deem necessary.
Not sure.
Yes, but you'll need to create a template. Search for tuturorials on that.
1) Your solution folders should match your namespace structure. Visual Studio is set up to work this way and will automatically create a matching namespace. Yes, this requires a using for stuff in the folders but that's what it's for.
So yes, group common stuff together under an appropriate namespace.
2) Yes, subclasses should probably live in the same namespace/folder as their abstract base, or a sub folder of it. I'm not sure if you mean all in the same file? If so I would say generally not unless they're very very simple. Different files, same folder.
3) Not that I'm aware of. If you right click the classname when you use it you can get Studio to automatically resolve it and add a using (Ctrl + . also does this)

Automatically marking c# classes for serialization

I want to build a visual studio plugin that automatically annotates classes for serialization. For example for the built in binary serializer I could just add [Serializable] to the class declaration, for WCF it could add [DataContract] to the class and [DataMember] to the members and properties (I could get [KnownType] information through reflection and annotate where appropriate). If using protocol buffers it could add [ProtoContract], [ProtoMember] and [ProtoInclude] attributes and so on.
I am assuming that the classes we are going to use this on are safe to serialize (so no sockets or nonserializable stuff in there). What I want to know is what is the easier way to take an existent piece of code (or a binary if that's easier) and add those attributes while preserving the rest of the code intact. I am fine with the output being source code or binary.
It comes to mind the idea of a using a C# parser, parse everything find the interesting code elements, annotate them and write back the code. However that seems to be very complex given the relatively small amount of modifications I want to make to the code. Is there an easier way to do so?
Visual Studio already has an API for discovering and emitting code which you might take a look at. It's not exactly a joy to use but could work for this purpose.
While such a plugin would certainly be a useful thing, I would consider rather making an add-in for a tool like ReSharper instead of VS directly. The advantage is somebody already solved the huge pile of problems you haven't even dreamed of yet and so it will be a lot easier to build such a specific functionality.
it looks to me like you need to have a MSBuild task similar to this one http://kindofmagic.codeplex.com/. is that about right?

Classes Generated with XSD.exe Custom Class Names

Is it possible to have any control over the class names that get generated with the .Net XSD.exe tool?
As far as I'm aware I don't think this is possible, the class names match almost exactly to whats in the schema.
Personally I would change the class names after XSD has generated the code, but to be honest I usually just stick with what XSD generates. Its then easier for someone else reading the code to understand what classes map to what parts of the XML.
Alternatively, if you have control over the schema you could update that?
Basically, no. If you were writing the classes manually, you could have:
[XmlType("bar")]
class Foo {}
however, you can't do this with the xsd-generated classes. Unfortunately, one of the things you can't do with a partial class is rename it. Of course, you could use xsd to generate it, change the .cs file and don't generate it again, but that is not ideal for maintenance.
Any schema with somewhat deep nesting then ends up with utterly useless names.
I don't know of a way to work around the problem, but my tip to at least reduce the negative impact is this: Define a list of aliases for the awfully-named types. This way you can write code that isn't completely unreadable without losing the ability to regenerate.
using AgentAddress = Example.Namespace.DataContract.RootElementNestedElementAgentAddress;
...
It's a pity this list itself has to be copy-pasted to all code files needing it, but I think this at least constitutes an improvement.

C# classes in separate files? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Should each class in my C# project get its own file (in your opinion)?
While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea.
I typically break this rule if I have a very small helper class that is only used by the main class, but I prefer to do that as a nested inner class for clarity's sake.
You can however, split a single class into multiple files using the partial keyword. This is useful for separating your code from wizard-generated code.
Files are cheap, you aren't doing anyone a favor by consolidating many classes into single files.
In Visual Studio, renaming the file in Solution Explorer will rename the class and all references to that class in your project. Even if you rarely use that feature, the cheapness of files and the ease of managing them mean the benefit is infinitely valuable, when divided by its cost.
As others have said, one file per type in general - although where others have made the public/private distinction, I'd just say "one top-level file per type" (so even top-level internal types get their own files).
I have one exception to this, which is less relevant with the advent of the Func and Action delegate types in .NET 3.5: if I'm defining several delegate types in a project, I often bunch them together in a file called Delegates.cs.
There are other very occasional exceptions too - I recently used partial classes to make several autogenerated classes implement the same interface. They already defined the appropriate methods, so it was just a case of writing:
public partial class MessageDescriptor : IDescriptor<MessageDescriptorProto> {}
public partial class FileDescriptor : IDescriptor<FileDescriptorProto> {}
etc. Putting all of those into their own files would have been slightly silly.
One thing to bear in mind with all of this: using ReSharper makes it easier to get to your classes whether they're in sensibly named files or not. That's not to say that organising them properly isn't a good thing anyway; it's more to reinforce the notion that ReSharper rocks :)
I personally believe that every class should be in its own file, this includes nested types as well. About the only exceptions to this rule for me are custom delegates.
Most answers have excluded private classes from this rule but I think those should be in their own file as well. Here is a pattern that I currently use for nested types:
Foo.cs: // Contains only Foo implementation
public partial class Foo
{
// Foo implementation
}
Foo.Bar.cs: // Contains only Foo.Bar implementation
public partial class Foo
{
private class Bar
{
// Bar implementation
}
}
It depends. Most of the time I would say yes, put them in separate files. But if I had a private helper class that would only be used by one other class (like a Linked List's Node or Element) I wouldn't recommend separating them.
As someone who has been coding in large files for years (limited to 1,000 lines), in fact, since I started programming as a child, I was surprised at the huge consensus in this "one class per source file" rule.
The "one class per source file" is not without its problems. If you are working on a lot of things at once, you will have many files open. Sure, you could close files once you're finished with them, but what if you needed to re-open them? There is usually a delay every time I open a file.
I am now going to address points others have made and explain what I think are bad reasons for the "one class per source file" rule. A lot of the problems with multiple classes in one source file are resolved with modern source-editing technology.
"I hate having to scroll up and down" - Bad Reason - Modern IDEs now either have built-in functionality for getting quickly to the code you want or you can install extensions/plugins for that task. Visual Studio's Solution Explorer does this with its search function, but if that's not enough, buy VisualAssist. VisualAssist provides an outline of the items in your source file. No need to scroll, but double-click on what you want.
There is also code-folding. Too much code? Just collapse it into one line! Problem solved.
"Things are easier to find because they're identified by file" - Bad Reason - Again, modern IDEs make it easy to find what you're looking for. Just use Solution Explorer or buy VisualAssist!! The technology is out there, use it!!
"Easier to read/too much code" - Bad Reason - I am not blind. I can see. Again, with code-folding I can easily eliminate the clutter and collapse the code I don't need to see. This is not the Stone Age of programming.
"You will forget where the classes are in large projects" - Bad Reason - Easy solution: Solution Explorer in Visual Studio and the VisualAssist extension.
"You know what's in a project without opening anything" - Good Reason - no dispute with that one.
Source Control/Merging - Good Reason - This is actually one good argument in favour of the "one class per source file" rule, especially in team projects. If multiple people are working on the same project. It allows people to see what has changed, at a glance. I can also see how it can complicate merging processes if you use large, multiple-class files.
Source control and merging processes are really the only compelling reason IMO that the "one class per source file" rule should apply. If I'm working on my own individual projects, no, it's not so important.
They should be in different files, even when it seems like overkill. It's a mistake I still frequently make.
There always comes a time when you you've added enough code to a class that it deserves it's own file. If you decide to create a new file for it at that point then you lose your commit history, which always bites you when you lest want it too.
Public classes: yes
Private classes: (needless to say) no
I actually prefer pretty big .cs files, 5000 lines is pretty reasonable IMO, although most of my files at the moment are only about 500-1000 (In C++, however, I've had some scary files), however, . The Object Browser/Class View, Go to Definition, and incremental search (-I; Thanks for that tip, Jeff Atwood!), all make finding any specific class or method pretty easy.
This is probably all because I am terrible about closing unneded tabs.
This is of course highly dependant on how you work, but there are more than enough tools to not need to use horrible old '70s based file source navigation (Joking, if it wasn't obvious).
Of course! Why wouldn't you? Other than private classes it is silly to have multiple classes in a single file.
I think the one-class-per-file approach makes sense. Certainly for different classes, but especially for base and derived classes, whose interactions and dependencies are often non-obvious and error-prone. Separate files makes it straightforward to view/edit base and derived classes side-by-side and scroll independently.
In the days of printed source code listings running to many hundreds of pages (think of a phone book), the "three finger rule" was good a working limit on complexity: if you needed more than three fingers (or paper clips or post-its) as placeholders to understand a module, that module's dependency set was probably too complex. Given that almost no one uses printed source code listings anymore, I'll suggest that this should be updated as the "three window rule" - if you have to open more than three additional windows to understand code displayed in another window, this code probably should be refactored.
A class hierarchy of more than four levels is a code smell, which is in evidence if you need more than four open windows to see the totality of its behavior. Keeping each class in its own file will improve understandability for depth less than four and will give an indirect warning otherwise.

Categories

Resources