code snippets
code snippets
Castle Windsor allows you to use single component for multiple services, which is called Forwarded Types. Forwarded Types In other words, you can tell Windsor – when IFoo is requested use FooBar as implementation, and when Bar is requested also use FooBar (when using default lifestyle of singleton you’ll get the same instance). Here’s some code: var container = new WindsorContainer();
container.Register(Component.For<Bar>().Forward<IFoo>()
.ImplementedBy<FooBar>());
var foo = container.Resolve<IFoo>();
...
There does not seem to be too much details on how to set up a test environment for NHibernate testing using SQLite. Ayende has a nice post on this, but he does not go into details of how, what and where, so I decided to fill in the blanks, and provide an up to date sample for NHibernate 2.1. Let’s first gather all the things we need: NHibernate (obviously) SQLite binding for .NET get the full version (not managed-only) SQLite itself scroll down to...
My fellow devlicio.us blogger Tim Barcz posted an interesting problem to solve. I think it's fun, so I decided to give it a try. Now, I don't know enough context to solve it for just about any case (and I don't think that's even possible), so I made a few assumptions. The strings we're gonna be handling are not too long. Otherwise I'd probably use a StringReader/Writer. I'm looking at minimal solution. YAGNI - I could do some optimizations probably, but I want to keep it simple, because the sample...
When you have a WCF service that is not a singleton, and you want to use non-default constructor, you enter a world of pain. There's a lot of hoops that you have to go through to plug an IInstanceProvider into the service. Even worse if you have many services. To alleviate the pain, I created a small helper method. private ServiceHost GetService<TService>( string address, Func<TService> createServiceInstance )
{
var service = new ServiceHost( typeof( TService ) );
var serviceInstanceFactoryBehavior = new ServiceInstanceFactoryBehavior(...
All .NET delegates inherit (indirectly) from System.Delegate class (and directly from System.MulticastDelegate) which has a static CreateDelegate method. The method has two powerful characteristics that are not widely known. All delegate types are implemented by the runtime. What do I mean by that? Let’s have a look at how any delegate type looks at the IL level: All methods are runtime managed, meaning that, in a similar fashion you provide implementation for interface methods, runtime provides implementation for delegate methods. Take a look at the constructor. Regardless of delegate type it always has two arguments:...
Not that I’m proud of that, but to circumvent the limitations of CLR and C# I sometimes had to use reflection, code generation, changing behavior depending on who’s calling etc.
However I think this code beats all that.
public static class HandleProvider
{
private static int _currentToken = typeof(object).GetConstructors()[0].MetadataToken;
private static ModuleHandle _moduleHandle = typeof(object).Module.ModuleHandle;
/// <summary>
/// This is an ugly hack to circumvent lack of useful public constructor on RuntimeMethodHandle struct
/// </summary>
/// <returns>Method handle of some method from mscorlib</returns>
...
I’ve been working with NHibernate for the last couple of days, and as I make my way though it, I find out about things, that were not so obvious to me at first, so I decided to post them here, so that someone else can benefit as well. First thing you learn about NHibernate (well ok – first thing I learned about NHibernate, but most of you probably as well) is that it requires you to mark your properties virtual, have parameterless constructor, and pay special attention to your GetHashCode() and Equals() methods. With all...
As a follow up to my previous post, here’s the simplified – Console based version of the code. Disclaimer. This is a solution. Not the best one, not recommended by anyone, just the one that happened to solve my problem. So take it with a (big) grain of salt, and if you know a better one, use the Leave your comment function below. using System;
using System.ComponentModel.Composition;
using System.Reflection;
[assembly:AllowNonPublicComposition]
namespace ConsoleApplication1
{
class Program
...
I was entertaining the idea of contextual components that would act differently depending on who called them. System.Diagnostics.StackTrace is the class that allows you to traverse the call stack, and see who called your method. There’s one catch though – it is painfully slow. And by painfully, I mean this: Those two methods are by no means comparable in regard of what they’re doing. They are mere examples of simple tasks: one involving Reflection, and one involving StackTrace. The fact that the difference in performance is nearly two orders of magnitude, should make you think twice...
How do you test collections for equality of their elements? I often used to write my own custom assert for that, something like: public void AssertCollectionElementsAreEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
var first = expected.GetEnumerator();
var second = actual.GetEnumerator();
int count = 0;
while(first.MoveNext())
{
if(second.MoveNext())
{
...
I wish generics in C# were more powerful. Why this is not legal?public class ServiceHost<TService> : ServiceHost where TService : class
{
public ServiceEndpoint AddServiceEndpoint<TServiceInterface>(Binding binding, string address)
where TService : TServiceInterface
{
return AddServiceEndpoint(typeof(TServiceInterface), binding, address);
}
}
Technorati Tags: Generics
Can you spot a bug here? Took me 20 minutes to find it. private List<string> GetLanguages(string path){ var languages = new List<string>(); if(File.Exists(path)) { using(var reader = new StreamReader(path,_encoding)) { var dscReader = new DscReader(reader); while(dscReader.Read()) { ...
My last two posts regarding Rhino.Mocks, attracted quite a lot of attention. Focusing on solution I proposed for limiting complexity around creation different kinds of mocks, one thing was pointed out by few people as not the best solution. Ayende called it "in your face! API design", that is stating the kind of mock you want to create explicitly, via method parameter. I don't think that doing it via method name is any less explicit, but let's not go there. Instead, let's think for a while - why do we need 4 kinds of mocks anyway? All differences boil down...
[UPDATE]: Example code is updated. I realized that Kind.Multi is not needed, since you can infer that from passed parameters (when ctorArgs are present, user obviously wants to create MultiMock). I also changed default Kind to Relaxed, since this is the most common one. Ayende wrote today about his ideas for new version of Rhino.Mocks. I like the new syntax (looks similar to what MoQ offers), but there's one more change I'd like to see. Here's the list of all methods of MockRepository, used to create some kind of mock: public T CreateMock<T>(params object[] argumentsForConstructor);public object CreateMock(Type type, params...
Ok, maybe this title is a little bit too catchy. However, I simply love the expressiveness of this little piece of code I wrote today. 1: public bool RegisterAll( Assembly assembly, Func<object, bool> isValidMessage ) 2: { 3: if( assembly == null ) 4: { ...
I've been playing with Boo recently and I find it to be very powerful language. One little thing I like particularly is, that I can do this: name = "Krzysztof"print "Hello, ${name}, on the beautiful day of ${date.Today}"
And get this:
Can I please have this in C# 4.0?
Technorati Tags: Boo, C# 4.0, String Interpolation
Last week I've read quite a few new blogposts about Moq mocking framework. I had looked at it once, when it was first released, but I didn't find it interesting back then. Now that version 2.0 was released I decided to give it a go once again. Here's very simple model I created: It's a class with one method that uses helper object to obtain a value and possibly raise an event. Here's the whole code: public interface IHelper { int Param { set; } ...
Here's the problem: Having some ID, get a new instance of some class corresponding to this ID. All classes implement the same common interface (by which we will use them). So we need to be able to write something like: public IMessage DoSomethingWithMessage(Id id){ IMessage message = MessageFactory.CreateMessage(id); message.DoSomething();}
Now, how to actually implement MessageFactory, knowing that it needs to be really fast, and without having to explicitly change its implementation when new messages are added, Ids change and so on? And how to bind IDs to Messages?
Here's my idea for the solution, and...
Can anyone tell me what am I missing here? Here's a simple class public class Mock<TType>{ private readonly TType _actual; public Mock(TType actual) { _actual = actual; } public TType Actual { get { return _actual; } } public static implicit operator TType(Mock<TType> item) { return item.Actual; }}
That's a...
I've been playing in my limited spare time with Rhino.Mocks, trying to come up with a way to simplify interactions with events, and creating strongly typed IEventRaiser (or something similar). Here's what I've come up with so far: It's not an easy task, but I have few ideas. If you have any ideas or suggestions post them in the comments. I'll submit it to Ayende, so if he likes it you may actually see this stuff in some future version of Rhino.Mocks. Technorati Tags: Rhino.Mocks
Let's play. What will this program output to the console: namespace Test{ public class Program { private static void Main() { System.Console.WriteLine(MyClass.Field); } } public class MyClass { private static readonly int _height = 3; private static readonly int...
In .NET < 3.5 the only collections you could initialize inline were arrays. So this was legal: public class CollectionTest{ public static readonly ICollection<string> _list = new string[]{"one","two","three"};}
However if you wanted to have List instead of array, you had to use a trick and pass array as constructor parameter:
public static readonly ICollection<string> _list = new List<string>(new string[]{"one","two","three"});
Not the most elegant piece of code, but at least it works. So far so good. What if you wanted to...
I found pretty slick new feature in C# 3.0 that I haven't seen anyone mentioning before. In C# 2.0 to initialize List<T> inline you had to use arrays, like List<string> keys = new List<string>(new string[]{"key1"});
As you probably already know, in C# 3.0 you can initialize collections in in similar way like you did with arrays in C# 2.0:
List<string> keys = new List<string>(){"key1"};
This has been said many times in many places. What I missed however, was that syntax for initializing arrays changed as well. Now you can simply write:
string[] keys = new[]{"key1"};
Did you know that?
Technorati Tags: C# 3.0, array initialization
I found nice trick. Instead of writing: private string SetNewName() { string newName = GetName(); _name = newName; return newName; }
you can write
private string SetNewName() { ...
I'm currently writing tests for a piece of code that has lot of events flying here and back. Something like: 1: public class Caller 2: { 3: public event EventHandler<CancelEventArgs> MyEvent; 4: 5: public void Call() 6: { 7: if (MyEvent != null) 8: ...
Joe Developer once had to read options from configuration file, where each line looked basically like this: option: first;second;third;;fifth; Each line consisted of option name, followed by few spaces, and its parameters delimited by semicolons. Now the question is: how would Joe get to those parameters? The most elegant way would be using Regular Expressions, but Joe has strong allergy to them. For this simple example String.Split method will do. Joe rolled up his sleeves and crafted that beautiful masterpiece of code: 1: ...
Everyone knows what the new keyword is for in C# - you use it to call constructor of an object, right? What can be simpler? Actually, that's true, but not the whole truth. That's the most common way to use it. However, new is one of contextual keywords, which means, it can have different meaning, depending on the context where it's being used. The new keyword can be used in three scenarios: the one presented above, everyone immediately thinks of - creating objects. as modifier, to hide members of a base class. as generic constraint. Creating objects is pretty...
You can call extension methods on null elements. It's obvious when you think about it: its a normal static method where you specify its first parameter with this. using System;namespace ExtensionMethods2{ class Program { static void Main(string[] args) { string isNull = null; Console.WriteLine(isNull.IsNullOrEmpty()); string isNotNull =...
In a project I'm currently working on, I needed to check if particular character is a part of given CodePage. Problem with .NET's Encoding class, is that although it maintains a table mapping Unicode characters to codes in particular CodePage, it keeps it as private field. Moreover it does its best to replace characters it does not contain, with some fallback character. One might use this fact, and compare character received this way from Encoding' instance, with original character, assuming, that if they are different, this character is not a part of that CodePage, but this is not an elegant...
It's sometimes useful to know what is the default ANSI CodePage, for some given culture. It's quite easy to achieve, thanks to System.Globalization namespace.
CultureInfo cultureInfo = CultureInfo.GetCultureInfo(1252);
Encoding encoding = Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage);
However this code will not always work correctly. The problem is, not every culture has default ANSI CodePage, and therefore, for them you'd have to have plan B, like using UTF-8.
CultureInfo cultureInfo = CultureInfo.CurrentUICulture;
...
Today I stumbled upon a strange bug, that seems to be a feature of .net framework. I had a method that performed some action upon a instance of a class, lets say Customer, based on the hash value of that record. Seems plain and simple, however my unit test exhibited a strange behavior - in some cases, although Customer record had been updated, it acted as if it was not changed. Short investigation pointed to a field of type bool? (Nullable<bool>), that although its value was changed, returned the same hash code. The problem is, that generic struct Nulllable<T> implements...
Using classes (and structures for that matter) that implement IDisposable has one implication: when you're done using it, you should ASAP call it's Dispose() method. Like in the example: Pies item1 = new Pies("Pies 1"); Console.WriteLine("Accessing {0}", item1.Name); item1.Dispose();
To make life easier, and not have to remember to call this method directly you can alternatively use some 'syntactic sugar' in form of the 'using' keyword, and...
Today I needed to parse colors encoded as string in the form 0xRRGGBB where RR GG and BB were red green and blue values of given color encoded in hexadecimal. Problem I stumbled upon, was, what if I have a number like: 0x008000
There was no problem converting it to System.Drawing.Color class, but back to string.
I used code like below:
string colorString = string.Format("0x{0:X}{1:X}{2:X}", color.R, ...
I've been using Regionerate for some time, and I'm addicted to it. Literally when I have to write some code on a computer that doesn't have Regionerate installed I feel odd. This tool is simply pure honey and nuts. Only thing I would change is it's default keyboard mapping (ctrl+R for running it), because it collides with Visual Studio/ReSharpers "Refactor" shortcut. So every time I install it I have to go to VS settings and change it to something else (alt+3 at the moment).
Main reason for this post however is not to praise Rauchy and his tool, but to...
First of all, take a look at the following code:
private string _targetText;
private int _maxLines;
private int _maxSize;
public int Lines
{
get
{
if (_targetText ==...
I love/hate regular expressions. I love them for their flexibility and amount of time you can save using RegEx as opposed to manipulating strings manually. I hate them, because writing them is such a pain in the... you get the point. Today I had to quickly assemble a small tool that would replace certain elements in text file. To be more accurate it had to read lots small text files that were kind of bilingual, meaning English/Chinese, and change them to true Unicode bilingual. I said kind of, because files were written in plain ASCII with English text written normally,...
One of projects I'm currently working on involves reading a file produced by other tool, that has rather unusual way of storing a date and time. For example 1st of July 2007, 14:00:00 would be stored as 20070701T140000Z (colors added for emphasis). Using Convert.ToDateTime(string) or DateTime.Parse(string) throws FormatException. Parsing manually (splitting string and parsing its substring to ints to create DateTime object from them) is not very elegant solution. There is however static method DateTime.ParseExact(string, string, IFormatProvider). First parameter is encoded DateTime, second is pattern, and third can be null. How to create pattern you can learn from this msdn article....
Today at work, a colleague came to me with quite interesting problem. He needed to find out first common directory for two given paths starting from the end. For example, for given paths like: c:\documents and settings\some user\my files\projects\project1\initialFiles\somefiles\ and d:\ My Projects\project1\ChangedFiles\MyFiles\ It would return 'project1'. I was surprised to find out that neither System.IO.Path, nor System.IO.Directory allows you to that. Here's simple solution I created for him. public static string FindLastCommonParentFolder(string path1, string path2) { ...
How often do you find yourself writing code like this: Code Snippet string[] files = GetFiles(path);
filesListView.BeginUpdate();
for (int i = 0; i < files.Length; i++)
{
//possibly something more
...
While cleaning old projects I found this one, that I wrote some time ago, and decided to post here, because it took me long time to figure it out, and although at the end it didn't work (to clarify things, not because there is something wrong with it, because if how that particular app registered its instances to ROT) I don't want to go through it again. IBindCtx bindCtx; Dictionary<string, Namespace.Application> items = new Dictionary<string, Namespace.Application>();...
ToolStrip is very useful container control, but it has it's default set of controls you can put onto it. What if you wanted to have, say DateTimePicker, or some totally custom control you have made? You can inherit it from ToolStripItem, override some methods and properties, but there is a much quicker way, if you don't need any custom behaviour. To illustrate this i created simple form with ToolStrip, and I embeded DateTimePicker into it, as you can se below (code follows) As you can see, all the magic that happens is thanks to ToolStripControlHost class. private void...
From time to time there is a need to measure how much time it takes for a certain fragment of code to execute. First thought how to do this would probably be something like this: DateTime start = new DateTime();
DoSomething();
TimeSpan time = DateTime.Now.Subtract(start);
Console.WriteLine("Time taken: {0}", time.Ticks.ToString());
In .NET 2.0 however there is a class...
While cleaning old temporary projects, I usually create to test some feature, I found one, that I think may me useful, so i decided to post it here.It's a program I created some time ago, when i needed to download a image, from given URL and display it, or save. Here is the simplest solution to do this. WebClient c = new WebClient();byte[] b = c.DownloadData(textBox1.Text);using (MemoryStream ms = new MemoryStream(b)){ Bitmap i = new Bitmap(ms); panel1.BackgroundImage = i;}panel1.BackgroundImageLayout = ImageLayout.Center;