Console.WriteLine is not working after Resolve() - c#

This code gives no error or warning during execution. but it ignores the console.read() function, i am newer with windsor. is it really a bug or the simple behavior of windsor ?
using System;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
namespace CastleProject
{
class Program
{
internal interface ILogger
{
void log(string message);
void showMethod();
}
internal interface Ishowing
{
void checkInterface();
}
class Logger : ILogger
{
public void log(string message)
{
Console.WriteLine(message);
Console.Read();
}
public void showMethod()
{
Console.WriteLine("This is again showing just function i existing");
}
}
class Showing : Ishowing
{
public void checkInterface()
{
Console.WriteLine("this is line from checkInterface()");
var a = Console.ReadLine();
Console.WriteLine(a);
}
}
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For<ILogger>().ImplementedBy<Logger>(),Component.For<Ishowing>().ImplementedBy<Showing>());
var logger = container.Resolve<ILogger>();
var logger2 = container.Resolve<Ishowing>();
logger.log("hello message");
logger.showMethod();
logger2.checkInterface();
}
}
}

I think you probably want to use Console.ReadLine rather than Console.Read.
Try this snippet of code to understand Read/ReadLine behavior:
var a = Console.Read();
Console.WriteLine(a);
var b = Console.ReadLine();
Console.WriteLine(b);

Related

How to pass parameters from main method to another class

How do I pass the parameters from main method to another class?
I have done like this. Is this right approach?
namespace classA
{
class Program
{
public static void Main(string[] args)
{
string abc= new string {"HELLO"};
Console.WriteLine("My result: {0}", ClassB(abc));
Console.Read();
}
public static string ClassB(string abc)
{
//code
return xyz;
}
}
}
well in the code you posted you have only one class with two methods but in principle yes, this would be one way:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string abc = "HELLO";
Console.WriteLine("My result: {0}", ClassB(abc));
Console.Read();
}
public static string ClassB(string abc)
{
return abc;
}
}
}
My result: HELLO
If you have your second method really in another STATIC class:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string abc = "HELLO";
Console.WriteLine("My result: {0}", myfuncclass.ClassB(abc));
Console.Read();
}
}
static class myfuncclass
{
public static string ClassB(string abc)
{
return abc;
}
}
}
My result: HELLO
And if your second method is NOT in a static class and your method is NOT static you have to create an instance of the class first and then call your method on this object:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string abc = "HELLO";
myfuncclass test = new myfuncclass();
Console.WriteLine("My result: {0}", test.ClassB(abc));
Console.Read();
}
}
public class myfuncclass
{
public string ClassB(string abc)
{
return abc;
}
}
}

How to test a thread that reads from Console.ReadLine i.e. how do I write to the console's input?

I've got a thread that reads from the console via Console.ReadLine, but to build a unit test for that thread, I want to essentially write to the console's input, I tried this:
Stream inputStream = Console.OpenStandardInput();
StreamWriter sw = new StreamWriter(inputStream);
sw.WriteLine("foo");
But the thread doesn't see the text? Is there another way?
I think you need to take a step back on this one. What you have done is couple your application to the console. Whereas you should really separate it... Here is some pseudo-code:
Your Application
public interface IUserInput
{
string ReadInput();
}
public class ConsoleInput : IUserInput
{
public ReadInput()
{
return Console.ReadLine();
}
}
public class YourClass
{
IUserInput _userInput;
// Can inject TEST or REAL input
public YourClass(IUserInput userInput)
{
_userInput = userInput;
}
// ... Your code
public void YourMethod()
{
var doSomething = _userInput.ReadInput();
}
}
Your Test
public class TestInput : IUserInput
{
public ReadInput()
{
return "This is dummy data";
}
}
[Test]
public void MyTest()
{
var testInput = new TestInput();
var systemUnderTest = new YourClass(testInput);
// ...
}

How attach event to console app on startup

I have application for which I need to add additional hidden logging.
I have put prototype in way.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start");
new DummyTest().Report();
Console.WriteLine("End");
Console.ReadKey();
}
}
public class DummyTest
{
public void Report()
{
var reporter = new Reporter();
Console.WriteLine("Reporting");
for (var i =0; i < 155; i++)
{
reporter.Process(i);
}
Console.WriteLine("Reporting end");
}
}
public class Reporter
{
// attach behavior here
public void Process(int requestId)
{
Console.WriteLine("Processing request: {0}" , requestId);
System.Threading.Thread.Sleep(100);
}
}
Now I have new project logger.dll that contains
using System;
namespace logger
{
public class Log
{
public Log()
{
Console.WriteLine("Line executed");
}
}
}
Now I would like to execute this method every time Main gets executed. This however cannot be referenced in any other way except only by referencing the dll.
=Update=
I do not mind to have reference to that dll. But in main code I cannot have any reference to Log. I thought about using reflection in order to make this work. The problem I am trying to solve first is how to attach that to the execution.
Why I cannot call logger from main?
This is supposed to be reporting on usage of the class, monitoring usage, in order to report on performance on bottle necks.
You could do something like this:
void Main()
{
System.Console.SetOut(new CustomTextWriter());
Console.WriteLine("test");
}
public class CustomTextWriter : TextWriter
{
private TextWriter _consoleOut = null;
private Log _logger = null;
public CustomTextWriter()
{
_consoleOut = System.Console.Out;
_logger = new Log();
}
public override void Write(char[] buffer, int index, int count)
{
this.Write(new String(buffer, index, count));
}
public override void Write(string value)
{
_consoleOut.Write(value);
_logger.Write(value);
}
public override void WriteLine(string value)
{
_consoleOut.WriteLine(value);
_logger.WriteLine(value);
}
public override Encoding Encoding
{
get { return System.Text.Encoding.Default; }
}
}
Wasn't sure if you wanted to do logging without actually calling Console.WriteLine() (if yes you'll need to look at Interception) but if that's ok then this should get you through.
Hope this helps.
You could do that with reflection like this:
// load the assembly
Assembly LogDll = Assembly.LoadFile(#"Log.dll");
// get the type of the Log class
Type LogType = LogDll.GetType("logger.Log");
// get instance of the Log class
object LogInstance = Activator.CreateInstance(LogType);
// invoke class member "Log()"
LogType.InvokeMember("Log",
BindingFlags.InvokeMethod |
BindingFlags.Instance |
BindingFlags.Public,
null,
LogInstance,
null);
Although I'm not sure if the constructor "Log()" already gets called by creating the instance. You should probably move your actual log method out of the constructor. To pass arguments you can use the last parameter of InvokeMember which is an array of the type Object.

C# app fall down when use Task in PCL

I've created PCL Library:
here code:http://dumpz.org/1131545/.
In this PCL I've created an interface and class, that class call an method of this interface with Task.
Next I've added C# Class Library project, added reference to pcl and implemented this interface(http://dumpz.org/1131549/).
After it, I've added ConsoleApp, added reference to PCL and added implemented from C# CLP as a link to files.(http://dumpz.org/1131550/)
namespace PortableClassLibrary1
{
public interface test
{
void test();
}
public class Class1
{
test Test;
public Class1(test Test)
{
this.Test = Test;
}
public Task<bool> Call()
{
return Task.Factory.StartNew(() =>
{
try
{
Test.test();
return true;
}
catch(Exception ex)
{
return false;
}
});
}
}
}
in C# CLP:
class Impl:test
{
public Impl()
{
}
public void test()
{
CookieContainer s = new CookieContainer();
}
}
Console App:
class Program
{
static Class1 s;
static void Main(string[] args)
{
s = new PortableClassLibrary1.Class1(new Impl());
test();
}
static async void test()
{
bool x = await s.Call();
if(x == true)
{
Console.WriteLine("test");
}
else
{
Console.Write("");
}
}
}
But when I call implemented method app fall down.
Please explain me why?
Thank you for your time.
When you await, control is yielded back to the caller. In your app, that means that when you await s.Call(), control yields back to test which is the last method inside Main, which then finishes execution and closes the console app.
What you have to do is explicitly call Wait on the Task
class Program
{
static Class1 s;
static void Main(string[] args)
{
s = new PortableClassLibrary1.Class1(new Impl());
test().Wait();
}
static async Task test()
{
bool x = await s.Call().ConfigureAwait(false);
if(x == true)
{
Console.WriteLine("test");
}
else
{
Console.Write("");
}
}

property injection using autofac 3.1.1

i am trying to inject through property in the following service, if I try constructor injection it works but I want to do property injection, what am I missing?
public class SodaService
{
public ISoda _s;
//public SodaService(ISoda s)
//{
// _s = s;
//}
public string GetSoda()
{
return _s.SodaName;
}
}
//Soda Class implementing ISoda
public class Soda : ISoda
{
public string SodaName
{
get { return "Default Soda"; }
}
}
public interface ISoda
{
string SodaName { get; }
}
//Main calling program
class Program
{
static void Main(string[] args)
{
var container = GetContainer();
SodaService s=container.Resolve<SodaService>();
Console.Write(s.GetSoda());
Console.Read();
}
private static IContainer GetContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Soda>().As<ISoda>();
builder.RegisterType<SodaService>()
.PropertiesAutowired();
var container = builder.Build();
return container;
}
}
EDIT:
The above was solved and i have one more question....
How can i make something like this work, i do not want to use
s = container.Resolve< ISodaService >();
and instead the dependencies should be automatically injected when i run the program
class Program
{
public static ISodaService s { get; set; }
static void Main(string[] args)
{
SetUpContainer();
//s = container.Resolve<ISodaService>();
Console.Write(s.GetSoda());
Console.Read();
}
private static void SetUpContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Soda>().As<ISoda>();
builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired();
builder.Build();
}
}
The problem you have is Main method is static. Instanciate a class of Program and use is as non static class
class Program
{
public ISodaService s { get; set; }
static void Main(string[] args)
{
var resolver=SetUpContainer();
var instance=resolver.Resolve<Program>();
instance.Execute(args);
}
public void Execute(string[] args)
{
Console.Write(s.GetSoda());
Console.Read();
}
private Autofac.IContainer void SetUpContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Soda>().As<ISoda>();
builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired();
builder.RegisterType<Program>().PropertiesAutowired();
return builder.Build();
}
}

Categories