I'm using this very nice mini ORM, Simple.Data, to setup a lot of test data, quick and easy.
I would really like to extend it for assertions. For example i would like to assert on count:
Db.MyTable.GetCount(); <- Returns a dynamic
So that I could evaluate more or less like you would do with FluentAssertions.
It could look like this:
Db.MyTable.GetCount().ShouldBe(X);
But I'm finding it very hard to do this without loosing the advantage of dynamics.
Does anyone have a hint of how this could be done or if its even possible within reason?
I'm currently traversing the src at GitHub trying to find a way i can do this locally and toying around with impromptu to find a way.
Sadly, there is no happy answer to this. Dynamic and extension methods do not mix, as explained by Jon S and Eric L here: Extension method and dynamic object
The answer, as in that question, is either to invoke ShouldBe as a static method:
AssertionExtensions.ShouldBe(Db.MyTable.GetCount(), 3);
or to inline-cast the method's return value to the known type:
((int)Db.MyTable.GetCount()).ShouldBe(3);
Or, as you are investigating, to use Impromptu to apply an interface to MyTable with a GetCount method. I'm guessing you've seen my blog post on Simple.Data and Impromptu, but if you haven't: http://blog.markrendle.net/2012/10/12/howto-dial-up-the-static-on-simple-data/
In the classes you are creating why dont you create your own custom assertion class and make the object classes you are creating inherit from them.
public class MyClass : MyCustomExceptionClass
{
}
In that way it would be easier for you to test the methods in the way you want
Related
I have a class that I am trying to design which uses dynamic as type parameter:
public class Idea : IEnumerable<dynamic>, IQueryable<dynamic>
{
}
Compiler: Cannot implement a dynamic interface
So I have this workaround which I'm not overly keen on:
public class Idea<T> : IEnumerable<T>, IQueryable<T>
{
}
public class Idea : Idea<dynamic>
{
}
Compiler: success!
I can't think of any other way to work around this issue, and I'm not really sure I want to expose Idea<T> to the user.
Questions:
I feel like there are code smells here... can you confirm?
Why does the CLR not allow implementation of dynamic interfaces?
Are there any patterns I could use to achieve this without exposing Idea<T>?
I had like to address your foremost question "Why does the CLR not allow implementation of dynamic interfaces?"
Simply because it doesn't make sense. Read this blog post of Chris Burrows that explains that thoroughly.
There are for example problems when overriding dynamic members, matching signatures, etc.
For example this line says a lot:
but it’s because when we look at method overrides and overloads, we treat object and dynamic as the same
Yeah, that is an issue. This sample was given in the article:
public class C
{
public void M(object x) { }
public void M(dynamic x) { }
}
That indeed doesn't make sense, and although the types seem to differ, in the CLR world they don't.
Although it seems to be possible, according to the CLI team, this needs a lot of more work to do. And they didn't find this useful to implement until now:
The metadata team reported that a reading of the CLI spec seemed to indicate that the tables for interface implementations and custom attributes might have permitted it, but anyway no one we know of has ever done this, and it would have been effort expended. We have priorities and a limited budget of time, and this didn’t make the cut.
To answer your other questions: Yes, you are right, the workaround feels bad, and it probably is, but it seems the only workable solution right now. Ask yourself if you really want and need this. If so, proceed with your current solution.
This question is equal parts C# and Salesforce, there are probably solutions possible from either side. Suggestions welcome!
I'm writing a generic class to read Salesforce data. The signature looks like this:
public abstract class SalesforceReader<SalesforceObjectType, RecordType>
where SalesforceObjectType: sObject
This lets me use this code later on:
List<RecordType> records = new List<RecordType>();
QueryResult queryResult = service.query(query);
foreach (sObject rawRecord in queryResult.records)
records.Add(ConvertRecord((SalesforceObjectType)rawRecord));
...
public abstract RecordType ConvertRecord(SalesforceObjectType record);
The plan is to write implementations of this class which know how to parse, for example, a Salesforce Lead object into a RecordType, which may be a basic object[], a Dictionary<string, value>, or a fully-defined struct as I choose later on.
So far, I'm all kinds of pleased with my brilliantly elegant solution. My Codey award is as good as won. Then I try to write an implementation. This definition is no good:
class LeadReader: SalesforceReader<Lead, object[]>
The compiler result is:
The type 'SalesforceExtractor.Salesforce.Lead' cannot be used as type
parameter 'SalesforceObjectType' in the generic type or method
'SalesforceUtilities.SalesforceReader<SalesforceObjectType,RecordType>'.
There is no implicit reference conversion from
'SalesforceExtractor.Salesforce.Lead' to
'SalesforceUtilities.Salesforce.sObject'.
Bummer. I have to have the where SalesforceObjectType: sObject constraint in the abstract class so I can cast sObjects, but because the conversion is not implicit, it's not good enough for the implementing class.
Do I need to kiss my neat little solution goodbye, or is there a way to salvage this? This is my first Salesforce project, so if I need to approach things differently, please let me know.
For the bad movie/MST3K buffs out there:
Where do "must" and "cannot" meet on the graph?
Aha, I just needed to walk away for half an hour and look at it again. After 20 years working with computers, you'd think I'd have learned that the problem is usually one of perspective.
Lead does inherit from sObject, but the abstract class was in a library, in a different namespace and project from the implementing class, and each of them was using the Salesforce WSDL. I was asking the compiler to cast SalesforceExtractor.Salesforce.Lead to SalesforceUtilities.Salesforce.sObject, which is not valid. I just had to be more explicit in my implementing class:
class LeadReader: SalesforceReader<SalesforceUtilities.Salesforce.Lead, object[]>
This compiles, and I think I should be good to go.
It sounds like you need to modify the Lead class to inherit from sObject. If those classes are not yours, you need to change your design.
The SF Lead object does inherit from sObject, so this is a job for generic type variance, a subset of covariance/contravariance. Good luck with your Codey acceptance speech.
Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.
Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }
public static XmlElement ToXmlElement(this XElement element) { }
Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }
There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.
In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.
This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.
If your proposed usage did not pass that test then it should have been shot down.
I would say you should avoid them when "they do not make the intend of the code more clear". Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless. (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method. I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class. This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class. Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern: The number of extension methods you create for a class exceeds three. I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects. However, the opposite is also true: If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would. If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.
I don't understand, why use dynamic MethodBags when I can use ExpandoObject? What am I missing here?
MethodBags and analogous implementations tend to have some limitations. It may be easier just to implement your own class if you find yourself running into these roadblocks. Specifically:
Hard to implement state in a method bag. (Expression trees cannot contain objects that are statically typed as dynamic; no good syntax to create methods that rely on internal state on the same dynamic object.)
Can only add public methods. No virtual, private, protected, or abstract methods.
Can't implement an interface.
In comparison, ExpandoObjects are true classes and are much richer and more full-featured. They more closely mimic what you'd otherwise get for free in, say, Ruby or Python.
Quick note: for those who don't know, dynamic method bag is a technique for adding methods dynamically to an object. Bill Wagner describes it here with source code here.
The simple answer is that the MethodBag concept is just showing you a technique. You can absolutely use the ExpandoObject to do this, but there may be a time when you want to write your own class that inherits from System.Dynamic.DynamicObject. An example of this might be to provide a dynamic JSON, YAML, or XML object that lets you reference your data in dot-properties-notation rather than in the traditional stringy ways. If you inherit from DynamicObject, you may find that you want to allow the addition of dynamic functions to your class too. The MethodBag technique shows you how to do that. The ExpandoObject is just one example of a class that implements this technique. ExpandoObject will be good for 95% of what you need, and the MethodBag technique shows you how to custom write your own when you decide to do that for the last 5%.
I recently asked this question:
Compiler error referencing custom C# extension method
Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...
If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?
I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...
My question is: Why can't we create an extension method that will work as a static Method?
I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.
var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();
which enables LINQ:
var foo = (from x in data
where x.IsActive
order by x.Price
select x).First();
With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.
As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.
Because that feature doesn't exist in C#.
As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.
For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.
The community is asking if we think it's a good idea for C# 4.0
My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.
The this parameter allows control and thus doesn't break compatibility.
Just an idea though.
First of all you would have to add yet another syntax to indicate you want to extend the static methods of the existing type. When extending syntax you really need a very good reason to do so.
Lets imagine I have a class called MyExts which allow me to add extension methods to MyClass. Why would:-
MyClass.DoSomethingExtra();
be better than
MyExts.DoSomethingExtra();
?