... Home Contact

Krzysztof Koźmic's blog

Designed in Poland, assembled in Australia.


Show appreciation: My Amazon.com Wish List


Me@Twitter

    Currently reading

    Article Categories

    Archives

    Post Categories

    MyPersonal

    Syndication:

    c#

    c# stuff, language tricks etc

    ConcurrentDictionary in .NET 4, not what you would expect

    .NET 4 brings some awesome support for multithreaded programming as part of Task Parallel Library, Concurrent collections and few other types that live now in the framework. Not all behaviour they expose is… not unexpected thought. What would be the result of the following code: private static void ConcurrentDictionary() { var dict = new ConcurrentDictionary<int, string>(); ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1)); ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1)); } ...

    On C# 4, co/contra-variance and generic constraints

    While trying to clean up some code today, I stumbled upon interesting result of certain refactoring. Given the following covariant interface and its implementation:   public interface IReference<out T> { } public class ComponentReference<T> : IReference<T> { } and the following usage: public static IReference<IInterceptor> ForType<T>() where T : IInterceptor { return new ComponentReference<T>(); } the code won’t compile. However, not all is lost – if you...

    Thoughts on C# 4.0’ optional parameters

    C# 4.0 is just round the corner and along with it set of nice new additions to the language, including optional parameters. There’s been some historical resistance to add this feature to the language, but here' it is, and I’m glad it’s coming, or at least I was. In few words, optional parameters, have their default value specified in the signature of the method. You can then skip them when calling method, and the method will be called with their default values. So, what’s the deal? To simplify the current discussion I will refer...

    Solving a programming puzzle

    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...

    WCF service host builder

    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(...

    Framework Tips XII: Advanced .NET delegates

    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:...

    On self-documenting code

    Take this piece of code: public int Count(string text) { Console.WriteLine("Counting..."); // simulate some lengthy operation... Thread.Sleep(5000); return text.Length; } What’s wrong with it? It’s not very obvious what the magic number 5000 means? Does it mean 5000 years? 5000 minutes? 5000 the time it takes to run around Main Market Square in Kraków? Sure, you can hover over the invocation (if you’re in Visual Studio) and see the tooltip and see that the number denotes milliseconds,...

    Mommy, there be dragons in my code.

    Every developer, and every shop has a Acme.Commons, or Acme.Core library, where they keep useful helper classes and extensions used in almost every project. Ayende has his Rhino Commons that I’ve seen him blogging about a few times but I never quite got around to actually take a look at the code… …until today, and I’m shocked. In a mostly positive way. There are few good ideas there, that I would like to discuss. The first class I found astonishing was HackExpiredException. My first reaction looked something like this: Then I looked for some...

    Working effectively with Reflection.Emit

    I’ve been working a little bit with dynamic code generation at runtime (classes in Reflection.Emit namespace, collectively referred to as Reflection.Emit). It’s a low level API, that requires you to work with IL operations, keep track of what is on the stack, and requires quite a bit of knowledge about IL and CLR. I’m no expert in IL, as probably most of developers, but there are ways to make this things easier. To work my way through generating code, I use iterative approach. Write a class/method in C# that exactly (or as closely as...

    Castle DynamicProxy tutorial part I: Introduction

    I’ve been experimenting lately quite a lot with Castle Dynamic Proxy, creating prototype for a project I work on at work and I even implemented a small feature that was missing from it. Generally, Dynamic Proxy (DP from now on) is a great, lightweight framework, but it’s greatest downside is lack of documentation. It’s surprisingly logical a easy to use, but since there are almost no resources on the web, that could help you get started with it, I decided to give it a go, and start a small tutorial series of posts, that will introduce various features of DP...

    Microoptimizations: foreach vs for in C#

    Patrick Smacchia wrote a post where he compares execution time while using different patterns to iterate over a collection, namely List<int> and int[]. Since he provided the code, I decided to give it a go as well. Only thing I did, was I added [MethodImpl(MethodImplOptions.NoInlining)] for each method, since they all were very simple, and could easily be inlined. That said, here are my results (release build ran without debugger, outside of Visual Studio): If you compare those to Patrick’s results, you may notice few things: Patrick has a faster PC...

    You don’t get the C# 4.0, do you?

    Sorry for the daring topic, but that’s really what comes to my mind when I read or hear people whining about C# loosing purity/object-orientation/strongly-typedness/goal/insert your favorite here, with the advent of version 4.0. To sum it up, there are four major new areas of improvement coming up with the forthcoming version of the language, as outlined by Charlie Calvert in "New Features in C# 4.0". dynamic keyword (type) along with all its implications. Optional and named parameters. Co/Contra-variance of generics Few additional features geared towards easing...

    Creating tree of dependencies with MEF

    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 ...

    .NET 4.0 and Visual Studio 2010

    I’m downloading .NET 4.0 and Visual Studio 2010. Currently it looks like  this: It looks like I will have to wait till tomorrow to play with partial local types, dynamic objects, and whatever Anders is announcing right in this very moment. Good night.

    Slower than Reflection; meet StackTrace

    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...

    Framework Tips XI: What is this?

    Lately while going through the code of latest MEF release, I stumbled upon a piece of code that used a very little known feature of .NET Just take a look: public struct Tuple<TFirst, TSecond> { public Tuple(TFirst first, TSecond second) { this = new Tuple<TFirst, TSecond>();//looks strange? this.First = first; this.Second = second; ...

    Testing collections with NUnit

    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()) { ...

    Framework Tips X: More on enums

    Yes, I know that previous Framework Tips had number VIII, but I didn’t notice that I already had VIII, so this makes this part 10th in the row. Each enum, is a named collection of flags, that mask a numeric type. For example: public enum ErrorCodes { FileNotFound = 0x12, OutOfDiskSpace = 0x14 } You could use this enum in an error handling method like: public void HandleError(ErrorCodes errorCode) { switch(errorCode) ...

    On generics limitations

    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?

    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()) { ...

    Framework Tips VIII: Enums and Extension Methods

    I have somewhat mixed feelings towards enums in C#. On the one hand, they can greatly improve readability of your code, but on the other hand, they are not much more than textual masks on numeric values. You can't inherit from them, you can't use enum as generic constraint (for which I see no good reason), and you can't extend them... Or can you? With the addition of Extension Methods in C# 3.0 you finally have the tools to put some life in them. Consider you have an enum like this:public enum Mp3Player { IPodClassic, ...

    Beautiful code

    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: { ...

    So is it a class or what?

    C# doesn't stop to surprise me. While looking at Moq source code I noticed something strange: Generic constraint says class but yet somehow interfaces account for class? Technorati Tags: Moq, Generics

    Implicit casting of generic classes

    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...

    Fighting with events: Rhino.Mocks strongly typed EventRaiser attempt #2

    I just spent good few hours trying to fight awkward limitations of .NET framework in regard to generics, events, delegates and expression trees. And I'm actually not much further than when I started. It bothers me: why put artificial limitations in regard to delegates as generic constraints? I wish I could do: public IEventManager<T1,T2> Metod<T1,T2,TEvent>(TEvent @event) where TEvent: Func<T1,T2> (this will not compile, can not use delegates as constraints...) or even better: public IEventManager<T1,T2> Metod<T1,T2,TEvent>(TEvent @event) where TEvent: void delegate(T1,T2) This seems to ruin my every idea. Even worse, when I looked for help at Expression Trees, I learned that you can't have...

    Strongly Typed EventRaiser with Rhino.Mocks

    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

    More on inline initialization (answer)

    Well, due to overwhelming feedback for the previous post, here's the answer: 0. Now the most interesting part: why? When you use inline initialization, compiler generates a static constructor for you, and does all the initialization there. It looks like, it's not smart enough to pick this kind of dependencies, and simply initializes fields in the order they've been declared in the class' body. That's why, by the time Field is initialized, _height has value 3, but _width is still 0. If you wanted to overcome this, you'd have to use const instead of readonly (that's an option only for...

    Using Extension Methods to make code more readable.

    Let's look at an example:   This is somewhat simplified diagram of classes that are part of object model I created for a certain XML format (it doesn't reflect physical structure of XML file, rather it's a conceptual, higher level model). Document can contain few types of elements. To achieve this, it has a method Add, that takes a ValueElement (which is an abstract class). The problem here, is that it is not obvious what is a ValueElement. You have to know what you can put into Add method, which means, you have to know what ValueElement's children are. Their...

    C# tricks: Array initialization in C# 3.0

    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

    C# tricks: set and return in one line

    I found nice trick. Instead of writing: private string SetNewName() { string newName = GetName(); _name = newName; return newName; } you can write private string SetNewName() { ...

    Testing callbacks with Rhino.Mocks

    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: ...

    Hello World: the 'new' keyword

    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...

    Framework Tips V: Extension Methods and nulls

    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 =...

    Framework Tips IV: Check if character exists for given Encoding (CodePage)

    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...

    Framework Tips II: How to get default ANSI Encoding for given culture

    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; ...

    Framework Tips I: Clear StringBuilder

    StringBuilder is a class that allows you to manipulate strings in mutable manner. It has many methods allowing you to Append, Insert and Replace, portions of the string. However it does not contain Clear() method, that would allow you to clear the content of a StringBuilder.There is Remove(int,int) method, that allows you to do this, but it requires you to pass two parameters to achieve this. int startIndex = 0; stringBuilder.Remove(startIndex, stringBuilder.Length); There is however easier, and more elegant way to do this. Other than in case of most classes in the framework, StringBuilder's Length...

    Nullable<bool> GetHashCode() - bug or a feature?

    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 'using'

    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...

    I'm really loving new C# 3.0 features

    The more I use new C# 3.0 syntax the more I love it. I basically still use .NET 2.0/3.0 and VS 2005 at work, but at home I'm migrating to Orcas. And I have to admit that more and more, when I'm at work I wish I could use new syntax. var keyword: it's as simple as it can be, but when you get used to writing: var filteredItem = filter(item); instead of:FilteredItem<MtfModificationLog> filteredItem = filter(item); it's really hard to go back. Initially I thought that using this new keyword would make code less readable. That I would have to...

    Extension Methods "Hello World" I: Introduction

    I decided that it's about time to familiarize myself with new features of .NET 3.5 and C# 3.0. And I don't mean see an overview, because I've read many times about what's new in it, and I have basic understanding of all those new goodies that new version of framework/language brings. What I mean by familiarize is understand thoroughly and that is what this "Hello World" series (hopefully) is (hopefully) about. I'm gonna start with extension methods as this is what I've started playing with already, and then... well we'll see :) Extension Methods are a completely new concept to OOP world (at least...

    Convert int to string as hex number

    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, ...

    How do You regionerate your code?

    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...

    Fun with ?: operator

    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 ==...

    Replace text elements with Regular Expressions

    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,...

    Converting custom Strings to DateTime

    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....

    Compare paths from the end in C#

    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) { ...

    Not working ReSharper 3 and disabled menus issue resolved... kind of

    As I see, many visitors from Google come to my blog after running query like "ReSharper 3 menus disabled", "ReSharper 3 not working" and similar. Well, I have good news and bad news for you. Good news is, I installed ReSharper once again and it works now. The bad news however is, that I reinstalled Visual Studio first, so I'm aware that it may not be acceptable solution for some people. I needed to install VSIP Factory and my GAX kept throwing errors, so I got mad, uninstalled the whole thing (meaning Visual Studio and all things on top of...

    Regionerate - very cool plugin for VS and #Develop

    Today I found (via Roy's post) very nice plugin that works with both Visual Studio and SharpDevelop. It's called Regionerate, is free and is developed by Omer Rauchwerger. As Omer wrote: Regionerate (pronounced ri-jeh-neh-rate) is a new open-source tool for developers and team leaders that allows you to automatically apply layout rules on C# code.  I feel very happy to find it, since it does exactly this, what I wanted for a long time, and it's something that neither Refactor! Pro, nor ReSharper allows you to do. At the moment it's in its infancy (current version is 0.6beta) but even...

    ReSharper 3.0 final... still doesn't work

    Congratulations to JetBrains for pulling out new release of ReSharper. I hoped that it would resolve problem I had with beta release, but unfortunately it does not. Situation looks exactly like it was with beta release. ReSharper installer claims that installation was successful, but was it really?   Still, all options are grayed out, and that menu, and ReSharper logo are actually only signs of ReSharper's presence. Add-in manager in Visual Studio even doesn't list it . I reported the issue to JetBrains, but their investigation of the problem ended with one question after which they closed the case as 'Cannot Reproduce' the following...

    Updating Controls in Windows Forms

    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 ...

    Get to running application from ROT

    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>();...

    How to embed custom control in ToolStrip

    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...

    Measure code execution time

    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...

    How to get an image given its URL

    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;