Linqpad's souped-up Console.WriteLine is awesome. However, how can I do a standard Console.WriteLine of an object?
Debug.WriteLine will also do the trick.
Huh, obvious now - put in an explicit ToString
Console.WriteLine(x.ToString());
You can also add these methods to your "MyExtensions" file in the "My Queries" pane. This way you can use .DumpToString instead of .Dump. Maybe they should be renamed DumpDebug ...
// Write custom extension methods here. They will be available to all queries.
public static void DumpToString<T>(this IEnumerable<T> list)
{
list.ToList().ForEach(x => Debug.WriteLine(x));
}
public static void DumpToString(this object o)
{
Debug.WriteLine(o);
}
public static void DumpToString(this string o)
{
Debug.WriteLine(o);
}
You can also do
x.Dump();
Which will use the LinqPad API to pretty format the output.
Related
newbie here...thanks for your patience. I'm interested in writing a test class for the following controller, but not sure where to begin:
public class savecontroller
{
private final Emp__c emps;
public savecontroller(ApexPages.StandardController controller)
{
this.emps= (Emp__c)controller.getRecord();
}
public void autosave()
{
upsert emps;
}
}
Thank you
Your code is a little bit strange... From this part:
public savecontroller(ApexPages.StandardController controller)
it looks like your controller is not really a "controller", but more like an extension of a standard controller for Emp__c object. I know, it doesn't affect anythingin your post (except maybe semantics), BUT (!) it does have an affect on how you write your test class. Since this is an extension, test class would look something like this:
#isTest
public class saveconttroller_test {
public static Emp__c test_emp; // declaration
static {
test_emp = new Emp__c();
insert test_emp; //since you have upsert you can leave this out
}
static testMethod void testsavecotroller() {
Test.startTest();
//in the next two lines we contruct standard controller and the extension
ApexPages.StandardController sc = new ApexPages.StandardController(test_emp);
savecontroller ext = new savecontroller(sc);
ext.autosave();
Test.stopTest();
}
}
Now, let me point out a few things... first, as I'm sure you know, test should cover as much code as possible. SF requires 75%, but the closer you get to 100% the better. But (!), you should always include something to assert if your method is doing what it is suppose to be doing. For example in your case, i would change method autosave() like this:
public PageReference autosave()
{
try {
upsert emps;
return new ApexPages.StandardController(test_emp).view();
} catch(Exception e) {
return null;
}
}
By doing so, you can include System.assertEquals(ref1, ref2); in your test class, wher ref1 is reference you would expect (if the upsertion was successful this would be test_emp page reference) and ref2 would be the reference you actually get from the test.
Second thing is using static method in the test. Whatever you write in this method will always execute on Test.startTest(); call.
Hope this helps you! :)
Cheers, G.
I saw this post and I want to know if this is possible in VB.
So like extension method, do extension properties exists in VB.Net?
Here I've read they do, but cannot find any examples.
I believe that person is incorrect. From MSDN
You cannot define an extension property, field, or event.
This is almost possible. Learned this neat trick from Daniel Cazzulino.
You return a type from an extension method which exposes the properties. This is C#, but should be understandable.
public static class ListExtensions
{
// this extension method returns the type with properties
public static ListExtender<T> Extend<T>(this List<T> target)
{
//null check skipped
return new ListExtender<T>(target);
}
}
public sealed class ListExtender<T>
{
private List<T> _target;
// this is a pseudo extension property
public T First { get { return _target[0]; } }
public ListExtender(List<T> target)
{
_target = target;
}
}
Other than that, the answer is no.
According to the MSDN(draft) documentation for Visual Studio 11, extension properties are not available in VS 11 (i.e., .NET 4.5) either.
It's odd though searching does throw up a few instances where bloggers, etc., think it to be possible, including Ayende in an article on his blog here.
I know with Castle Windsor, you can register aspects (when using method interception in Windsor as AOP) using code instead of applying attributes to classes. Is the same possible in Postsharp? It's a preference things, but prefer to have aspects matched to interfaces/objects in one place, as opposed to attributes all over.
Update:
Curious if I can assign aspects to interfaces/objects similiar to this:
container.Register(
Component
.For<IService>()
.ImplementedBy<Service>()
.Interceptors(InterceptorReference.ForType<LoggingAspect>()).Anywhere
);
If you could do this, you would have the option of NOT having to place attributes on assemblies/class/methods to apply aspects. I can then have one code file/class that contains which aspects are applied to which class/methods/etc.
Yes. You can either use multicasting (http://www.sharpcrafters.com/blog/post/Day-2-Applying-Aspects-with-Multicasting-Part-1.aspx , http://www.sharpcrafters.com/blog/post/Day-3-Applying-Aspects-with-Multicasting-Part-2.aspx) or you can use aspect providers (http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx , http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx).
Example:
using System;
using PostSharp.Aspects;
using PostSharp.Extensibility;
[assembly: PostSharpInterfaceTest.MyAspect(AttributeTargetTypes = "PostSharpInterfaceTest.Interface1", AttributeInheritance = MulticastInheritance.Multicast)]
namespace PostSharpInterfaceTest
{
class Program
{
static void Main(string[] args)
{
Example e = new Example();
Example2 e2 = new Example2();
e.DoSomething();
e2.DoSomething();
Console.ReadKey();
}
}
class Example : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something");
}
}
class Example2 : Interface1
{
public void DoSomething()
{
Console.WriteLine("Doing something else");
}
}
interface Interface1
{
void DoSomething();
}
[Serializable]
class MyAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("Entered " + args.Method.Name);
}
}
}
I recommend that if you have complex requirements for determining which types get certain aspects that you consider creating an aspect provider instead.
Have a look at LOOM.NET, there you have a post compiler and a runtime weaver. With the later one you are able to archive exactly what you want.
It should be possible to use the PostSharp XML configuration. The XML configuration is the unification of the Plug-in and Project models in the project loader.
Description of .psproj could be found at http://www.sharpcrafters.com/blog/post/Configuring-PostSharp-Diagnostics-Toolkits.aspx.
Note, that I've only seen examples how PostSharp Toolkits use this XML configuration.
But it should work for custom aspects the same way.
Warning: I've noticed that installation of a PostSharp Toolkit from Nuget overwrites existing psproj file. So do not forget to back up it.
I want to specify a column name convention that basically takes a pascal cased field and converts it to all uppercase with underscores. So property OrderId becomes column "ORDER_ID". I also want this convention to be applied only if I don't already specify one in the mapping. So far I have the skeleton below:
public class PascalCaseColumnNameConvention : IPropertyConvention
{
public bool Accept(IPropertyInstance instance)
{
//Not sure what I should have here
}
public void Apply(IPropertyInstance instance)
{
instance.Column(instance.Property.Name.ChangePascalCaseToUnderscore());
}
}
Also is there a better way of channging the case besides an string extension method? Any libraries that already do this sort of thing?
In Accept method in this case you should just return true. This method is to decide whether your convention should apply for a given instance, for example you might want to change the default name only for your int-typed fields etc. If you're defining a general convention, true means just "accept all instances". It can be still overriden by specyfying the column name in the mapping, though.
About changing the case - I don't know such a library, either. But the task is quite simple, so your solution seems very reasonable here.
EDIT
Well, what FNH version are you using? I can't see IPropertyConvention to have bool Accept method.
What you can do here is to implement both IPropertyConvention (with void Apply only) and IPropertyConventionAcceptance (with Accept method working a bit differently). Try something like that (haven't tested):
public class PascalCaseColumnNameConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => !x.Columns.HasUserDefined());
}
public void Apply(IPropertyInstance instance)
{
instance.Column(instance.Property.Name.ChangePascalCaseToUnderscore());
}
}
I've also found a neat class doing lot of useful string conversions - see Inflector. But anyway, if you need only this particular conversion, I would stay with own simple solution.
Given the new dynamic support in C# 4, is it possible to write a class in such a way that if a method is invoked on an instance and that method is not present, dispatch is passed to another method? This might look something like:
public class Apple : ... {
// ...
private ... MethodMissing(string name, ...) {
if (name == "TurnIntoOrange") {
// do something
}
}
}
dynamic d = new Apple();
d.TurnIntoOrange(); // Not actually defined on Apple; will pass to MethodMissing.
Other languages would call this "method_missing support", under the more general heading of metaprogramming. I'm not sure what C# calls this specifically. But is it possible?
Absolutely. Either implement IDynamicMetaObjectProvider or derive from DynamicObject for a much simpler route. See the DLR documentation for some good examples.
Here's a quick example of DynamicObject:
using System;
using System.Dynamic;
public class MyDynamic : DynamicObject
{
public override bool TryInvokeMember
(InvokeMemberBinder binder,
object[] args,
out object result)
{
Console.WriteLine("I would have invoked: {0}",
binder.Name);
result = "dummy";
return true;
}
public string NormalMethod()
{
Console.WriteLine("In NormalMethod");
return "normal";
}
}
class Test
{
static void Main()
{
dynamic d = new MyDynamic();
Console.WriteLine(d.HelloWorld());
Console.WriteLine(d.NormalMethod());
}
}
<plug>
I have a bigger example of DynamicObject in the 2nd edition of C# in Depth but I haven't yet implemented IDyamicMetaObjectProvider. I'll do so before the book's release, but the early access edition only has the DynamicObject example at the moment. Btw, if you buy it today it's half price - use the code twtr0711. I'll edit this answer later on to remove that bit :)
</plug>