commandline parser - building a command line string from verb object - c#

I have an instance of a working command line verb object - and i'd like to generate a command line string that it represents.
using CommandLine;
[Verb("myVerb")]
public class MyClass
{
[Option("myOption")]
public string MyOption { get; set; }
}
public static void Initialise()
{
var instance = new MyClass();
instance.MyOption = "Option Value";
System.Console.WriteLine(BuildCommandLineStringFromInstance(instance));
// Output
// myVerb --myOption="Option Value"
}
Is there anything in the library which provides something similar to the method
string BuildCommandLineStringFromInstance(object)

Related

How to pass values from one class to another class using wpf?

I would like to pass values from one class file to another class.
E.g:
Step1:
Class1.cs
public class Class1
{
public string LogedInPerson { get; set; }
public string Name
{
get { return this.LogedInPerson; }
set { this.LogedInPerson = value; }
}
}
Step2:
Value has been assigned in below method:
test.xaml.cs
public void assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
}
Step3:
I would like to get "test123" values from Class2.cs.
E.g:
public void test()
{
string selected_dept = ?? //How to get "test123" from here.
}
You can have variables class that includes public variables. Define instance of class1 in variables class .
public static class1 myclass=new class1();
in test.xml.cs set value
public void assignValue()
{
myclass.LogedInPerson = "test123";
}
in class2.cs
public void test()
{
string selected_dept = myclass.LogedInPerson;
}
Initialize Class1 outside assignValue() methos
Class1 obj = new Class1();
public void assignValue()
{
obj.LogedInPerson = "test123";
}
public string returnValue()
{
return obj.LogedInPerson;
}
if your second class name test.xaml then call it like this, but I don't think you can use class name test.xaml so use a nice name instead there eg: Class2
public void test()
{
test.xaml test = new test.xaml();
test.assignValue();
string selected_dept = test.returnValue(); //How to get "test123" from here.
}
I believe this question is more on the topic of basic Object Oriented Programming principles, not so much about WPF specific features. Therefore, I will provide you a non-WPF specific answer, as it will allow me to address your question in the most direct way.
In OOP, a method can return a result to the caller. So, for instance,
public string GetReturnObject(){
return "This is a return object";
}
You can create a new object and pass it back to the caller,
public void Test(){
string data = GetReturnObject();
}
And now data will be assigned the object that was returned from the method that Test() called. So, if you modify your AssignValue method by adding a return type and passing the instantiated Class1 object back to the caller, you will have the answer you need
public Class1 assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
return obj;
}
Hope that helps.

Call constructor with other class constant value

I want a constructor call to only allow a limited range of "extensions". Let's say I have these 2 classes:
public class Foo
{
public Foo(Extension ext)
{
// do something
}
}
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
}
So, when another developer would want to use Foo he can only do so with the values from the Extension class like so:
Foo foo = new Foo(Extension.TXT);
But when trying to do this I get an IDE error saying: "cannot convert from 'string' to '<ProjectName>.Extension'.
As a "workaround" I could change my Extension class to something like this:
public class Extension
{
public enum File
{
TXT,
XML
}
}
and use it like this:
Foo foo = new Foo(Extension.File.TXT);
which works perfectly fine but what I do not like is that the call is one level longer (class -> enum -> element instead of class -> element).
So, the questions is is my workaround actually the only valid, correct or best practice solution?
You can use a Java style enum class
public class Extension
{
string _Extension = null;
private Extension(string ext)
{
_Extension = ext;
}
public static Extension TXT
{
get { return new Extension(".txt"); }
}
public static Extension XML
{
get { return new Extension(".xml"); }
}
public override string ToString()
{
return _Extension;
}
public override bool Equals(object obj)
{
var e = obj as Extension;
if (e == null) return false;
return e._Extension == this._Extension;
}
public override int GetHashCode()
{
return _Extension.GetHashCode();
}
}
The first example has Extension being used as a class with a couple of string constants. The second example uses an enum in lieu of the constants.
public class Foo
{
// this .ctor expects a type of Extension, not a string.
public Foo(Extension ext)
{
// do something
}
}
// This class has only constant string values.
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
}
Attempting to pass in a string to the above .ctor will not work as it is expecting a type of Extension, not a string.
// this passes in a string, not a type.
Foo foo = new Foo(Extension.TXT);
As you are wanting to limit the values available to the Foo .ctor, then use an enum as you have in your 2nd example:
public class Foo
{
public Foo(File ext)
{
// do something
}
}
public enum File
{
TXT,
XML
}
Then this will work as expected:
Foo foo = new Foo(File.TXT);
Why not to declare enum outside of class Foo and without any special class like extension?
public enum Extension
{
TXT,
XML
}
public class Foo
{
public Foo(Extension ext)
{
// do something
}
}
Then when you are constructing a Foo object you can simply do:
Foo foo = new Foo(Extension.TXT);
You could define a default constructor and implicit operator for string to Extension. Eg. something like:
public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
private _value;
public Extension(string value){if(value == TXT || value == XML) _value = value; else throw new NotImplementedException();}
public static implicit operator string(Extension value){return _value;}
public static implicit operator Extension(string value){if(value == TXT || value == XML) _value = value; else throw new NotImplementedException();}
}
that way you could call Foo(".txt") or Foo(Extension.TXT)
or you could define TXT as an instance of Extension:
public class Extension
{
public const Extension TXT = new Extension(".txt");
public const Extension XML = new Extension(".xml");
public Value{get;private set;}
public Extension(string value){Value = value;}
}
Just change the first declaration of Extesion from Class to Enum

windows Workflow foundation - passing custom variable between different activity in a workflow

I am passing a custom variable type from one action to another action in a workflow. Here is the definition of the custom object
public class ConfigDatabase
{
public string Name;
public string Host;
public string Port;
public string Instance;
public string User;
public string Password;
}
public class ConfigDatabases
{
public string DatabaseToUse;
public List<ConfigDatabase> DatabaseList;
public ConfigDatabases()
{
DatabaseList = new List<ConfigDatabase>();
}
}
public class ConfigEnvironment
{
public ConfigDatabases EnvironmentConfigDatabase;
public ConfigEnvironment()
{
EnvironmentConfigDatabase = new ConfigDatabases();
}
public ConfigDatabase ReturnDatabaseInfo()
{
ConfigDatabase ConfigDatabaseInfo = new ConfigDatabase();
for (int Count1 = 0; Count1 < EnvironmentConfigDatabase.DatabaseList.Count; Count1++)
{
if (EnvironmentConfigDatabase.DatabaseList[Count1].Name == EnvironmentConfigDatabase.DatabaseToUse)
{
ConfigDatabaseInfo = EnvironmentConfigDatabase.DatabaseList[Count1];
return ConfigDatabaseInfo;
}
}
return ConfigDatabaseInfo;
}
public string GetDatabaseConnectionString()
{
ConfigDatabase DatabaseInfo = ReturnDatabaseInfo();
string ConnectionString = "Data Source=(description=(address=(protocol=tcp)(host=" + DatabaseInfo.Host + ")(port=" + DatabaseInfo.Port + "))(connect_data=(sid=" + DatabaseInfo.Instance + ")));User ID=" + DatabaseInfo.User + ";Password=" + DatabaseInfo.Password + ";";
return ConnectionString;
}
}
During the first step of the action, it will run the following code to load the config data from a file and store in an object (ConfigEnvironment) that is returned in function Execute
public sealed class InitializeEnvironment : CodeActivity<ConfigEnvironment>
{
// Define an activity input argument of type string
public InArgument<string> EnvironmentFileLocation { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override ConfigEnvironment Execute(CodeActivityContext context)
{
// Obtain the runtime value of the Text input argument
string EnvironmentFile = context.GetValue(this.EnvironmentFileLocation);
EnvironmentConfigInitialization EnvironmentInitialize = new EnvironmentConfigInitialization(EnvironmentFile);
ConfigEnvironment EnvironmentDetail = EnvironmentInitialize.LoadData();
return EnvironmentDetail;
}
}
In the subsequent activity in the workflow, I would like to obtain the data stored in this object. However, the following code will have a compile error as EnvironmentDetail object could not find the function GetDatabaseConnectionString.
public sealed class ExecuteSQL : CodeActivity<DataRowCollection>
{
// Define an activity input argument of type string
public InArgument<string> SQLScript { get; set; }
public InArgument<ConfigEnvironment> EnvironmentDetail { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override DataRowCollection Execute(CodeActivityContext context)
{
string connectionString4 = EnvironmentDetail.GetDatabaseConnectionString(); //This create a compile error
}
}
The compile warning is the following
'System.Activities.InArgument' does not contain a definition for 'GetDatabaseConnectionString' and no extension method 'GetDatabaseConnectionString' accepting a first argument of type 'System.Activities.InArgument' could be found (are you missing a using directive or an assembly reference?)
As it turns out, EnvironmentDetail is of Type InArgument (or InArgument<ConfigEnvironment>) but not of Type ConfigEnvironment You need to do a context.Get<ConfigEnvironment>() to get a variable of Type ConfigEnvironment.
Let me know if this solves your problem or if there's something else still amiss ;-)

Change a class property from external method using ref

An error has been occurred while try changing the string property inside class,
but if assign ('f.StartTime' to a string variable it's work but doesn't change the 'StartTime' property)
like:
string x = f.StartTime;
ChangeText(ref x); // There's no error, but f.StartTime didn't change.
//Unless:
f.StartTime = x;
of course it's Fake Method...
so i want perform the following code.
public class MainClass
{
public class Foo
{
public string StartTime { get; set; }
public string ToTime { get; set; }
}
private void ChangeText(ref string Time)
{
Time = DateTime.Now.ToString();
}
public void SetClassObjects()
{
Foo f = new Foo()
{
StartTime = "Any Text",
ToTime = "Any Text"
};
ChangeText(ref f.StartTime);
// An error: A property, indexer or dynamic member access may not be passed as an out or ref parameter
}
Strings are immutable, assigning f.StartTime to x creates a copy of the value not of the reference. Hence you need to re-assign f.StartTime. The ref inclusion will correctly re-assign the reference x (to actually point at a new string under x), but the reference to f.StartTime is lost due to the value-type semantics of strings. Note that strings are reference types, they just follow the semantics of value types.
I would shy away from providingstring as a ref in this instance and instead do something like:
f.StartTime = GetText();
private string GetText()
{
return DateTime.Now.ToString();
}
Or alternatively pass Foo into the ChangeText method:
private void ChangeText(Foo fooItem)
{
fooItem.Time = DateTime.Now.ToString();
}
Then just ChangeText(f);.
If you want to provide a generic mechanism for mutating a property string, you could have an interface:
public interface ICanHaveMyTextChanged
{
void ChangeText(string newText);
}
Which Foo implements:
class Foo : ICanHaveMyTextChanged
{
public string StartTime { get; private set; }
public void ChangeText(string newText)
{
StartTime = newText;
}
}
And then specify the interface as the argument instead of Foo:
private void ChangeText(ICanHaveMyTextChanged item)
{
item.ChangeText(DateTime.Now.ToString());
}
And call thus:
var f = new Foo();
ChangeText(f);
Now any class that implements this interface can have it's text changed.

C# add const field using attributes

We have class 'SomeClass':
namespace Namespace
{
class SomeClass
{
// something
}
}
And attribute 'SomeAttribute':
class SomeAttribute : System.Attribute { }
Task: add to all classes market by SomeAttribute 'public const string Type' field. Modified classes must be following:
class SomeClass
{
// something
public const string Type = #"Namespace.SomeClass";
}
UPD:
I'm using following approach for message transaction:
class Manager
{
// message has 3 parts:
// string message = String.Format("{0}{1}{2}",
// typeof(SomeClass).ToString(),
// splitter,
// Manager.Serialize(someClassObj)
// )
public static string GetType(string message) { /* some code */ }
public static string Serialize(SomeClass message) { /* XML serialization */ }
public static SomeClass Deserialize(string message) { /* deserialization */ }
}
class Logic
{
public void ProcessMessage(string message)
{
switch (Manager.GetType(message))
{
case SomeClass.Type:
{
SomeClass msg = Manager.Deserialize(message) as SomeClass;
// send message to binded objects
}
break;
case ClassInheritedFromSomeClass.Type:
{
// the same
}
break;
// etc.
}
}
}
UPD 2:
More about messages. At this time I'm using next approach:
public class BaseMessage
{
public const string Type = #"Messages.BaseMessage";
}
public class LoginMessage : BaseMessage
{
public new const string Type = #"Messages.Client.LoginMessage";
public string Nickname { get; set; }
public string Password { get; set; }
}
Conclusion
I think best case is to modify Manger like this:
class Manager
{
// create event table
public Action<BaseMessage> this[string eventName]
{
get
{
if (!m_eventTable.ContainsKey(eventName))
{
m_eventTable.Add(eventName, new Action<BaseMessage>(message => { }));
}
return m_eventTable[eventName];
}
set
{
m_eventTable[eventName] = value;
}
}
public void Send(BaseMessage message, string messageName)
{
if (m_eventTable.ContainsKey(messageName) && this[messageName].Method != null)
{
this[messageName].Invoke(message);
}
}
private Dictionary<string, Action<BaseMessage>> m_eventTable = new Dictionary<string, Action<BaseMessage>>();
}
Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).
In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.
Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.

Categories