Tag Archive for 'c#'

C#: How to get service name listening at specific port number?

How to get service name listening at specific port in C#? What you have as input is only two pieces of information: host name and the port number the service is listening at.


Apparently, .NET does not provide such feature so one needs to stretch a bit to get the answer. What I can suggest (I’m far from saying it’s good approach, though) is to get the name in two steps:

  1. Use netstat -a -o and parse the output (ouch!) to get ID of the process (PID) that is listening at given port number
  2. Perform a WMI call to get the name of the service: SELECT Name FROM Win32_Service where ProcessId = PID

Following this will give you what you want, but to be honest any time I need to parse output to get some information I feel anxious… This is the first place in the code where errors can be introduced.

If there is/are better/safer way(s) to retrieve service name having the host name and port it’s listening at, please share it.

Book review: LINQ Unleashed for C#

linq unleashed Book review: LINQ Unleashed for C#

I find this book relevant and very informative. If you want to master LINQ lingo, just read it.

For broader evaluation see my review on DZone.

P.S. DZone’s IT Book Zone is another great initiative. In short DZone gives you a free copy of a book and expects to receive its review in return. Fair agreement – one can stretch the envelope of IT domains for free, while DZone broadens thier public resources.

C#: GetHashCode() might cause OverflowException

Microsoft recommends if you overload Equals method you should also overload GetHashCode. Now, how to properly implement GetHashCode? There are many resources on the web that describe it. A good starting point might be this article on Stack Overflow.

Following MSDN guidlines GetHashCode must fulfill these requirements:

  • If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
  • For the best performance, a hash function must generate a random distribution for all input.
  • The hash function must return exactly the same value regardless of any changes that are made to the object.

Sticking to first bullet, you (probably?) should consider the same fields in Equals and GetHashCode methods. Let’s have a look at the example in which I did so:

public class Contact
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override bool Equals(object obj)
        // If parameter is null return false.
        if (obj == null)
            return false;

        // If parameter cannot be cast to Contact return false.
        Contact c = obj as Contact;
        if c == null)
            return false;

        // Return true if the fields match:
        return ID == c.ID 
            && FirstName == c.FirstName
            && LastName == c.LastName;;

    public override int GetHashCode()
        return ID.GetHashCode()
            + FirstName.GetHashCode()
            + LastName.GetHashCode();

Now, what is wrong with this example of GetHashCode? There’s one drawback here. The hash is calculated as a sum of three integer values, which might give a value that is greater than int.MaxValue and that will result in OverflowException.

Continue reading ‘C#: GetHashCode() might cause OverflowException’

Comparison of .Net libraries for fetching emails via POP3

Sending emails in C# is easy; for basic use cases you don’t need external resources to send a note because .NET BCL already ships it. On .Net Developer Center, there’s a short description how to do it.

Now, how to fetch the email? It turns out it is not that easy – it’s not supported by .Net BCL. I spent a while researching for the best library that matched my purposes and I want to share my views on a couple of components I looked at.

Note: Please bear in mind I was interested only in a small piece of functionality such library could provide. My need was only to fetch an email (in plain text) with attachments. That was supposed to be done via POP3. I was not really interested in features like advanced sending emails (e.g. email templates), request and delivery receipts, support for iCalendar, email in HTML, etc. To sum up, I did not test libraries from that angle and therefore this comparison will not suit needs of all developers.

Continue reading ‘Comparison of .Net libraries for fetching emails via POP3′

An attempt was made to load a program with an incorrect format. Exception from HRESULT: 0x8007000B (BadImageFormatException)

Note: I assume you can rebuild the program you are having problems with because changes in its configuration settings are required.

If you are struggling with this problem you are probably running 64bit OS and executing 64bit exe that loads 32bit dll, or the other way – 32bit OS on which 32bit exe tries loading 64bit dll. For the sake of this post, let’s assume this is the former matter.


You need to assure that 32bit dll is loaded by the program with the same bittness, even if it’s running on 64bit platform.

In order to achieve that you need to change the configuration settings of the project whose outcome is that exe so that platform target is always x86, disregarding configuration platform. Let’s assume that program is written in C#.

Open project’s properties, go to Build tab and make change as below:

cs project settings 350x140 An attempt was made to load a program with an incorrect format. Exception from HRESULT: 0x8007000B (BadImageFormatException)

How to invoke a common coded web test method from GetRequestEnumerator()?

It’s a fact that coded web test methods give more flexibility to the developer, i.e. common code reuse. So let’s create a coded web test in whose GetRequestEnumerator() method you want to call a common method which tests some other requests. Let’s make it look as GetCommonRequests() in the example below:

public class AWebTest : WebTest
    private IEnumerator<WebTestRequest> GetCommonRequests()
        WebTestRequest req1 = new WebTestRequest("http://google.com");
        yield return req1;

        WebTestRequest req2 = new WebTestRequest("http://google.com");
        yield return req2;

    public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        WebTestRequest req = new WebTestRequest("http://google.com");
        yield return req;


You would expect to see three requests in the test result. You will see only one though…

Continue reading ‘How to invoke a common coded web test method from GetRequestEnumerator()?’

How to quickly add logging to a coded web test?

A coded web test, as opposed to a basic web test, brings more flexibility to the developer: conditioning, looping, code re-usage, etc. If you haven’t created one yet, you can follow an instruction on MSDN.

Now, because a coded web test can have some logic inside, it makes sense to add logging so that there’s a trace on what’s going on while it executes.

Continue reading ‘How to quickly add logging to a coded web test?’

Robust generation of XML documentation comments for C#

Writing comments is something you need to get used to; sooner or later you will understand it’s worth writing comments. Haven’t you find yourself in a sitation where you don’t understand what a couple of lines of YOUR OWN code do? I have…

XML documentation comments are also important, particularly for public members/methods. Even if your project doesn’t require generating full XML documentation of the code, using Intellisense can be much more effective if it summarizes the method you are trying to use. If you want to generate XML documentation for C# in the twinkling of an eye you MUST install Roland Weigelt’s GhostDoc plugin for Visual Studio. Let me cite the author:

Continue reading ‘Robust generation of XML documentation comments for C#’

Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for XXX —> NHibernate.Exceptions.GenericADOException: could not delete collection

The beginning of the stack trace I got today looked as below:

2009-05-19 11:01:45,078 ERROR [5232] XXX - Speaker already deleted: Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for Speaker ---> NHibernate.Exceptions.GenericADOException: could not delete collection: [XXX#XXX][SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'SpeakerId', table 'XXX.dbo.lnk_Session_Speaker'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
   at SpeakerProxy3e9fd3b0e82745c2b91b8a353acaa93d.DeleteAndFlush()


I had three tables and classes representing them: Session / app_Session, Speaker / app_Speaker, and SessionSpeaker / lnk_Session_Speaker.

Continue reading ‘Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for XXX —> NHibernate.Exceptions.GenericADOException: could not delete collection’

C# 3.0 Pocket Reference: Instant Help for C# 3.0 Programmers

For those who work with C# I’d like to recommend a book which is a kind of summary of knowledge on C# 3.0. The book is quite short (and small by the way – yet pocket reference) but it covers lots of details on C# and describes what’s new in C# 3.0. Everything in short and simple, with code snippets.

I read this book as a first step towards TS: Microsoft .NET Framework – Application Development Foundation. Basically, I’ve started wondering if passing this exam is not a good step in my .NET career and this is the entry point.

Anyway this book is not a C# bible, but it can really help as a knowledge reresher.


 C# 3.0 Pocket Reference: Instant Help for C# 3.0 Programmers