Why does ManyConsole display public members of a CommandLine class? - c#

I'm using ManyConsole as a command line command and options parser for a console app. All commands are defined as a command class that derives from ConsoleCommand, and then implement a specific task. I defined an intermediary base class, ParkPayConsoleCommand derived from that class:
abstract class ParkPayConsoleCommand: ConsoleCommand
{
protected readonly ParkPayDbContext DbContext = new ParkPayDbContext();
}
Then all my command classes derive from my base class, and enjoy a built in DbContext, e.g:
class ReadStartsCommand : ParkPayConsoleCommand
{
public ReadStartsCommand()
{
_commandTrace = new TraceSource(CommandName, SourceLevels.All);
IsCommand("read-starts", "Processes imported vehicle entry movements to create new VehiclePresence records with start date-times based on those movements");
HasRequiredOption("b|batchId:", "The Id of the VehicleMovementBatch used to create new vehicle presences.", b => _batchIdOption = b);
}
public override int Run(string[] remainingArguments)
{
// Do the business of the command.
return (int)ExitCodes.Success;
}
}
It's a ManyConsole convention for each command class to name and describe itself, and define its command line options in its constructor, as you see above. Normally when I run a command such as the ReadStartsCommand above, it just writes to console what command is running, and not what options I passed.
Yet when I make ParkPayConsoleCommand.DbContext public, not protected, it outputs the string
DbContext : ParkPay.Model.Context.ParkPayDbContext
to the console at the end of the running command's name and description. Why does it do this when DbContext is not anywhere defined as a command option itself. This may seem trivial, but essentially I'm asking quite an important 'meta-question', and that is: Does ManyConsole implicitly interpret all public properties of its command classes as command options, even if they are not explicitly declared as such?

I can't speak to the original intent, but as you've found out, yes, it appears to do that. A suggestion of why this might be useful:
Sometimes the commandline options do not map 1-to-1 on to Properties of your ConsoleCommand class. Consider
public class VerbosityCommand : ConsoleCommand
{
public int VerbosityLevel {get;set;}
public VerbosityCommand(){
this.IsCommand("Verbosity","Control the level of verbosity");
this.HasOption("v|verbose","Increase verbosity, cumulative",x => Verbosity++);
}
}
Now the block printed by ManyConsole will (helpfully) have VerbosityLevel : 3 (for example) rather than (unhelpfully) have
Verbose : set
Verbose : set
Verbose : set
or something similar.
Another example would be preset-type flags, which configure a number of properties in to common configurations.
In your case, it might be useful to make _batchIdOption public and ParkPayDbContext protected or private.

Basically yes all public properties are printed as Greg said. This does not imply they are all treated as arguments (and they are not). Some additional points:
if you do any work overriding OverrideAfterHandlingArgumentsBeforeRun() and assign the result to public members, that result will show up when the command is printed to the console. This can be useful to document some intermediate result for the user
to format how the members are printed, you can override ToString on the public member's type
I hope using ManyConsole is smooth otherwise.

Related

Dependency Injection resolve correct implementation for database export

I want to store multiple objects in the database. The type of objects are not fixed and can be dynamically added by loaded modules. At one part in my application I want to search for the correct implementation to invoke the method with the created object.
One example. I have 3 objects:
public class Employee : Person { }
public class Supervisor : Person { }
public abstract class Person { }
and there are implementations of IExporter registered at the DI container:
public interface IExporter<T> where T: Person
{
Task ExportAsync(T person);
}
public class EmployeeExporter : IExporter<Employee>
{
public Task ExportAsync(Employee exployee) => Task.CompletedTask; // TODO
}
public class SupervisorExporter : IExporter<Supervisor>
{
public Task ExportAsync(Supervisor supervisor) => Task.CompletedTask; // TODO
}
How would my person factory which returns a person would know which Exporter is the right one to choose for export?
var type = typeof(IExporter<>).MakeGenericType(person.GetType());
var exporter = (IExporter<Employee>)serviceProvider.GetRequiredService(type);
await exporter.ExportAsync(person);
Something like this but without explicitly specify the IExporter<Employee> cast.
Or do I something completely wrong?
I already mentioned Jimmy Bogard's article, so I won't repeat that. Besides the options mentioned by Jimmy, there's another option, which is to use C# dynamic. This looks like this:
var type = typeof(IExporter<>).MakeGenericType(person.GetType());
dynamic exporter = serviceProvider.GetRequiredService(type);
await exporter.ExportAsync((dynamic)person);
At runtime, the C# compiler goes look for a method called ExportAsync. This is about the most concise solution you can get. But be aware of the following downsides:
Refactoring: This is not refactoring safe. If you refactor the IExporter<T> interface, this code keeps compiling but fails at runtime. You should add a unit test for your factory to make sure it still works.
Public only: Using the dynamic keyword, you can only invoke public methods on public classes. Even if your IExporter<T> is defined as public, when the exporter implementation (or the outer-most decorator your decided to wrap it with) is internal, the invocation will fail. To me this seems like a quirk in the C# compiler, because IMO it should be able to call ExportAsync when its interface is public, but that's not how it works. So again, you might want to add some unit tests to make sure it works.
What it comes down to when using dynamic, is that you'll be adding more tests than with the approaches Jimmy suggests. His solutions have more code and need less testing. Dynamic needs no extra code, but more testing code.

Adding parameter to base class constructor, auto-add to all descendants

I am trying to improve some code to take out initialisations and use of the Service Locator in my View Model, so that the container can create them within the constructor. But there are changes to base classes that have hundreds of descendants and this will take a long time to manually fix everyone.
Is there a way that Visual Studio or any other add-in can do this for you? On the descendant it will need to add it into the main constructor and pass it through to the base constructor also. There is only a single constructor on all.
e.g. I have just added the someNewInjectedClass parameter to the base class constructor below:
public class BaseClass
{
private ISomeNewInjectedClass _someNewInjectedClass;
public BaseClass(ISomeNewInjectedClass someNewInjectedClass)
{
_someNewInjectedClass = someNewInjectedClass;
}
}
And that needs to be added to my descendant which is currently this:
public class OneOfManyDecendants : BaseClass
{
public OneOfManyDecendants()
: base()
{
}
}
To become this:
public class OneOfManyDecendants : BaseClass
{
public OneOfManyDecendants(ISomeNewInjectedClass someNewInjectedClass)
: base(someNewInjectedClass)
{
}
}
If you have Resharper you can use "Change Signature" (Ctrl+R,S) refactoring. When doing it select "Resolve with call tree" option. In a next dialog pick "Create parameter..." option for each subclass.
Not quite an answer to my exact question but I am going to go a long the lines of #sinatr's suggestion with this related post: Use class as a single parameter for base parameters
This seems the best way for us going forward and can more easily change in the future.

BaseColumns does not contain a constructor that takes 0 arguments

I'm porting an Android Studio project to Visual Studio / Xamarin.
I have this Java code:
public class EmployeeDataContract {
public EmployeeDataContract() { }
public static abstract class EmployeeDataEntry implements BaseColumns {
public static final String TABLE_NAME = "tblEmployeeData"; // Local SQLLite table
public static final String COLUMN_NAME_LOCAL_ID = "_id";
translated to C#:
public class EmployeeDataContract {
public EmployeeDataContract() {}
public abstract class EmployeeDataEntry : BaseColumns { // had to remove "static"
public const string TABLE_NAME = "tblEmployeeData"; // Local SQLLite table
public const string COLUMN_NAME_LOG_ID = "_id";
Visual Studio gives the compile error:
BaseColumns does not contain a constructor that takes 0 arguments
So then I go look at the BaseColumns and it doesn't contain a constructor, nor does it inherit a class (that might have a constructor), therefore it inherits from Object, which should have a constructor with 0 arguments.
What is the problem?
There is a bug report about this behavior here: https://bugzilla.xamarin.com/show_bug.cgi?id=36791
Basically in Java this interface contains just two constants, defining names of id and count columns. In C# interfaces cannot contain constants, so such constants are moved to an abstract class like you see. It cannot be inherited (in other assemblies), because it's only constructor is internal, and child class should call parent's constructor. Because this interface contains only constants, xamarin does not generate (empty) interface for it.
If you are porting code manually (not binding to a Java library) - maybe you can ignore inheriting from this class, since it does not provide anything useful anyway. Of course some another code might only accept instances of this class, but that is unlikely.

C#: Force constructor signature using abstract class?

I've been searching for a while on this because I'm naturally forgetful and I thought it would be nice to build something (an abstract class, interface, etc.?) that would force me to implement certain bits of code in a class I was writing.
In particular, I would like to force a new class to always have a constructor that takes a single parameter typed as itself in order to make duplication of the object easier. I've seen articles/questions elsewhere that talk about this, but I'm not sure this particular question has been asked (at least that I can find) or I'm simply not understanding enough of the other articles/questions to realize it. My apologies in advance.
I'm not interested in having a constructor in an abstract class, interface, etc. actually do anything. I'm merely interested in defining the requirement for a constructor signature in a derived class.
My ideal class would look like this:
public class GoodClass
{
public GoodClass(GoodClass goodClass)
{
// copy components of goodClass to this instance
}
}
So, I first began researching interfaces and also started reading up on abstract classes. I was thinking something like the code below would work, but alas I get errors. Is what I'm trying to do even possible? Is there any other way I could accomplish my goal without putting a sticky note on my monitor? :)
abstract class SelfConstructor
{
abstract public SelfConstructor(SelfConstructor) { }
}
class NewClass : SelfConstructor
{
//Required by SelfConstructor:
public NewClass(NewClass newClass)
{
// copy components of newClass to this instance
}
}
You could write a ReSharper plugin that recognises this case and highlights the class if it doesn't have a "copy constructor". This would be a daemon stage that would process the file as it's being edited, and add highlights. You can look through the abstract syntax tree of the file, look for all instances of IConstructorDeclaration, and then get the constructor's parameters from the ParameterDeclarations property. You can check that there is a constructor that only has one parameter, and that parameter is the same type as the class it's declared in.
You can compare the types by getting the constructor's parameter's TypeUsage and trying to downcast to IUserTypeUsage. You can then use ScalarTypeName.Reference.Resolve() to get an instance of IDeclaredElement. Compare this against the class's IClassDeclaration.DeclaredElement to see if they're the same instance.
In C++, what you are talking about is a copy constructor, you actually get one by default!
C# doesn't have that concept (though of course you can define one); however, it is easier (and preferred) to simply implement ICloneable (MSDN), which requires you to implement the Clone method, that does the same thing.
Instead of:
object myObj = new CloneableObject(otherObj);
You write:
object myObj = otherObj.Clone();
The other thing you could do is force a constructor signature by not having a default:
public class BaseClass
{
//No abstract constructors!
public BaseClass(BaseClass copy)
{
}
}
Now when you derive, you have to use that overload in the constructor. Nothing will force the derived signature, but at least you have to explicitly use it:
public class DerivedClass : BaseClass
{
public DerivedClass() : base(this)
{
}
}
The above example clearly shows that it doesn't "force" you to have a copy constructor, but like a sticky note, would serve as a good reminder.
I would definitely go the interface route, as that is what is there for (and you can use an abstract implementation!).
Note that you can take advantage of Object.MemberwiseClone if you want a shallow copy for free. All objects get this, no interface required.

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Categories

Resources