Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to make a class the user of my library can derive from and then access a method for debugging the times of each action. Because my main debug method, where most information is stored, is static (and needs to be), I cannot use it to derive a class or add an overridable method in it. To combat this, I added the following code:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
internal class Call : IDebug
{
internal void CallEvent(Log log)
{
base.Event(log);
}
}
public class IDebug
{
public virtual void Event(Log log) {Console.WriteLine("test");}
}
class Program : IDebug
{
public override void Event(Log log)
{
Console.WriteLine(log.log);
}
}
Every time, it outputs 'test' instead of the log message. How can I fix this? Are there any alternatives to do the same thing?
Your Debug.CallObjectEvent() method explicitly instantiates a Call object and calls the overridden method in that class:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
The CallEvent() method in the Call class simply calls base.Event(), which resolves to IDebug.Event(). The Program.Event() override is never invoked because Program is not in the class hierarchy at the point of the call.
When you override a method or property, the override applies only to the class where it is defined (and all of its child classes, of course). Since Program isn't a parent class of Call there's no reason why its overrides would ever be referenced.
From what you've written it looks like you're trying to set up a system for handling different log outputs depending on the program's requirements. You need a way to register the appropriate log writer for your program. Something like:
public interface ILogWriter
{
void Event(Log item);
}
private class DefaultLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[test] {item.Time} {item.Message}");
}
}
internal static class Debug
{
private static ILogWriter _writer = null;
public static ILogWriter Writer
{
get
{
if (_writer == null)
_writer = new DefaultLogWriter();
return _writer;
}
set => _writer = value;
}
internal static void CallObjectEvent(string log)
{
Writer.Event(new Log(log, Timer.GetTime()));
}
}
class Program
{
private class MyLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[MyLogWriter] {item.Time} {item.Message}");
}
}
static void Main()
{
Debug.Writer = new MyLogWriter();
Debug.CallObjectEvent("Test message.");
}
}
Related
I'm trying to write a logging class that would work like this:
Log.Info("Something happened");
Log.Error("Something else happened");
Log.Debug("Yet another thing happened!");
It should be accessible from every part of the namespace and quick to write, so I thought it'd be best to make it static. That way one can avoid having to create an object just to log a message.
At this point it is sort of like Console.WriteLine();
However, I wanted it also to be able to have two different modes: LogToConsole and LogToFile.
Thus the following syntax would be the most convenient:
LogConsole.Info("This will display in the console");
LogFile.Debug("This will be saved to a file");
LogAll.Error("This will be saved to a file AND displayed in a console");
However, I realized that there could be an large amount of "modes" multiplied by a very large amount of "logtypes".
How could I do this efficiently, in a way that I only have to write each logtype method once and depending on the derived class that calls the method, action a happens or action b happens?
Ideally I would like to define all methods once, and then create the classes that inherit them. But, since they are static methods their behavior is always the same. I can't tell them: "Find out what your superclass is and execute that class' SaveLog() method".
I realize that this would all be very very easy with abstract classes, but then I'd have to create objects.
Is there any way I could do this in C#?
Thanks!
Like Boo, would also recommend a logger like log4net.
If you do want to write it yourself, I would recommend against static methods as they would inhibit your ability to test the classes / methods that call it. Instead, inject your ILogger interface to all classes that might need logging. Then separate the "mode" from the target, so you can inject a list of targets to your logger.
public interface ILogTarget
{
void Save(string message);
}
public class LogToFile : ILogTarget
{
public void Save(string message)
{
//
}
}
public class LogToConsole : ILogTarget
{
public void Save(string message)
{
//
}
}
public interface ILogger
{
void Debug(string message);
}
public class Logger : ILogger
{
private readonly List<ILogTarget> _targets;
private static Logger _logger;
public Logger(List<ILogTarget> targets)
{
_targets = targets;
}
public void Debug(string message)
{
foreach (var target in _targets)
target.Save($"Debug: {message}");
}
}
public class TheClassThatMakesTheCall
{
private readonly ILogger _logger;
public TheClassThatMakesTheCall(ILogger logger)
{
_logger = logger;
}
public void AMethod()
{
_logger.Debug("some message");
}
}
//In your IoC, register Logger as a type of ILogger, and pass in the targets that you want
//If your target vary per situation, you'll need a ILogTarget factory that returns a different list of loggers based on the situation
You cannot inherit from static classes. But you can get away with making only the functions static. don't make the classes as static. Just make the functions as static, then you can use the "new" keyword in the derived class. It would be something like this
// IF this is your base class
public class Log
{
public static bool Info(string Message)
{
Console.WriteLine(Message + " From Log");
return true;
}
public static bool Success(string Message)
{
return true;
}
public static bool Error(string Message)
{
return true;
}
}
//Then this can be your derived class
public class LogFile : Log
{
public static new bool Info(string Message)
{
Console.WriteLine(Message + " From LogFile");
return true;
}
public static new bool Success(string Message)
{
return true;
}
public static new bool Error(string Message)
{
return true;
}
}
Hope this helps.
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 5 years ago.
Improve this question
I'm looking for a clean way to run a method that could have different implementations from within a static method.
The reason for this requirement is that I would like access to a static method A that will always call method B. The implementation of method B however might be different.
Simple example of the code is as follows.....
public class PageFactory
{
public static void InitializeElements()
{
new PageFactory().Initialize();
}
public virtual void Initialize()
{
Console.WriteLine("Page factory initialize");
}
}
public class SepaPageFactory : PageFactory
{
public override void Initialize()
{
Console.WriteLine("SEPA Factory initialize");
}
}
class Program
{
static void Main(string[] args)
{
// "Page factory initialize"
PageFactory.InitializeElements();
// I would like to see "SEPA Factory initialize here"
SepaPageFactory.InitializeElements();
Console.ReadLine();
}
}
Obviously SepaPageFactory.InitializeElements(); doesn't return the result I would like.
This is the first option I considered
public static void InitializeElements(PageFactory factory)
{
factory.Initialize();
}
And then do...
PageFactory.InitializeElements(new PageFactory());
PageFactory.InitializeElements(new SepaPageFactory());
Also I could do...
public static void InitializeElements<T>() where T : PageFactory, new()
{
new T().Initialize();
}
And...
PageFactory.InitializeElements<PageFactory>();
PageFactory.InitializeElements<SepaPageFactory>();
Is there a better way of achieving this?
I'm open to any design suggestions that solve this problem.
EDIT
I'll try to describe the actual use case.....
This is to be part of a test automation framework where elements on a webpage are represented by fields in a class. These 'page' classes can have upwards of 50 elements that all require instantiating. As they all have the same constructor parameters, a quick and clean way to do this (IMO) is with reflection.
The 'real' initialize method will be used to reflect over and instantiate certain fields on these pages.
Using my generics implementation above it would look like...
public static void InitializeElements<U,T>(IWebDriver driver, T page) where U : PageFactory, new()
{
new U().Initialize(driver, page);
}
public virtual void Initialize<T>(IWebDriver driver, T page)
{
var pageType = typeof(T);
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.DeclaredOnly;
foreach (var field in pageType.GetFields(flags))
{
var findsByAttribute = (FindsByAttribute)field.GetCustomAttribute(typeof(FindsByAttribute));
var frameAttribute = (FrameLocatorAttribute)field.GetCustomAttribute(typeof(FrameLocatorAttribute));
var fieldType = field.FieldType;
if (fieldType.IsSubclassOf(typeof(Control)) || fieldType == typeof(Control))
{
field.SetValue(page,
frameAttribute != null
? InitializeControls<Control>(field, driver, findsByAttribute, frameAttribute)
: InitializeControls<Control>(field, driver, findsByAttribute));
}
}
}
U in this context is the class that provides the implementation of the Initialize method.
Most of the time this implementation will be sufficient, however on occasion there will different constraints on which field types are instantiated, hence the need for virtual/override.
This would then be used in the constructor of the pages where I wish to initialise all my fields, e.g....
public class LoginLinkPage : BasePage<LoginLinkPage>
{
[FindsBy(".content a[href='/Account/SignIn']", How.CssSelector)]
public Control LoginLink;
public LoginLinkPage(IWebDriver driver) : base(driver)
{
PageFactory.InitializeElements<SepaPageFactory, LoginLinkPage>(driver, this);
}
}
Which I would like to be consistent regardless of which implementation of Initialize is to be used.
Well, this shouldn't be the best way, but you can also do something like this:
public class Foo
{
public static void DoWork(int a)
{
}
}
public class Doh : Foo
{
public **new** static void DoWork(int a)
{
}
}
That should "override" the method, but maybe it would be better to think about different approach :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am using command pattern in C#.
There is a class that contains some properties named RequiredData.
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
There is an abstract class BaseCommand and there are some derived classes like command1 , command2 etc.
abstract class BaseCommand : ICommand { }
The commands operate some actions like:
command1.Execute();
command2.Execute();
I want during the whole process to have a shared RequiredData object which can be updated and used from all commands.
For example:
in command1 Execute method to access the value1 like :
RequiredData.Value1 = 5
and then in command2 Execute method to have this value like
var k = RequiredData.Value1 //and be 5..
or RequiredData.Class1.something = "something"
I tried this one in the base class:
abstract class BaseCommand : ICommand
{
//or protected and not private...
public static RequiredData RequiredData = new RequiredData();
}
is this thread-safe?
What changes needed here for a thread-safe solution?
You could solve this by using several methods.
Pass the shared instance into the constructor
Singleton pattern/static could help, but is more restricted.
Reminder is, if you use the class on different thread, you need to care about thread safety.
Normally I avoid a static object that can be readed/writed by multiple threads. I advise you to try to get rid from this.
But... you need to be sure, that the object/reference types are not accessible from the outside.
like:
// you could create the locking in this class, but the class1 property is a
// reference type, so just locking in the property is not enought, it
// goes wrong when the Class1 has properties itself. (then these will be
// altered outside the lock..
// I choose to wrap the whole object and only returning value types
public class RequiredData
{
public Class1 class1 { get; set; }
public int value1 {get; set;}
}
abstract class BaseCommand : ICommand
{
// protected.. should not be accessable from the outside..!
protected static RequiredData RequiredData = new RequiredData();
public int GetValue()
{
lock(RequiredData)
return RequiredData.value1;
}
public void SetValue(int value)
{
lock(RequiredData)
RequiredData.value1 = value;
}
// or you could wrap this in a property
public int Value
{
get { return lock(RequiredData) RequiredData.value1; }
set { lock(RequiredData) RequiredData.value1 = value; }
}
public string GetSomething()
{
// try to avoid returning reference types, but the can be referenced from outside the object.
lock(RequiredData)
return RequiredData.Class1.something;
}
}
So the locking should be inside the BaseCommand. And the BaseCommand should be responsible for communicating with the RequiredData. (so no other object could have a reference to the RequiredData)
Like I said: Multithreading / static read/writer = playing with fire.
If you have many readers/writers you should have a look at the ReaderWriterLock(Slim). Because multiple threads can read simultaneously and only one writer is active.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
WiresharkFile abstract class:
public abstract class WiresharkFile
{
private PlayBehavior _playBehavior;
public void Transmit()
{
_playBehavior.Transmit();
}
public virtual void Dispose()
{
// Implemented inside inherit classes.
}
}
Play options abstract class:
public abstract class PlayBehavior
{
public WiresharkFile wiresharkFile;
public abstract void Transmit();
}
Play options son class:
public class Normal : PlayBehavior
{
public override void Transmit()
{
using (this.wiresharkFile)
{
}
}
}
So i have this derived class:
public class Libpcap : WiresharkFile, IDisposable, IEnumerable<Packet>
{
private BinaryReader binaryReader;
public void Dispose()
{
if (binaryReader != null)
binaryReader.Close();
}
...
// Severl methods
...
public override void SendPackets()
{
base.Transmit();
}
}
My question:
Inside this Libpcap class when call base.Transmit(): where to use the using ?
Inside this Libpcap class SendPackets():
public override void SendPackets()
{
using(this)
{
base.Transmit();
}
}
Or inside Normal class Transmit():
public class Normal : PlayBehavior
{
public override void Transmit()
{
using (this.wiresharkFile)
{
}
}
}
Calling using(this) never makes sense. It means you're calling Dispose on yourself, which means that A) your class will be at an undefined state at the end of the using block, and B) code calling you will see you're IDisposable and expect to be able to control your lifetime, but you're actually controlling it yourself from within your code.
If your Libpcap's lifetime ends after the Transmit call, you can use using on it from your PlayBehavior class - it holds the reference to it, so it controls its lifetime.
Implementing IDisposable is a contract. By doing so, you're saying "My operation holds references to unmanaged resources (files, tcp connections, etc), and you, my caller, need to call my Dispose method when you're done with me to release them". If this is not the usage contract that WiresharkFile expects, don't implement IDisposable.
If you have unmanaged resources that are created and released as part of your normal operations, but which doesn't require your caller to explicitly release, simply do it yourself - release an internal unmanaged resource when you're done with it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Lets say I have 3 tasks: Registration, Assessment, Enrollment.
I want to be able to make my application have these 3 interchangeable in position in the process. So for one setting, I can do Registration -> Assessment -> Enrollment. I can change for another setting to Registration -> Enrollment -> Assessment.
And also I need to be able to switch on/off some functionality of task (like Registration).
Can you guys give me an idea of where to start?
I would set up a chain of responsibility. From GoF:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Here's a barebones example that uses the names of business processes you've given:
// These all should be named something relevant to your domain
public interface IHandler
{
void Handle(string request);
}
public class Handler
{
protected IHandler successor;
protected Handler(IHandler successor)
{
this.successor = successor;
}
protected virtual void Successor(string request)
{
successor?.Handle(request);
}
}
public class Registration : Handler, IHandler
{
public Registration(IHandler successor)
: base(successor) { }
public void Handle(string request)
{
Console.WriteLine($"Registration handled request {request}");
base.Successor(request);
}
}
public class Enrollment : Handler, IHandler
{
public Enrollment(IHandler successor)
: base(successor) { }
public void Handle(string request)
{
Console.WriteLine($"Enrollment handled request {request}");
base.Successor(request);
}
}
public class Assessment : Handler, IHandler
{
public Assessment(IHandler successor)
: base(successor) { }
public void Handle(string request)
{
if (request.Equals("Bob", StringComparison.InvariantCulture))
{
Console.WriteLine("Bob failed assessment.");
return;
}
Console.WriteLine($"Assessment handled request {request}");
base.Successor(request);
}
}
and example use:
// Consumers of this don't need to know anything more than it's an IHandler service
// Consumers of this don't need to know anything more than it's an IHandler service
IHandler noregistrationHandlers = new Assessment(new Enrollment(null));
// or Autofac
// builder.Register(c => new Assessment(c.Resolve<Enrollment>(null))).Named("NoRegistration");
// or your favorite IoC container
noregistrationHandlers.Handle("Smith");
IHandler registrationHandlers = new Registration(new Assessment(new Enrollment(null)));
// builder.Register(c => new Registration(c.Resolve<Assessment>(c.Resolve<Enrollment>(null)))).Named("Registration");
registrationHandlers.Handle("Bob");
Here's the takeaway on this - the consuming code (the usage example) doesn't need to know anything except the format to send the request to the handler. The fact that the constructors are invoked in the example is a matter of mere convenience for example's sake. You can very well have an MVC controller that depends on an IHandler but knows nothing else about it.
public class UserController
{
private readonly IHandler handler;
public UserController(IHandler handler)
{
if (handler == null) throw new NullReferenceException(nameof(handler));
this.handler = handler;
}
// ...
public ActionResult Save(string id)
{
handler(id);
}
}