C#
Challenge: Robust enumeration over external code
Here is an interesting little problem: public class Program
{
private static void Main()
{
foreach (int i in RobustEnumerating(Enumerable.Range(0, 10), FaultyFunc))
{
Console.WriteLine(i);
}
}
public static IEnumerable<T> RobustEnumerating<T>(
IEnumerable<T> input,Func<IEnumerable<T>, IEnumerable<T>> func)
{
//...
Instantiating interfaces
How do you make this code legal? var foo = new IFoo(1);
And yes, IFoo is an interfacae.
The answer is quite simple, actually. It was there since C# 1.0, I am told, and I just stumbled upon it. Take a look at this code:
class Program
{
static void Main(string[] args)
{
var foo = new IFoo(1);
foo.Do();
}
}
[
ComImport,
Guid("C906C002-B214-40d7-8941-F223868B39A5"),
CoClass(typeof(FooImpl))
]
public interface IFoo
{
void Do();
}
public class FooImpl : IFoo
{
private readonly int i;
public FooImpl(int i)
{
this.i = i;
}
public void Do()
{
Console.WriteLine(i);
}
}
We have an interface, and we specify the co class that implements it and is the default implementation. The rest is just required to make the...
Dictionary<Enum,T> Puzzler
A while ago in the NHibernate mailing list we got a report that NHibernate is making use of a dictionary with an enum as the key, and that is causing a big performance issue. The response was almost unanimous, I think, “what?! how can that be?!!?”. Several people went in to and tried to figure out what is going on there. The answer is totally non oblivious, Dictionary<K,V> force boxing for any value type that is used as the key. That sound completely contradictory to what you would expect, after all, one of the major points in generics...
Elegant code
I just like this code, so I thought I would publish it. 1: public static class ArrayExtension
2: {
3: public static T[] GetOtherElementsFromElement<T>(this T[] array , T element)
4: {
5: var...
Why NH Prof isn't functional
One of the things that I wanted to do with NH Prof is to build it in a way that would be very close to the Erlang way. That is, functional, immutable message passing. After spending some time trying to do this, I backed off, and used mutable OO with message passing.
The reason for that is quite simple. State.
Erlang can get away with being functional language with immutable state because it has a framework that manages that state around, and allow you to replace your state all the time. With C#, while I can create immutable data structures, if I...
Making code easier to read
I didn't like this code: I find this much easier to read:
A case study of bad API design: ASP.Net MVC Routing
I am doing a spike in ASP.Net MVC now (and I'll talk about this at length at another time). I hit the wall when I wanted to do something that is trivially simple in MonoRail, limit a routing parameter to be a valid integer. Luckily, just looking at the API signature told me that this is a supported scenario: Unfortunately, that is all that it told me. This method accept an object. And there is no hint of documentation to explain what I am suppose to do with it. A bit of thinking suggested that I am probably...
Reading MEF code
Okay, here is the deal. There is a feature in MEF that I find interesting, the ability to dynamically recompose the imports that an instance have. Well, that is not accurate. that doesn't really interest me. What does interest me is some of the implementation details. Let me explain a bit better. As I understand the feature, MEF can load the imports from an assembly, and if I drop another file into the appropriate location, it will be able to update my imports collection. Now, what I am interested in is to know whatever MEF allow me to update file...
More code review errors
Take a look at this method: Now, let us make this simple, shall we? Same meaning, and a significant reduction of complexity. Damn, but this is annoying.
Common issues found in code review
I am going over a code base that I haven't seen in a while, and I am familiarizing myself with it by doing a code review to see that I understand what the code is doing now. I am going to post code samples of changes that I made, along with some explanations. This code can be improved by introducing a guard clause, like this: This reduce nesting and make the code easier to read in the long run (no nesting). I hope you recognize the issue. The code is using reflection to do...
Emulating Java Enums
Java Enums are much more powerful than the ones that exists in the CLR. There are numerous ways of handling this issue, but here is my approach. Given this enum (defined in Java): private static enum Layer {
FIRST,
SECOND;
public boolean isRightLayer(WorkType type) {
if (this == FIRST && type != WorkType.COLLECTION) return true;
return this == SECOND && type == WorkType.COLLECTION;
}
}
And the C# version is:
private class Layer
{
public static readonly Layer First = new Layer(delegate(WorkType type)
{
return type != WorkType.Collection;
...
Setting out to break the compiler...
I look at a bit of code that dealt with traversing expression an expression tree, using recursion, of course. The edge condition immediate popped to mind was unbounded expression. I decided to see if I can kill the compiler using this. Why? Because. The first thing to do is to find out how deep a stack we usually need. I wrote this simple test: class Program
{
static void Main(string[] args)
{
Recursive(1);
}
static void Recursive(int i)
{
Console.WriteLine(i);
Recursive(i+1);
}
}
The last result was: 79994
Obviously this change based on how much stack space each function takes, but it is a good number to go...
Not all objects are created equals
I found something extremely surprising while profiling a project. Take a look at this piece of code: Stopwatch stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
new WeakReference(null);
}
stop.Stop();
Console.WriteLine("WeakRef: " + stop.ElapsedMilliseconds);
stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
new string('a', 5);
}
stop.Stop();
Console.WriteLine("'aaaaa': " + stop.ElapsedMilliseconds);
On my machine, this has the following output:
WeakRef: 980
'aaaaa': 35
Creating a WeakReference is much more costly than creating a normal object. Not surprising, when you think of it, WeakReference has deep ties to the CLR, but I couldn't really believe it when I...
Challenge: What does this code do?
Without compiling this, can you answer me whatever this piece of code will compile? And if so, what does it do? var dummyVariable1 = 1;
var dummyVariable2 = 3;
var a = dummyVariable1+-+-+-+-+ + + + + + +-+-+-+-+-+ dummyVariable2;
Oh, and I want to hear reasons, too.
Bug of the day...
Using MbUnit 2.4, this test pass: Guid g = Guid.Empty;
Assert.AreEqual(Guid.Empty, g);
Assert.AreNotEqual(Guid.Empty, g);
ReSharper is smarter than me
Given the following block of code: if (presenter.GetServerUrlFromRequest!=null)
GetServerUrlFromRequest.Checked = presenter.GetServerUrlFromRequest.Value;
else
GetServerUrlFromRequest.Checked = true;
Resharper gave me the following advice:
And turned the code to this piece:
GetServerUrlFromRequest.Checked = !(presenter.GetServerUrlFromRequest!=null) || presenter.GetServerUrlFromRequest.Value;
And while it has the same semantics, I actually had to dechiper the code to figure out what it was doing.
I choose to keep the old version.
Csc.exe and delegate inference, or: Why C# has awkward syntax
I just tried to to do a major revamp of Rhino Mocks' interface. It was intended to make it easier to work with C# 3.0 and use the smarter compiler to get better syntax. I shouldn't have bothered. Take a look at this. public class TestCsc
{
public static void TestMethod()
{
Execute(Bar); // fail to compile
Execute(delegate(int ia, string x) { }); // compiles fine
Execute((int i, string x) => { return; }); // Compiles fine
Execute((int i, string x) => { return true; }); // fail to compile
Execute(Foo);// fail to compile
Execute(delegate(int ia, string x) { return true; }); // fail to compile
}
public static bool Foo(int ia,...
Generic extension methods
I was playing around with the compiler when I hit this interesting feature. I was very surprised to see that this has compiled successfully. 1: static class Program
2: {
3: static void Main(string[] args)
4: {
5: ...
On Syntactic Sugar and Weight
Greg Young posted about some issues that he run into with yield statements and compile time verifications in Spec#. He ends with: Given this information are iterators something that are THAT desirable? Iterators are syntactical sugar, I can duplicate what an iterator does rather simply in code that does not use an iterator … Are they worth me giving up the possibility of removing all of my runtime checks or introducing this complexity? My answer, yes, they are 100% desirable. OO is syntactic sugar, there is enough object oriented C code out there to prove that, at least....
Performance, threading and double checked locks
A very common pattern for lazy initialization of expensive things is this: GetDescriptionsHelper.Delegate getDescription;
if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false)
{
MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType);
getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate(
typeof(GetDescriptionsHelper.Delegate),
getDescriptionInternalGeneric);
GetDescriptionsHelper.Cache.Add(entityType, getDescription);
}
This tends to break down when we are talking about code that can run in multiply threads. So we start writing this:
lock(GetDescriptionsHelper.Cache)
{
GetDescriptionsHelper.Delegate getDescription;
if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false)
{
MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType);
getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate(
typeof(GetDescriptionsHelper.Delegate),
getDescriptionInternalGeneric);
GetDescriptionsHelper.Cache.Add(entityType, getDescription);
}
}
Except, this is really bad for performance, because we always lock when we try to get the value out. So we start playing with it and get this:
GetDescriptionsHelper.Delegate getDescription;
if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false)
{
lock(GetDescriptionsHelper.Cache)
{
MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType);
getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate(
typeof(GetDescriptionsHelper.Delegate),
getDescriptionInternalGeneric);
GetDescriptionsHelper.Cache.Add(entityType, getDescription);
}
}
This code has a...
System.Type.GUID stability
Here is an interesting issue. Can you rely on System.Type.GUID to be stable? By stable I mean that it will generate the same value for the same type across compilations. Empirical evidence suggest that this is the case, with the following factors determining the Guid of a type: Type name (including the namespace) Assembly name Assembly public key Reflectoring into the system, it turns out that System.Type.GUID is eventually translated to a call to System.RuntimeType.GetGUID, this is one of the scary InternallCall method that are implemented directly in the runtime itself. I wonder...
Multi threading challenge: can you spot a bug?
One of the problems of multi threading is that there are a lot of intricacies that you have to deal with. Recently I run into issues that dictated that I would have to write an AsyncBulkInserterAppender for log4net. One of the reasons that I want to do that is to avoid locking the application if the database is down or the logging table is locked.I just had a recent issue where this casued a problem. When I implemented that, I started to worry about what would happen if the database is locked for a long duration. There is a...
Statically typed? Compiler checked? Ha!
Just a nod toward the people that cling to static typing with both hands, their teeth and the tail:RouteTable.Routes.Add(new Route
{
Url = “admin/[controller]/[action]“,
Defaults = new
{
Controller = “Admin“,
Acton = “Index”
},
Validation = new
{
Conrtoller = “Admin|Users|Categories”
},
RouteHandler = typeof(MvcRouteHandler)
});
Now, instead of abusing the language to get this, can we get first class support for this things?
Do you trust your compiler? Really trust your compiler?
There is a discussion in the alt.net mailing list right now about how far you can and should trust your compiler. I thinks that this is interesting, because this piece of code of mine is on its way to production: public Guid Create<T>(T newEntity)
{
using (CrmService svc = GetCrmService())
{
object cheatCompiler = newEntity;
Guid guid = svc.Create((BusinessEntity) cheatCompiler);
return guid;
}
}
This is part an implementation of an interface in an assembly that cannot reference BusinessEntity.
I am feeling good with this.
The WPF mystery
Okay, here are a few weird things that I wish I didn't know about WPF. It does some low level cheating all over the place, for fun & profit, put the following like in the main window ctor: Debug.Assert(Application.Current.MainWindow != this); Remember that on the CLR, you don't often see other objects referencing before you even started your constructor.
Then there is this fun puzzle, when I am registering to the Application.Startup event, I am getting inconsistent results with regards to Application.MainWindow being null or not. After a short investigation, I pinned the blame on the async initialization of the windows....
The VS 2008 Experience
So far, I haven't done much with VS 2008. I build Linq for NHibernate, but that was mostly so I could understand how Linq works. I am now writing a pet project using VS 2008, and I am going to use this post to document the initial impressions. No ReSharper for the 3.5 features - EAP is in about a month, YEAH! Add reference dialog comes up fast. It comes in a second or so, instead of the 30 - 60 seconds that it used to. TestDriven.NET just works. I had to use Reflector to figure out how the...
Riddle me this...
What is the result of this piece of code? application.Startup += delegate
{
Console.WriteLine("will it");
application.Startup += delegate
{
Console.WriteLine("work?");
};
};
As usual, I am raffling a Rhino Mocks license among those who will answer correctly.
Who is hacking my CLR?
Interesting way to cache that :-)
Object / Object mapping
Fairly often, we need to do some sort of a transformation between one object to another. It is usually across layers, such as when we want to turn an entity to a DTO (for sending on the wire of for UI purposes). Here is the overall pattern to solve such a task. I did try to make it into a framework, but even I can't make it more complex than this. public class OrderToOrderDTO
{
public delegate void Transformer(Order o, OrderDTO d);
List<Transformer> transforms = new List<Transformer>()
{
(y, z) => z.ID = y.Id,
(x,z) => z.CustomerName = x.Name
};
public OrderDTO Transform(Order k)
{
OrderDTO t =...
Why C# doesn't have extension properties
I just run into this problem, and I came up with a different reason than the usual one. C# simply doesn't have the concept of indexed properties. This is not legal C# code: public static string Items[string something]
{
get { return something; }
}
I think you can do that with VB.Net, and I am certain that C++ supports it.
The interesting part is that I run into it while building a DSL. The limit of the implementation language has actually limited the DSL itself.
Code Review: PetShop 3.0
I got some feedback about my previous review, that the PetShop 2.0 was recognized as architecturely unsound, and that I should look at version 3.0 of the code, which is: Version 3.x of the .NET Pet Shop addresses the valuable feedback given by reviewers of the .NET Pet Shop 2.0 and was created to ensure that the application is aligned with the architecture guideline documents being produced by the Microsoft. I have to say, it looks like someone told the developers, we need an architecture, go build one. The result is... strange. It make my spider sense tingle. I...
The difference between meta programming and IL weaving
Ivan also posted a response to Jeremy's C# vNext features, and he said something that caught my eye: 5. Metaprogramming => no objection here although you can do it now with reflection emit No, there is a big difference between reflection emit and byte code weaving. Reflection emit is done after compilation is completed, meta programming occurs during compilation. This matters because it means that your code cannot refer to the results of the change being made. A case in point, I am using IL Weaving to add the Dispose method to a class, but because I am doing it...
What does Mixin mean?
Bill Wagner has a proposal about the usage of mixins. He is talking about having a marker interface with minimal methods (or no methods), and then extending that using extension methods. To a point, he is correct, this will give you some sense of what a mixin is. But it is not enough. It is not enough because of the following reasons: It is not really a cohesive solution. There is no really good way to specify something like SnapshotMixin. You need interface and static class and inherit from the marker interface, etc. Those are... problematic. I want to just...
C# vNext
Jeremy Miller asks what we want in C# vNext. I have only real one request, to have meta programming of sufficent power, after which will be able to add all the required semantics without having the compiler team to argue with. I am not holding my breath on that one, though. I can just imagine the arguments against it (let us start from the potentail for abuse, move to version and backward compatability hell, and then move forward). I want to go over Jeremy's list, and see what I can add there. Mixin's - Agree 102%. This is something...
Deep dive into Binary Reader / Writer
So, as I mentioned, I was doing low level binary IO stuff today, and I started the class going on doing stuff using BitConvertor, FileStream.Write, etc. After they finished the first exercise, I started to show them how they can replace this tedious code with BinaryReader / BinaryWriter. That was much easier, except that we had strings going into the binary files, and I stopped in the middle to try to read the file written using BinaryWriter with the code that manually manipulated the file stream. I got consistent results for numbers, but for strings it was giving weird results....
Did you know: Find out if an exception was thrown from a finally block!
This is a big biggie for me, because it enables a much nicer syntax for a lot of stuff. But first, let us show this:using(new ExceptionDetector())
{
if(new Random().Next(1,10)%2 == 0)
throw new Exception();
}
How can you tell, from the ExceptionDetector, if an exception was thrown or not? Well, conventional wisdom, and what I thought about until 15 minutes ago, says that you can't. I want to thank Daniel Fortunov, for teaching me this trick:public class ExceptionDetector : IDisposable
{
public void Dispose()
{
...
Using partials in Web Forms
Partial is a MonoRail term to a piece of UI that you extract outside, so you can call it again, often with Ajax. This is something that is harder to do in WebForms. Yesterday I found an elegant solution to the problem. ASPX code:<div id="UserDetailsDiv">
<ayende:UserDetails runt="server" ID="TheUserDetails"/>
</div>
User Control:<div>
Name: <asp:label ID="Name" runat="server"/> <br/>
Email: <asp:label ID="Email" runat="server"/>
</div>
Client Side Code:function changeUser(newUserId, div)
{
var srv = new MyApp.Services.UserDetails();
srv.GetUserDetailsView(newUserId, onSucccessGetUserDetailsView, null, div);
}
function onSucccessGetUserDetailsView(response, userContext)
{
var div = $(userContext);
div.innerHTML = response;
new Effect.Highlight(div);
}
Web Service Code:[WebMethod(EnableSession = true)]
public string GetUserDetailsView(int userId)
{
User user = Controller.GetUser(userId);
//there may be a better way to do this, I haven't bothered looking
UserDetails...
Sweat, Hash Literals in C# 3.0
Alex has figured out how to get really nice hash literals in C# 3.0, awesome.
C# 2.0 is done
At this point, I believe that there really isn't anything that can be done any more with C# 2.0, I have taken it to the very limits of its expressiveness, and now I hit a wall. C# 3.0 adds some interesting features, and extension methods, initializers, etc will significantly improve the expressiveness of the language. Even now, I can see the limitations that even C# 3.0 will give us. But on the other hand, I fully expect some interesting developments in taking the capabilities of the language and pushing them forward.
What kind of persistence would Ayende write without OR/M?
Rodrigo thinks that I am ignoring the obvious when I think about persistence only in terms of RDBMS. He is probably right. I want to point out that the last time I wanted to have a non-DB persistence, I used C# as the file format. That was fairly successful, although I will probably won't do it again.
Are you familiar with WebForms ITemplate?
It looks like a lot of people are not familiar with this, and that is a shame. Recently we have run into several instances where we wanted to do some things that are not supported out of the box by the repeater. Specifically, render an empty template and render markup after each row, except the first one, etc. After some time thinking about how easy it would be to do this in MonoRail, I decided to implement it in the same way I would in MonoRail. WebForms has the concept of an ITemplate, a piece of markup/code that can be handed...
ReSharper Wishlist
My main pain point with R# is very simple, when it generates properties or methods, it doesn't generate virtual ones. Since I tend to generate quite a few properties at one go, it is a pain to have to go and add it to all of them. Currently the issue is marked as "Not for 3.0", which is something that I would like to change, please visit the issue and vote for it: http://www.jetbrains.net/jira/browse/RSRP-26697
ReSharper 3.0 Beta
I am using R# 3.0 Beta, and I am loving it, check out the suggestions: And this one: Or this one: The really great thing about it is that it is three key strokes from suggestions to having better code!
At what point do you say WTF?! Runtime addition of methods to class in C#
Assume that I have this piece of code: public interface InterfaceWithExplicitImpl<T>
{
IEnumerator<T> GetEnum1();
}
Now, check the picture. This is 100% repreducable, but only under very specific set of scenarios (basically, running...
The Complexity Suppression Disorder
So, applying the separation of concerns principal to blog posts again, I wanted to talk about another aspect that had me thinking as a result of teaching .Net. I literally had no idea how complex development was until I had to stand in class and explain the tradeoffs for the various approaches for implementing things. Several things that kept popping up are: Concurrency Multi thread safety (in the abstract, at least) - That one is easy, don't do multi threading. Failing that, don't do multi threading on shared state. Failing that, welcome to the fun world of multi...
Tools are not Evil (but needing them is an indication of a problem)
Chris Holmes commented on my thinking for tools, but I think that he missed a crucial distinction that I made (but not clear enough). If you require a tool in order to work effectively with something, this is an issue. By requiring a tool I mean something beyond VS + R#, which are the bare minimum stuff that you need to be effective in C# (it does says something on C#, doesn't it?). The Entity Framework Designer is a good example for something where I think that the dependence on the tools indicate a problem. I have been corrected about requiring...
Let us corrupt C# for code generators: The horror story of partial methods
I think you can pretty much understand how I feel about this feature. Think about it, a compile time only method declaration, that you can "override" in another method, like this: partial class C { ...
Development stats
A single page. 34 integration tests. 432 lines of test code (excluding data setup and stuff move to test infrastructure). 66 lines of code behind 210 lines of Javascript 641 lines of in the ASPX file (include the javascript above) ...
Wanted: MethodMissing
I am listening to this webcast, talking about dynamic dispatch on the JVM, and 19:30 it starts to get really interesting. The JVM is getting support for MethodMissing. As far as I understand, this is most relevant for compiler writers, but it is something that I really would like to have on the CLR (and exposed for C# & VB). The reason for wanting this is very simple, it lets me handle advance scenarios very easily. Take a look at Boo's duck typing capabilities to see some of the stuff that can be...
The missing Linq: Stateful extentions methods
It seems to me that right now there is a lot of exploring going on with extention methods. People are doing some really cool stuff with them. What I am afraid of is that this exploration is going to hit glass wall the moment people are going to try to do the interesting stuff with them. The reason for this is that beyond the simplest cases, I would really want to have some sort of a state between method calls. Here is a code sample that demonstrate the issue:object myRandomObj = new object(); ...
WebForms and lies
I made the comment several times that I feel that WebForms lies to me, Joe Young asks what do I mean by that. Here is a small reproduction that I just created, that demonstrate the problem. Put this in an ASP.Net page, and run, select another value, and see what you get. <script runat="server"> protected void...
And I took the path less traveled by...
Evaluate the following approaches: List<Address> addresses = new List<Address>(); addresses.Add(customer.HomeAddress); addresses.Add(customer.BusinessAddress); ...
C# 3.0: What you can do with extention methods
Take a look here, for some amazing stuff that you can do with C# 3.0 extention methods. The ability for a much clearer syntax is amazing.
If Program I Can't, Programmer Am I?
Jeff Atwood has posted about the difficulities of some so-called programmers to program. The intersting facts are here. An extremely simple task is given, and quite a bit of people simply can't handle it, or take an undue amount of time to solve it. A while ago I posted all sort of interesting questions that I would not put in interviews, it was the sort of interview questions from hell. I did a lot of interviews since then, and I have gotten sick of the level of people that I meet. ...
Method Dispatch Internals
Sasha Goldshtein just posted some very interesting stuff about the way the JIT optimize method dispatch. Despite the interesting topic, what caught my eye more than everything else was:Currently, the JIT is documented (perhaps "blogged about" would be more precise here) I found it hilarious. Recommended reading.
Generics Challange: Solved
Take a look here to see what it takes to solve my previous challange. It was extremely hard to get it to work in all scenarios, and I am pretty sure that there are additional edge cases that I have not thought of, but for now, all the tests are green. I also have a 100% repreducable (on several machines) VS crashing bug, which is about the fifth that I know of. I actually started to put MsgBox.Show() in the code, and had a serious JavaScript deja-vu as a result...
Hanselman vs. Boo
Scott Hanselman has an amusing post about working with the .Net OpenID library, which is written in Boo. I suggest that you would read it, but a few of notes first: I had to go through a similar process when porting Brail from Boo to C#. I have to say that the code afterward has a lot more cruft than before. Scott is making a reference to my Boo.Reflector project, I...
Generics Challage: Assert Return Types Matches
I feel that I gave it too much already, and I am giving up. A workaround is too good for this issue. Given the following class defination: public class Dog { ...
Reusable tests
It is generally accepted that reusability is not something that you should strive for in your tests. However, I have found that reusing tests is an interesting way to save time when you are testing a full process. Take for instance this piece of code: [Test] public void SuccessfullySavingTemplateWillShowConfirmation() ...
The Usefulness of Commented Code
In general, my approach to commented code is fairly simple, continious application of the delete key until it no longer exists. I have a source control, thank you very much, and except for short periods when debugging, I absolutely abhor it. One case where I do leave the code commented is when its absence is something that a later programmer (such as myself) will try to add, with usually unpleasant results. Here is a simple example:
Structure Map Fluent Interface
Now, I am not a user of StructureMap, but the interface looks cool:// Add an instance with properties registry.AddInstanceOf<IWidget>() .WithName("DarkGreen") .UsingConcreteType<ColorWidget>() .WithProperty("Color").EqualTo("DarkGreen"); Jeremy calls it a DSL, but I don't think that it is the correct term, it is just using a diffeerent (and better) approach for coniguring it with code. The main problem I have with this is that it is something that breaks down when you need the complex stuff, because you...
On the "Why the hell do I know this?" front
Did you know? The C# compiler will generate different code if your base class is in a different assembly. The situation is observable when you are implementing an interface by rely on the base class implementation. If the base class is in the same assembly, nothing will happen, but if it belongs to a different assembly, the compiler will silently generate a method that will implement the interface method and call the base class method for the implementation. I'll leave as an excersize for the reader why this is...
More on Emitting Multi Dimentional Arrays
Here is a small code sample that demonstrate the problem. This doesn't work, but changing the Run method parameter to anything but a multi dimentional array does work. public interface WithMatrix { ...
How much a hypothesis weight?
Well, roughly 6Gb. That is the download that I had to go through to get Orcas. And I am not even that interested in Orcas itself at the moment. I just want to test a crazy idea that I had. At any rate, I got the answer that I was looking for. The code below is not legal: public class Foo { [IsValid( x => x==null )] ...
Collection Initializers gone from C# 3.0
David Hayden points out that the syntax for Collection Initializers for C# 3.0 has changed, and in my eyes, this render the entire idea of collection initializers useless. Before:List<Customer> listOfCustomers = new List<Customer> { { Id = 1, Name="Dave", City="Sarasota" }, { Id = 2, Name="John", City="Tampa" }, { Id = 3, Name="Abe", City="Miami" } }; After:List<Customer> listOfCustomers = new List<Customer> { new Customer { Id = 1, Name="Dave", City="Sarasota" }, ...
Building Applications Using Castle RC2: Part I
Well, now that Castle RC2 is out, let us see what this release can do for us, shall we? After my recent talk, I got forums heavy on my mind, so let us build one. You can get the release here. I suggest that you would get the MSI installer. After installing the MSI, open Visual Studio and create a new project, you should see this screen: Choose Castle ActiveRecord Project and name the project "Castle.Forums.Model", name the solution (last text box) "Castle.Forums". Note:...
Bringing it all together: Even More Magic,
So, I had done a couple of fairly cool stuff recently, but it is all in seperated pieces, let us try to bring them together and see what we get, shall we? ProjectionQuery<User> query = new ProjectionQuery<User>(Where.User.Name.Like("Ayende", MatchMode.Start), ...
C# != C++ : Sometimes I need a reminder
Apperantly mixing implicit operators and params array is not something that you should do. The C# Compiler refuse to understand that it can first implictly convert to the type and then satisfy the params array decleration. Sometimes it is not worth getting up in the morning. That ruined a beautiful API.
Projections Support In Active Record
Ken, this post if for you... So, I have been a busy implementing crazy generics stuff and I can show you this: public class ProjectionQuery<ARType> : ProjectionQuery<ARType, object[]> Neat class, isn't it?Please not that this is not the same class that I shows here, that class has been renamed ScalarProjectionQuery, since it better fits its duy. What can you do with it? Well, things like this: ...
Generic Specialization
It is not often that I am arriving to work and the first application that I
open is Visual Studio, and I can't get it to open fast enough. Today was such a
day, mostly because I got an Eureka moment. It is not often that I get those, so
I really want to try it out.
Check out the following code:
public
class Aggregator<T> : Aggregator<T, List<T>>
{}
public
class Aggregator<T,
TCollection>
where
TCollection : ICollection<T>, new()
{
private
ICollection<T> collection = new TCollection();
}
Can you tell why I am excited? Because this means that I have static generic
specialization (I already have dynamic generic...
Unit testing with NHibernate / Active Record
One of the more difficult regions to test in an application is the data access layer. It is difficult to test for several reasons: It is usually complicated - fetching data effectively is not something trivial in many cases. It can be highly dependant on the platform you are using, and moving between platforms can be a PITA. It is usually hard to...
How to (lamely) create a map in C#
There are a lot of cases where I need to define in code some sort of a map that I would later want to modify. This is usually as simple as mapping a static list to be used in the code. This about mapping from System.Type to SqlType, for instance. This is something that javascript can do very easily, and one of the reasons that I really like Boo. Check this out: typeToSqlType = {...
Interesting VB.Net Snippets
I using auto convertion to move code from C# to VB.Net, and I just run into this tidbit.Public Shared Widening Operator CType(ByVal expr As QueryBuilder(Of T)) As DetachedCriteria Widening? Apperantly there is also Narrowing operator. I'm not sure how they relate to the actual operation performed, though. But perhaps the best looking piece of code is this one: Post.FindOne( Where.Post.Blog Is Nothing ) Yes, this is real code. VB 2005 and NHibernate...
Trivial fact of the day: Max Length of Identifier in C#
It came up in conversation today, and the answer is 512 characters.
Opening Up Query Batching
I have ranted before about the annoying trend from Microsoft, to weld the hood shut in most of the interesting places. One particulary painful piece is the command batching implementation in .Net 2.0 for SQL Server. The is extremely annoying mainly because the implementation benefits are going for those who are going to be using DataSets (ahem, not me), but are not avialable to anyone outside of Microsoft. (See topic: OR/M, NHibernate, etc). Today, I have decided to actually check what the performance difference are all about. In order to do this,...
Why you can't code in Hebrew...
In response for my DDD in Hebrew, I was asked why it is not recommended to code in Hebrew. I decided to question my initial response, and give it a shot. I quickly gave it a try and created the following domain model. I don't expect you to be able to read it (although if you can, you'll find it hilarious). Here is my DDD in Hebrew, the classes are Employee (right, top), Report (Left, Top), HoursReport (Middle, Bottom), WontBeHereReport (Left, Bottom) and Repository<T> (Right, Bottom): ...
MVP on ASP.Net
Bill Piece continues his talk about MVP in ASP.Net using Castle's Windsor. It looks very interesting...
What is the difference?
Here is another challange, related to the previous one, what is the difference between the following lines of code: throw Activator.CreateInstance<ThreadAbortException>(); Thread.CurrentThread.Abort();
Special Exceptions Riddle
Here is a good riddle for interviews. It is short, concise, and it shows that they have quite a bit of experiance. What special exceptions do you know of in .Net? By special I mean exceptions that behave differently from normal exceptions (such as ApplicationException). Note: Of the top of my head, I can think of at least three or four that I would consider special, but there are probably more.
Reflection.Emit vs. CodeDOM
Both technologies allow you to generate executable code at runtime (even though CodeDOM may not have been originally intended for this). This opens up some interesting possibilities (Rhino Mocks and NHibernate, for instnace, uses Dynamic Proxy, which uses Reflection.Emit to generate proxies for object at runtime). Reflection.Emit gives you complete control of the generated IL, while CodeDOM leaves you creating source code dynamically. Reflection.Emit has the following advantages: You can generate new classes directly into an existing assembly, this helps...
And there was much rejoicing, for the Exception was raised
A lot of programmers seems to be afraid of exceptions. The moment they get one they throw their hands up in dispair and exclaim "This piece of shit doesn't work." And then they come to me to help. They usually start with "It threw an error", "It doesn't work", etc. At first I try to hone my clairvoyant skills, and give them an answer anyway, but after being accused for using KGB interrogation technique* I decided to stop that. Nowadays, I refuse to help them unless they tell me what the exception is. And...
The most useful key in the keyboard is...
The little DEL one. I keep telling people, "you have source control, just delete this stuff." There is also nothing as satisfying as working with someone when you just select a couple hundreds lines and delete them. The expressions are priceless. Delete as much code as you can, it means less stuff that you'll need to puzzle out in 6 months time.
I am very glad that this is a debugger error
Otherwise, I would really hate to debug this script.
Useful blogging
I wrote this comment last week over a piece of code: /// <summary> /// Yes, this is ugly. /// Yes, we need fix it. /// If you read it, take the time to do it yourself. ...
C# Compiler Generating Invalid IL When Dealing With Generics
I just had to find out the reason for a strange bug in Rhino Mocks. The issue turned out to be the C# Compiler producing invalid IL, which cause the following error:failed: System.BadImageFormatException : An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) Let us start from the beginning, here is an interface and a class: public interface MyInterface ...
Using Active Record As A Rule Engine
I posted a riddle about how to use Active Record as a Rule Engine, here is the answer. First, just to remind you of the scenario: A rule engine that can process big amount of data. The engine will run as a Windows service, and not as a part of another application. Throughput is important, as well as flexibility in the rules and what they can do. The processing of each rule can be quite complex, so it is important that the rule engine will not limit what the rule can do. The...
Safe Multi Threading
I am using the code below to run work in multiply threads. A client registers a callback and an input, and it is executed on the thread pool. I have some notes about this code below: public class WorkManager<T> : IWorkManager<T> { ...
The Null Method Operator "?!"
After reading this, I was reminded how much I want the null method operator. Here is the scenario: string name = user != null ? user.Name : "no-name"; The Null Method Operator work like this:string name = user.Name ?! "no-name"; The rules: The first object reference is checked, and if it is null, it skips the method call and goes to the other line. Only the first object reference is checked. Chained method calls are not supported, this should throw an NullReferenceError,...
Rhino Commons
I made some updates to my commons library. It is just a set of utility classes that I find useful. At the moment it contains: Static Reflection Bulk Deleter Collection Actions - Find, Select All, Select All Not, etc Date Range with operations - For Each...
ADO.Net Entity Framework: Round II
After my last post about the ADO.Net Entity Framework, I got a long comment from Pablo Castro, the ADO.NET Technical Lead. I took the time answerring it, mainly because I wanted to consider my words carefully. Again, I'm probably not a partial side in this matter, with my strong NHibernate bias, but I do have quite a bit of experiance with Object Relational Mapping and how they map to real world applications. My previous post was mainly about extensibility in the framework, and how much I can extend it to fit the needs...
The Case For Statics
I talked about why statics are evil a couple of days ago. Now let us see why we want to use them anyway. Let us talk about a common scenario, and see what we have there. The scenario that I present here is extremely simplistic, of course, but it should be enough that you would get the point. Let us take the common scenario of dispalying a web page. Most web pages are composed of many small pieces of data, and it is often not possible to fetch them from the same source....
Interface + Base Class
Oren Ellenbogen has posted about generic constraints in the case where you have both an interface and a common base class. I tend to use the same Interface + Default base class often enough in my code. The issue I have with this is whatever the interfaace is even needed? I often find myself extending only from the base class and never directly from the interface. Take for instance the MethodRecorderBase and IMethodRecorder from Rhino Mocks. Everythings works against IMethodRecorder, but all the concrete classes are decendants of MethodRecorderBase. In this case,...
Field Access Performance Tests
Dave Peck has a post about the performance of Linq over collections, where he makes the comment: static field access on generic classes is up to 100x more expensive than on regular classes. I never even heard on this issue, so I decided to make a check, here is my test harness: static void Main(string[] args) ...
If a tree falls in a forest and there is no one there to hear it fall does it make a noise?
According to my code, it doesn't. Here is the scenario, the scenario is supporting on the fly view updates for Brail. Recent changes in MonoRail meant that loading the view is now the responsability of the framework, and not the responsability of the view engine. This, however, presented a problem. Brail's view are compiled classes, but I want to allow edit & refresh cycles, so I can't force the develop to restart the application every time a view change. So far, I handled it with a FileSystemWatcher that took care of...
Command Batching in ADO.Net 2.0
I got one question about this. How am I supposed to do this? No, using a data adapter is not an option, I want to create my own commands and batch them. Searching gave no answer, and Reflecting over the relevant classes bring me to a whole mess of internal classes and methods in System.Data. Any ideas? I would really like it to be DB agnostic (or be able to query if I can batch or not), but even something for SQL Server only will be helpful....
List is broken
It is broken because it is a basic framework class that doesn't have a single virtual method. I want to have a list where a delegate is called when an item is added or removed, but I can't do that, since this means that I need to override the Add()/Remove() methods. I need to create a completely new class, implement the entire IList<T> functionality, to get such a basic behavior. Yes, I know about Collection<T>, but this isn't acceptable. Why have two seperate classes? If I want a custom collection with ForEach() method on it,...
Creating Your Own Using Statement
This is a C# feature only, so sorry to all you VB guys (and all the Boo guys are laughing at me for having to go to such great lengths to do trivial things).
The idea here is to wrap a piece of code with behaviors, and allow you to act upon certain things (such as exception) when they happen.
For instance, let us take a transaction handler. The default way to handle a transaction in .Net is this:
using (ITransaction tx = Context.BeginTransaction())
{
//do work
tx.Commit();
}
You have to call the Commit() method at the end of the using block,...
NHibernate’s association is cool
I need to preface the cool part with also mentioning that <any> is a part of an evil plot to overtake the world, so don’t use it if you don’t know what you are doing. If you do, however, it is one hell of a feature to have.
Currently I’m using it for a set of rules, which can be applied to several objects, which does not have a common ancestor. This is usually a problem, since I have no way to map those objects to the database and back.
It turned out that NHibernate has support for <any>...
Client Side C# - Script#
Nikhil has implemented a C# to javascript/ajax compiler. It looks very interesting. I got a request just like this one just a few days ago. Being able to write Ajax in a strongly typed langauge is going to have a huge affect on the cost of using it, in my opinion. Especially if it produce valid javascript for all browser. (And from what I have seen, it does). The killer application for this would be to be able to debug the C# code, of course. But I wouldn't like it, since...
Yet Another Way To Crash VS.Net
This one is in the common path, incredibly easy to trigger, and will cause you to lose your work. In Vs.Net, create a C# console application project Right click the project and click View Class Diagram Ctrl+A, Delete to get rid of everything Now change the ClassDiagram1.cd name to Foo.cs (the extention...
Solving the Assembly Load Context Problem
One of the more annoying things about the way .Net is handling assemblies is the load context. If you load an assembly using Assembly.LoadFile(), it will not be available if you then do Assembly.Load(). There are any number of scenarios where this is a major hurdle. Any kind of plug in architecture, for instance. After getting bit by this when I wrote NHibernate Query Analyzer, I know way too much about resolving assemblies and the problems that this entails. It can get much worse when you try to load assemblies...
Model View Controller In ASP.Net
As it turned out, it takes 20 lines of code to add MVC to ASP.Net*: public class ModelViewControllerHandlerFactory : IHttpHandlerFactory { public IHttpHandler GetHandler(HttpContext context, ...
More Dynamic Than Thou
Well, that didn't take very long. In a couple of hours, I have four ways to solve my challange. I guess this means that C# is getting near C++ in expressiveness, I guess. Omer van Kloeten got very near to what I had in mind, but I am afraid that it is not dynamic enough for me. So, without further ado, I present to you my Foo: class
A Challange: Implement This...
How would you write the following code so it would print "Bar" to the screen: Foo foo = new Foo(); foo.DoWork("Foo"); foo.DoWork("Bar"); Can you...
NHibernate.Generics 1.0.7
I'm pretty ashamed to admit it, but I managed to foul up IEnumerator<T> for EntityDictionary<T,K>. I was very surprised to realize this, I assure you, I thought that at this point I could be trusted to handle a simple collection delegation, but apperantely this is not the case. There is a new version which fix this issue, add some better error messages, etc. As usual, you can get it here.
Cheating The compiler: Generic Properties
One of the more annoying design decision in C# is the lack of generic properties. This mean that I can't do things like: Context .Repository<Customer>.Get(15); This is incredibly annoying, since the syntax for the above is just ugly with methods. Using the same example as the last several ones, here is how I implemented it: public static class
A Few Words About The Decorator Pattern
I was asked about my recent post about Generic Repositores, the question was what is the place of the Security Decorator? The Decorator Pattern is one of my favorites with regard to building flexible APIs. For the purpose of the discusion, I am going to concentrate on just the Get(id) method: public class SecurityReposiotyDecorator<T> : IRepository<T> ...
The nature of Generic Type Names
I got a chance today to work with reflection & generics, and I learned some interesting things about generic type names. First, let us look at a generic name:System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib In this case it is a Dictionary<string,string>. You should note several things here. Orange - Before the tick "`", it is a normal type name plus namespace. Pink - The number after the tick is the number of...
Writing Maintainable Code
Brian Kernighan said:Debugging is twice as hard as writing code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Quite often I find myself rewriting parts of code that I written to make them reasable to a future me (that is without even starting to talk about other developers who may have to maintain my code). Consider the following code, what does it do? foreach (Order order...
Visual Studio 2005 Web Application Projects RTMed!
Visual Studio 2005 Web Application Projects are out. I had a lot of problems with the ASP.Net Web Site projects, so this is really great news to hear. It should speed up development by quite a bit, just by taking out the loong compile times.
Linq Update
Yes, there is a new Linq CTP, but this isn't exciting. What is exciting is this post. The exciting thing about it is that I can now intermingle code & data freely. This is going to have some major reprecussions, I think. I can do it now, using LCG, but I don't know a lot of people that would like to do that on a day to day basis. This puts us in a whole different level. One simple thing that this may mean is that I can build a smart cache...
Compiler wish list: Attributes & Lambda Expressions
Right now, you can't pass delegates to attributes, which is a shame, this would open up a whole new world of powerful patterns. In C# 3.0, there are Lambda expressions, which make the idea even more attractive. Consider the following: [Validation(string value => string.IsNullOrEmpty(value) )] public string Name ...
DLinq Answers
I posted this two days ago, and I got some answers to share. I'm not an expert on DLinq, so this isn't writ in stone. DLinq supports lazy loading, but call it delay / deferred loading. Not sure why they pick a different term than the standard one in other O/RM. It also supports rich eager fetching support, which is...
AccessViolationException in Windows Services
I wrote a Windows Service and I couldn't get the service to start properly. After trying too long to debug it in a service mode, I gave up and tried running it as a console application, I immediately got the following error:Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. I so thought that I left those kind of bugs when I left C++. Just to be clear, there isn't a hint of unsafe / unmanaged code in the application. It turned out...
Book Review: Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NETand
Data Binding with Windows Forms 2.0 : Programming Smart Client Data Applications with .NET (Microsoft Net Development Series) 12:57: I got this book from a friend, and I'm going through it in a speedy pace. I'm only finsihed chapter 2 right now, but I think that I can tell that this is going to be a good book. The datasets chapter was very good, without being condensingly simple, like most of the datasets tutorial that I encountered. As someone who can honestly claim to have never...
I Inerit from ValueType, But I am a Reference Type, who am I?
Apperantly, the winner for this question is Enum. Check out the 1.1 documentation for it. I can't make heads or tails of this statement:Class Enum is derived from class ValueType; that is, Enum is itself a reference type, not a value type. Anyone knows what this is?
My synchronization primitive: WaitForConsumersEvent
I mentioned that I had an issue with the producer having to wait for multiply consumers to finish consuming before it can continue producing. The amounts I'm talking about here is in the thousands, so WaitForMultiplyObjects or WaitHandle.WaitAll() are not applicable (both are limited to waiting on 64 items only. For the record, I don't usually write my own thread synchronization primitives, but it seems like there is no other good way to do this. This is a very simple wrapper to ManualResetEvent, which reset the internal event when it is set with...
Fun With Threads
I'm doing a project that is heavily multi-threaded now, so I got a chance to experiance the love :-) A couple of pretty obvious things that you may want to remember: If your tests execute multi threaded code, make sure that the code has finished running before the test complete. I got a couple of interesting bugs this way, and I wasn't able to track them down until I realized that the test run, succeeded, and while the next test...
On Comments, Yet Again
After making such a point about commenting being mostly noise, and that code should be able to stand on its own, I found myself adding the following comment (related to this issue) to Rhino Mocks. //This can happen only if a vritual method call originated from //the constructor, before Rhino Mocks knows about the existance //of this proxy. Those type of calls will be ignored and not count //as expectations, since there is not way to relate them to the ...
How to invoke a method asynchronously
A long time ago I posted about Static Reflection, here is a good use for it, asynchronous invocation without all the bother. How? It's pretty simple, actually. Let's say that I've the following method. public void Dispatch() { // Take a long time } If I want to run it asynchornously, I need to create...
Don't touch that exception!
It is evil to swallow exceptions. I am working with a library that is choked full with stuff like:
try { //do stuff }catch (Exception e){ Trace.WriteLine(e.Message, "Name of the method");}
This is a UI component, and it is driving me mad. Stuff stops working all of a sudden, and I need to run the app under the debugger with "catch all exception" to find out what is going on. The exception message itself (when I manage to find it) is often not very helpful, and I don't get the stack.My rules for exceptions are:- Always throw exceptions if conditions are not valid.- Throw exception...
Anonymous Delegates: Under the Hood
How does C# anonymous delegates works? Like most things in computers*, it's a big fat lie. Let's assume that I have this code: static void Main (string[] args) ...
String.IsNullOrEmpty()
Can somebody explains to me why this is happening? I looked at the generated IL, and it looks fine, but it consistently generate a Null Reference exception if I compile it with: csc /debug+ /optimize+ test.cs The stack trace points to for loop line, but I have no idea what is happening there.
The Most Useless Comment
I wrote this comment today:// This is because of C# Spec 21.5.2, I think it's stupid, go blame Andres
Generics & Specialization
Here is a proof that I didn't do C++ in too long, I completely forgot about template specialization. Pierre-Andre van Leeuwen has a post that reminded me that such things exists. The following code works as expected: static void Main (string[] args) ...
Speaking Of ReSharper
Looks like build #229 is fresh out the oven. I'll give it a spin tomorrow, and see if the stuff I run into has been fixed already.
Merging .Net 1.1 and 2.0 code, or abusing the type system...
If you've a code that you want to use for .Net 1.1, but still use features from .Net 2.0 (because they are such fun), you usually end with a bunch of #ifdef all over the place, or you create a second class and delegate functionality. It occured to me that C# allows a funky way to combine this functionality without too much bother. The idea is only applicable where you've a class that you want to be generic in .Net 2.0, and use System.Object on 1.1, this is the case in quite a...
Castle Demo App: Code Update
I've updated the code that is avialable. Now I also bundle the parts of Castle that you need in order to run it, so you will have easier time build and testing this code. All the binaries you need can be found in the Deps directory, you'll need to change the references to point to that directory. You will also need SQL Server or SQL Express for the database, as well as .Net 2.0. You can get the new release here (1.2Mb).
Castle Demo App: Queries and Foreign Keys
Okay, one thing that I'm sure that you have noticed is that we have a bug in the DeleteUser method. The problem is that we don't check for foreign keys violations, and that will cause problems down the road (someone tries to delete a user that is assigned to a project, and he suddenly stares at an error page asking "But what did I do?" Let's try to prevent it before we get a bug report about it. First, we need to make a couple of policy decsisions. There are two ways that...
Why So Many Snippets
So Microsoft has posted a lot more snippets, a Jeff has made them more accessible. I downloaded them and took a look. I'm pretty sure that you could hear my cries of horror all the way to Remond. Why? That is the question I have. Snippets are useful for things like generating a foreach (although the Microsoft implementation sucks, try the way ReSharper does it.) or maybe generating a method skeleton. I see them doing things there like Hashing A Password, Encrypting Files, etc. Why? This is just a recipe...
A Real Challange
I'm working on a side project that involves web services & databases. It's not complicated or hard by any means, but it does touch on stuff that I haven't done much with in the past. I didn't have any problem so far, and in fact, I managed to learn / create several new things along the way, until I reach the point where I needed to get a dataset. If you have read my blog for a while you probably knows what I think about datasets vs. business objects. For me, business objects with...
How to kill the C# Compiler
My legendary skills in breaking code have now reached a new level, in which I managed to break the C# Compiler. Check out this code: public delegate void Proc(); ...
Israeli C# User Group Meeting
I was at the C# User Group meeting today, and Ido gave a talk about Indigo (Windows Communication Foundation - Horrible name) which I found facinating. I'll post about it shortly, I hope. There was also a huge raffle, but I didn't win anything. It was the first time that I managed to dedicate time to go to the user group meeting, and if all the talks are at this level, it's well worth it.
.Net 2.0 Code Conversion
This one is Cool. The Sharp Develop folks has a code convertor out that works for .Net 2.0 (including generics!) and it works for C# <-> VB.Net and VB.Net / C# -> Boo! You can get it here, and there is even a web service you can call to do it automatically from your code. I like the design of only converting to Boo, obviously once you've got your code in Boo, you never need to move it to another language. This convertor uses the NRefactory library, so it's pretty robust, and...
SqlClr and anonymous delegates
Okay, I'm playing around with SqlClr (doing runtime DDL stuff, mainly), and I discovered that SqlClr and anonymous delegates don't play along very well. The issue is that code like this:
CallWithAction(delegate(DateTime dt) { return dt; } );
Is actually translated to something like this:if(ClassName.<> HiddenFieldName == null) ClassName.<> HiddenFieldName = new SomeDelegate(HiddenMethodName);CallWithAction(ClassName.<> HiddenFieldName);
And that causes problem with the SqlClr, since the method is trying to store into a static field, which doesn't seem to be allowed on the safe level (which I really don't want to pass.)
It doesn't happen if the anonymous method uses local variables,...
String Comparison Performance
During the Tel Aviv Launch I had an argument with Justin about the performance of string comparisons. The issue was whatever it is good to use str == "" or str.Length == 0, and the meriths of string.IsNullOrEmpty(str) in .Net 2.0. Since Stefano just posted a comparison in VB.Net, I thought I would make the same check on C# (since VB.Net uses a compatability layer for string comparison). I merely ported Stefano's code: DateTime start = DateTime.Now; string str = ""; for (int i = 0; i < 1000000000; i++) {...
NHibernate.Generics Update
Okay, it's about time that I update this thing. Now it's properly versions in the NQA repository, and you can reach it via: svn://svn.berlios.de/nqa/NHibernate.Generics/ or via: http://svn.berlios.de/wsvn/nqa/NHibernate.Generics/.
There are some new stuff there as well:
Tests for ManyToMany, which a lot of people requested.
Pay attention to many-to-many, lazy loading, and the edge case I talk about here.
I added an overload for this, and you must use this overload when you are creating the collection that will be the authoritative source (inverse=false, in the mapping). Check the User class in the tests for the detials.
Proper handling of Clear() on EntitySet
Introducing the...
Resharper 211: Impressions
I can see some big improvements that were made on generics support. It's still far from perfect, but it's much better than even 210. It's not surprising that memory is still an issue, since the performance tuning has not started yet. One thing I can tell you is that it's nearly like having an old friend back, tips & tricks at your fingertips, just amazing. I've just began to use it, so it's a bit early to tell how good it is, but I already found some new stuff that I liked.
Commons Is Out
It's mainly there because I need to access it from a different computer and it's a hassle to create a public SVN Repository, but you can get it here. Right now there isn't much there, but where there is, is promising, I think. :-) At worst, it's a hell of a test case for ReSharper :-D
Resharper 211
I'm putting this here so I wouldn't forget, but Resharper has a new build out, and this is the one (or the one right after it) that should mark the stabilization & optimization phase, so we have great things ahead of us. :-)
Movie Review: Harry Potter & The Goblet Of Fire
I went to see Harry Potter & The Goblet Of Fire, since I thoroughly enjoyed the books. I'm in two minds about the movie, though. The good things about it is that it's a beautiful movie, the scenes are breath-takingly beautiful, and the atmosphere is just right for each and every scene. It really put life into some of the scenes in the book. The dragon flight was especially amazing. The bad things about it is that it has cut about 50% of the...
Wishful thinking
I wish we could do the following:// CS0689.cs class A<T> : T // CS0689 { } That is, inherit from a type paraemeter. Unfortunately, this is forbidden by the C# compiler (CS0689 error, as you can see). The options that this would've opened are quite impressive. This is one technique that you can use in C++, and it's very impressive one. Anyone can pipe in with the reason for this limitation? And whatever it's...
Common Work
Okay, so far I've implemented & tested the following: Disposable Action Property Indexers Static Reflection Delegate definations for most concievable function proto types. Basic Validation Routines Basic Date Stuff: ...
Aspects and Decorators
There has been some discussion recently on the Castle about Aspect Oriented Programming* and their usage in production applications. I thought about using aspects for logging & security in my current project. But I decided against it. The reasons varied from not wanting to add more new stuff to an already complex project, other developers who would use the code, and ease of debugging/testing. Instead, I used this approach: The Container class is the central axis of my project, it binds together many services and allows...
The Ultimate Disposable
I'm very partial to safe code, so I really like the using() statement in C#. The problem with this statement, however, is that I want to do different things at different times, which require different disposing semantics from the same class. Here is an example from Rhino Mocks: using(mocks.Ordered()) { using(mocks.Unordered()) { }...
New ReSharper EAP
There is a new build out, build-210, of the greatest boost to productivity since the syntax coloring :-D Go get it here. It is mildly frustrating, to put it mildly, to get almost all the features that I so crave, only to put them away again because it's still alpha. What is cool is that you could actually see it improving every week or so.
Are you null? Or Not?
Take a look at this: In the case, "type" was a value that I got from MethodInfo.GetGenericArguments(). It's an unbound type, and it's not null, as you can see. It took me a while to realize what is going on. The System.Type type is probably configured to display in the debugger its FullName property, which is null in this case. Until I figured it out, I was certain that GetGenericArguments() is returning null for unbound generic arguments.
WOW! Native Queries in C# 2.0
Will you take a look at that.
This is about the coolest thing that you are going to see until C# 3 &
lambdas will arrive.
It has so many possibilities that I can't
really comprehend now, the guys at db4o are brilliant, and that is even
before you consider that Rodrigo invented Boo,
the nicest compiler on earth. I'm going to investigate this deeply, and
see if I can do something similar. If I can combine this with lightweight code
generation, it will open up a completely new approach to solving problems.
If you missed it so far, I'm super
excited about this stuff. Great job, and wonderful idea.
Code Resuse?
Here is an interesting question, I've a couple of UI Controls, which are remarkably similiar, and share the same base class. The only differences are some strings that are displayed to the user, and the result of some action. I'm using the controls as a way to create instances of a base class, so you may think of them as a UI Factory. The issue is generating the following UI:Name: .... Owner: .... -- this is a per control area Color: ... Sterile: ......
New NUnit version is out
After nearly a year, we've a new version of NUnit, 2.2.3. You can find the details in the release notes. But they added a bunch of really cool asserts, IsInstanceOf / IsAssignableFrom / Contains, etc. There is also a new StringAssert, which is also nice.
Overload Static Methods Inheritance: A Bug Story
Today I had a bug, a very nasty one. This bug was quite innocent, is looked like this:Animal animal = Poodle.Black("My Doggie"); A pretty simple code, isn't it? The Black() method is a static method that just creates the object (its purpose is to simplify instansiating the object, nothing more). But instead of getting a poodle, I was getting a generic dog! The sad part about it is that it worked when I was trying to save it, and only bombed when I tried to load it, meaning that I got the exception on a...
Ayende vs Web Projects: Part N
For the last week of so, my life has been relatively free from annoyances with web projects. I've learned to work around most of the issues, and except from the slow build times (Ctrl+Shift+B is hardwired into my left hand now, and I can't really change it, anyone has a config editor for muscles?) and the slower refactoring times, I'm happy. I just adore refactoring, and I use it all over the place, and the slowness of refactoring in each and every time I make a change in a solution that includes a...
Type vs Generics
An interesting post on The Moth on which of the two you should prefer? new Blah<SomeType>(); new Blah(typeOf(SomeType)); Personally, I like the first one better, but I can see the benefits of the other one as well. I'm currently have a faint smell regarding this with a method calls that look like this:Container.Repository<Blog>().Save(blog); I could've written it the other way, like this:Container.Repository(typeof(Blog)).Save(blog); But it's shorter and...
Cool tool
It's not new, but I just found this, and I had an "Oh, My GOD!" moment on seeing this. It's the control debug visualizer for Asp.Net, which mean that you can see how the control looks like during debug. So you could see what is happening to it as it traverse your code. This is very cool.
Updaing NHibernate.Generics
I've released an update to NHibernate.Generics, the library that allows you to use strongly typed collection with NHibernate. You can download it here. The new stuff: Supporting lazy loading for classes as well as collections - previous version loaded classes too early. A couple of new overloads for the constructors, so you can use it easily even if you don't have any action to do on add/remove or change/clear. ...
Using advanced features in the real world
Many of the new features of C# 2.0 seems to be targeted toward a very spesific problem. Here is a short list of the things that I've seem. It just the feature, the target it's used for, and what I am using it for in a real project. When I'm talking about the intended usage, I'm talking about the main problem this feature is aimed to solve, and I deduct that simply by looking at where the most examples of it are. ...
Great Things are happening
[Via Tim Haines] Ghost Doc for VS 2005 is out! Now I run out of excuses for not putting comments on my code. Strangely enough, other people just don't believe me when I say that I believe that code that needs comments is code that need rewriting. [Via Wallace] SQL Management Studio Express is out in another CTP. I've complained about it here, so it's great to hear this.
Phoenix & Boo
Check out this MSDN article! If I'm reading it correctly, this has the potential to bring the Open Compiler Architecture from Boo to the rest of .Net world, as well as to native code. The implications of this are stagerring. Yes, please let it out. Show it the light of day. Bring bliss to our work.* But seriously, this is something that I really wants, since it can cut down code so fast you couldn't even believe. In truth, I would be very surprised if Microsoft released this tool to the...
Visual Studio on eWeek
Seems that the story about VS quality has reached eWeek, and I was mentioned. There is an interesting Microsoft Watch article about it, too. Since I recently went on a ranting spree, I want to clarify some things. I don't agree with some of the design decisions that Microsoft did. But it is their framework, and I think that they have done a wonderful job in both dotNet Framework and in VS 2005. I just found out that conditional breakpoints works in C#, and it saved me half an hour of stepping to...
Servicing plans for VS 2003 and VS 2005
There is going to be a service pack for VS 2005 and 2003. This is very good.
VS 2005 Web Deployment Projects Are looking Cool
Take a look at the things you could do with this. I can't wait until it'll be out.
I really hate web projects.
And I mean hate them. The cause me to lose time. I can't quite tell you how aggravated they made me. Here are the most recent butch of problems: Using Subversion for SCM, I commit and move to another machine, checkout and try to work. The web project refuse to compile. The reason? Who knows, but it looks like it lost the knowledge about referenced projects. It treats them as if they were normal files in the bin directories, and since...
More on VS 2005 Quality
I got mentioned on Mini Microsoft, along with couple of others that had similar problems. The comments there are pretty interesting. The official launch is tomorrow, so that means that anyone who is using 2005 RTM is a hard core guy, and they are the fellows that are passionate about it. They are the ones that are hurt by those bugs. Because you're not supposed to find so many bugs in a product so fast. Some of those bugs will cause me to lose my work. That is unacceptable. What is going to...
What Visual Studio did good
After slamming so much into VS.Net, some might think that I don't like it. This couldn't be further from the truth. I really like it. If I didn't, I wouldn't be so pissed off about the finishing touches. When working on MonoRail, I've to use Visual Studio 2003. And it's plainly visible where they gotten things better. Hell, just the visuals of setting a breakpoint in 2003 vs 2005. Are they functionaly the same? Yes, but the 2005 makes me feel better. Speaking about breakpoints, debugging in VS 2005 is...
Do you grok C# 2.0: Answers
So a couple of days ago I posted the Do you grok C# 2.0 challange. Here is the code that I presented:using System; using System.Collections.Generic; public class Sample<T> where T:class { private static string typeName = typeof(T).FullName; public string TypeName { get { return typeName; } } public List<Printer> PrintNumbers() { string [] names = { "Ayende", "Rahien", "Foo", "Bar" }; List<Printer> list = new List<Printer> (); foreach(string s in names) { ...
Watching the PDC: Scripting and Dynamic Languages on the CLR
I'm currently watching the Scripting and Dynamic Languages on the CLR session from the PDC. Rodrigo (creator of Boo) is there, and it's a very interesting discussion. I still think that Boo is the best language on the CLR, mainly because I, as a user, can write what I want, and not how I want it. Rodrigo mentioned the IReflect interface, which was new to me. Any idea what is it used for in the CLR right now, beside Type? On adding keywords to the language: VB.Net & C# took different approaches....
Didja know? Web projects do time traveling...
It's a little known fact that Microsoft managed to add time traveling capabilities to web projects. In order to activate this capability, all you need to do is to discover a bug in your application. Suppose it's an instantly recognizable, and instantly fixable. Now, in order for this to work, the bug must be in a library that the web project references. Fix the bug, and run the application again. It works! :-) Dance a little jig, and then keep on working. Five seconds later, you'll discover the same bug....
Visual Studio 2005 RTM: Buggy, Buggy, Buggy
Seems to me that there is a lof of bugs in the RTM version of Visual Studio 2005. Here is a random collection of things that I run into recently: Wesner Moise, Frans Brouma, Roy Osherove, Michael Teper and Rolf Bjarne all have found bugs that I would categorize as Very Serious. I myself have run into this bug, and ReSharper is nearly unusable because VS.Net doesn't respect the colors that ReSharper tells it to paint. (It paints strange stuff that is...
Is there hope for web projects
Appernatly I'm not the only one that noticed how bad the web projects were, Rick noticed nearly 5 months ago, and notified Microsoft about it. It seems like there might be a add on project type that would solve this problem. I'm drolling over the feature list of the project, and that is just because I can see it shaving at least an hour a day of waiting for the project to run.
Ayende vs GridView: Part 2
Okay, here is a simple scenario, I need to add a couple of buttons to the end of each row on the GridView. How do I do that? Well, I started out by adding them by override the OnDataBound () method and adding the buttons as ButtonField. It works, it's simple, but it's not done. I wanted to add a javascript confirm to one of the buttons, since it's a destructive change. How do I do that? No idea, and I don't see it being possible. I took a look using Reflector, and...
Web Projects Sucks!
No, I'm not talking about the idiocy that took away the project file (an endless source of fun, truck why I keep seeing the bug I fixed a couple of hours ago. Oh, I didn't rebuilt from scratch, the old binary are still thre...). I'm talking about worse idiocy! The slowness of the bloody thing. Take a decent size web project ~50 pages and several custom control, make a single line change, and try to run the page you just changed. Watch how Vs.Net precompile the whole freaking thing for just one page!...
Ayende vs the GridView: Part 1
I'd a problem in my project today, where I just couldn't figure out how to solve the problem of binding a data grid to a custom list of business objects. I'm certain that there is a lot of info there, but I needed something simple, just take a list of object, and bind them to the grid, based on what I would tell you. I really wanted to keep the nice features of the GridView which allows for rapid proto-typing, so you could declare it like: ...
Do you grok C# 2.0?
I run into a couple of great questions in .Net 2.0 today, which influenced some of the things that I did there. I'm wonderring how many others would spot them. Without compiling the code, what is the result of the following code snippet? using System; using System.Collections.Generic; public class Sample<T> where T:class { private static string typeName = typeof(T).FullName; ...
Thinking about partial classes
I'm thinking about the way ASP.Net are working, and I can't help thinking that I'm missing something with regard to partial classes. The issue here is that of how the compiler knows to take the aspx page and turn it into code. Is it done it the compiler level in the first place? If so, how does the compiler knows about it? Is it possible to get your own code to run when this is done? I think that the answer to those is no, and that it is...
Generic using alias
Why can't I do this:using Hashtable<TKey, TValue> = System.Collections.Generics.Dictionary<TKey, TValue>; I can do it if I specify the generic parameters, but not while keeping the generic parameters free.
Static Reflection
I've a confession to make. It's a very serious one. I don't like strings and Reflection. In fact, you could say that I hate them with a passion. I hate them because they hide important information from the compiler. This post is actually not a rant, it presents a solution to the problem. I hate them so much that I wrote my own Mocking Framework that don't use strings at all. .Net has some really great stuff that you can do with Reflection, but it has two big problems. ...
How to use the GC for caching...
Consider the following situation: You need to do a transformation on an object, which is potentially a very expansive operation. The result of the transformation is needed in several locations, and you've no way to control when/how they need it. (The object reside in a repository and can be requested by anyone). ...
More on ReSharper 2.0 EAP
I'm currently testing build 208, I like it, but it still has its fair share of problems. It's an alpha, so it's to be expected. The code formatter isn't there yet, there aren't enough options about anonymous delegates, which really bother me. You can't tell R# to do this: Method(delegate(int i) { return i*3; }; ...
Generic firing of asynchoronous events
Tomer Gabel had a problem with raising events from outside the class that declared them. The problem was compounded by the need to process the event asynchoronously, since System.Delegate doesn't implement BeginInvoke(). His solution was to use Reflection to do that. I was interested enough to investigate whatever I could do that without Reflection. I was surprised to learn that BeginInvoke was only available on specialized delegates. My solution is based around this article: Calling Synchronous Methods Asynchronously which truly proves that you can solve anything in computers by putting another layer of indirection, except...
Sharp Develop 2.0
I've had a fairly strong negative reaction to #Develop in the past, mostly because you really couldn't use if without the IDE started to throw exceptions and refusing to work (my pet peeve was the inability to create & rename new folders, an issue that often require a manual editing of the project file.) I got a couple of recommendation about #Develop 2, which is currently only available from the Subversion repository (svn://sharpdevelop.net/corsavy/trunk) (or so I understand). I'm writing this review based on revision 619. Over all, I've got a...
C# .0 Code Formatter
Does anyone knows of a C# 2.0 code formatter that is available now? I want something just like what ReSharper has for 1.1, where you get tons of options for just about anything. Spesifically, I need something that will understand how to handle anonymous delegates. Right now R# doesn't handle them very well. My current code style is://one liner sw.Action = delegate(ISalesContext sales) { return sales.Items.Count;} //multi line sw.Action = delegate(ISalesContext sales) { ...
Rules, Delegation, and Yielders, oh my!
Like I said, I've just wrote a rule that used pretty much all the new features that C# 2 has to offer. I'm aware that I tend to like new things for their own sake, but I like to think that I'm using them wisely. Let's take an example, since this is the best way to do it, in my opinion. I present here a case similar to the one I ended up with, and I would appreciate comments about the readability / maintainability of the code. I have a graph of...
Covariance in delegates
I'm not sure if it's the way to call it, but why does the C# compiler errors on this:public IList<object> GetList() { return new List<string>(); } Seems to me that a generic of a derived type should be able to satisfy the compiler when requesting a generic of a base type. Any idea what the reasoning behind this decision was?
Correnting My Mistake: Static Methods & Child Classes
In a previous post
I said that you can't "inherit" static methods from your parent class.
Apperantly I was mistaken. The following code works on both 1.1 &
2.0: public class Parent { public static void Static() { } } public class Child : Parent { ...
Static Generic Class
Now this is a cool feature I just discovered. I don't think that
this is the true name, but it describe what it does. I'm currently
trying to give ActiveRecord
a more .Net 2.0 interface, and I'm currently concentrating on the
static methods of the ActiveRecordBase class. The current best practice
for ActiveRecord is to create a type safe wrapper on your class when
you're inheriting from ActiveRecordBase. The reasoning is very simple: Blog []blogs = Blog.FindAll(); ...
Test First & Code First
This post really hit a chord. I'm a firm believer in the values of tests. They're essenstial to have heathly software. But I often find myself in situations where a new functionality is just isn't testable. It's not testable because I've no idea how it is going to look until I write it. Let's take a recent scenario, I wanted to add a rule that checks some variables within a spesific range. So I create a test that looks like this:[TestMethod] public void AtLeast5OccurancesInMonth() { Calendar calendar= //.. create calender ......
Repeat Yourself Early And Often
RYEAO (Pronunciation: it just sounds like cat when you step on it's tail) is the only thing that comes to my mind when I see things like: public class Employee { public int EmployeeID { ... } public string EmployeeName { ... } } You really want to make sure that you're dealing with an employee here, I guess. I see if...
Hebrew in Development
This is a plea to all those developers who are speaking a langauge
with a non-latin character set and wants to use non-english names
during development. If the database support Unicode names, use them. If
it doesn't use the correct trasnlation to English. The most confusing database schema that I saw was Hebrew words spelled in English. And this one had a twist, it was abberviated Hebrew words.
If you want to have a column that would store the date of birth, you
can call it DateOfBirth, of if you really want to use Hebrew, call it:
"ת. לידה". Both are very clear. Taleda...
Generic Template Delegate
I think that I talked about it before, but I really loves the new abilities that Generics & Anonymous Delegates gives me. I find myself writing API that takes delegates, and it's a pleasure to work with. It's not only property indexers and NHibernate Generics, it's a whole different way of thinking. I think that we will see a lot more code that is written to take advantage of this features. Generic Template Delegate is a great pattern to seperate concerns, and it's very nearly delerative coding, in my opinion. Some...
A new way to abuse C@
No, the the title is not a mistake, I just figured out something that should've been obvious. You can use C# to write code like this:int @class = 0; And the compiler will translate the name to the IL even though it's a reserved work. It stands to reason that you can also use it on non reserved words, doesn't it?object @something = null; The above compiles fine, and it's a very Ruby way to name a variable. What about the part about abusing the language? Well, consider this code:string @a = "Cat"; a += @a; ...
Mixin & Dicing in C# 3
Note: It's probably pretty early to start talking about patterns for C# 3, but the thought popped to my mind and wouldn't go away. Mixin: In computer science, a mixin is a group of functions which can be mixed into a class and become methods. They allow certain classes to take on certain functionality, in an object-oriented programming including in languages that do not support multiple inheritance, just as if the class were a cooking dish and a mixin was a specific ingredient. Ruby on Rails recently got a act_as_taggable mixin, which...
More on static interfaces
I've opened a ladybug feature request for it. One other thing that it's going to be useful for is interface operators (but which can be also solved using extentions operators).
Feature Request: Static Interfaces
I want C# 3 to have support for static interfaces! What is a static interface? A static interface is like a normal interface which a class can implement, but it may contain static methods and constructors. The syntax is simple, just add the static keyword on the methods that you want to be static, add constructors as usual and you're set (I've bolded the new parts): public interface IDocument { void Save(); ...
Cool Linq Idea: UI Mapping
This is purely hypotetical, but imagine the following way to show the user's details: User user = ... ;//Get user something var view = new View( user, new Text(u => u.Name, s => user.Name = s), new Password( u => u.Password, s => user.Password = s ), new List(from g in user.Groups select g, g => user.Groups.Add(g), g => user.Groups.Remove(g)) ); view.Show(); Where View is...
More on innovation
Just thinking, I think that Microsoft was the first* that made deep integration between the language constructs mix with the framework it live on. I'm talking about such things as using and IDisposable, where you had a language construct that you can control and add to. This theme continue with the Linq infra structure, it's not ADO.Net build into the language, it's simply macro transformation that is open for the developer to extend with his own code. I'm familiar with the concept from Boo, and it's a very powerful one. ...
How to make C# 3 even better...
After getting so excited about the things that are going to be in C# 3, let's see the things that I would like to see coming: Extentions method for properties and operators - Operators are super important because this would be the only way to add operators to interfaces. Extentions properties are a must have if we have extentions methods. The spec mentions that they are considered, I certainly think that they should go in. Compiler time reflection information - By that I mean a way to explicitly get reflection...
Great C# 3 discussion
Check out Cyrus post. The devil is in the details, read the comments.
Innovation
I'm still digesting all the new things that we're going to get in C# 3. I've already expressed my joy about the things that this would allow me to do. I think that those changes should shut anyone who claims that Microsoft cannot innovate. Yes, some of the new features have been there in other langauges before, but I've never seen a main stream language that make such a move. The interesting thing is that while Linq will probably get all the attention, it's the foundations that makes it so interesting, since you...
Microsoft, Release C# 3 ASAP
I don't want to wait until mid 2007 to start using the cool stuff they've right now. The things I could do with LINQ are just astounding. Please don't make all of us droll too long.
C# 3 Usage
Check out this post, where Cyrus is showing a cool way to combine the abilities of C# 3 to create some powerful code. This is possible to do in 1.1 or 2.0, just painful. Syntatic Sugar Isn't!
C# 3, so cool!
Just look at C# 3 future, it's so pretty I want it now. Check out the videos that they have there. There is so much good stuff there, and it's only the start. First of all, read the C# 3.0 spec [doc file], or just read the rest of the post to see the highlights. Type inferencing and implicitly typed arrays- I got addicted to that when using Boo, it's something so simple, but it saves so much. In most cases, it means no more casting hell. Andres let it slip in a...