... Home Contact

Krzysztof Koźmic's blog

You're doing it wrong.


Show appreciation: My Amazon.com Wish List

Me@Twitter

    Currently reading

    Article Categories

    Archives

    Post Categories

    MyPersonal

    Syndication:

    .NET

    .NET stuff

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

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

    Code generation and DRY

    I’m generally against code generation for a variety of reasons I’m not going to talk about here. However in some cases, small, targeted code generation is good, as it helps you avoid repetitive typing in verbose languages like C# without creating unmaintainable blob of poor quality code. In other words, I very much like being able to go from this: to this: by just pressing Enter.

    Ayende on Castle ActiveRecord

    I don't usually do that, but here's Ayende' presentation from last year's Oredev conference (yes, it says 2007, but it really is from 2008). It's fun, very informative if you don't know Active Record, and of surprisingly good quality (means you can actually hear what Ayende is saying, and see the code). Most of all, this is an awesome presentation. How many times have you gone to a presentation when presenter said "Give me a domain model that you want to work on" and then went and implemented it! It's a must see. Highly recommended. And if you register to viddler, you can...

    Meffing with Castle Windsor

    Patrik Hägne has an interesting post on removing compile time dependencies between assemblies, while still reaping benefits of using fluent interfaces to bootstrap AutoFac container (go read it, I’m not going to reiterate what Patrick wrote) using MEF. It inspired me to do similar thing for Castle Winsor. I created a simple solution with 3 project. One is the main application entry, which also holds a MefInstaller which we’ll talk about in a second. Second one: Services, contains interfaces that our application rely on. Impl contains implementation of these interfaces. Pretty simple huh? The...

    Comparing execution speed of .NET dynamic proxy frameworks

    A recent comment on Twitter from Tim Barcz started me thinking about alternative proxy frameworks (alternative to Castle Dynamic Proxy that is). Recently LinFu Dynamic Proxy started gaining some popularity, after it was included as one of standard bytecode providers in NHibernate. Disclaimer: To make things clear. I'm a long time user of Castle Dynamic proxy and I may be biased towards it. I also happen to know how to use it, contrary to all the other frameworks, that’s why the following test may not be realizing their full potential. If you spot...

    WPF memory leak with VisualBrush TileMode="Tile"

    Recently at work, while working on WPF GUI for our application we noticed, that our app leaks memory. After some time (actually a lot of time, since we first though that it was video codec’s fault) we nailed it, and unfortunately, it looks like it’s a bug in the WPF itself. I attach a sample application that exposes the issue. What it does is basically… blinking a rectangle. The key thing is, how the rectangle is declared: <Rectangle Name="ResultsBorder" Height="100" Width="100" Opacity="0.0"> ...

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

    The most important part of .NET 4.0 – code contracts

    There’s been about a year since .NET 3.0 along with C# 3.0 became RTM. Clearly the most publicized feature of the release was LINQ. Is it the most widely used feature? I’d doubt so. Simply because scope of it’s usage is limited and people have yet to learn how to use it properly. Personally the things I’m using the most often are ‘var’ and a feature I’ve been really skeptical about – automatic properties. Now, few weeks after announcements of what is going to be present in the next wave of .NET, Visual Studio and the language, the dust...

    Multilingual .NET applications. Enter .NET localization

    Creating multilingual applications is a huge topic. There are whole books devoted to it, and if you’re serious about it, you should definitely read those, because what you see on surface, is only the tip of an iceberg. If you only want to play with localization or need a quick reference, hopefully this post will help. Fist thing is, .NET is really well thought of if it comes to localization, so if you know what you’re doing, it’s pretty painless to create application that will be easy to translate to other languages (localization is a LOT bigger topic...

    My $0.02 on internal sealed API vs public virtual discussion

    Accidently this post hit the wave of discussion on the blogosphere regarding Microsoft’s approach of keeping very big chunks of APIs internal, sealed, or otherwise unusable by users, and backward compatibility. To some extent I can agree with both sides, because as always, the truth is in the middle, and I believe we’re talking about the solution (keeping things non-public and non-extensible) instead of the actual problem (the way API is designed, that makes a lot of useless parts public, and useful parts non-visible). One ridiculous example I saw is the IlGenerator class. It’s...

    Unity framework and the Principle of the Least Surprise

    I don’t like the Unity Inversion of Control framework. I find it too verbose, requiring user to be too explicit (except for cases where it doesn’t while it should), not intuitive and I generally don’t like its design. Unfortunately, it’s the only IoC framework I’m allowed to used at work, so I’m stuck with it, good or bad. There are times however that I’m just astonished by how it works, and mostly, in a negative sense. There’s an important principle in computer science, called Principle of the Least Surprise, that says, that framework (in particular) should have its API designed in...

    Expressions aren’t made equal

    I got surprised by Expressions last week while trying to create a caching mechanism for them. To be precise, this piece of code static void Main() { Expression<Action<string>> first = s => Console.WriteLine(s); Expression<Action<string>> second = n => Console.WriteLine(n); Expression<Action<string>> third = n => Console.WriteLine(n); Check(first, second); Check(second, third);   }   private static void Check(Expression<Action<string>> a, Expression<Action<string>> b) { ...

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

    Delegate.CreateDelegate exception with proxies

    While playing with dynamic invocation of WCF proxies I found a strange behavior with Delegate.CreateDelegate method. It throws exception when trying to create delegate for WCF proxy method. The following sample code causes the ArgumentException with message “Error binding to target method.”   private static void Main() { ...

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

    Skip generated types when performing analysis in NDepend

    Code created in more recent versions of C# has a lot of generated types, even if you don’t use code generation explicitly. Interators (the yield keyword), and anonymous delegates both use generated types underneath. Also those neat anonymous types introduced in C# 3.0 are nothing more than a compiler magic. All this may clutter your NDepend window of choice, when looking at your projects. You can however get rid of generated stuff, pretty easily, with this simple CQL query: // <Name>Types not generated by the compiler</Name> SELECT TYPES FROM ASSEMBLIES "YourAssembly" WHERE...

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

    Remove assemblies from Dependency Graph in NDepend

    Last minor version of NDepend introduced cool, interactive Dependency Graph, that was really a huge step forward as compared to static .png we got earlier. You can now load set of assemblies, and immediately see dependencies between them, without running your_picture_viewer_here. You also can drill down the dependency tree  and see dependencies between namespaces within an assembly, classes within namespace, methods within class… One thing (ok, there are more, but we’ll get to that in a minute), that I missed, was the ability to remove an element from the graph. You could do this using CQL, but this just...

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

    AnkhSVN 2.0 – Visual Studio SVN integration reinvented

    Along with Subversion 1.5 and TortoiseSVN 1.5 a new version of AnkhSVN has been released some time ago. AnkhSVN v1.x used to suffer from many issues. It was instable, used far too much resources, and had many usability bugs, that repelled many people. For version 2.0 many parts of the tool have been rewritten from ground up, and now it’s a very descent tool that you should give second chance if you abandoned it after trying out previous version. I was very pleasantly surprised by it, when I fired up my Visual Studio...

    Free ebook: “Foundation of Programming” (the ALT.NET way)

    Karl Seguin, has created, and made available for free and ebook, called “Foundation of Programming”. Don’t be fooled by its name however. If you’re thinking, “Foundation? I’m a senior level developer, what possibly could I learn from a foundation book?” and intend to pass by it, think again. The topic range spreads from Domain Driven Development, Persistence, Dependency Injection, Unit Testing, Mocking, Object/Relational Mapping to Memory Management, Exceptions and Proxies. Looks like a solid weekend read. Thanks a lot Karl! Technorati Tags: ebook, ALT.NET, Foundation of Programming, Karl Seguin

    WCF WTF (part 2)

    Here’s few things I learned the hard way, about WCF. Say you’re using sessions and you have custom behavior on your service and your session. Your session doesn’t get committed and first (or any other) message in session gets delivered over and over (or no message get’s delivered at all) – i.e. it becomes a Poison Message. You have tracing turned on, but all it says is enigmatic ‘RequestContext aborted.’ The reason for that may be that your custom behavior throws an exception, that does get caught silently, but strangely, it...

    Is Entity Framework the Pure Evil?

    I could risk saying, that Entity Framework made what ALT.NET movement is today. It was strong voice of resistance against it, that gave the impulse to action for people that started evangelizing about alternative approaches, pointing out its flaws and suggesting corrective actions. I guess to some extent this strong voice has been heard at Microsoft, but due to various reasons, not many changes have been made for v1.0 release. I’m not very surprised to see ADO .NET Entity Framework Vote of No Confidence. (Here you can see who signed it). Sure it' won’t change anything instantly, but I think that...

    WCF and custom behaviors exceptions

    I encountered interesting issue with WCF today. When calling a service method on the client side, I sometimes received fault with the following message: The message with Action 'SomeUri/Foo/Bar' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None). Turns out that this message is...

    Posting to Twitter with Launchy

    [UPDATE2] This tool has been deprecated. I leave the download links as they are, but if you want to interact with Twitter from within Launchy you better check out updated version of this tool here. [UPDATE] I uploaded a binary version of the tool, for those who don’t want/can’t deal with source code. Grab it here. I've been using Twitter for few days now, and I've tried quite a few options to use it. Currently I've settled on three different ways of interaction with the services (excluding browsing its website) When...

    ALT.NET for dummies

    ALT.NET is a wonderful movement. It's a bunch of very smart and open minded people valuing good practices and using common set of tools. It's discussion group is a great place to share ideas and ask for tips and help. It's all great, however there's one thing that bothers me. The site says: We are a self-organizing, ad-hoc community of developers bound by a desire to improve ourselves, challenge assumptions, and help each other pursue excellence in the practice of software development. It's true. However, as much as I feel strongly about patterns, practices and tools advocated by the...

    I want that in C# 4.0 (or showing spec# love)

    I don't usually do that kind of things, but now I feel obligated. Well, here's the deal: Microsoft has put together a promising set of extensions to C# called spec#, that you can read, hear, or watch about, and even download it. It's a very nice set of features like non-nullable value-type fields,  preconditions, postconditions and more. Those are very helpful features, and I want to join the movement on the blogosphere, that arose spontaneously to show Microsoft that we do care about those things and we'd love to see those features incorporated into C# 4.0. ...

    Simplifying Rhino.Mocks, Round III: kinds of mocks

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

    Static method vs instance method, Reflection.Emit and DynamicMethod

    On IL level, when you're accessing method's parameters there's a <sarcasm>small</sarcasm> difference between static and instance methods. Instance methods have implicitly 0th parameter set to this. So if you want to access your 1st parameter in instance method you have to emit ldarg.1, and in static method you have to emit ldarg.0. It's basic OO, yet it took me 2h to find out that this was the cause why my DynamicMethod was throwing NullReferenceException. I created a method that looked kind of like what I wanted my dynamic method to look like, and looked at its IL in Reflector. It...

    Mocking with Moq and Rhino.Mocks

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

    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

    Framework Tips VIII: Initializing Dictionaries and Collections

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

    Smarties - new productivity plug-in for Visual Studio

    I've missed it, but two days ago Smarties v1.0 has been released. This is a new productivity plug-in for Visual Studio, with lots of useful refactorings, and strong emphasis on managing #regions. There are quite a few screencasts on the website, so better go and check them out for yourself. The tool is not free, but very reasonably priced, and there's a trial version. Highly recommended. Technorati Tags: Smarties, Reafactoring tools, Productivity tools

    Is Subtext project... dead?

    I've been using Subtext for this blog since its very beginning 10 months ago. Back then I installed what was the latest version (1.9.5 with later security-fix). I was pretty happy with it. I don't have high needs: it is supported by Windows Live writer, is stable and just works. However I've been receiving emails from people complaining that they cant post comments to my blog. I checked the issue, and I was able to reproduce it, with error message presented on the screenshot. I googled for it, but I didn't find out anything useful. I decided to upgrade my...

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

    ReSharper 4.0 EAP... you said what? January?

    January came and went, and much anticipated ReSharper 4.0 Early Access Program is still not available. It seems, that we'll have to wait another two weeks, before I stop turning off ReSharper every time I want to write something using new C# 3.0 features. What bothers me however is that, although I do understand the vastness of the tool, I'm more and leaning towards agreeing with Alan's comment on a recent post. C# is getting bigger, .NET is getting bigger, and it looks like JetBrains starts having troubles to keep up. I hope I'm wrong. Technorati Tags: ReSharper, EAP, C#...

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

    Linkz: Continuous Integration - how to...

    Carel Lotz has published updated version of his great "Continuous Integration: From Theory to Practice" guide. Updates include: Updated to use VS 2008, .NET 3.5 and MSBuild 3.5 (including new MSBuild features like parallel builds and multi-targeting). All tools (NUnit, NDepend, NCover etc.) are now stored in a separate Tools folder and kept under source control. The only development tools a developer needs to install are VS 2008, SQL Server 2005 and Subversion. The rest of the tools are retrieved form the mainline along with the latest version of the source code. Added the CruiseControl.NET configuration (custom...

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

    Regionerate your life

    After much waiting (two and a half months!). Rauchy released the new version of his great tool Regionerate. New version brings many changes and bugfixes: You can now choose how you want custom (created by Regionerate) regions to differentiate from other regions, by specifying custom prefix, wrapper, or usage of high ASCII character looking like space (read more here). Older versions of Regionerate were leaving fragments of source code embedded within regions not created by Regionerate (not having Regionerate' prefix to be exact) intact. Now you can make it also look into those regions (and remove them, putting their...

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

    NDepend - take high level view at your projects

    In order to avoid accusation for doing crypto-advertisement, I honestly admit, that I have received for free professional licence for NDepend (worth EUR 299) from Patrick Smacchia (dev lead and inventor of the tool). It's kind of weird - I knew about the tool for some time, I even once downloaded its free version, but I got lost when I saw its interface and I didn't actually play with it much then and I ended up thinking that it's another crazy/fancy tool for PMs or whoever and I didn't really see how I might benefit from using it. Then...

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

    Technical books and blogs

    I've just listen to new .NET Rocks podcast with Don Box, and Chris Sells about, well - about myriad of things, but main topic was technical books and ways of learning new technologies. They mostly focused on shrinking market of books, as blogs become more popular and people gain their knowledge from blogs more and more and less from books. However, I thing there is one difference that they barely touched, although it's the most important one. There will be place for books, and not only as a way to get the zen of a technology, but as a...

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

    Bug in UTF8Encoding class?

    As I work at translation/localization company, I deal a lot with files with different code pages, and strange formats. While working on a project recently I stumbled across strange thing, that I think is a bug in UTF8Encoding class. I was reading a plain text file, encoded with Windows 1252 code page, using FileStream and StreamReader. Everything was working fine, but I noticed that when reading one particular file, program produced strange results. TO be precise when reading file with string like this:   Results looked like this: StreamReader ate up umlaut characters. When file was saved as UTF8...

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

    Acropolis team on Dot Net Rocks

    Microsoft project Acropolis is creating a lot of buzz lately. Actually more than I would have expected, which is a good thing. I am only surprised that there are no non-Microsoft samples yet. When Silverlight (WPF/E back then) was first introduced, there were some really stunning samples made the very next day. I guess it's just because, Silverligh mostly about what you see, while Acropolis is about what you don't see. Guys from Acropolis team have been recently very busy blogging, and posting new samples. As a matter of fact they've produced so much content, and I have been so busy...

    Install SCSF v2 without having VB solution installed

    When Smart Client Software Factory v2 came out, I couldn't install it on my machine, because I didn't have VB solutions installed with Visual Studio. P&P team published a solution to this. I didn't check it yet, but it should work, although it looks like a lot of hassle to get it to work. Technorati tags: SCSF, P&P, Visual Studio, VB

    Why not support SharpDevelop?

    In his great post about ORMs, EF, eSQL and data access in general, Sahil Malik wrote something about Visual Studio 2005, that I would like to comment on. The VS2005 IDE is stuck in a rather unfortunate monopolistic situation. There is no incentive for any other company to create a better IDE because the IDE costs some serious $$$ to create, and MSFT gives it away for peanuts. It is impossible to compete with such a model, so I don't expect google or adobe to come out with a Visual Studio.NET that is better.  And I...

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

    Acropolis Hello World

    Yesterday I gave Orcas Visual Studio 2008 beta 1 another try. At first, when it came out, I deleted it, due to free hard disc space shortage, and it's annoying errors. I actually downloaded it (which took me almost entire day on my 1.5Mb wire) solely to play with new Acropolis bits. I don't have anything interesting to share yet, since I finished installation and VM Setup quite late, but I must say that my first impression is very nice. I’m a little bit confused by the Visual Studio Designer, that is like nothing I know from CAB and SCSF,...

    Acropolis to replace CAB/SCSF

    I like CAB and SCSF, I really do, although I'm by no means expert at it, I used it in one, not so big project so far, when I moved over the hard part (getting used to naming conventions and getting to know how the things are organized and how they fit together) I really liked it. When I learned about Acropolis I got the feeling that Microsoft just said: "This is the way you are supposed to do smart client applications", and that it means good bye to CAB. Glenn Block just said it clear and loud: With the announcement of Acropolis, we currently...

    Visual Studio 2008 Shell and Sharp Develop for Applications

    The think that drew attention in last couple of days is the new Visual Studio 2008 Shell. What it is, is basically bare bones core of Visual Studio that Microsoft is going do release (for free I believe) , so that you could build your own VS-like Apps on top of that. Nice idea isn't it? That's something that Eclipse has been allowing for some time now, and as I just learned, Sharp Develop too. I found this, almost one year old post from Sharp Develop dev team, announcing Sharp Develop for Applications, that utilizes the same idea. Technorati tags:...

    Microsoft vs Jamie Cansdale's TestDriven.NET case is getting famous

    It seems that Jamie Cansdale's case is attracting attention not only in .NET world. Today I noticed that biggest Polish IT news portal dobreprogramy.pl published a news about it entitled "Microsoft sends out lawyers to community". It's good that case is getting famous, because it may trigger wider debate about vague software licenses. Technorati tags: Jamie Cansdale, TestDriven.NET, Microsoft, Work Around Technical Limitations

    My 3 cents about ALT.NET; do it Microsoft way vs do it the right way

    David Laribee coined the term ALT.NET. What it means, and why it's going to be the_hot_word? David basically explained it in 4 points: What does it mean to be to be ALT.NET? In short it signifies: You’re the type of developer who uses what works while keeping an eye out for a better way. You reach outside the mainstream to adopt the best of any community: Open Source, Agile, Java, Ruby, etc. You’re not content with the status quo. Things can always be better expressed, more elegant and simple, more mutable, higher quality, etc. You know tools are great, but...

    Get ready for Acropolis!

    I've been concerned that CAB since its 1.0 release seemed to be a dead project, although there certainly was a lot to do. P&P team focused on other things like software factories, leaving CAB as it was. I guess we now have the answer why. Microsoft announced (and released 1st CTP of) project Acropolis. It looks like CAB for WPF on steroids, and may be the-hot-thing in desktop development. There's a crappy quality screencast up on this site. Basically project is announced but still I couldn't find many information about it. Is it going to be integrated with Orcas, or...

    ReSharper 3.0 beta... gone?

    It seems like I may not be able to play with ReSharper after all, at least not until I find a solution to this: After installing ReSharper 3.0 beta, onto previous build, ReSharper seems to be disabled. First, I had Two ReSharper menus, both with all options disabled like here. After I Removed ReSharper, Rolled back my VS settings to state before installing ReSharper and installing it once again, Nothing changed except for the fact that instead of two dead menus I have one. Any solution? (other than reinstalling VS ). [UPDATE] It seems I'm not the only one having this problem after installing beta version....

    ReSharper

    I probably shouldn't even admit but: 'I haven't been using ReSharper'... I mean, never before. And before you ask - no, I haven't been on a remote island for last X years. I actually knew that there was such a tool, I simply didn't realize how great it is! It was Jean-Paul S. Boodhoo's series of screencasts on Demystifying Design Patterns, on DNR TV, that made me like - 'Wow, that's a great tool he's using' (he actually does more ReSharper magic that actual coding in these screencasts , but that's OK - J.P - great series by the way,...

    Krzysztof Cwalina's great lecture available to download

    You know who Krzysztof Cwalina is - right? The Framework Design guy. He recently gave a lecture on that topic at Microsoft Research center, and now he made it available for download. I haven't seen it whole yet (it's iver 3h long!) but i strongly recomend it. Get it here, and if you didn't already - subscribe to Krzysztof's blog: here.   Technorati tags: Krzysztof Cwalina, .NET, .NET framework, design, lecture, Microsoft

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

    SCSF May 2007 is out!

    Smart Client Software Factory v2 (aka May 2007) is out. You can read more about it in David Hayden's post. Nice new feature is 'Check dependencies'. Basically it allows you to see, whether you have installed all required products, and if you don't it will provide you with a link to download page. Unfortunately I was unable to install this factory. During installation I received following error message: I guess it's because I don't have VB part of my Visual Studio installed. Unfortunately you can't uncheck installing VB support so I'm afraid my only option is to add...

    Roy Osherove vs. Oren Eini discussion about VSTS, TFS and OSS alternatives.

    There is a very interesting discussion going on between two great Israeli blogers: Roy Osherove (a.k.a. ISerializable) and Oren Eini (better known as Ayende). It started with Roy's post, that his company is looking for a developer experienced in VSTS. Then Oren pointed out why he would avoid Visual Studio Team System. In response Roy wrote a post explaining his choice of VSTS. It didn't take long for Oren, to write a response, where he basically said, that all what Roy wrote above (and more) can be accomplished with other - free tools. As a result, Roy wrote a great post about...

    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;