Proxy class C# how to make a variable of a call - c#

I got a class that handles the proxys for a project i bought. And i am looking for learning while doing some modifications to this project.
My question is how can i get a variabel from a void call? I supose the call Proxy.NewProxy(); is the one that grabs the new proxy from my list. But what i want to do is to make a variable of the proxy it got so i can list it in a logfile for example.
My class looks like this
class Proxy
{
private static List<string> proxies = new List<string>();
private static int proxyIndex = 0;
public static WebProxy GetProxy()
{
string[] proxy = proxies[proxyIndex].Split(':');
WebProxy wp = new WebProxy(proxy[0], Convert.ToInt32(proxy[1]));
return wp;
}
public static void NewProxy()
{
if (proxyIndex < proxies.Count - 1)
{
proxyIndex++;
}
else
{
proxyIndex = 0;
}
}
public static void AddProxy(string proxy)
{
proxies.Add(proxy);
}
public static void ClearProxy()
{
proxies.Clear();
}
public static void RemoveProxy(string proxy)
{
proxies.RemoveAll(a => a == proxy);
}
public static List<string> ListProxy()
{
return proxies;
}
}

You can add an event to your class:
public class ProxyGivenEventArgs : EventArgs
{
public String ProxyName { get; private set; }
public ProxyGivenEventArgs(String proxyName)
{
this.ProxyName = proxyName;
}
}
public static class Proxy
{
// ...
public static event EventHandler<ProxyGivenEventArgs> ProxyGiven;
private static void OnProxyGiven(String proxyName)
{
if (Proxy.ProxyGiven != null)
Proxy.ProxyGiven(null, new ProxyGivenEventArgs(proxyName));
}
public static WebProxy GetProxy()
{
string[] proxy = proxies[proxyIndex].Split(':');
WebProxy wp = new WebProxy(proxy[0], Convert.ToInt32(proxy[1]));
OnProxyGiven(proxy[0]);
return wp;
}
// ...
}
and use it like:
Proxy.ProxyGiven += (sender, args) =>
{
Logger.Log("Proxy {0} is given.", args.ProxyName);
};
P.S.: You can tailor ProxyGivenEventArgs to include more info that will suit your needs.
For example if you need the instance of the instantiated proxy, then you can:
public class ProxyGivenEventArgs : EventArgs
{
public WebProxy ProxyInstance { get; private set; }
public ProxyGivenEventArgs(WebProxy proxy)
{
this.ProxyInstance = proxy;
}
}
//...
private static void OnProxyGiven(WebProxy proxy)
{
if (Proxy.ProxyGiven != null)
Proxy.ProxyGiven(null, new ProxyGivenEventArgs(proxy));
}
public static WebProxy GetProxy()
{
string[] proxy = proxies[proxyIndex].Split(':');
WebProxy wp = new WebProxy(proxy[0], Convert.ToInt32(proxy[1]));
OnProxyGiven(wp);
return wp;
}
and use it like:
Proxy.ProxyGiven += (sender, args) =>
{
Logger.Log("Proxy {0} is given.", args.ProxyInstance.ToString());
};
P.S.1: If you aren't familiar with event model you may want to read this MSDN article.

Related

How can use Extension Method in MoonSharp?

ExtensionType in MoonSharp Unity has cache issue?
public static class ExtMethods
{
public static void Test1(this MyClass c) { Debug.Log("test1"); }
public static void Test2(this MyClass c) { Debug.Log("test2"); }
public static void Test3(this MyClass c) { Debug.Log("test3"); }
}
public class MyClass
{
public MyClass() { }
}
public class Scripts
{
Script _script = new Script();
string _myScript =
"local a = Class()" +
"a.Test1()" +
"a.Test2()" +
"a.Test3()" +
public void InitScript()
{
UserData.RegisterExtensionType(typeof(ExtMethods));
UserData.RegisterType(typeof(MyClass));
_script.Globals["Class"] = typeof(MyClass)
_script.DoString(_myScript);
}
}
it only cache just first method of ExtensionType
local a = Class.__new()
a.Test1() -- access success
a.Test2() -- failed
a.Test3() -- failed

Create wrapper around interface and get method/paramters called

Lets say I have this interface
public interface ITest
{
int Property1 { get; set; }
void Method1();
string GetMethod1();
void MethodWithParam(string str);
}
How can I create a wrapper object around this?
And then capture the methods called or paramters and values accessed etc.
For example:
var myWrapper = GetWrapper<ITest>();
myWrapper.Property1 = 7;
How would I be able to using reflection or whatever to know the following:
Paramter name being called and value being set
var data = myWrapper.GetMethod1("Test");
Get method name of "GetMethod1" along with paramaters and then return a value based on that?
Hope makes sense
Ok so answer quite simple using Castle Core proxy generator:
https://github.com/castleproject/Core
public interface ITest
{
int Property1 { get; set; }
void Method1();
string GetMethod1();
void MethodWithParam(string str);
}
public static class Wrapper
{
private class MethodInterceptor : IInterceptor
{
Action<IInvocation> OnIntercept;
public MethodInterceptor(Action<IInvocation> OnIntercept)
{
this.OnIntercept = OnIntercept;
}
public void Intercept(IInvocation invocation)
{
OnIntercept?.Invoke(invocation);
}
}
private static void CallAPI(IInvocation invocation)
{
var methodName = invocation.Method.Name;
var valuespassed = invocation.Arguments;
var retType = invocation.Method.ReturnType.FullName;
//DO API THINGS NOW
}
public static T Get<T>()
{
ProxyGenerator generator = new ProxyGenerator();
var interceptor = new MethodInterceptor(CallAPI);
var c = generator.CreateInterfaceProxyWithoutTarget<ITest>(interceptor);
return (T)c;
}
}
public class Test123
{
public void Test()
{
var c = Wrapper.Get<ITest>();
c.Property1 = 7;
var propval = c.Property1;
}
}
Any action on c calls the intercept function where can get everything from method name being called to arguments passed.

How can I cause Simple Injector to use different concrete classes for the same interface, but with different classes

I can do this with StructureMap using Constructor Injection. However I cannot find a way to do this with Simple Injector. Here is some code that illustrates this (sorry for the length)
I've looked at the lambda in the Register method, but can't seem to understand how to call a single application wide instance of the container to get the one instance I need.
These are the object graphs I wish to construct:
var bannerTalker =
new LoudMouth(
new ConsoleShouter(), // Implements IConsoleVoicer
new ObnoxiousBannerGenerator());
var plainTalker =
new TimidSpeaker(
new ConsoleWhisperer()); // Implements IConsoleVoicer
Here's the code:
``` c#
public interface IConsoleVoicer
{
void SaySomething(string whatToSay);
}
public class ConsoleWhisperer : IConsoleVoicer
{
public void SaySomething(string whatToSay)
{
Console.WriteLine(whatToSay?.ToLower());
}
}
public class ConsoleShouter : IConsoleVoicer
{
public void SaySomething(string whatToSay)
{
Console.WriteLine(whatToSay?.ToUpper());
}
}
public interface IBannerGenerator
{
string GetBanner();
}
public class ObnoxiousBannerGenerator : IBannerGenerator
{
public string GetBanner()
{
return "OBNOXIOUS";
}
}
public interface IBannerTalker
{
void SayWithBanner(string somethingToSay);
}
public class LoudMouth : IBannerTalker
{
private IConsoleVoicer Voicer { get; set; }
private IBannerGenerator BannerGenerator { get; set; }
public LoudMouth(
IConsoleVoicer concoleVoicer, IBannerGenerator bannerGenerator)
{
Voicer = concoleVoicer;
BannerGenerator = bannerGenerator;
}
public void SayWithBanner(string somethingToSay)
{
Voicer.SaySomething(string.Format("{0}:{1}",
BannerGenerator.GetBanner(), somethingToSay));
}
}
public interface IPlainTalker
{
void SayIt(string somethingToSay);
}
public class TimidSpeaker : IPlainTalker
{
private IConsoleVoicer Voicer { get; set; }
public TimidSpeaker(IConsoleVoicer concoleVoicer)
{
Voicer = concoleVoicer;
}
public void SayIt(string somethingToSay)
{
Voicer.SaySomething(somethingToSay);
}
}
And this is what I've tried:
static void Main(string[] args)
{
var container = new Container();
container.Register<IBannerGenerator, ObnoxiousBannerGenerator>();
container.Register<IPlainTalker, TimidSpeaker>();
container.Register<IBannerTalker, LoudMouth>();
//HERE IS THE DILEMMA! How do I assign
// to IBannerTalker a A LoudMouth contructed with a ConsoleShouter,
// and to IPlainTalkerTalker a A TimidSpeaker contructed with a ConsoleWhisperer
//container.Register<IConsoleVoicer, ConsoleShouter>();
container.Register<IConsoleVoicer, ConsoleWhisperer>();
var bannerTalker = container.GetInstance<IBannerTalker>();
var plainTalker = container.GetInstance<IPlainTalker>();
bannerTalker.SayWithBanner("i am a jerk");
plainTalker.SayIt("people like me");
}
Ric .Net is right in pointing you at the RegisterConditional methods. The following registrations complete your quest:
container.Register<IBannerGenerator, ObnoxiousBannerGenerator>();
container.Register<IPlainTalker, TimidSpeaker>();
container.Register<IBannerTalker, LoudMouth>();
container.RegisterConditional<IConsoleVoicer, ConsoleShouter>(
c => c.Consumer.ImplementationType == typeof(LoudMouth));
container.RegisterConditional<IConsoleVoicer, ConsoleWhisperer>(
c => c.Consumer.ImplementationType == typeof(TimidSpeaker));

AppDomainUnloadedException using MAF (Microsoft Addin Framework)

I'm having a AppDomainUnloadedExcpetion from time to time on some machines when calling an addin hosted using MAF (System.AddIn). This is what my pipeline looks like:
[AddInContract]
public interface IGatewayV2 : IContract
{
ITopUpResultContract TopUpPhoneAccount(ITopUpRequestContract request);
}
This is my Host Adapter:
[HostAdapterAttribute()]
public class GatewayContractToViewHostSideAdapter : Dogs.Pipeline.HostView.IGatewayV2
{
private Dogs.Pipeline.Contracts.IGatewayV2 _contract;
private ContractHandle _handle;
public GatewayContractToViewHostSideAdapter(Dogs.Pipeline.Contracts.IGatewayV2 contract)
{
_contract = contract;
_handle = new ContractHandle(contract);
}
public TopUpResult TopUpPhoneAccount(TopUpRequest request)
{
var topupRequestViewToContractHostSideAdapter = new TopUpRequestViewToContractHostSideAdapter(request);
return
new TopUpResultContractToViewHostSideAdapter(
_contract.TopUpPhoneAccount(topupRequestViewToContractHostSideAdapter));
}
}
always on the host adapter side I have a topupRequestViewToContractHostSideAdapter:
class TopUpRequestViewToContractHostSideAdapter : ContractBase, ITopUpRequestContract
{
private TopUpRequest _topUpRequest;
public TopUpRequestViewToContractHostSideAdapter(TopUpRequest topUpRequest)
{
this._topUpRequest = topUpRequest;
}
//properties here
)
and a TopUpResultContractToViewHostSideAdapter which handles the reference to the external appdomain:
public class TopUpResultContractToViewHostSideAdapter : TopUpResult
{
private ITopUpResultContract _contract;
private ContractHandle _handle;
public TopUpResultContractToViewHostSideAdapter(ITopUpResultContract contract)
{
this._contract = contract;
_handle = new ContractHandle(contract);
}
//properties here
}
On the addin side instead I have the following code:
[AddInAdapter()]
public class GatewayViewToContractAddInSideAdapter : ContractBase, Dogs.Pipeline.Contracts.IGatewayV2
{
private Dogs.Pipeline.AddinViewV2.IGatewayV2 _view;
public GatewayViewToContractAddInSideAdapter(Dogs.Pipeline.AddinViewV2.IGatewayV2 view)
{
this._view = view;
}
public ITopUpResultContract TopUpPhoneAccount(ITopUpRequestContract request)
{
var result = _view.TopUpPhoneAccount(new TopUpRequestContractToViewAdapter(request));
return new TopUpResultViewToContractAdapter(result);
}
}
where the TopUpResultViewToContractAdapter is:
public class TopUpResultViewToContractAdapter : ContractBase, ITopUpResultContract
{
private TopUpResult _topUpResult;
public TopUpResultViewToContractAdapter(TopUpResult result)
{
this._topUpResult = result;
}
//properties here
}
and the TopUpRequestContractToViewAdapter is:
public class TopUpRequestContractToViewAdapter : TopUpRequest
{
private ITopUpRequestContract _contract;
private ContractHandle _handle;
public TopUpRequestContractToViewAdapter(ITopUpRequestContract contract)
{
_contract = contract;
_handle = new ContractHandle(contract);
}
//properties here
}
Everything seems compliant with what I've read so far and in particular with what I can read at this link: http://msdn.microsoft.com/en-us/library/bb384186(v=vs.100).aspx
So I'm wondering if I'm doing something wrong or there is a possibility that the pipeline doesn't work on certain machines (as I'm having problem not on all the machines I'm using for testing).
Thanks for any hint.

nunit testing of method which calls other method

Am very new to nunit.below is the business unit code
public enum HighlightType
{
IP,
Item,
Address
}
public class UniformGridHighlighting
{
public static event HighlightingChangedDelegate HighlightingChanged;
private static List<string> _highlightedIPs = new List<string>();
private static List<long> _highlightedItems = new List<long>();
private static ContactInfoType _highlightedAddress;
public static void ClearIPHighlighting()
{
_highlightedIPs.Clear();
OnHighlightingChanged(HighlightType.IP);
}
private static void OnHighlightingChanged(HighlightType type)
{
if (HighlightingChanged != null)
{
HighlightingChanged(type);
}
}
}
I need to write unit test cases for ClearIPHighlighting. How do i proceed.
[Test(Description = "to ")]
public void ClearIPHighlightingTets()
{
UniformGridHighlighting.ClearIPHighlighting();
//How to call method
}
Given the current setup you can only test that the event is triggered.
[Test()]
public void ThatTheEventIsTriggeredWhenTheListIsCleared()
{
// Arrange
bool eventTriggered = false;
UniformGridHighlighting.HighlightingChanged += _ => { eventTriggered= true; };
//Act
UniformGridHighlighting.ClearIPHighlighting();
//Assert:
Assert.IsTrue(eventTriggered);
}
And that it's of the right type
[Test(Description = "to ")]
public void ThatTheEventIsTriggeredWithTheIPArgumentWhenTheIPListIsCleared()
{
// Arrange
HighlightType? type = null;
UniformGridHighlighting.HighlightingChanged += x => { type = x; };
//Act
UniformGridHighlighting.ClearIPHighlighting();
//Assert:
Assert.AreEqual(s, HighlightType.IP);
}
To test that your previous highlight was removed is going to be harder:
[Test]
public void ThatTheIpIsNotHighlightedIfTheListWasCleared()
{
UniformGridHighlighting.HighlightIP("1.1.1.1");
//Act
UniformGridHighlighting.ClearIPHighlighting();
UniformGridHighlighting.Highlihst(Grid);
//Assert:
//Go through the grid to figure out that the IP was not highlighted. The below is a total guess:
bool wasHighlighted = Grid.Rows.Any(row => row.Cells.Any(Cell.Highlighted));
Assert.Isfalse(wasHighlighted);
}

Categories