Override Default Constructor of Partial Class with Another Partial Class - c#

I don't think this is possible, but if is then I need it :)
I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008.
The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated.
I tried making another partial class and redefining the default constructor, but that doesn't work. I then tried using the override and new keywords, but that doesn't work.
I know I could inherit from the partial class, but that would mean I'd have to change all of our source code to point to the new parent class. I would rather not have to do this.
Any ideas, work arounds, or hacks?
//Auto-generated class
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public MyWebService() {
string myString = "auto-generated constructor";
//other code...
}
}
}
//Manually created class in order to override the default constructor
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public override MyWebService() { //this doesn't work
string myString = "overridden constructor";
//other code...
}
}
}

I had a similar problem, with my generated code being created by a DBML file (I'm using Linq-to-SQL classes).
In the generated class it calls a partial void called OnCreated() at the end of the constructor.
Long story short, if you want to keep the important constructor stuff the generated class does for you (which you probably should do), then in your partial class create the following:
partial void OnCreated()
{
// Do the extra stuff here;
}

This is not possible.
Partial classes are essentially parts of the same class; no method can be defined twice or overridden, and that includes the constructor.
You could call a method in the constructor, and only implement it in the other part file.

Hmmm,
I think one elegant solution would be the following:
//* AutogenCls.cs file
//* Let say the file is auto-generated ==> it will be overridden each time when
//* auto-generation will be triggered.
//*
//* Auto-generated class, let say via xsd.exe
//*
partial class AutogenCls
{
public AutogenCls(...)
{
}
}
//* AutogenCls_Cunstomization.cs file
//* The file keeps customization code completely separated from
//* auto-generated AutogenCls.cs file.
//*
partial class AutogenCls
{
//* The following line ensures execution at the construction time
MyCustomization m_MyCustomizationInstance = new MyCustomization ();
//* The following inner&private implementation class implements customization.
class MyCustomization
{
MyCustomization ()
{
//* IMPLEMENT HERE WHATEVER YOU WANT TO EXECUTE DURING CONSTRUCTION TIME
}
}
}
This approach has some drawbacks (as everything):
It is not clear when exactly will be executed the constructor of the MyCustomization inner class during whole construction procedure of the AutogenCls class.
If there will be necessary to implement IDiposable interface for the MyCustomization class to correctly handle disposing of unmanaged resources of the MyCustomization class, I don't know (yet) how to trigger the MyCustomization.Dispose() method without touching the AutogenCls.cs file ... (but as I told 'yet' :)
But this approach offers great separation from auto-generated code - whole customization is separated in different src code file.
enjoy :)

Actually, this is now possible, now that partial methods have been added. Here's the doc:
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
Basically, the idea is that you can declare and call a method in one file where you are defining the partial class, but not actually define the method in that file. In the other file, you can then define the method. If you are building an assembly where the method is not defined, then the ORM will remove all calls to the function.
So in the case above it would look like this:
//Auto-generated class
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public MyWebService() {
string myString = "auto-generated constructor";
OtherCode();
}
}
}
partial void OtherCode();
//Manually created class in order to override the default constructor
partial void OtherCode()
{
//do whatever extra stuff you wanted.
}
It is somewhat limited, and in this particular case, where you have a generated file that you'd need to alter, it might not be the right solution, but for others who stumbled on this trying to override functionality in partial classes, this can be quite helpful.

The problem that the OP has got is that the web reference proxy doesn't generate any partial methods that you can use to intercept the constructor.
I ran into the same problem, and I can't just upgrade to WCF because the web service that I'm targetting doesn't support it.
I didn't want to manually amend the autogenerated code because it'll get flattened if anyone ever invokes the code generation.
I tackled the problem from a different angle. I knew my initialization needed doing before a request, it didn't really need to be done at construction time, so I just overrode the GetWebRequest method like so.
protected override WebRequest GetWebRequest(Uri uri)
{
//only perform the initialization once
if (!hasBeenInitialized)
{
Initialize();
}
return base.GetWebRequest(uri);
}
bool hasBeenInitialized = false;
private void Initialize()
{
//do your initialization here...
hasBeenInitialized = true;
}
This is a nice solution because it doesn't involve hacking the auto generated code, and it fits the OP's exact use case of performing initialization login for a SoapHttpClientProtocol auto generated proxy.

You can't do this. I suggest using a partial method which you can then create a definition for. Something like:
public partial class MyClass{
public MyClass(){
... normal construction goes here ...
AfterCreated();
}
public partial void OnCreated();
}
The rest should be pretty self explanatory.
EDIT:
I would also like to point out that you should be defining an interface for this service, which you can then program to, so you don't have to have references to the actual implementation. If you did this then you'd have a few other options.

I am thinking you might be able to do this with PostSharp, and it looks like someone has done just what you want for methods in generated partial classes. I don't know if this will readily translate to the ability to write a method and have its body replace the constructor as I haven't given it a shot yet but it seems worth a shot.
Edit: this is along the same lines and also looks interesting.

Sometimes you don't have access or it's not allowed to change the default constructor, for this reason you cannot have the default constructor to call any methods.
In this case you can create another constructor with a dummy parameter, and make this new constructor to call the default constructor using ": this()"
public SomeClass(int x) : this()
{
//Your extra initialization here
}
And when you create a new instance of this class you just pass dummy parameter like this:
SomeClass objSomeClass = new SomeClass(0);

This is in my opinion a design flaw in the language. They should have allowed multiple implementations of one partial method, that would have provided a nice solution.
In an even nicer way the constructor (also a method) can then also be simply be marked partial and multiple constructors with the same signature would run when creating an object.
The most simple solution is probably to add one partial 'constructor' method per extra partial class:
public partial class MyClass{
public MyClass(){
... normal construction goes here ...
OnCreated1();
OnCreated2();
...
}
public partial void OnCreated1();
public partial void OnCreated2();
}
If you want the partial classes to be agnostic about each other, you can use reflection:
// In MyClassMyAspect1.cs
public partial class MyClass{
public void MyClass_MyAspect2(){
... normal construction goes here ...
}
}
// In MyClassMyAspect2.cs
public partial class MyClass{
public void MyClass_MyAspect1(){
... normal construction goes here ...
}
}
// In MyClassConstructor.cs
public partial class MyClass : IDisposable {
public MyClass(){
GetType().GetMethods().Where(x => x.Name.StartsWith("MyClass"))
.ForEach(x => x.Invoke(null));
}
public void Dispose() {
GetType().GetMethods().Where(x => x.Name.StartsWith("DisposeMyClass"))
.ForEach(x => x.Invoke(null));
}
}
But really they should just add some more language constructs to work with partial classes.

For a Web service proxy generated by Visual Studio, you cannot add your own constructor in the partial class (well you can, but it does not get called). Instead, you can use the [OnDeserialized] attribute (or [OnDeserializing]) to hook in your own code at the point where the web proxy class is instantiated.
using System.Runtime.Serialization;
partial class MyWebService
{
[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
// your code here
}
}

I'm not quite addressing the OP, but if you happen to be generating classes with the EntityFramework Reverse POCO Generator, there's a partial method called in the constructor which is handy for initializing things you're adding via partial classes on your own...
Generated by tool:
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.37.3.0")]
public partial class Library {
public string City { get; set; }
public Library() {
InitializePartial();
}
partial void InitializePartial();
}
added by you:
public partial class Library {
List<Book> Books { get; set; }
partial void InitializePartial() {
Books = new List<Book>();
}
}
public class Book {
public string Title { get; set; }
}

A bit late to the game, but this is indeed possible. Kind of.
I recently performed the trick below in a code generator of mine, and the result is satisfying. Yes, a dummy argument is required, but it will not cause any major concerns. For consistency, you may want to apply some rules:
Rules
Manually created constructor must be protected.
Generated constructor must be public, with the same arguments as the protected one plus an extra optional dummy argument.
The generated constructor calls the original constructor with all the supplied arguments.
This works for regular construction as well as reflection:
var s1 = new MyWebService();
var s2 = (MyWebService?)Activator.CreateInstance(
typeof(MyWebService),
BindingFlags.CreateInstance | BindingFlags.Public);
And for IoC, it should also work (verified in DryIoc). The container resolves the injected arguments, skipping the optional ones:
var service = container.Resolve<MyWebService>();
Sample code
// <auto-generated />
public partial class MyWebService
{
public MyWebService(object? dummyArgument = default)
: this()
{
// Auto-generated constructor
}
}
// Manually created
public partial class MyWebService
{
protected MyWebService()
{
}
}
The above works for any number of constructor arguments. As for the dummy arguments, we could invent a special type (maybe an enum) further restricting possible abuse of this extra argument.

Nothing that I can think of. The "best" way I can come up with is to add a ctor with a dummy parameter and use that:
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public override MyWebService(int dummy)
{
string myString = "overridden constructor";
//other code...
}
}
MyWebService mws = new MyWebService(0);

Related

.Net how to make a constructor for a partial class?

I have a partial class with a constructor, but the constructor is throwing an error because 'a member with the same signature is already declared' (a constructor of the same name exists in the other partial class). How do I make a constructor for a partial class when the name is already being used?
public partial class DigitalArchivesAssetsDataContext
{
public DigitalArchivesAssetsDataContext()
: base(System.Configuration.ConfigurationManager.ConnectionStrings["digitalArchivesAssets"].ConnectionString, mappingSource)
{
OnCreated();
}
}
You can't. The compiler essentially merges the text of all the partial classes together in to one class when the project is built. You can't have more than one method (including constructors) with the same name and signature per class.
One option is to use a different signature for the constructor, or modify your architecture to not need a constructor. For instance, you could use the existing constructor and have some kind of Initialize method that runs the code from your other constructor.
You could also use "Partial Methods". These are methods marked as partial that you could call from the existing constructor "if they exist". They are designed as extension points for partial classes that come from a code generator, but you may be able to make use of them too. See MSDN for more information.
You can not create multiple constructors with matching signature in to the splitted partial classes because at the compile time both the parts are merged together to generate a single class file. for example
class ClassRoom
{
private int boycount; //field
public ClassRoom() //default constructor
{
boycount = 30;
}
public ClassRoom(int bcount) //overloaded constructor
{
boycount = bcount;
}
public double Avg() //method
{
//statements goes here
}
}
In above example we can split the class like this.
//Calculation1.cs
partial class ClassRoom
{
private int boycount; //field
public ClassRoom() //default constructor
{
boycount = 30;
}
}
//Calculation2.cs
partial class ClassRoom
{
public ClassRoom(int bcount) //overloaded constructor
{
boycount = bcount;
}
public double Avg() //method
{
//statements goes here
}
}
Hope it is clear.

Is this the correct way to use a inheritence?

I'm sorry if these types of questions aren't allowed.
I have a simple base for something similar to plugins.
Here's my example
class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
Now currently I'm doing something like this:
class CustomPlugin : Plugin{
public override void Run(object source, System.EventArgs args)
{
base.Run(source, args);
}
}
First of all is the logic behind this correct?
Secondly can I force them to implement the Run function from the partial class or do I need to create an interface for that?
You can define an abstract class with "default" behavior by declaring a method as virtual and overriding it in derived classes.
A derived class is not forced to override a virtual method in an abstract base class. If the method is not overridden, the behavior defined in the abstract class is used. Overriding the method can be used to replace the behavior entirely, or implement additional functionality (on top of calling base.MethodName()).
Unless I've misunderstood your question, this pattern should work for your scenario.
dotnetfiddle link: https://dotnetfiddle.net/7JQQ6I
Abstract base class:
public abstract class Plugin
{
public virtual string Output()
{
return "Default";
}
}
A derived class that uses the default implementation, and one that overrides it:
public class BoringPlugin : Plugin
{
public override string Output()
{
return base.Output();
}
}
public class ExcitingPlugin : Plugin
{
public override string Output()
{
return "No boring defaults here!";
}
}
Test result:
public static void Main()
{
var boring = new BoringPlugin();
Console.WriteLine(boring.Output());
var exciting = new ExcitingPlugin();
Console.WriteLine(exciting.Output());
}
Default
No boring defaults here!
This is not the correct way to use the partial keyword. The partial keyword merely allows you to spread the definition of a class into multiple source files. It isn't something you use to describe the architecture of your program. You would use it to split the definition into multiple files, something like this:
Plugin1.cs
partial class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
}
Plugin2.cs
partial class Plugin {
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
But this isn't helpful to you, and you should forget about the partial keyword (for now). You seem to be struggling with concepts related to object-oriented programming. The partial keyword has nothing to do with that, so don't worry about it.
If you want classes which inherit from Plugin to be 'forced' to implement the Run method, you should use an abstract method. HOWEVER, as you will read in that link, if you use an abstract method, you will not be able to define the 'default' behavior which you are currently defining in the body of the run method.
If you want classes which inherit from Plugin to be forced to define ADDITIONAL behavior, you can't really do that easily just using concepts like abstract classes / methods / interfaces. You will find it easier to compromise, and allow classes which inherit from plugin to 'just' have the default behavior of the Run method as described in your Plugin base class.
You will probably find this compromise acceptable. I think you will find that forcing classes which inherit from Plugin to do additional things in the Run method doesn't buy you anything. The behavior in the base Run method should still be considered a 'correct', if minimal / useless 'Run' of any type of derived Plugin.
I can't speak to the logic of your program, it isn't clear what you intend for these Plugins to do, but hopefully this will help you figure out exactly what you want to do, and how to do it.

Partial methods and inheritance from non-partial classes

I imported a table from the database using designer, then I've edited the corresponding cs file to add extra functionality to the model (it's a partial exactly for this reason). Now I came up with some ideas on how to make that functionality more reusable and packed that into a base class (so in the context code I have partial class Foo : BaseClass). I made the partial class inherit the base class and all is fine... except for partial methods.
The generated partial class has some partial methods that normally don't have any code (namely the OnCreated method). I've added an OnCreated method to the base class and put a breakpoint in it, but it's never hit.
Can I somehow make a partial class take the code for partial method from a non-partial parent or am I doing something wrong here?
Background: I have a certain structure (columns containing author's id, id of user who was the last one to modify the record and dates of create and update dates) that is appearing in multiple tables and I'm trying to define most code for handling that in a single place in my project. It involves having uniform access to associated users and I had some luck doing that by defining associations in my base class (basically this, but with few modifications). So far it appears to works perfectly, except for the fact that I should be assigning default values to storage variables inside of the constructor of the generated class
(this._SomeVariable = default(EntityRef<SomeModel>)). However modifying the generated code is pointless, since all changes will be lost when the file is generated anew. So the next best thing would be to implement OnCreated partial method which is run at the end of the generated class. I can implement that in the non-generated cs file for my model, but I'd rather put it inside the base class which is shared with all similar models.
Here is some minimal code to make it more clear:
Generated code:
partial class Foo
{
public Foo()
{
// does some initialization here
this.OnCreated();
}
partial void OnCreated();
}
Extended code for Foo:
partial class Foo : BaseClass // Thanks to this I can use the uniform JustSomeModel association
{
// This code here would run if it was uncommented
// partial void OnCreated() {}
// However I'd rather just have the code from base.OnCreated()
// run without explicitly calling it
}
Base class:
public class BaseClass
{
protected EntityRef<SomeModel> _SomeVariable;
[Association(Name = "FK_SomeModel", Storage = "_SomeVariable", ThisKey = "SomeModelId", OtherKey = "Id", IsForeignKey = true)]
public SomeMode JustSomeModel
{
get
{
return this._SomeVariable.Entity;
}
}
// This never runs
public void OnCreated()
{
this._SomeVariable = default(EntityRef<SomeModel>)
}
}
The best solution I can think of right now would be to do this:
partial class Foo : BaseClass
{
partial void OnCreated()
{
base.OnCreated(); // Haven't really tested this yet
}
}
However this means I will have to add this piece of code to every model inheriting from BaseClass that I use and I'd rather avoid it.
Based on information posted by Eugene Podskal I can assume this cannot be done and my best bet is implementing the partial method and calling base method inside it.
partial class Foo : BaseClass
{
partial void OnCreated()
{
base.OnCreated();
}
}
Edit: Tested it and it works.

IntelliSense doesn't show partial class method

I have partial class User generated by LINQtoSQL as shortly following:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.[User]")]
public partial class User : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
...
Then I created separate folder "Proxy" in my project and put there extra piece of User class:
namespace LINQtoSQL_sample.Proxy
{
public partial class User
{
public static string GetActivationUrl()
{
return Guid.NewGuid().ToString("N");
...
Issue happens when I try to invoke that extra static method from another part of same project. Let's say I have once more folder "SqlRepositoryImpl" and another one partial class there:
namespace LINQtoSQL_sample.SqlRepositoryImpl
{
public partial class SqlRepository
{
public bool CreateUser(User instance)
{
if (instance.ID == 0)
{
instance.added_date = DateTime.Now;
instance.activated_link = LINQtoSQL_sample.Proxy.User.GetActivationUrl();
...
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
Please, advise why such happens and where I'm wrong?
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
When you call a method from a class, there are no “parts” of the class anymore.
If you need to (and can) specify the full namespace of the class to invoke a method from it that means you actually have two different classes in two different namespaces. If the two partial declarations are in different namespaces, then you have actually declared two separate classes, not a single class from two parts.

class modifier issues in C# with "private" classes

I had a class that had lots of methods:
public class MyClass {
public bool checkConditions() {
return checkCondition1() &&
checkCondition2() &&
checkCondition3();
}
...conditions methods
public void DoProcess() {
FirstPartOfProcess();
SecondPartOfProcess();
ThirdPartOfProcess();
}
...process methods
}
I identified two "vital" work areas, and decided to extract those methods to classes of its own:
public class MyClass {
private readonly MyClassConditions _conditions = new ...;
private readonly MyClassProcessExecution = new ...;
public bool checkConditions() {
return _conditions.checkConditions();
}
public void DoProcess() {
_process.DoProcess();
}
}
In Java, I'd define MyClassConditions and MyClassProcessExecution as package protected, but I can't do that in C#.
How would you go about doing this in C#?
Setting both classes as inner classes of MyClass?
I have 2 options: I either define them inside MyClass, having everything in the same file, which looks confusing and ugly, or I can define MyClass as a partial class, having one file for MyClass, other for MyClassConditions and other for MyClassProcessExecution.
Defining them as internal?
I don't really like that much of the internal modifier, as I don't find these classes add any value at all for the rest of my program/assembly, and I'd like to hide them if possible. It's not like they're gonna be useful/reusable in any other part of the program.
Keep them as public?
I can't see why, but I've let this option here.
Any other?
Name it!
Thanks
Your best bet is probably to use partial classes and put the three clumps of code in separate files adding to the same class. You can then make the conditional and process code private so that only the class itself can access them.
For "Helper" type classes that aren't going to be used outside the current assembly, Internal is the way to go if the methods are going to be used by multiple classes.
For methods that are only going to be used by a single class, I'd just make them private to the class, or use inner classes if it's actually a class that's not used anywhere else. You can also factor out code into static methods if the code doesn't rely on any (non-static) members of your class.
I can
define MyClass as a partial class,
having one file for MyClass, other for
MyClassConditions and other for
MyClassProcessExecution.
Maybe it's my C++ background, but this is my standard approach, though I bundle small helper classes together into a single file.
Thus, on one of my current projects, the Product class is split between Product.cs and ProductPrivate.cs
I'm going for something else - the issue of public / protected / private may not be solved specifically by this, but I think it lends itself much better to maintenance then a lot of nested, internal classes.
Since it sounds like you've got a set of steps in a sequential algorithm, where the execution of one step may or may not be dependent upon the execution of the previous step. This type of sequential step processing can sometimes use the Chain of Responsibility Pattern, although it is morphed a little bit from its original intention. Focussing only on your "processing method", for example, starting from something like below:
class LargeClass
{
public void DoProcess()
{
if (DoProcess1())
{
if (DoProcess2())
{
DoProcess3();
}
}
}
protected bool DoProcess1()
{
...
}
protected bool DoProcess2()
{
...
}
protected bool DoProcess3()
{
...
}
}
Using Chain of Responsibility, this could be decomposed into a set of concrete classes for each step, which inherit from some abstract step class. The abstract step class is more responsible for making sure that the next step is called, if the necessary preconditions are met.
public class AbstractStep
{
public AbstractStep NextStep { get; set; }
public virtual bool ExecuteStep
{
if (NextStep != null)
{
return NextStep.ExecuteStep();
}
}
}
public class ConcreteStep1 : AbstractStep
{
public bool ExecuteStep
{
// execute DoProcess1 stuff
// call base
return base.ExecuteStep();
}
}
...
public class ConcreteStep3 : AbstractStep
{
public bool ExecuteStep
{
// Execute DoProcess3 stuff
// call base
return true; // or false?
}
}
To set this up, you would, in some portion of the code, do the following:
var stepOne = new ConcreteStep1();
var stepTwo = new ConcreteStep2();
var stepThree = new ConcreteStep3();
stepOne.NextStep = stepTwo;
stepTwo.NextStep = stepThree;
bool success = stepOne.ExecuteStep();
This may help clean up the code bloat you've got in your single class - I've used it for a few sequential type algorithms in the past and its helped isolate each step nicely. You could obviously apply the same idea to your condition checking (or build them into each step, if that applies). You can also do some variation on this in terms of passing state between the steps by having the ExecuteStep method take a parameter with a state object of some sort.
Of course, if what you're really concerned about in this post is simply hiding the various steps, then yes, you could make each of your substeps a protected class within your class that creates the steps. Unless you're exposing your library to customers in some form or fashion however, and you don't want them to have any type of visibility into your execution steps, this seems to be a smaller concern then making the code maintainable.
Create the classes with the same access modifier as the methods you have refactored. Partial classes are only really usefull when you have multiple people or automat5ed code generating tools frequently modifying the same classes. They just really avoid source merge hell where your source controll mashes your code because it can't merge multiple edits to the same file.

Categories

Resources