I have an ADK provided by a hardware manufacturer for connecting to and using their hardware.
The ADK is a DLL we have referenced in our project, then called and used methods based on events. The problem is that the DLL constantly writes some text to the console. The string is always the same, We need to use the console so completely turning it off is not a viable solution.
I have attempted an implementation of the TextWriter class that ignores this string but this output from the DLL does not come into the class when I breakpoint inside it.
The TextWriter we built looked like this;
public class MyTextWriter : TextWriter
{
private TextWriter _standardOut;
public MyTextWriter(TextWriter ConsoleOut)
{
this._standardOut = ConsoleOut;
}
public override Encoding Encoding
{
get
{
return Encoding.ASCII;
}
}
public override void WriteLine(string val)
{
if(val != "Hello")
{
_standardOut.WriteLine(val);
}
}
}
Is there any other way to stop this DLL writing to the console?
Related
I'm trying to forward the Console output to a Windows Forms TextBox control. So I attached a custom TextWriter to the Console which appends the output to the TextBox.
But I think the TextWriter or TextBox is inaccessible from within an external class. How to fix this? Check my code below:
partial class Form1 : Form
{
public StringWriter _TextWriter;
public Form1()
{
InitializeComponent();
this._TextWriter = new TextBoxStreamWriter(this.textBox1);
Console.SetOut(this._TextWriter);
Console.WriteLine("This text does appear in the TextBox, works perfect.");
Test ConsoleOutputExternalClass = new Test();
}
}
public class TextBoxStreamWriter : StringWriter
{
TextBox _output = null;
public TextBoxStreamWriter(TextBox output)
{
this._output = output;
}
public override void WriteLine(string value)
{
base.WriteLine(value);
this._output.AppendText(value.ToString());
}
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
private class Test
{
public Test()
{
// HERE I GET AN EXCEPTION ERROR !!
Console.WriteLine("System.IO.IOException: 'The handle is invalid.'");
}
}
As I found out after experimenting, the problem had another cause than I expected. In my program I used Console.Clear() to remove all printed lines, but apparently this also destroys the link to the custom set output stream.
And this wouldn't clear the TextBox after all, I should be using TextBox.Clear().
I'm sorry for this, because my question is not to the point in this case, the problem appeared to lie somewhere else. In fact, the code in my question does work perfectly because there is no call to Console.Clear(), but I just didn't find out what really caused the problem yet.
The real question would be: how to "override" Console.Clear() in order to clear the TextBox? But this is for another topic.
I have been working on Android app Development and now have switched to windows.
1) I have a scenario where i need to create a child project and library project, we have done this Android as given in the link - http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject
How to acheive the same thing in Visual Studio ? for Windows Phone app development.
2) i have to create a class which will have some methods defined with some values,like :
In my base project
Class{
public void string appName(){
return "XYZ"
}
public void int appVersion(){
return 1;
}
}
Now in my child project i should be able to override the above methods and change the implementation and also if i did not give the implementation it should take the default value.
How to acheive this in C# ?
Usually you don't reuse files in C# but reuse classes,
Create your library project and put your base class there :
namespace YourLibraryNameSpace
{
public class BaseClass
{
public virtual void string AppName()
{
return "XYZ";
}
public virtual void int AppVersion()
{
return 1;
}
}
}
then in your main project add a reference to the library project and add your child class like this:
namespace MainProjectNameSpace
{
using YourLibraryNameSpace;
public class ChildClass : BaseClass
{
public override void string AppName()
{
return "ABC";
}
public override void int AppVersion()
{
return 2;
}
}
}
And I suggest following C# naming conventions, like pascal casing method names.
In C# it works in pretty much the same way. A library project is a dll, so you can create this one first. Then create your main project. In the solution explorer tree you can right-click on the main project and add a reference to the library project.
Regarding overriding implementation, in c# you need to explicitly mark your methods as virtual if you want this behaviour:
Class{
public virtual void string appName(){
return "XYZ"
}
public virtual void int appVersion(){
return 1;
}
}
and then when you override them in your child class, change virtual to override (needs to be explicitly stated you are overriding, unlike java).
C#. I have a base class called FileProcessor:
class FileProcessor {
public Path {get {return m_sPath;}}
public FileProcessor(string path)
{
m_sPath = path;
}
public virtual Process() {}
protected string m_sath;
}
Now I'd like to create to other classes ExcelProcessor & PDFProcessor:
class Excelprocessor: FileProcessor
{
public void ProcessFile()
{
//do different stuff from PDFProcessor
}
}
Same for PDFProcessor, a file is Excel if Path ends with ".xlsx" and pdf if it ends with ".pdf". I could have a ProcessingManager class:
class ProcessingManager
{
public void AddProcessJob(string path)
{
m_list.Add(Path;)
}
public ProcessingManager()
{
m_list = new BlockingQueue();
m_thread = new Thread(ThreadFunc);
m_thread.Start(this);
}
public static void ThreadFunc(var param) //this is a thread func
{
ProcessingManager _this = (ProcessingManager )var;
while(some_condition) {
string fPath= _this.m_list.Dequeue();
if(fPath.EndsWith(".pdf")) {
new PDFProcessor().Process();
}
if(fPath.EndsWith(".xlsx")) {
new ExcelProcessor().Process();
}
}
}
protected BlockingQueue m_list;
protected Thread m_thread;
}
I am trying to make this as modular as possible, let's suppose for example that I would like to add a ".doc" processing, I'd have to do a check inside the manager and implement another DOCProcessor.
How could I do this without the modification of ProcessingManager? and I really don't know if my manager is ok enough, please tell me all your suggestions on this.
I'm not really aware of your problem but I'll try to give it a shot.
You could be using the Factory pattern.
class FileProcessorFactory {
public FileProcessor getFileProcessor(string extension){
switch (extension){
case ".pdf":
return new PdfFileProcessor();
case ".xls":
return new ExcelFileProcessor();
}
}
}
class IFileProcessor{
public Object processFile(Stream inputFile);
}
class PdfFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
class ExcelFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
This should make sure you are using the FileProcessorFactory to get the correct processor, and the IFileProcessor will make sure you're not implementing different things for each processor.
and implement another DOCProcessor
Just add a new case to the FileProcessorFactory, and a new class which implements the interface IFileProcessor called DocFileProcessor.
You could decorate your processors with custom attributes like this:
[FileProcessorExtension(".doc")]
public class DocProcessor()
{
}
Then your processing manager could find the processor whose FileProcessorExtension property matches your extension, and instantiate it reflexively.
I agree with Highmastdon, his factory is a good solution. The core idea is not to have any FileProcessor implementation reference in your ProcessingManager anymore, only a reference to IFileProcessor interface, thus ProcessingManager does not know which type of file it deals with, it just knows it is an IFileProcessor which implements processFile(Stream inputFile).
In the long run, you'll just have to write new FileProcessor implementations, and voila. ProcessingManager does not change over time.
Use one more method called CanHandle for example:
abstract class FileProcessor
{
public FileProcessor()
{
}
public abstract Process(string path);
public abstract bool CanHandle(string path);
}
With excel file, you can implement CanHandle as below:
class Excelprocessor: FileProcessor
{
public override void Process(string path)
{
}
public override bool CanHandle(string path)
{
return path.EndsWith(".xlsx");
}
}
In ProcessingManager, you need a list of processor which you can add in runtime by method RegisterProcessor:
class ProcessingManager
{
private List<FileProcessor> _processors;
public void RegisterProcessor(FileProcessor processor)
{
_processors.Add(processor)
}
....
So LINQ can be used in here to find appropriate processor:
while(some_condition)
{
string fPath= _this.m_list.Dequeue();
var proccessor = _processors.SingleOrDefault(p => p.CanHandle(fPath));
if (proccessor != null)
proccessor.Process(proccessor);
}
If you want to add more processor, just define and add it into ProcessingManager by using
RegisterProcessor method. You also don't change any code from other classes even FileProcessorFactory like #Highmastdon's answer.
You could use the Factory pattern (a good choice)
In Factory pattern there is the possibility not to change the existing code (Follow SOLID Principle).
In future if a new Doc file support is to be added, you could use the concept of Dictionaries. (instead of modifying the switch statement)
//Some Abstract Code to get you started (Its 2 am... not a good time to give a working code)
1. Define a new dictionary with {FileType, IFileProcessor)
2. Add to the dictionary the available classes.
3. Tomorrow if you come across a new requirement simply do this.
Dictionary.Add(FileType.Docx, new DocFileProcessor());
4. Tryparse an enum for a userinput value.
5. Get the enum instance and then get that object that does your work!
Otherwise an option: It is better to go with MEF (Managed Extensibility Framework!)
That way, you dynamically discover the classes.
For example if the support for .doc needs to be implemented you could use something like below:
Export[typeof(IFileProcessor)]
class DocFileProcessor : IFileProcessor
{
DocFileProcessor(FileType type);
/// Implement the functionality if Document type is .docx in processFile() here
}
Advantages of this method:
Your DocFileProcessor class is identified automatically since it implements IFileProcessor
Application is always Extensible. (You do an importOnce of all parts, get the matching parts and Execute.. Its that simple!)
I want to exit the program if I see some key words apprearing in Console.Out. This is because we use a third party DLL which has a problem that when it encounters some particular exception it never exits.
The only sulotion to us seems to be monitoring the log that is populated back to console.Out. And base on the log on console.out, the host application can edecide what to do when such exception are encountered.
Someone told me that I can use trace listener... but I am not sure about that.
what do you guys think?
The Console class provides the SetOut method which can be used to write output to a custom stream. For example, you could stream to a StringBuilder and monitor changes, or write a custom stream implementation that watches for the keywords.
For example, here is a KeywordWatcherStreamWrapper class that watches for specified keyword, and raises an event for all listeners whenever the keyword is seen:
public class KeywordWatcherStreamWrapper : TextWriter
{
private TextWriter underlyingStream;
private string keyword;
public event EventHandler KeywordFound;
public KeywordWatcherStreamWrapper(TextWriter underlyingStream, string keyword)
{
this.underlyingStream = underlyingStream;
this.keyword = keyword;
}
public override Encoding Encoding
{
get { return this.underlyingStream.Encoding; }
}
public override void Write(string s)
{
this.underlyingStream.Write(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
public override void WriteLine(string s)
{
this.underlyingStream.WriteLine(s);
if (s.Contains(keyword))
if (KeywordFound != null)
KeywordFound(this, EventArgs.Empty);
}
}
Sample usage:
var kw = new KeywordWatcherStreamWrapper(Console.Out, "Hello");
kw.KeywordFound += (s, e) => { throw new Exception("Keyword found!"); };
try {
Console.SetOut(kw);
Console.WriteLine("Testing");
Console.WriteLine("Hel");
Console.WriteLine("lo");
Console.WriteLine("Hello");
Console.WriteLine("Final");
} catch (Exception ex) { Console.Write(ex.Message); }
On the second Write statement which contains the entire keyword, the event will be raised and thus the exception will be thrown. Note also that this silently wraps the underlying stream and still writes to it, so console output is still generated as normal.
Sample output:
Testing
Hel
lo
Hello
Keyword found!
if you can wrap this into an exe, maybe you can use Process.StandardOutput.
Okay, I think the title can be quite confusing... :)
My application is using CS-Script as a script interface.
In the scripts my application will be running, I want to have some sort of "Debug print" - meaning somewhere in the script the scripter can do "Debug.Print("BLAAAAH!!!");") and that would show up somewhere in my very funky output dialog.
Of course I can create my own debug-ooutput-stuff, but since I'm using C# as a scripting language and people using C# would be used to use System.Diagnostics and use Debug.Print("..."),
it would be great if I could reroute System.Diagnostics.Debug.Print("") and System.Diagnostics.Debug.WriteLine("...") to trace their output to my cool output-window.
So.
Does anybody know if it's possible to reroute C#'s System.Diagnostic.Debug print/writeline output to something I have control over ?
For that, you can create a custom TraceListener.
You should set the compile time DEBUG symbol or run the script with /dbg option
cscs /dbg <yourScript>
You will also need to create a custom TraceListener or simply use a trace viewer like the sysinternals DebugView
I use the TraceListener for this also, but here's my code snippets:
Classes:
using System.Diagnostics;
public class DebugOutputListener : TraceListener
{
public event EventHandler<DebugMessageArgs> DebugMessage;
public override void Write(string message)
{
EventHandler<DebugMessageArgs> h = DebugMessage;
if (h != null)
{
DebugArgs args = new DebugArgs
{
Message = message
};
h(this, args);
}
}
public override void WriteLine(string message)
{
Write(message + "\r\n");
}
}
public class DebugMessageArgs : EventArgs
{
public string Message
{
get;
set;
}
}
To receive debug messages, instantiate an instance of the DebugOutputListener, subscribe to the DebugMessage event handler and register the listener with the Debug.Listeners collection.
e.g.
private void InitialiseDebugListener()
{
DebugListener dl = new DebugListener();
dl.DebugMessage += new EventHandler<DebugArgs>(Console_OnDebugMessage);
Debug.Listeners.Add(dl);
}
private void Console_OnDebugMessage(object sender, DebugMessageArgs e)
{
string debugMessage = e.Message;
// Do what you want with debugMessage.
// Be aware this may not come in on the application/form thread.
}