Tom Fischer

  Home  |   Contact  |   Syndication    |   Login
  14 Posts | 0 Stories | 25 Comments | 0 Trackbacks

News

Archives

Post Categories

.NET Framwork

TFS

Tools

Visual Studio

Wednesday, August 11, 2010 #

I finally decided to move to my own site:

http://tomafischer.com/

I moved most of the blog entries to the new site.

Please update your RSS feeds.

Thanks

Tom


Wednesday, October 29, 2008 #

Hi all,

People were asking why I did not post anymore.... Here is the exiting answer:

My wife and me had our second daughter!

Welcome Katja!

We are totally thrilled and sooooo happy!

Tom

 


Tuesday, September 30, 2008 #

After moving a branch from one TFS server to another I got the error:

"The item \$TFSProject\mylocation\myfile.cs does not exist at the specified version".

First I thought the Check in was buggy and went to another machine. And like a miracle it worked there.

Then I googled and found out that this usually relates a messed up workspace.

Especially the following link was very interesting:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2367863&SiteID=1

But this was not my problem.
I had two Visual Studios (2008) open. 
Inside one instance I used the Team Explorer to disconnect from one TFS server and connected to another TFS server without closing the second instance or restarting VS.
I guess the TFS integration in VS got confused and was choking.

So I restarted VS and everything went back to normal.

Sometimes a simple restart does the trick. But at least I learned about how to delete your workspace :-)

Tom


Monday, September 29, 2008 #

I am sorry this is not a C# blog today. I am still in TFS land :-)

Recently I was talking to different people about when to create a new TFS project or reuse an existing one.

Here is what I got out of the conversations:
- Too many projects slow down the server and are hard to maintain.  (Depending on the project type, TFS 2008 has an upper limit of around 200 - 500 projects)

- Security on too many projects can be very hard to maintain (especially keeping track of current permissions, removing expired permissions, etc.)

- Using the built-in TFS Groups in TFS is usually enough. Add NT accounts/groups manually to certain permissions if you have to.

- If the intent of adding a project to TFS is simply to have Source Control, try to stick it into a group specific (generic) TFS project. Move it later if necessary.

- If you don't know exactly how much project management will be included or how big the project will be, stick it in a current TFS project and move it later.

- Moving Source control Items from one TFS project to another works great and is very easy. The history is still searchable.

- Moving Work items is super tricky and should be minimized. See  http://blogs.msdn.com/granth/archive/2008/06/26/how-to-move-work-items-between-team-projects.aspx

- Separating Source Control and Project Management causes more work, because you have to modify the default queries.

- IF you need exclusive permissions for the same user => new TFS project

- IF you need different Template => new TFS projects 
 

See  http://msdn.microsoft.com/en-us/library/ms242894.aspx for a more thorough analysis.

I hope this might help you.
Tom

P.S.: Special thanks to Scott, Robert, and Jeevan for all your input and being a great sounding board!

 


Monday, September 15, 2008 #

Using() Statement in 3 seconds and a bug in Reflector

The boring, known accross the board definition from the MSDN site:
Defines a scope, outside of which an object or objects will be disposed

The more interesting definition from Tom:
The using() Statement generates a try{} finally{ //virtual call of the dispose method } block with null check!

Let's take a deeper look.

Let's write two test methods first:

//Testmethod for Using   
public static void UsingTest()
{
    using (SqlConnection con = new SqlConnection())
    {
        con.ConnectionString = "Test Connection";
    }
}

//TestMethod for try finally
public static void TryFinallytest()
{
    SqlConnection con = new SqlConnection();
    try
    {
        con.ConnectionString = "Test Connection";
    }
    finally
    {
        con.Dispose();
    }
}

Note: The TryFinallyTest() method has no null check inside the finally block. This means in case con is null the function would throw a Null Reference Exception. The UsingTest() method does not.

When you compile both methods and look at them disambeled in Reflector they both look exatly the same:

public static void UsingTest()
{
    using (SqlConnection con = new SqlConnection())
    {
        con.ConnectionString = "Test Connection";
    }
}

public static void TryFinallytest()
{
    using (SqlConnection con = new SqlConnection())
    {
        con.ConnectionString = "Test Connection";
    }
}

But looking at the IL (see below) reveals a very important difference:
-  Frist both get translated into a try{} finally {} block. (see IL code below). This is what we expected
The using(){} statement adds a null check before calling the dispose method inside the finally.
-  The compiler did not add a null check for the TryFinallyTest method (as intented)

The Problem:
The TryFinallyTest method gets disasembeld from IL into C# (or VB) by using a using() statement .
This is not correct because a using() statement has a null check before calling the dispose() method.
This means the disasembled C# code does not relfect the IL correctly.

Here is the IL code for the UsingTest() method:

.method public hidebysig static void UsingTest() cil managed
{
    .maxstack 2
    .locals init (
        [0] class [System.Data]System.Data.SqlClient.SqlConnection con,
        [1] bool CS$4$0000)
    L_0000: nop 
    L_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlConnection::.ctor()
    L_0006: stloc.0 
    L_0007: nop 
    L_0008: ldloc.0 
    L_0009: ldstr "Test Connection"
    L_000e: callvirt instance void [System.Data]System.Data.Common.DbConnection::set_ConnectionString(string)
    L_0013: nop 
    L_0014: nop 
    L_0015: leave.s L_0027
    L_0017: ldloc.0     
    L_0018: ldnull  
    L_0019: ceq 
    L_001b: stloc.1 
    L_001c: ldloc.1 
    L_001d: brtrue.s L_0026    //Nullcheck
    L_001f: ldloc.0 
    L_0020: callvirt instance void [mscorlib]System.IDisposable::Dispose()  //dispose call
    L_0025: nop 
    L_0026: endfinally 
    L_0027: nop 
    L_0028: ret 
    .try L_0007 to L_0017 finally handler L_0017 to L_0027
}

Note: L_001d: brtrue.s perfoms the null check. In case con is null it jumps directly to the endfinally. This means in case con is null there is no Null Reference Exception

Here is the IL code for the TryFinallyTest method:

.method public hidebysig static void TryFinallytest() cil managed
{
    .maxstack 2
    .locals init (
        [0] class [System.Data]System.Data.SqlClient.SqlConnection con)
    L_0000: nop 
    L_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlConnection::.ctor()
    L_0006: stloc.0 
    L_0007: nop 
    L_0008: ldloc.0 
    L_0009: ldstr "Test Connection"
    L_000e: callvirt instance void [System.Data]System.Data.Common.DbConnection::set_ConnectionString(string)
    L_0013: nop 
    L_0014: nop 
    L_0015: leave.s L_0021
    L_0017: nop 
    L_0018: ldloc.0   //it loads con and calls directly dispose in the next line. No null check
    L_0019: callvirt instance void [System]System.ComponentModel.Component::Dispose()
    L_001e: nop 
    L_001f: nop 
    L_0020: endfinally 
    L_0021: nop 
    L_0022: ret 
    .try L_0007 to L_0017 finally handler L_0017 to L_0021
}

Note: Inside the the finally block the IL loads con on the Excution Stack and calls dispose() directly without a null check. In case con is null, an Null Reference Exception is thrown.

 

So, what to use? Using() or try{} finally{}?
Well, usually I would recommend using Using(), so you don't have to remember the null check.
But if you have multiple using inside eachother I would rather use one try{} finally{}.

If you don't know (or if you are too lazy to check)  if your object implements IDisposable you can always use the following pattern to be on the save side:

public static void ObjectAsDispose(SqlConnection con)
{
    using (con as IDisposable)
    {
        con.ConnectionString = "Test Connection";
    }
}

I hope you enjoyed this one again.

Tom

P.S.: Thanks Ian for reminding me to add the safty pattern for using!


Friday, September 12, 2008 #

C#, Events and Delegates as an Elevator Pitch - Or in 3 seconds

Here are the elevator pitches you should know about events and delegates:


   A Delegate is a (or collection of) strongly typed FunctionPointer(s)

   An Event is a wrapped Delegate 
 

But to be honest this is not big news and not the reason for this blog. I thought this would make a nice starter... Like when you go for a nice dinner.  Today I had the chance to look under the hood and I was astonished to see what really happens. This made me think... hmm sounds like an interesting post for Friday afternoon. (Thank you Mark!)

So let's take a second to verify the second statement. An Event is a wrapped Delegate:

First we define an Event and subscribe to it:

//Test class with the event
public class TomsEventClass
{
    public event EventHandler ItsTomTime;
}

//test program
class Program
{
    static void Main(string[] args)
    {
        TomsEventClass tom = new TomsEventClass();
        tom.ItsTomTime += tom_ItsTomTime;
    }
    static void tom_ItsTomTime(object sender, EventArgs e)
    {
       //let's see what we can do it
    }
}

But what was actually generated by the compiler? Let's use Reflector to look at the IL

The Event gets translated into one private delegate:
.field private class [mscorlib]System.EventHandler ItsTomTime

... and into two public methods to add and remove Subscribers:
.event [mscorlib]System.EventHandler ItsTomTime
{
   .addon instance void ConsoleApplication3.TomsEventClass::add_ItsTomTime(class [mscorlib]System.EventHandler)
   .removeon instance void ConsoleApplication3.TomsEventClass::remove_ItsTomTime(class [mscorlib]System.EventHandler)
}

And when we subscribe we see we actually call the generated add_ItsTomTime method:

 callvirt instance void ConsoleApplication3.TomsEventClass::add_ItsTomTime(class [mscorlib]System.EventHandler)

That's it!

I have to admit, even knowing that events where restriced delegates I never took the time to really look under the hood.
This won't make me a better programer but it is fun to know (at least for a Geek on geekswithblogs :-)

Tom


Wednesday, September 10, 2008 #

C#: The difference between out and ref.

Today we had an interesting discussion about out and ref in C#.

Here is a very quick elevator pitch summary:

The MSDN documentation (http://msdn.microsoft.com/en-us/library/t3c3bfhx(VS.80).aspx">http://msdn.microsoft.com/en-us/library/t3c3bfhx(VS.80).aspx) is very good on that and it says:
"The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed."

This means inside your method implementation which takes an out parameter you have to set a value before you can use it. At least you have to assign a value before you can return.
This also means you can not use the out paramter to pass a value to the method. (With ref you can)
This also means you can not have any logically includes comparison (e.g. if(param>0 ){ ...}) inside your method before you assign a value to your incoming parameter (I know this sounds weird).

Also nice to know:
"The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument."

To see the difference in IL, I used Reflector to see how the IL looks like for out/ref  on Value Types (in my case int32):

out:
[out] int32& result

ref:
int32& result

Remarks:
- Most of the Framework functions (e.g. TryParse) use out and not ref  (which was surprising to me). But inside the internal implementation the Framework mainly uses ref.
- Properties can not be passed via out or ref. (Under the hood they are function calls)
- It is very handy if you have several Value Types as return values and you don't want to create a class or struct.

 


Thursday, September 04, 2008 #

C# (or .NET): Primitive Types, Value Types, Reference Types and System.ValueType.

I think this is one of the most important topics in .NET, but it is interesting to see what kind of misunderstandings are out there. Even with programmers who have used .NET for years.

DISCLAIMER 1:
The goal of this blog entry is not to give another in depth, all-encompasing overview - but rather a summary of the conversations I've had with people and a summary of some confusing MSDN documentation. Also I won't address the issue of what to use when and the wonderful side effects (which is indeed very important to understand but I'll leave it for another time). There are really good articles out there that do a way better job than I could anyway. Click here for one of them.

But let's get back to business here...

In the following I will refer to one MSDN article as MSDN. You can find it  here.

DEFINITIONS (based on MSDN):

Primitive Types:
MSDN: Any data types directly supported by the compiler are called primitive types
TOM: e.g. int->System.Int32, long -> System.Int64
Complete List of Types: http://msdn.microsoft.com/en-us/magazine/bb984984.aspx

Value Types:
MSDN (on top of the page): A type declared using struct is a Value Type

Reference Types:
Types declared using class are reference types.

Hence:

RESULT 1: A primitive Type is not the same then a Value Type! (I don't know how often I heart people saying that they are. Including me in the past :-)

QUESTION 1: What about Enum? Aren't they Value Types too?

QUESTION 2: How do we test for Value Types?

ANSWER 1: The MSDN article gives a well known answer a little bit later:
Value types are implicitly derived from  System.ValueType !

QUESTION 3: Are structs derived from System.ValueType too? I thought they are "the" Value Type by Definition?

Before we answer question 3, let's answer question 2 and use it as a springboard to answer this.

ANSWER 2:
Test for Value Type (according to ANSWER 1). Click here for details.

if (x is ValueType) { //yep x is a Value Type }

Now let's use answer 2 to answer question 3:
(I hope you are totally confused about all the questions and answers by now :-)

public struct TomStruct
{
public string First { get; set; }
public string Last { get; set; }

public override string ToString()
{
return First + ", " +Last;
}
}



TomStruct p1 =
new TomStruct() { First = "Tom", Last = "Fischer" };
if (p1 is System.ValueType)
{
Console.WriteLine(
"TomStruct derives from System.ValueType");
}

And as we suspeceted the output verifies that struct (or Enum) derives from ValueType!

So let's try a new Tom Definition for ValueTypes:

DEFENTIION for Value Types:
Every type, deriving from  System.ValueType is a Value Types. This includes types defined via struct or enum .

(I bet now I forgot a type here:-) But at least this Defintion does not exclude it :-) You gotta love logic!

I hope you had some fun with me here. Sometimes the most basic stuff is the easiest to get confused about :-)
Looking forward to reading lots of comments,

Tom

 

Friday, August 29, 2008 #

ToString() and the underestimated IFormattable

Everyone knows you always should override the ToString() function on you custom objects. But most programmers (including me until yesterday) leave it there.

I ran into a problem these days where I wanted a specific xml representation and a tap separated representation of the same custom object. The "experienced" programmer would just write their own format function. But it felt more old fashion and not quite OO like.

And then I read the Tip 5 in the book Effective C# programming - and it change my life again (there is lot's of life changing going on :-)

I totally agree with Scott Meyers about IFormattable but I have a slightly different approach for implementing, which makes it even easier to read (at least from my perspective)

So what is IFormattable? IFormatProvider? ICustomFormatter?  Why are there so many?

The quick answer is: Don't worry about IFormatProvider or ICustomFormatter for most of your stuff.

Implementing IFormatProvider via the pattern described below is all you will need...  usually!

When you implement IFormattable you have to implement one function (hurray that's it):

public string ToString(string format, IFormatProvider formatProvider)
You can use
- either only the first string parameter  (then you have access to all your private/protected members)
- or pass you own implementation of how you want to have it formatted. (Then you only have public members available)

I personally think for most of the cases the first option is easier and good enough. But it was fun yesterday to play around with the implementation of IFormattable. First it was not straight forward but after getting to know it (especially realizing the pattern the .NET team chose to use)- it is pretty cool (Ended up being a Factory Pattern)

Here is the code for a simple class which implements IFormattable.

public class TomType : IFormattable
{
public virtual string Name { get; set; }
public string First { get; set; }

public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider != null)
{
ICustomFormatter fmt = formatProvider.GetFormat(
this.GetType()) as ICustomFormatter;
if (fmt != null) { return fmt.Format(format, this, formatProvider); }
}
switch (format)
{
case "a": return First + ", " + Name;
case "first": return First;
case "G": default: return Name;
}
} }

Note: First we check if the consumer wants to use a custom formater or if we just want to use our internal formating option. Simple but very effective.

The case statement is the actual place where all the "magic" happens.
Note: Make sure that there is always an implementation for G. In my case I use the default in the switch, so I could have skipped it.

This already solved my problem with the two ToString() Implementations I needed: plain and xml

But let's look at the more fancy way and see how a custom Formatter works.

The implementation of  IFormatPorvider is like the name says a provider aka "Factory Pattern". You choose the actual Formatter (worker) class, depending on the calling Type. In our case the implementation of IFormatProvider checks for our Type (TomType) and returns an instance (a "Singleton Pattern" could also be instead) of the actual implementation: TomsCustomFormatter:

public class CustomFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(TomType))
{
return new TomsCustomFormater();
}
return null;
}
}

public class TomsCustomFormater : ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
TomType t = arg
as TomType;
if (t == null) { return arg.ToString(); }
return "TomsCustomFormater: " + t.First + ", " + t.Name;
}
}

If we run a little demo now:

static void Main(string[] args)
{
TomType t =
new TomType() { Name = "Fischer", First = "Tom" };

Console.WriteLine(t.ToString(
"a", null));
Console.WriteLine(t.ToString(
"first", null));
Console.WriteLine(t.ToString(
null, new CustomFormatProvider()));
}

We will get the expected result:

Tom, Fischer
Tom
TomsCustomFormater: Tom, Fischer

That's it. I hope you enjoyed this as much as I did it when I stumbled over it

Tom


Wednesday, August 27, 2008 #

Why it is time to retire the old cast operator in C#:  MyType t= (MyType)o

 These days I am reading the book "Effective C#: 50 Specific Ways to improve C#" by Scott Meyers. After using C# for many years, you get into the mindset: "I know everything already". But this book really inspires me to rethink the basics I am using every day and make a step forward in sharpening my C# skills.

The goal of these blog series is not to copy the book but write down my thoughts in a compressed way on certain topics. So when I will wonder in the future "Why am I doing this" I can just come back and re-read it and also maybe for you guys who don't have the time to give you a quick overview of the little things we use everyday without knowing.

So enough talk time for the topic:
Why is it time to retire the old cast operator in C#

Don't get me wrong there are reasons (maybe 0.05%) but it is time to explore the better casting options we have in C#:

is, as and typeof are the new heroes!

So what is the big difference in a nutshell:

is compares if an object is of specific type and returns true or false.  Every is operator could be replaced with
as will attempt to cast it into the specific type and returns either the type or null
typeof checks if the actual type of the object (A comparison of a derived type does not match the parent type)

But let's have a look at some code:

First same basic class definition:

public class DeriveTomType : TomType
{
public int Age { get; set; }
}

public class TomType
{
public virtual string Name { get; set; }
}

Now the actual test code:

object o = new DeriveTomType();

if(o is TomType)
{
Console.WriteLine(
"is: o is TomType");
}
//no try catch required. If cast fails, t will be null. //No exception thrown
TomType t = o
as TomType;
if (t != null)
{
Console.WriteLine(
"as: o is TomType");
}
//the same in one line: t = null;
if ((t = o as TomType) != null)
{
Console.WriteLine(
"as Replacement: o is TomType");
}

if( o.GetType()!= typeof(TomType))
{
Console.WriteLine(
"GetType: o is not TomType");
}

And the result is

 is: o is TomType
as: o is TomType
as: o is TomType
getType: o is not TomType

The interested reader might think: "Wow this is cool. But why should I not use the cast operator anymore again?"

And the quick answer is:
- No try catch required => Easier on the CLR (this is the main reason)
- Easier to read code  (very important to me)

I know there is more to it, but for this blog entry I think this is good enough.
Otherwise I would contradict my intention: Keep it short AND GOOD ENOUGH!

Tom