.NET Tools: Extract Interface and Implement Wrapper Class - c#

Is there a tool that can generate extract and generate interfaces for existing classes?
I know Visual Studio will extract an Interface for an existing class. However, I would also like to generate a wrapper class that implements that functionality.
I believe this would help tremendously for unit testing.
Example Existing Class:
public class ThirdPartyClass
{
public void Method1(){}
public void Method2(){}
}
This can be generated by Visual Studio (Extract Interface):
public interface IThirdPartyClass
{
void Method1();
void Method2();
}
I would like to go one step further:
public class ThirdPartyClassWrapper : IThirdPartyClass
{
private tpc = new ThirdPartyClass();
public void Method1()
{
tpc.Method1();
}
public void Method2()
{
tpc.Method2();
}
}
Update:
This would be especially useful for static classes. As Morten points out I can just use a stub, however, I would like to break up my coupling if possible.

Found a way around it for non-sealed classes.
1 - Inherit from the external class
class MyWrapper : ExternalClass
2 - Extract interface for all public methods
class MyWrapper : ExternalClass, IExternalClass
3 - Remove the inheritance from the external class
class MyWrapper : IExternalClass
4 - You will get a hint on the class name about members from the interface not being implemented. Alt + Enter on it and let Resharper automatically implement them
5 - Use this code template to wrap properties
get { return $INNERCOMPONENT$.$NAME$; }
set { $INNERCOMPONENT$.$NAME$ = value; }
6 - Use this code template to wrap methods
return $INNERCOMPONENT$.$NAME$($SIGNATURE$);

I don't know a tool that would do that for you.
You probably know, but Visual Studio goes just half step further - it can provide empty implementation of interface. I would stop there if it is one time task.
Depending on actual goal using some other way may work - i.e. for testing you can use mocking frameworks - usually there is a way to wrap existing class and override some methods as needed.

Another really slick way of doing this is to use Resharper to generate the "Delegating members" for you as described here: https://stackoverflow.com/a/2150827/1703887
Steps:
Create a new class that inherits from the class you want to wrap with a private variable of that class' type:
public class ThirdPartyClassWrapper : ThirdPartyClass
{
private ThirdPartyClass _ThirdPartyClass;
}
Do a Alt-Insert in/on the class to use Resharper to generate "Delegating members". Choose the methods you want to expose and pass through to the private variable.
If you have the free version of the GhostDoc extension installed you can highlight all of the created properties, methods, etc. and do a Ctrl-D to automatically grab all of the documentation from the base class and put it on the new members. (Resharper can do this too but I think you'd have to put "new" on each item which would then allow you to Alt-Enter and choose "Add xml-doc comments" from the Resharper popup menu).
You can then delete the base class and do some additional cleanup in case the method/property signatures expose any other types that you need to wrap.

What you are looking for is a stub, this can be done either by making your own stub implementation of the interface, or by using a mocking framework like Rhinomocks. Wrapping a difficult class in another class for testpurposes does nothing good for you.
Regards
Morten

I strongly suggest you look into a mocking framework like Fakeiteasy.
But to give you exactly what you asked for see below. I suspect ReSharper didn't have this operation when others answered.
add the interface to the class you wish to be the wrapping class
class MyWebElement : IWebElement { }
Find/Click "Delegate implementation of "YourInterfaceHere" to a new field
Select your options
Click finish and enjoy your new class
class MyWebElement : IWebElement
{
private IWebElement _webElementImplementation;
public IWebElement FindElement(By #by)
{
return _webElementImplementation.FindElement(#by);
}
public ReadOnlyCollection<IWebElement> FindElements(By #by)
{
return _webElementImplementation.FindElements(#by);
}
public void Clear()
{
_webElementImplementation.Clear();
}
public void SendKeys(string text)
{
_webElementImplementation.SendKeys(text);
}
public void Submit()
{
_webElementImplementation.Submit();
}
public void Click()
{
_webElementImplementation.Click();
}
public string GetAttribute(string attributeName)
{
return _webElementImplementation.GetAttribute(attributeName);
}
public string GetCssValue(string propertyName)
{
return _webElementImplementation.GetCssValue(propertyName);
}
public string TagName
{
get { return _webElementImplementation.TagName; }
}
public string Text
{
get { return _webElementImplementation.Text; }
}
public bool Enabled
{
get { return _webElementImplementation.Enabled; }
}
public bool Selected
{
get { return _webElementImplementation.Selected; }
}
public Point Location
{
get { return _webElementImplementation.Location; }
}
public Size Size
{
get { return _webElementImplementation.Size; }
}
public bool Displayed
{
get { return _webElementImplementation.Displayed; }
}
}

Related

Inheritance in Specflow test steps cause Ambiguous Steps

I've read that using inheritance is not possible when using Specflow, which makes sense most of the time. However, I've run across a situation that seems to require the proper the use of inheritance. Here are my classes:
Base Class:
public class StepBaseClass
{
protected readonly ScenarioContext scenarioContext;
public StepBaseClass(ScenarioContext scenarioContext)
{
this.scenarioContext = scenarioContext;
}
}
First Inherited Class:
[Binding]
public class StudioEnterpriseImportConnectorSteps:StepBaseClass
{
public StudioEnterpriseImportConnectorSteps(ScenarioContext scenarioContext) :base(scenarioContext)
{
}
[Given(#"I have a data record that I want to send to the import service")]
public void GivenIHaveADataRecordThatIWantToSendToTheImportService()
{
scenarioContext.Pending();
}
[When(#"I send the information to an invalid URL")]
public void WhenISendTheInformationToAnInvalidURL()
{
scenarioContext.Pending();
}
[Then(#"an error should be generated")]
public void ThenAnErrorShouldBeGenerated()
{
scenarioContext.Pending();
}
}
2nd inherited class:
[Binding]
public class SitemapSteps:StepBaseClass
{
public SitemapSteps(ScenarioContext scenarioContext):base(scenarioContext)
{
}
[When(#"I visit the URL (.*)")]
public void WhenIVisitTheSitemapURL(string URL)
{
scenarioContext.Add("result", TestUtilities.GetResponseCode(URL));
scenarioContext.Add("response", TestUtilities.GetResponseBody(URL));
}
[Then(#"the response code should be (.*)")]
public void ThenTheResponseCodeShouldBe(string responseCode)
{
HttpStatusCode result = scenarioContext.Get<HttpStatusCode>("result");
Assert.Equal(responseCode, result.ToString());
}
}
As you can see, the only thing that I'm inheriting the the scenarioContext, which is something that I need to do in order to write multi-threaded tests. So instead of repeating this piece of code for each of my classes, I would like to be able to inherit from a base class. What is the proper method of initializing that variable so that I can use it in each of my derived classes?
The proper way depends as always on your individual situaion.
I recommend always to not use base classes and use context injection everywhere. The small number of code that is repeated in the constructor is a small price for a good separation and splitting of your bindings and their implementation.
To get more info about this topic, Gaspar Nagy wrote a nice blog article about the pros and cons of step base classes in SpecFlow:
http://gasparnagy.com/2017/02/specflow-tips-baseclass-or-context-injection/
After initializing my Dependency Injection in the Specflow Test hooks, I would have a class called ApplicationContext with a static resolve method which would return me my ScenarioContext instance like so:
public class ApplicationContext
{
public static T Resolve<T>() where T: class
{
return container.GetInstance<T>();
}
}
Then in my steps class, I would resolve the ScenarioContext like this:
scenarioContext = (ScenarioContext)ApplicationContext.Resolve<IScenarioContext>();

Pass-through constructors from its base class

An external framework has the following classes:
public class Boatmaker
{
}
public class Wood
{
}
public class Axe
{
}
public class Lake
{
}
public class Boat
{
public Boat(Wood wood, Axe axe) {
}
public Boat (Boatmaker maker) {
}
public Boat (Lake lake) {}
}
I need to do a lot of subclassing of Boat. For each of my subclasses, I have to assume that the external framework may want to instantiate it via any of the above constructors. So my subclasses get pass-through constructors. Notice how they never go away:
public class SmallBoat: Boat
{
public void DoSmallBoatStuff() {
// some code here
}
private void Initialize() {
this.DoSmallBoatStuff();
}
public SmallBoat(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public SmallBoat (Boatmaker maker): base(maker) {
this.Initialize();
}
public SmallBoat (Lake lake): base(lake) {
this.Initialize();
}
}
public class Canoe: SmallBoat
{
public void DoCanoeStuff() {
// some code here
}
private void Initialize() {
this.DoCanoeStuff();
}
public Canoe(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public Canoe (Boatmaker maker): base(maker) {
this.Initialize();
}
public Canoe(Lake lake): base(lake) {
this.Initialize();
}
}
I am wondering if there is a way to simplify the appearance of the code. The only difference between the way the constructors are written in SmallBoat and Canoe is the word SmallBoat or Canoe. Everything else is the same.
So if there were a way to write a constructor without actually using the name of the class in the constructor, it would help a lot. I could use direct copy and paste without a .tt file (which is not really viable for me -- most of my work is not done in Visual Studio). Is there a way to do that?
No. There is not. You have to specify which constructors of the base class you want to make available from the current class. There is no way to write the constructor without mentioning the real class name.
It might be a simplification you are showing, but if Initialize is the only method called, you might want to move that call to the base class calling a protected Initialize method you can override from the implementing classes. (You have to take in consideration the order of calling that method and instantiating properties/fields. You can run into trouble there, so it might not be viable in your situation)
1. Automation of code typing
There is code snippet : ctor that helps create "only" default constructor.
To use it type ctor an tabulation twice.
The original code snippet can be copied to create your own.
In Visual Studio, go in Tools menu/Code snippet manager.
You can see here the directories of the snippet files.
You can copy a snippet ( ctor.snippet for instance ) to "My Code Snippets", rename it and edit.
2. Design of the boat hierarchy
The boat hierarchy can also be designed so there is only a default constructor in the base class, and you have public properties or public method(s) in the base class to provide Lake, Axe, BoatMaker, ...
If you can change the design, I highly recommend separate object instantiation from the object itself. This way, the Factory Method combining with Template Method design pattern comes very helpful:
public abstract class BoatFactory
{ protected abstract void Initialize();
protected Wood Wood;
protected Axe Axe
protected Boatmaker Boatmaker ;
public Boat MakeBoat(Wood wood, Axe axe)
{
this.Wood = wood;
this.Axe = axe;
Initialize();
}
public Boat MakeBoat(Boatmaker maker)
{
this.Boatmaker = Boatmaker ;
Initialize();
}
public Boat MakeBoat(Lake lake)
{
this.Lake = lake;
Initialize();
}
}
public class SmallBoatFactory : BoatFactory
{
protected override void Initialize()
{
// do customized init operations here
}
}

How to auto generate Decorator pattern in C#

I have some interface, and a class implementing this interface, say:
interface IMyInterface
{
void Func1();
void Func2();
}
class Concrete : IMyInterface
{
public virtual void Func1() { //do something }
public virtual void Func2() { //do something }
}
Now, I want to create a class that decorates each of the concrete class methods with some specific logic, to be executed in non production environment, before and after the call.
class Decorator : Concrete
{
public override void Func1() { Pre(); base.Func1; Post(); }
public override void Func2() { Pre(); base.Func2; Post(); }
}
My question is there a simpler way to auto generate such class other than use reflection on the interface and create a text file with cs extension?
Personally I would just explicitly log where needed, but if you are set on using a decorator to do this you could use the RealProxy class.
It could look something like this:
public class DecoratorProxy<T> : RealProxy
{
private T m_instance;
public static T CreateDecorator<T>(T instance)
{
var proxy = new DecoratorProxy<T>(instance);
(T)proxy.GetTransparentProxy();
}
private DecoratorProxy(T instance) : base(typeof(T))
{
m_instance = instance;
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage methodMessage = msg as IMethodCallMessage;
if (methodMessage != null)
{
// log method information
//call method
methodMessage.MethodBase.Invoke(m_instance, methodMessage.Args);
return new ReturnMessage(retval, etc,etc);
}
}
}
Have you tried PostSharp? It can help you automatically "instrument" classes and achieve your logging scenario without actually creating decorators.
What about the Logging Application block?
http://msdn.microsoft.com/en-us/library/ff647183.aspx
I have written a T4 template capable of generating decorator for fairly complex classes based on some simple conventions. The project can be found on GitHub - T4Decorators. Works similar to T4MVC, that is where I got the idea.
Could you use T4 and reflection?
Maybe these other questions could help:
T4 Code generation: Access types in current project
How do you use .Net reflection with T4
We have the same requirement and wrote a Roslyn generator to do this, take a look here: https://github.com/proactima/ProxyGen
You need to modify the code slightly to fit your needs. Basically we wrap the methods of an interface (all from a certain namespace) in a 'ReliableServiceCall' method. It's trivial to modify this to do something else.
Best approach here is to use Decorator Pattern via interfaces. I know this is a very old post, but if you use an IoC injector, like SimpleInjector, you can setup these decorator calls in 1 line of code. Then you can do something like this:
public class Decorator : IMyInterface
{
private readonly IMyInterface _next;
public Decorator (IMyInterface next) { _next = next; }
public override void Func1() { Pre(); _next.Func1; Post(); }
public virtual void Func2() { Pre(); _next.Func2; Post(); }
}

Please explain the utility of abstract methods in C#

Just the 5 minute overview would be nice....
public abstract class MyBaseController {
public void Authenticate() { var r = GetRepository(); }
public abstract void GetRepository();
}
public class ApplicationSpecificController {
public override void GetRepository() { /*get the specific repo here*/ }
}
This is just some dummy code that represents some real world code I have (for brevity this is just sample code)
I have 2 ASP MVC apps that do fairly similar things.
Security / Session logic (along with other things) happens the same in both.
I've abstracted the base functionality from both into a new library that they both inherit. When the base class needs things that can only be obtained from the actual implementation I implement these as abstract methods. So in my above example I need to pull user information from a DB to perform authentication in the base library. To get the correct DB for the application I have an abstract GetRepository method that returns the repository for the application. From here the base can call some method on the repo to get user information and continue on with validation, or whatever.
When a change needs to be made to authentication I now only need to update one lib instead of duplicating efforts in both. So in short if you want to implement some functionality but not all then an abstract class works great. If you want to implement no functionality use an interface.
Just look at the Template Method Pattern.
public abstract class Request
{
// each request has its own approval algorithm. Each has to implement this method
public abstract void Approve();
// refuse algorithm is common for all requests
public void Refuse() { }
// static helper
public static void CheckDelete(string status) { }
// common property. Used as a comment for any operation against a request
public string Description { get; set; }
// hard-coded dictionary of css classes for server-side markup decoration
public static IDictionary<string, string> CssStatusDictionary
}
public class RequestIn : Request
{
public override void Approve() { }
}
public class RequestOut : Request
{
public override void Approve() { }
}
Use of abstract method is very common when using the Template Method Pattern. You can use it to define the skeleton of an algorithm, and have subclasses modify or refine certain steps of the algorithm, without modifying its structure.
Take a look at a "real-world" example from doFactory's Template Method Pattern page.
The .NET Stream classes are a good example. The Stream class includes basic functionality that all streams implement and then specific streams provide specific implementations for the actual interaction with I/O.
The basic idea, is to have the abstract class to provide the skeleton and the basic functionality and just let the concrete implementation to provide the exact detail needed.
Suppose you have an interface with ... +20 methods, for instance, a List interface.
List {interface }
+ add( object: Object )
+ add( index:Int, object: Object )
+ contains( object: Object ): Bool
+ get( index : Int ): Object
+ size() : Int
....
If someone need to provide an implementation for that list, it must to implement the +20 methods every time.
An alternative would be to have an abstract class that implements most of the methods already and just let the developer to implement a few of them.
For instance
To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods
AbstractList: List
+ get( index: Int ) : Object { abstract }
+ size() : Int { abstract }
... rest of the methods already implemented by abstract list
In this situation: get and size are abstract methods the developer needs to implement. The rest of the functionality may be already implemented.
EmptyList: AbstractList
{
public overrride Object Get( int index )
{
return this;
}
public override int Size()
{
return 0;
}
}
While this implementation may look absurd, it would be useful to initialize a variable:
List list = new EmptyList();
foreach( Object o: in list ) {
}
to avoid null pointers.
Used it for a home-made version of Tetris where each type Tetraminos was a child class of the tetramino class.
For instance, assume you have some classes that corresponds to rows in your database. You might want to have these classes to be considered to be equal when their ID is equal, because that's how the database works. So you could make the ID abstract because that would allow you to write code that uses the ID, but not implement it before you know about the ID in the concrete classes. This way, you avoid to implement the same equals method in all entity classes.
public abstract class AbstractEntity<TId>
{
public abstract TId Id { get; }
public override void Equals(object other)
{
if (ReferenceEquals(other,null))
return false;
if (other.GetType() != GetType() )
return false;
var otherEntity = (AbstractEntity<TId>)other;
return Id.Equals(otherEntity.Id);
}
}
I'm not a C# guy. Mind if I use Java? The principle is the same. I used this concept in a game. I calculate the armor value of different monsters very differently. I suppose I could have them keep track of various constants, but this is much easier conceptually.
abstract class Monster {
int armorValue();
}
public class Goblin extends Monster {
int armorValue() {
return this.level*10;
}
}
public class Golem extends Monster {
int armorValue() {
return this.level*this.level*20 + enraged ? 100 : 50;
}
}
You might use an abstract method (instead of an interface) any time you have a base class that actually contains some implementation code, but there's no reasonable default implementation for one or more of its methods:
public class ConnectionFactoryBase {
// This is an actual implementation that's shared by subclasses,
// which is why we don't want an interface
public string ConnectionString { get; set; }
// Subclasses will provide database-specific implementations,
// but there's nothing the base class can provide
public abstract IDbConnection GetConnection() {}
}
public class SqlConnectionFactory {
public override IDbConnection GetConnection() {
return new SqlConnection(this.ConnectionString);
}
}
An example
namespace My.Web.UI
{
public abstract class CustomControl : CompositeControl
{
// ...
public abstract void Initialize();
protected override void CreateChildControls()
{
base.CreateChildControls();
// Anything custom
this.Initialize();
}
}
}

Fluent interface design and code smell

public class StepClause
{
public NamedStepClause Action1() {}
public NamedStepClause Action2() {}
}
public class NamedStepClause : StepClause
{
public StepClause Step(string name) {}
}
Basically, I want to be able to do something like this:
var workflow = new Workflow().Configure()
.Action1()
.Step("abc").Action2()
.Action2()
.Step("def").Action1();
So, some "steps" are named and some are not.
The thing I do not like is that the StepClause has knowledge of its derived class NamedStepClause.
I tried a couple of things to make this sit better with me.
I tried to move things out to interfaces but then the problem just moved from the concrete to the interfaces - INamedStepClause still need to derive from IStepClause and IStepClause needs to return INamedStepClause to be able to call Step().
I could also make Step() part of a completely separate type. Then we do not have this problem and we'd have:
var workflow = new Workflow().Configure()
.Step().Action1()
.Step("abc").Action2()
.Step().Action2()
.Step("def").Action1();
Which is ok but I'd like to make the step-naming optional if possible.
I found this other post on SO here which looks interesting and promising.
What are your opinions? I'd think the original solution is completely unacceptable or is it?
By the way, those action methods will take predicates and functors and I don't think I want to take an additional parameter for naming the step there.
The point of it all is, for me, is to only define these action methods in one place and one place only. So the solutions from the referenced link using generics and extension methods seem to be the best approaches so far.
I'll give you two options.
Option A
var a = new A.NamedStepClause();
a.Action1()
.Step("abc").Action2()
.Action2()
.Step("def").Action1();
namespace A
{
public class StepClause<SC> where SC : StepClause<SC>
{
public SC Action1() { return null; }
public SC Action2() { return null; }
}
public class NamedStepClause : StepClause<NamedStepClause>
{
public NamedStepClause Step(string name) { return null; }
}
}
Option B
var b = new B.StepClause();
b.Action1()
.Step("abc").Action2()
.Action2()
.Step("def").Action1();
namespace B
{
public class StepClause
{
public StepClause Action1() { return null; }
public StepClause Action2() { return null; }
}
public static class StepClauseExtensions
{
public static StepClause Step(this StepClause #this, string name)
{ return null; }
}
}
Both options compile and give you the fluent interface that you're looking for. I'm more inclined to go with option A as it gives you access to the inner workings of the class. Using extension methods means you may need to give some sort of external access to your class thus breaking encapsulation.
Good luck!

Categories