Constructor keeps disappearing - c#

I have a c# program that interacts with an sql database. I added the database using Server Explorer, and now have a dbml file to interact with it. The name is MasterDatabase.dbml. The IDE generated several overloaded constructors in MasterDatabase.designer.cs.
I added another overloaded constructor that takes no parameters (every one the computer generated takes at least one parameter). The code works perfectly with this overloaded constructor, but it will occasionally disappear! The constructor will be there for days, and then one day I will run my code and get a bunch of errors saying that there is no constructor that takes 0 arguments. I will then go back to MasterDatabase.designer.cs, and my constructor is no longer there. So I add it again, and the cycle repeats itself.
Has anyone experienced this before? And more importantly, how do I fix it so that my constructor stops disappearing?
I did not post any code, because this is a general question, and I don't think my specific code will help solve the problem, but let me know if you need to see any of it and I will.

You generally don't want to modify those generated classes directly. Those classes may be rebuilt without warning. I don't have much experience in this, but I believe those generated classes are partial classes. Create a new .cs file completely, with the same class name (including the partial keyword) and add the constructor there.

The problem is you are editing a generated file. WPF uses partial classes to seperate YOUR code from GENERATED code. You can create 'partial' classes of your own, although this serves no particular use other than organization of code. To get to the point, whatever code you write in a partial class can be rewritten in any other partial class file, so long as the classes are same. So take your overloaded constructor and put it into a NON-GENERATED file. This will prevent the generator from editing any changes you have made in that file. If the code worked sometimes in the generated partial file, it should always work if put into a non-generated partial file, because the code is not altered by Visual.

Related

C# Can I use partial classes to make code more readable

So for example I have this Web Api controller class AdministratorController and it contains a lot of tasks:
Create
Delete
Edit Password
Update
Get
Get all
Etc...
Now I have all these Tasks in 1 file AdministratorController.cs. But with all comments and annotations the file is pretty long.
Is it a good method to split this controller up into partial class pieces to make developers that search for a specific function get quicker to their destination? Or is this abusing the partial keyword
So for example I have a folder structure of:
--Controllers
⠀|-- Administrators
⠀⠀⠀⠀|-----AdministratorCreateController.cs
⠀⠀⠀⠀|-----AdministratorDeleteController.cs
⠀⠀⠀⠀|-----AdministratorEditPasswordController.cs
Obviously, this is a opinionated answer. Technically speaking, yes you can. It will compile.
I think you are right to split this into multiple files if it gets to long.
You could have partial classes. Or you could just have multiple classes. No one forces you to put all those methods into a single controller.
Personally, I'd opt for the multiple classes for practical reasons. You probably do dependency injection and you probably do it via constructor injection, because this is the default. With partial classes, which just means one big class but multiple files, you now need to edit your current file, plus the file that the constructor resides in to add a new service. It also means all the methods will need the DeleteDataService injected, although only the Delete method uses it. If you had one controller per method, you'd have the constructor in the same file and the other classes are not dependent on it.
But if for example you do injection via [FromService] attribute in your method then there is little difference between your two choices.
Structuring them in different files if keeping them in one file is too long is good. So good, that I don't think it would be too bad, even if you picked the "wrong" method to do it. So pick the one that seems most practical to you.
It depends on what you mean by "readable." To the extent that we must read a class, whatever we have to read doesn't become less by being placed in separate files. There's just as much to read either way. It could even be a nuisance looking through parts of a class across separate files looking for a particular member.
Partial classes might make us feel like we're separating code when we're really just making bigger classes. If we think we're making anything simpler with partial classes then they could even make our code harder to understand by encouraging us to add more to a single class while separating it into different files.
I'm not railing against partial classes. This stuff only exists if there is a use for it, and I don't mean to imply that anyone who uses them is abusing them. One example is autogenerated classes, like when we add a service reference (do we still do that?) We might make some modifications to the class, but then they get lost if we update the service reference and redo the auto-generation. If we put our custom code in a partial class then we can generate part while leaving the rest intact.

Create method with refactor shortcut, is there a way to chose between partial or non partial target?

So basically, I have a tool that I designed, that generates some code based on the model, and pastes this code automatically inside the .partial classes, on this approach, .partial is used for generated code, and his normal class is used for my manual code, this way I don´t loss my code everytime is auto-generated.
The problem is, in previous versions of visual studio, when you pressed CTRL+(dot) to refactor and create new methods, it automatically created this inside the regular file, not the partial. Knowing this I designed my tool to write auto-generated code on the partial.
Now i´m using Visual studio 15 and above, and it seems this changed, refactors are created into .partial files, making my approach annoying... I need constantly to move generated method.
is there a way to configure where to place this refactored methods?

Visual Studio Partial Class Per Method Downsides?

In Visual Studio, using a c# project, instead of placing a class that contains multiple methods and properties in a single file would there be any downsides to using multiple files with the partial keyword and nested file linking?
For example, if I have a class called Customer that has some properties and two methods: GetOrders and GetAddress. Instead of creating one file called Customer.cs and placing all the code for the properties and two methods in that file I would create a Customer.cs and place only the properties in that file. I would mark the class as partial. I would then create each method in a new file called Customer_GetOrders.cs and Customer_GetAddress.cs, each containing a Customer class marked as partial and only the code for that method. In Visual Studio I would nest the Customer_GetOrders.cs and Customer_GetAddress.cs files under the Customer.cs file.
The upsides I can see are less code in a file to look at so instead of scrolling up and down in a big file you would only see the code dealing with the method you are working on. Also if you are using source control merges would be easier since you would only have to deal with the code in each method. And since methods are bound by physical files you could easily see the change history of a method by looking at the change history of the file.
The downsides I can see are having a lot of small files but I don't think that would be so bad. Are there any other downsides with this line of thought?
Thanks,
Frank
The upsides I can see are less code in a file to look at so instead of scrolling up and down in a big file you would only see the code dealing with the method you are working on. Also if you are using source control merges would be easier since you would only have to deal with the code in each method. And since methods are bound by physical files you could easily see the change history of a method by looking at the change history of the file.
All of these upsides, in my opinion, are only "upsides" if the class is too big. If your class adheres to the Single Responsibility Principle, the file should never be "too big" to manage.
Also, most IDEs (such as Visual Studio) already provide a huge amount of functionality to navigate the files quickly (such as the pulldowns that jump directly to members).
The downsides I can see are having a lot of small files but I don't think that would be so bad. Are there any other downsides with this line of thought?
You're splitting your types up across multiple files, which makes it far less maintainable and more difficult to follow, as the data used by the type is no longer near the methods that use it.
You also add extra maintenance cost to refactoring, as method renames, for example, now would require additional work (file renames) which would break your "history" of that method within that file.
Overall, I'd find this a bad practice. Partial classes are great if you have generated code, and want to be able to add other logic to a generated code file, but otherwise, they tend to be something I'd personally avoid.
It is a Code Smell to me: a class sufficiently large that something is gained in understanding by partitioning into multiple parts is an indication that it has too many responsibilities. It's probably a poorly thought out abstraction that should be partitioned into multiple classes.
For example, if I have a class called Customer that has some properties and two methods: GetOrders and GetAddress. Instead of creating one file called Customer.cs and placing all the code for the properties and two methods in that file I would create a Customer.cs and place only the properties in that file. I would mark the class as partial. I would then create each method in a new file called Customer_GetOrders.cs and Customer_GetAddress.cs, each containing a Customer class marked as partial and only the code for that method. In Visual Studio I would nest the Customer_GetOrders.cs and Customer_GetAddress.cs files under the Customer.cs file.
From a modelling perspective, GetAddress() and GetOrders() shouldn't be methods, at least, not on the Customer object. A Customer probably has 1 or more Address properties and single, collection-like property, Orders, that represents the customer's order history.
I think your abstraction is missing some classes. Perhaps you need an OrderFactory, that given a Customer (and possibly other criteria), knows how to find 1 or more of the customer's orders.
There is actually a big problem with visual studio. The more files that you have the longer it takes to compile and even load a solution. Give it a go sometime with lots of text files, imagine 7 or 8 extra files per class a standard solution would explode in size in no time and .
From a .net compiler perspective there is nothing wrong with this.
The only other problem is maintainability ie code navigation knowing what goes where.

Functions with <>s and listing partial classes under a single file?

What are functions with <> called? I mean, I usually see them in defining lists like List<> SortedList<> etc. And they get value types into their parameters (as I've seen). (List<bool> etc.). Could I create a class that gets value types as parameters like that?
CustomClass<bool, int>(32, "asd") test;
Other question:
Could I list seperated but partial classes under a single file (like Form's form.designer.cs and form.resx)
Generics
Other question: no afaik (if you talk about vs solution explorer) but you can put partial classes into single file.
In general, have multiple partial classes in the same file. The only limitation is that they are part of the same assembly.
However, the Form1.designer.cs and Form1.resx files are generated by VS's editing tools. If you try messing around with generated files, they just get generated again. Furthermore, the .resx file isn't even C# -- it's XML!

Why does the Visual Studio Designer delete code?

Several times throughout the course of our current project, the visual studio designer has made modifications that resulted in losing code. For example, event handlers wirings that were set up manually in the designer code were lost. Does anyone know why this happens?
Edit: I understand that editing these files manually is not a good idea, but it has also happened with other event wirings set up through the designer.
Well for starters read the XML at the top of your designer.cs file.
/// <summary>
/// Required method for Designer support - do not modify
/// contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
Generally you shouldn't be modifying these files as they are auto-generated. It's probably the reason why there is a slight attempt to hide the code within a branch, underneath the main partial class.
I have on occasion found that the process has removed its own auto-generated code that I've had to merge back in. Most commonly it decides it's not going to instantiate custom user controls anymore, so when I start running I get a NullReferenceException.
Really the answer is to put the code somewhere else, like in the constructor before calling the InitializeComponent() method. If fellow developers aren't aware of this, then you should inform them and educate them, the fact that the files are .designer.cs should raise questions even to newer developers as to why the strange extension.
You guys aren't modifying generated code files, are you? Like MyForm.Designer.cs? This is why we were given partial classes.
Because it is designer generated and more or less maintained code. It is recommended that you not add or modify code in the designer partial class manually exactly because of the behavior you described (I think it even mentions this in the generated file itself). If you need to wire up event handlers manually then do it in your custom code possibly the constructor of your control.
Write all necessary initialization code only in your own .cs file, you have number of places to do this, like form constructor and form Load event handler.
Moving the designer code into user maintained code classes defeats the benefits of being able to modify the user interface. Perhaps this might be something you would want to do if the program never needs to be modified again, but if that is the case... where is the benefit as well?
This issue of the designer class losing lines of code has existed since Visual Studio was initially released and has caused me countless nightmares because the loss occurred perhaps weeks before, when the program was previously modified.
I can't prove it but it seems obvious that something in Microsoft's code generator is failing and there isn't any alerts to tell you it crashed. So, Microsoft... fix what is crashing or at least, tell us about it when it happens.

Categories