Best .net questions in March 2012

What is the proper way to check for null values?

91 votes

I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.

 int y = x ?? -1;

That's great, except if I need to do something simple with x. For instance, if I want to check Session, then I usually end up having to write something more verbose.

I wish I could do this:

string y = Session["key"].ToString() ?? "none";

But you can't because the .ToString() gets called before the null check so it fails if Session["key"] is null. I end up doing this:

string y = Session["key"] == null ? "none" : Session["key"].ToString();

It works and is better, in my opinion, than the three-line alternative:

string y = "none";
if (Session["key"] != null)
    y = Session["key"].ToString();

Even though that works I am still curious if there is a better way. It seems no matter what I always have to reference Session["key"] twice; once for the check, and again for the assignment. Any ideas?

What about

string y = (Session["key"] ?? "none").ToString();

Are there any cases when it's preferable to use a plain old Thread object instead of one of the newer constructs?

72 votes

I see a lot of people in blog posts and here on SO either avoiding or advising against the usage of the Thread class in recent versions of C# (and I mean of course 4.0+, with the addition of Task & friends). Even before, there were debates about the fact that a plain old thread's functionality can be replaced in many cases by the ThreadPool class.

Also, other specialized mechanisms are further rendering the Thread class less appealing, such as Timers replacing the ugly Thread + Sleep combo, while for GUIs we have BackgroundWorker, etc.

Still, the Thread seems to remain a very familiar concept for some people (myself included), people that, when confronted with a task that involves some kind of parallel execution, jump directly to using the good old Thread class. I've been wondering lately if it's time to amend my ways.

So my question is, are there any cases when it's necessary or useful to use a plain old Thread object instead of one of the above constructs?

The Thread class cannot be made obsolete because obviously it is an implementation detail of all those other patterns you mention.

But that's not really your question; your question is

are there any cases when it's necessary or useful to use a plain old Thread object instead of one of the above constructs?

Sure. In precisely those cases where one of the higher-level constructs does not meet your needs.

My advice is that if you find yourself in a situation where existing higher-abstraction tools do not meet your needs, and you wish to implement a solution using threads, then you should identify the missing abstraction that you really need, and then implement that abstraction using threads, and then use the abstraction.

Is it possible to write a JIT compiler (to native code) entirely in a managed .NET language

63 votes

I'm toying with the idea of writing a JIT compiler and am just wondering if it is even theoretically possible to write the whole thing in managed code. In particular, once you've generated assembler into a byte array how do you jump into it to begin execution?

And for the full proof of concept here is a fully capable translation of Rasmus' approach to JIT into F#

open System
open System.Runtime.InteropServices

type AllocationType =
    | COMMIT=0x1000u

type MemoryProtection =
    | EXECUTE_READWRITE=0x40u

type FreeType =
    | DECOMMIT = 0x4000u

[<DllImport("kernel32.dll", SetLastError=true)>]
extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect);

[<DllImport("kernel32.dll", SetLastError=true)>]
extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, FreeType freeType);

let JITcode: byte[] = [|0x55uy;0x8Buy;0xECuy;0x8Buy;0x45uy;0x08uy;0xD1uy;0xC8uy;0x5Duy;0xC3uy|]

[<UnmanagedFunctionPointer(CallingConvention.Cdecl)>] 
type Ret1ArgDelegate = delegate of (uint32) -> uint32

[<EntryPointAttribute>]
let main (args: string[]) =
    let executableMemory = VirtualAlloc(IntPtr.Zero, UIntPtr(uint32(JITcode.Length)), AllocationType.COMMIT, MemoryProtection.EXECUTE_READWRITE)
    Marshal.Copy(JITcode, 0, executableMemory, JITcode.Length)
    let jitedFun = Marshal.GetDelegateForFunctionPointer(executableMemory, typeof<Ret1ArgDelegate>) :?> Ret1ArgDelegate
    let mutable test = 0xFFFFFFFCu
    printfn "Value before: %X" test
    test <- jitedFun.Invoke test
    printfn "Value after: %X" test
    VirtualFree(executableMemory, UIntPtr.Zero, FreeType.DECOMMIT) |> ignore
    0

that happily executes yielding

Value before: FFFFFFFC
Value after: 7FFFFFFE

Why is casting a dynamic of type object to object throwing a null reference exception?

30 votes

I have the following function:

public static T TryGetArrayValue<T>(object[] array_, int index_)
{
    ... //some checking goes up here not relevant to question

    dynamic boxed = array_[index_];
    return (T)boxed;
}

When I call it in the following way,

object a = new object();
object v = TUtils.TryGetArrayValue<object>(new object[] { a }, 0);

(T)boxed throws a null reference exception.

Any other type I put in there other than "object", it works perfectly fine.
Any ideas what this is, and why it's throwing the exception?

Edit: The reason why I use dynamic is to avoid exception when converting types, for example:

double a = 123;
int v = TUtils.TryGetArrayValue<int>(new object[] { a }, 0);

I agree with the other answerers who say that this looks like a bug. Specifically it appears to be a bug in C# runtime binding layer, though I have not investigated it thoroughly.

I apologize for the error. I'll report it to the C# 5 testing team and we'll see if it has already been reported and fixed in C# 5. (It reproduces in the recent beta release, so it is unlikely that it has already been reported and fixed.) If not, a fix is unlikely to make it into the final release. In that case we'll consider it for a possible servicing release.

Thanks for bringing this to our attention. If you feel like entering a Connect issue to track it, feel free to do so and please include a link to this StackOverflow question. If you don't, no problem; the test team will know about it either way.

Which exceptions should a program never attempt to recover from?

28 votes

Exceptions can have different degrees of impact on a program. For example a program should probably abort if OutOfMemoryException is raised, but it is possible to safely and appropriately handle System.Data.SqlClient.SqlException without putting the program in an unknown state.

I do understand that any exception has the potential to put the program in an unstable state if it is not properly handled. Are there exceptions that should never be handled beyond simply logging and throwing up the stack?

The Framework Design Guidelines cover this pretty completely:

Do not catch System.Exception or System.SystemException in framework code, unless you intend to re-throw.

...

Do not catch System.StackOverflowException.

It is extremely difficult to programmatically handle a stack overflow. You should allow this exception to terminate the process and use debugging to determine the source of the problem.

...

Do not catch System.Runtime.InteropServices.SEHException explicitly.

Why are AND instructions generated?

26 votes

For code such as this:

int res = 0;
for (int i = 0; i < 32; i++)
{
    res += 1 << i;
}

This code is generated (release mode, no debugger attached, 64bit):

 xor edx,edx 
 mov r8d,1 
_loop:
 lea ecx,[r8-1] 
 and ecx,1Fh     ; why?
 mov eax,1 
 shl eax,cl 
 add edx,eax 
 mov ecx,r8d 
 and ecx,1Fh     ; why?
 mov eax,1 
 shl eax,cl 
 add edx,eax 
 lea ecx,[r8+1] 
 and ecx,1Fh     ; why?
 mov eax,1 
 shl eax,cl 
 add edx,eax 
 lea ecx,[r8+2] 
 and ecx,1Fh     ; why?
 mov eax,1 
 shl eax,cl 
 add edx,eax 
 add r8d,4 
 cmp r8d,21h 
 jl  _loop

Now I can see the point of most instructions there, but what's up with the AND instructions? ecx will never be more than 0x1F in this code anyway, but I excuse it for not noticing that (and also for not noticing that the result is a constant), it's not an ahead-of-time compiler that can afford to spend much time on analysis after all. But more importantly, SHL with a 32bit operand masks cl by 0x1F already. So it seems to me that these ANDs are entirely useless. Why are they generated? Do they have some purpose I'm missing?

The and is already present in the CIL code emitted by the C# compiler:

    IL_0009: ldc.i4.s 31
    IL_000b: and
    IL_000c: shl

The spec for the CIL shl instruction says:

The return value is unspecified if shiftAmount is greater than or equal to the size of value.

The C# spec, however, defines the 32-bit shift to take the shift count mod 32:

When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.

In this situation, the C# compiler can’t really do much better than emit an explicit and operation. Best you can hope for is that the JITter will notice this and optimize away the redundant and, but that takes time, and the speed of JIT is pretty important. So consider this the price paid for a JIT-based system.

The real question, I guess, is why the CIL specifies the shl instruction that way, when C# and x86 both specify the truncating behaviour. That I do not know, but I speculate that it’s important for the CIL spec to avoid specifying a behaviour that may JIT to something expensive on some instruction sets. At the same time, it’s important for C# to have as few undefined behaviours as possible, because people invariably end up using such undefined behaviours until the next version of the compiler/framework/OS/whatever changes them, breaking the code.

DateTime - Strange daylight savings behaviour

17 votes

My local timezone is (UTC+10:00) Canberra, Melbourne, Sydney

Sat 31-Mar-2012 15:59 UTC = Sun 01-Apr-2012 02:59 +11:00
Sat 31-Mar-2012 16:00 UTC = Sun 01-Apr-2012 02:00 +10:00

Daylight savings finishes at 3 AM first Sunday in April and the clock wind back 1 hour.

Given the following code ....

DateTime dt1 = DateTime.Parse("31-Mar-2012 15:59", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

DateTime dt2 = DateTime.Parse("31-Mar-2012 15:59", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal).AddMinutes(1);
DateTime dt3 = DateTime.Parse("31-Mar-2012 16:00", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

Console.WriteLine("{0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt1);
Console.WriteLine("{0:yyyy-MMM-dd HH:mm:ss.ffff K} ({1}) = {2:yyyy-MMM-dd HH:mm:ss.ffff K} ({3})", dt2, dt2.Kind, dt3, dt3.Kind);
Console.WriteLine("{0} : {1} : {2}", dt1.ToUniversalTime().Hour, dt2.ToUniversalTime().Hour, dt3.ToUniversalTime().Hour);

I get the following output

2012-Apr-01 02:59:00.0000 +11:00
2012-Apr-01 03:00:00.0000 +10:00 (Local) = 2012-Apr-01 02:00:00.0000 +10:00 (Local)
15 : 17 : 16

Adding 1 minute to the original datetime makes the local time 3AM but also set the offset to +10 hours. Adding 1 minute to the UTC date and parsing correctly sets the local time to 2 AM with a +10 UTC offset.

Repeating with

DateTime dt1 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc);

DateTime dt2 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc).AddMinutes(1);
DateTime dt3 = new DateTime(2012, 03, 31, 16, 0, 0, DateTimeKind.Utc);

or

DateTime dt1 = DateTime.Parse("31-Mar-2012 15:59", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

DateTime dt2 = DateTime.Parse("31-Mar-2012 15:59", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal).AddMinutes(1);
DateTime dt3 = DateTime.Parse("31-Mar-2012 16:00", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); 

gives

2012-Mar-31 15:59:00.0000 Z
2012-Mar-31 16:00:00.0000 Z (Utc) = 2012-Mar-31 16:00:00.0000 Z (Utc)
15 : 16 : 16

as expected

Repeating again with

DateTime dt1 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc).ToLocalTime();

DateTime dt2 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc).ToLocalTime().AddMinutes(1);
DateTime dt3 = new DateTime(2012, 03, 31, 16, 0, 0, DateTimeKind.Utc).ToLocalTime();

gives the original

2012-Apr-01 02:59:00.0000 +11:00
2012-Apr-01 03:00:00.0000 +10:00 (Local) = 2012-Apr-01 02:00:00.0000 +10:00 (Local)
15 : 17 : 16

Can anyone explain this ?

Indecently if I use the TimeZoneInfo to convert from UTC to AUS Eastern Standard Time I get the correct time, but I lose the offset information in the DateTime instance as the DateTime.Kind == DateTimeKind.Unspecified

== Additional scenario to highlight

This is just simple timespan adding, starting with an NON-ambiguous UTC date, 1 minute before Daylight savings finishes.

DateTime dt1 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc);  
DateTime dt2 = new DateTime(2012, 03, 31, 15, 59, 0, DateTimeKind.Utc).ToLocalTime();  

Console.WriteLine("Original in UTC     : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt1);  
Console.WriteLine("Original in Local   : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt1.ToLocalTime());  
Console.WriteLine("+ 1 Minute in Local : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt1.AddMinutes(1).ToLocalTime());  
Console.WriteLine("+ 1 Minute in UTC   : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt1.AddMinutes(1));  
Console.WriteLine("=====================================================");
Console.WriteLine("Original in UTC     : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt2.ToUniversalTime());  
Console.WriteLine("Original in Local   : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt2);  
Console.WriteLine("+ 1 Minute in Local : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt2.AddMinutes(1));  
Console.WriteLine("+ 1 Minute in UTC   : {0:yyyy-MMM-dd HH:mm:ss.ffff K}", dt2.AddMinutes(1).ToUniversalTime());  

gives

Original in UTC : 2012-Mar-31 15:59:00.0000 Z
Original in Local : 2012-Apr-01 02:59:00.0000 +11:00
+ 1 Minute in Local : 2012-Apr-01 02:00:00.0000 +10:00
+ 1 Minute in UTC : 2012-Mar-31 16:00:00.0000 Z

=====================================================

Original in UTC : 2012-Mar-31 15:59:00.0000 Z
Original in Local : 2012-Apr-01 02:59:00.0000 +11:00
+ 1 Minute in Local : 2012-Apr-01 03:00:00.0000 +10:00
+ 1 Minute in UTC : 2012-Mar-31 17:00:00.0000 Z

I believe the problem is in terms of when the conversions are performed.

You're parsing assuming universal time, but then implicitly converting to a "local" kind - with a value of 2:59:59. When you ask that "local" value to add a minute, it's just adding a minute to the local value, with no consideration for time zone. When you then print the offset, the system is trying to work out the offset at the local time of 3am... which is +10.

So effectively you've got:

  • Parse step 1: treat string as universal (15:59 UTC)
  • Parse step 2: convert result to local (2:59 local)
  • Addition: in local time, no time zone values are applied (3:00 local)
  • Format step 1: offset is requested, so work out what that local time maps to (17:00 UTC)
  • Format step 2: compute offset as difference between local and universal (+10)

Yes, it's all a bit painful - DateTime is painful in general, which is the main reason I'm writing Noda Time, where there are separate types for "date/time in a zone" vs "local date/time" (or "local date" or "local time"), and it's obvious which you're using at any one point.

It's not clear to me what you're actually trying to achieve here - if you can be more specific, I can show you what you would do in Noda Time, although there may be some inherent ambiguities (conversions from local date/times to "zoned" date/times can have 0, 1 or 2 results).

EDIT: If the aim is merely to remember the time zone as well as the instant, in Noda Time you'd want ZonedDateTime, like this:

using System;
using NodaTime;

class Program
{
    static void Main(string[] args)
    {
        var zone = DateTimeZone.ForId("Australia/Melbourne");
        ZonedDateTime start = Instant.FromUtc(2012, 3, 31, 15, 59, 0)
                                     .InZone(zone);
        ZonedDateTime end = start + Duration.FromMinutes(1);

        Console.WriteLine("{0} ({1})", start.LocalDateTime, start.Offset);
        Console.WriteLine("{0} ({1})", end.LocalDateTime, end.Offset);
    }
}

See the notes on calendar arithmetic for some more information about this.

new [] or new List<T>?

16 votes

I'm just thinking about some style and performance. I used to wrote something like,

var strings = new List<string> { "a", "b", "c" };
var ints = new List<int> { 1, 2, 3};

But now I a little more tend to that style,

var strings = new [] { "a", "b", "c" }.ToList();
var ints = new [] { 1, 2, 3}.ToList();

I prefer that second style, but now considering - it is really worth to do that, maybe it's not so efficient and requires more operations?

I disagree with Darin: they're not equivalent in terms of performance. The latter version has to create a new array, and ToList will then copy it into the new list. The collection initializer version is equivalent to:

var tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
var ints = tmp;

Assuming the list starts off with a large enough buffer, that won't require any further allocation - although it will involve a few method calls. If you do this for a very large number of items, then it will require more allocations than the ToList version, because it will copy the items as it goes.

The performance difference is likely to be negligible, but it's non-zero (and not clearly better in either direction - there are fewer calls in the array version, but more allocation).

I would concentrate more on style than performance unless you have a reason to suspect that the difference is significant, in which case you should measure rather than just guessing.

Personally I prefer the first form - I think it makes it clearer that you're using a list right from the start. Another alternative would be to write your own static class:

public static class Lists
{
    public static List<T> Of<T>(T item0)
    {
        return new List<T> { item0 };
    }

    public static List<T> Of<T>(T item0, T item1)
    {
        return new List<T> { item0, item1 };
    }

    public static List<T> Of<T>(T item0, T item1, T item2)
    {
        return new List<T> { item0, item1, item2 };
    }

    ... as many times as you really care about, then ...

    public static List<T> Of<T>(params T[] items)
    {
        return items.ToList();
    }
}

Then you can write:

var ints = Lists.Of(1);
var ints = Lists.Of(1, 2, 3);
var ints = Lists.Of(1, 2, 3, 5, 6, 7, 8); // Use the params version

This still makes it clear that you're using lists, but takes advantage of type inference.

You may well consider it overkill though :)

Implementation change to .NET's Random()

15 votes

I am migrating a method that is used for decoding from .NET Framework 1.1 to .NET Framework 4. I noticed that implementation of Random changed. So given the same seed, Random.NextBytes returns different result.

So if I run the following code.

byte[] bytes = new byte[4];
System.Random random = new System.Random(50);
random.NextBytes(bytes);

for(int i=0; i< bytes.Length; i++)
{
  Console.WriteLine("bytes[" + i + "] = " + bytes[i]);
}

Under .NET Framework 1.1 it returns:

bytes[0] = 216
bytes[1] = 124
bytes[2] = 183
bytes[3] =  58

Under .NET framework 4 it returns:

bytes[0] = 154
bytes[1] =  49
bytes[2] = 183
bytes[3] =  48

What is the best way to resolve this problem?

You can just use Reflector to copy the Random class from the 1.1 mscorlib.

public class Random1_1
{
    // Fields
    private int inext;
    private int inextp;
    private const int MBIG = 0x7fffffff;
    private const int MSEED = 0x9a4ec86;
    private const int MZ = 0x0;
    private int[] SeedArray;

    // Methods
    public Random1_1()
        : this(Environment.TickCount)
    {
    }

    public Random1_1(int Seed)
    {
        this.SeedArray = new int[0x38];
        int num2 = 0x9a4ec86 - Math.Abs(Seed);
        this.SeedArray[0x37] = num2;
        int num3 = 0x1;
        for (int i = 0x1; i < 0x37; i++)
        {
            int index = (0x15 * i) % 0x37;
            this.SeedArray[index] = num3;
            num3 = num2 - num3;
            if (num3 < 0x0)
            {
                num3 += 0x7fffffff;
            }
            num2 = this.SeedArray[index];
        }
        for (int j = 0x1; j < 0x5; j++)
        {
            for (int k = 0x1; k < 0x38; k++)
            {
                this.SeedArray[k] -= this.SeedArray[0x1 + ((k + 0x1e) % 0x37)];
                if (this.SeedArray[k] < 0x0)
                {
                    this.SeedArray[k] += 0x7fffffff;
                }
            }
        }
        this.inext = 0x0;
        this.inextp = 0x15;
        Seed = 0x1;
    }

    public virtual int Next()
    {
        return (int)(this.Sample() * 2147483647.0);
    }

    public virtual int Next(int maxValue)
    {
        if (maxValue < 0x0)
        {
            throw new ArgumentOutOfRangeException("maxValue");
        }
        return (int)(this.Sample() * maxValue);
    }

    public virtual int Next(int minValue, int maxValue)
    {
        if (minValue > maxValue)
        {
            throw new ArgumentOutOfRangeException("minValue");
        }
        int num = maxValue - minValue;
        if (num < 0x0)
        {
            long num2 = maxValue - minValue;
            return (((int)((long)(this.Sample() * num2))) + minValue);
        }
        return (((int)(this.Sample() * num)) + minValue);
    }

    public virtual void NextBytes(byte[] buffer)
    {
        if (buffer == null)
        {
            throw new ArgumentNullException("buffer");
        }
        for (int i = 0x0; i < buffer.Length; i++)
        {
            buffer[i] = (byte)(this.Sample() * 256.0);
        }
    }

    public virtual double NextDouble()
    {
        return this.Sample();
    }

    protected virtual double Sample()
    {
        int inext = this.inext;
        int inextp = this.inextp;
        if (++inext >= 0x38)
        {
            inext = 0x1;
        }
        if (++inextp >= 0x38)
        {
            inextp = 0x1;
        }
        int num = this.SeedArray[inext] - this.SeedArray[inextp];
        if (num < 0x0)
        {
            num += 0x7fffffff;
        }
        this.SeedArray[inext] = num;
        this.inext = inext;
        this.inextp = inextp;
        return (num * 4.6566128752457969E-10);
    }
}

Tested and it gives the desired output.

Why is AddRange faster than using a foreach loop?

15 votes
var fillData = new List<int>();
for (var i = 0; i < 100000; i++)
{
     fillData.Add(i);
}

var stopwatch1 = new Stopwatch();
stopwatch1.Start();
var autoFill = new List<int>();
autoFill.AddRange(fillData);
stopwatch1.Stop();

var stopwatch2 = new Stopwatch();
stopwatch2.Start();
var manualFill = new List<int>();
foreach (var i in fillData)
{
    manualFill.Add(i);
}
stopwatch2.Stop();

When I take 4 results from stopwach1 and stopwach2, stopwatch1 has a lower value than stopwatch2. That mean addrange is always faster than the foreach. Does anyone know why??

Potentially, AddRange can check where the value passed to it implements IList or IList<T>. If it does, it can find out how many values are in the range, and thus how much space it needs to allocate... whereas the foreach loop may need to reallocate several times.

Additionally, even after allocation, List<T> can use IList<T>.CopyTo to perform a bulk copy into the underlying array (for ranges which implement IList<T>, of course.)

I suspect you'll find that if you try your test again but using Enumerable.Range(0, 100000) for fillData instead of a List<T>, the two will take about the same time.

What happens when I interrupt a C# console application with Control-C?

12 votes

What happens when I interrupt my C# console application with Control-C?

Is the process killed? Is memory freed? Are finally blocks executed? What happens to database connections?

Does any of this differ if the application is built for debug or release, or run inside/outside Visual Studio?

Short Answer: It's doing nothing after CTRL-C

Long Answer: There is good article about it on the MSDN which clearly states, that it sends an signal (interrupt) instead of keypress-events.

There is also a cancelKeyPress-Event triggered which you can subscribe to and do whatever you want!

Unluckily there is no more info about, what's actually done by default. Maybe in the worst-case you can check it out by yourself. But imo there should be some documentation about it...

UPDATE: Alois Kraus wrote an codeproject-Article about gracefully shuting down a console-application after receiving CTRL-C.

To quote Alois Kraus:

The default behavior of the CLR is to do nothing. This does mean that the CLR is notified very late by a DLL_PROCESS_DETACH notification in which context no managed code can run anymore because the OS loader lock is already taken. We are left in the unfortunate situation that we get no notification events nor are any finalizers run. All threads are silently killed without a chance to execute their catch/finally blocks to do an orderly shutdown. I said in the first sentence default, because there is a way to handle this situation gracefully. The Console class has got a new event member with .NET 2.0: Console.CancelKeyPress. It allows you to get notified of Ctrl-C and Ctrl-Break keys where you can stop the shutdown (only for Ctrl-C, but not Ctrl-Break). The main problem here is if you catch the Ctrl-C/Break event and exit the handler there are no finalizers called. This is not what I would call a cooperative shutdown. The first thing that comes to my mind is to call Environment.Exit but it does not trigger any finalizers. All is not lost. I did come up with a dirty trick to run all finalizers: we spin up a little helper thread inside the event handler which will then call Environment.Exit. Voila, our finalizers are called.

Strange Queue<T>.Enqueue(T item) code

12 votes

While reflecting with ILSpy i found this line of code in the Queue<T>.Enqueue(T item)-method:

if (this._size == this._array.Length)
{
    int num = (int)((long)this._array.Length * 200L / 100L);
    if (num < this._array.Length + 4)
    {
        num = this._array.Length + 4;
    }
    this.SetCapacity(num);
}

I'm just wondering why somebody would do this? I think it's some kind of a integer overflow check, but why multiply first with 200L and then divide by 100L?

Might this have been a issue with earlier compilers?

Usually things first multiplied then divided by 100 are percentage calculations - Perhaps there was some const XxxPercentage = 200 or something like that in the original code. The compiler does not seem to optimize the * 200 / 100 to * 2.

This code sets the capacity to twice its size - but if twice its size would be smaller than the original size + 4, use that instead.

The reason it is converted to long probably is because if you multiply an integer by the "200 percent" it would overflow.

Extension methods overload choice

12 votes

I have two extension methods:

public static IPropertyAssertions<T> ShouldHave<T>(this T subject)
{
    return new PropertyAssertions<T>(subject);
}

public static IPropertyAssertions<T> ShouldHave<T>(this IEnumerable<T> subject)
{
    return new CollectionPropertyAssertions<T>(subject);
}

Now I write some code which uses it:

List<Customer> collection2 = new List<Customer>(); 
collection2.ShouldHave(); //first overload is chosen
IEnumerable<Customer> collection3 = new List<Customer>(); 
collection3.ShouldHave(); //second overload is chosen

Second overload is chosen only if I explicitly specify IEnumerable type. Is there any way to make second overload to be chosen in both cases?

The first overload is a better match, because T is inferred as List<Customer>, which gives an exact match. For the second overload, it would infer T as Customer, so the parameter would be IEnumerable<Customer>, which is a less exact match than List<Customer>.

Circular reference in same assembly a bad thing?

10 votes

Assume I have the following classes in the same assembly

public class ParentClass : IDisposable
{
  public ChildClass Child
  {
    get { return _child; }
  }
}   

public class ChildClass 
{
   public ParentClass Parent
   {
     get { return _parent; }
     set { _parent= value; }
   }

   public ChildClass (ParentClass parent)
   {
     Parent= parent;
   }

}

Correct me if I am wrong but this IS bad design. Will this lead to a memory leak or some other unforseen issues later on? Apparently the garbage collector is capable of handling such kind of circular references.

Edit

What if the two classes end up getting used like this in some other class?

ParentClass objP = new ParentClass ();
ChildClass objC =new ChildClass(objP);
objP.Child = objC;

Thoughts please ....

Don't worry about the garbage collector; it handles reference graphs with arbitrary topologies with ease. Worry about writing objects that lend themselves to creating bugs by making it easy to violate their invariants.

This is a questionable design not because it stresses the GC -- it does not -- but rather because it does not enforce the desired semantic invariant: that if X is the parent of Y, then Y must be the child of X.

It can be quite tricky to write classes that maintain consistent parent-child relationships. What we do on the Roslyn team is we actually build two trees. The "real" tree has only child references; no child knows its parent. We layer a "facade" tree on top of that which enforces the consistency of the parent-child relationship: when you ask a parent node for its child, it creates a facade on top of its real child and sets the parent of that facade object to be the true parent.

UPDATE: Commenter Brian asks for more details. Here's a sketch of how you might implement a "red" facade with child and parent references over a "green" tree that only contains child references. In this system it is impossible to make an inconsistent parent-child relationship, as you can see in the test code at the bottom.

(We call these "red" and "green" trees because when drawing the data structure on the whiteboard, those were the marker colours we used.)

using System;

interface IValue { string Value { get; } }
interface IParent : IValue { IChild Child { get; } }
interface IChild : IValue { IParent Parent { get; } }

abstract class HasValue : IValue
{
    private string value;
    public HasValue(string value)
    {
        this.value = value;
    }
    public string Value { get { return value; } }
}

sealed class GreenChild : HasValue
{
    public GreenChild(string value) : base(value) {}
}

sealed class GreenParent : HasValue
{
    private GreenChild child;
    public GreenChild Child { get { return child; } }
    public GreenParent(string value, GreenChild child) : base(value)
    { 
         this.child = child; 
    }

    public IParent MakeFacade() { return new RedParent(this); }

    private sealed class RedParent : IParent
    {
        private GreenParent greenParent;
        private RedChild redChild;
        public RedParent(GreenParent parent) 
        { 
            this.greenParent = parent; 
            this.redChild = new RedChild(this);
        }
        public IChild Child { get { return redChild; } }
        public string Value { get { return greenParent.Value; } }

        private sealed class RedChild : IChild
        {
            private RedParent redParent;
            public RedChild(RedParent redParent)
            {
                this.redParent = redParent;
            }
            public IParent Parent { get { return redParent; } }
            public string Value 
            { 
                get 
                { 
                    return redParent.greenParent.Child.Value; 
                } 
            }
        }
    }
}
class P
{
    public static void Main()
    {
        var greenChild1 = new GreenChild("child1");
        var greenParent1 = new GreenParent("parent1", greenChild1);
        var greenParent2 = new GreenParent("parent2", greenChild1);

        var redParent1 = greenParent1.MakeFacade();
        var redParent2 = greenParent2.MakeFacade();

        Console.WriteLine(redParent1.Value); // parent1
        Console.WriteLine(redParent1.Child.Parent.Value); // parent1 !
        Console.WriteLine(redParent2.Value); // parent2
        Console.WriteLine(redParent2.Child.Parent.Value); // parent2 !

        // See how that goes? RedParent1 and RedParent2 disagree on what the
        // parent of greenChild1 is, **but they are self-consistent**. They
        // always report that the parent of their child is themselves.
    }
}

What is the right order of insertion/deletion/modification on dataset?

10 votes

The MSDN claims that the order is :

  1. Child table: delete records.
  2. Parent table: insert, update, and delete records.
  3. Child table: insert and update records.

I have a problem with that.

Example : ParentTable have two records parent1(Id : 1) and parent2(Id : 2)

ChildTable have a record child1(Id : 1, ParentId : 1)

If we update the child1 to have a new parent parent2, and the we delete parent1.

  1. We have nothing to delete in child table
  2. We delete parent1 : we broke the constraint, because the child is still attached to parent1, unless we update it first.

So what is the right order, and is the MSDN false on the subject?

My personnals thoughts is

  1. Child table: delete records.
  2. Parent table: insert, update records.
  3. Child table: insert and update records.
  4. Parent table: delete records.

But the problem is, with potentially unique constraint, we must always delete the records in a table before adding new... So I have no solution right now for commiting my datas to my database.

Edit : thanks for the answers, but your corner case is my daily case... I opt for the ugly solution to disabled constraint, then update database, and re-enabled constraint. I'm still searching a better solution..

Doesn't your SQL product support deferred constraint checking ?

If not, you could try

Delete all child records - delete all parent records - insert all parent records - insert all child records

where any UPDATEs have been split into their constituent DELETEs and INSERTs.

This should work correctly in all cases, but at acceptable speeds probably in none ...

It is also provable that this is the only scheme that can work correctly in all cases, since :

(a) key constraints on parent dictate that parent DELETES must precede parent INSERTS,
(b) key constraints on child dictate that child DELETES must precede child INSERTS,
(c) FK dictates that child DELETES must precede parent DELETES
(d) FK also dictates that child INSERTS must follow parent INSERTS

The given sequence is the only possible one that satisfies these 4 requirements, and it also shows that UPDATEs to the child make a solution impossible no matter what, since an UPDATE means a "simultaneous" DELETE plus INSERT.

What is the recommended practice to update or delete multiple entities in EntityFramework?

9 votes

In SQL one might sometimes write something like

DELETE FROM table WHERE column IS NULL

or

UPDATE table SET column1=value WHERE column2 IS NULL

or any other criterion that might apply to multiple rows.

As far as I can tell, the best EntityFramework can do is something like

foreach (var entity in db.Table.Where(row => row.Column == null))
    db.Table.Remove(entity);   // or entity.Column2 = value;
db.SaveChanges();

But of course that will retrieve all the entities, and then run a separate DELETE query for each. Surely that must be much slower if there are many entities that satisfy the criterion.

So, cut a long story short, is there any support in EntityFramework for updating or deleting multiple entities in a single query?

EF doesn't have support for batch updates or deletes but you can simply do:

db.Database.ExecuteSqlCommand("DELETE FROM ...", someParameter);

Edit:

People who really want to stick with LINQ queries sometimes use workaround where they first create select SQL query from LINQ query:

string query = db.Table.Where(row => row.Column == null).ToString();

and after that find the first occurrence of FROM and replace the beginning of the query with DELETE and execute result with ExecuteSqlCommand. The problem with this approach is that it works only in basic scenarios. It will not work with entity splitting or some inheritance mapping where you need to delete two or more records per entity.

XSLT to transform to HTML and format the HTML based on data in XML

6 votes

i am pretty new to XSLT / XML and HTML. I have a XML file that I currently convert to HTML in c# using an XSLT. The XML file represents nothing but data extracted from a table in a database. I can currently convert the XML file to HTML using XSLT fairly easily without much formating. the HTML when opened looks pretty ordinary. What i intend to is format the HTML i.e change the font, background color, font color etc based on certain key values in the XML document.

The XML is generated on a daily basis using C# code . the content of the XML file totally depends on the contents of the table in the database at that point in the day when the C# code is executed..

the XML looks something like this

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <defects>
    <Defectid>56</Defectid>
    <testid>111</testid>
    <summary>Release of DIT </summary>
    <DetectedDate>2011-09-21 </DetectedDate>
    <priority>2-Give High Attention</priority>
    <status>Ready to Test</status>
    <project>Business Intelligence</project>
    <assignedTo>peter</assignedTo>
    <detectedBy>john</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>829</Defectid>
    <testid>111</testid>
    <summary> Data request</summary>
    <DetectedDate>2012-01-12 </DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Open</status>
    <project>web</project>
    <assignedTo>tcm</assignedTo>
    <detectedBy>john</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>728</Defectid>
    <testid>999</testid>
    <summary>Data request</summary>
    <DetectedDate>2012-01-11</DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Fixed</status>
    <project>Business Intelligence</project>
    <assignedTo>chris</assignedTo>
    <detectedBy>peter</detectedBy>
    <severity>3-Average</severity>
  </defects>
</NewDataSet>

what i intend to do is generate and HTML table from this XML which would be in tabular format but the font color of the rows in the HTML table should be set based on "testid" attribute . i.e. for font color on the HTML should be unique per "testid" attribute. Since the rows per testid would change daily based on the data in the table in the database, I am not sure how this can be accomplished using XSLT.

the current XSLT looks something like this.. as you can see , I have hardcoded the font colors.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <table  BORDER="1" CELLPADDING="3" CELLSPACING="2" WIDTH="100">
      <tr>
        <td nowrap="nowrap" width = "70">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Defect ID</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "70">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Test ID</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "400">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Summary</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "150">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Detected Date</b>
          </h1>
        </td>
        <td width = "200">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Priority</b>
          </h1>
        </td>
        <td width = "200">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Status</b>
          </h1>
        </td>
        <td width = "200">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Project</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "100">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Assigned To</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "100">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Detected By</b>
          </h1>
        </td>
        <td nowrap="nowrap" width = "80">
          <h1 style="font-family:verdana ;font-size:60%;color:green">
            <b>Severity</b>
          </h1>
        </td>
      </tr>
      <xsl:for-each select="//defects">

        <tr>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="Defectid"></xsl:value-of>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="testid"/>
            </h1>
          </td>
          <td width = "400">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="summary"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="DetectedDate"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="priority"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="status"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="project"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="assignedTo"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="detectedBy"/>
            </h1>
          </td>
          <td width = "100">
            <h1 style="font-family:verdana ;font-size:60%;color:blue">
              <xsl:value-of select="severity"/>
            </h1>
          </td>

        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>

</xsl:stylesheet>

Does anybody know or could anybody guide me?

Below is a solution that applies up to 20 different colors - applying one particular color for each row with a specific testid.
Note that it is not important how many distinct testid's occur. Also note that color coding says nothing about the testid itself - but that's exactly the way you wanted it :-).

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet
    version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:std="http://www.standardColors.com">

    <xsl:output method="html"/>

    <xsl:variable name="colors">
        <color>#0000FF</color>
        <color>#FF0000</color>
        <color>#00FFFF</color>
        <color>#FFFF00</color>
        <color>#347C2C</color>
        <color>#800080</color>
        <color>#3B9C9C</color>
        <color>#A52A2A</color>
        <color>#3BB9FF</color>
        <color>#FF00FF</color>
        <color>#6698FF</color>
        <color>#808000</color>
        <color>#8D38C9</color>
        <color>#ADD8E6</color>
        <color>#F660AB</color>
        <color>#F87217</color>
        <color>#F9B7FF</color>
        <color>#FFA500</color>
        <color>#FFE87C</color>
        <color>#8E35EF</color>
    </xsl:variable>

    <xsl:variable name="testIDs" select="distinct-values(//testid)"/>

    <xsl:variable name="colorList">
        <xsl:for-each select="$testIDs">
            <xsl:variable name="pos" select="position() mod 20"/>
            <xsl:copy-of select="$colors/color[$pos]"/>
        </xsl:for-each>
    </xsl:variable>

    <xsl:template match="/">
        <html>
            <head>
                <style>
                    th, td {
                        border: solid black 1px ;
                        padding: 3px;                       
                        border-spacing:2px;
                        border-collapse: collapse;
                        width: 100px;
                    }
                    th {
                        font-family:verdana;
                        font-size:60%;
                        color:green;
                        align:center;
                        white-space: nowrap;
                    }
                    <xsl:for-each select="$testIDs">
                    <xsl:variable name="pos" select="position()"/>
                     tr.testid<xsl:value-of select="."/> {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:<xsl:value-of select="$colorList/color[$pos]"/>;
                        align:center
                    }
                   </xsl:for-each>
                </style>
            </head>                
            <body>
                <table>
                    <tr>
                        <xsl:for-each select="/NewDataSet/defects[1]/*">
                            <th>
                                <xsl:value-of select="name(.)"/>
                            </th>
                        </xsl:for-each>
                    </tr>
                    <xsl:apply-templates select="*"/>
                </table>
            </body>
        </html>
   </xsl:template>

    <xsl:template match="/NewDataSet/defects">
        <tr>
            <xsl:attribute name="class">testid<xsl:value-of select="testid"/></xsl:attribute>
            <xsl:for-each select="*">
                <td>
                    <xsl:value-of select="."/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>

</xsl:stylesheet>

I applied this on the below xml:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <defects>
    <Defectid>56</Defectid>
    <testid>111</testid>
    <summary>Release of DIT </summary>
    <DetectedDate>2011-09-21 </DetectedDate>
    <priority>2-Give High Attention</priority>
    <status>Ready to Test</status>
    <project>Business Intelligence</project>
    <assignedTo>peter</assignedTo>
    <detectedBy>john</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>829</Defectid>
    <testid>111</testid>
    <summary> Data request</summary>
    <DetectedDate>2012-01-12 </DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Open</status>
    <project>web</project>
    <assignedTo>tcm</assignedTo>
    <detectedBy>john</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>728</Defectid>
    <testid>999</testid>
    <summary>Data request</summary>
    <DetectedDate>2012-01-11</DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Fixed</status>
    <project>Business Intelligence</project>
    <assignedTo>chris</assignedTo>
    <detectedBy>peter</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>728</Defectid>
    <testid>321</testid>
    <summary>Data request</summary>
    <DetectedDate>2012-01-11</DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Fixed</status>
    <project>Business Intelligence</project>
    <assignedTo>chris</assignedTo>
    <detectedBy>peter</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>728</Defectid>
    <testid>457</testid>
    <summary>Data request</summary>
    <DetectedDate>2012-01-11</DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Fixed</status>
    <project>Business Intelligence</project>
    <assignedTo>chris</assignedTo>
    <detectedBy>peter</detectedBy>
    <severity>3-Average</severity>
  </defects>
  <defects>
    <Defectid>728</Defectid>
    <testid>202</testid>
    <summary>Data request</summary>
    <DetectedDate>2012-01-11</DetectedDate>
    <priority>3-Normal Queue</priority>
    <status>Fixed</status>
    <project>Business Intelligence</project>
    <assignedTo>chris</assignedTo>
    <detectedBy>peter</detectedBy>
    <severity>3-Average</severity>
  </defects>
</NewDataSet>

And got as result

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
                    th, td {
                        border: solid black 1px ;
                        padding: 3px;                       
                        border-spacing:2px;
                        border-collapse: collapse;
                        width: 100px;
                    }
                    th {
                        font-family:verdana;
                        font-size:60%;
                        color:green;
                        align:center;
                        white-space: nowrap;
                    }

                     tr.testid111 {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:#0000FF;
                        align:center
                    }

                     tr.testid999 {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:#FF0000;
                        align:center
                    }

                     tr.testid321 {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:#00FFFF;
                        align:center
                    }

                     tr.testid457 {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:#FFFF00;
                        align:center
                    }

                     tr.testid202 {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:#347C2C;
                        align:center
                    }
                   </style>
    </head>
    <body>
        <table>
            <tr>
                <th>Defectid</th>
                <th>testid</th>
                <th>summary</th>
                <th>DetectedDate</th>
                <th>priority</th>
                <th>status</th>
                <th>project</th>
                <th>assignedTo</th>
                <th>detectedBy</th>
                <th>severity</th>
            </tr>
            <tr class="testid111">
                <td>56</td>
                <td>111</td>
                <td>Release of DIT </td>
                <td>2011-09-21 </td>
                <td>2-Give High Attention</td>
                <td>Ready to Test</td>
                <td>Business Intelligence</td>
                <td>peter</td>
                <td>john</td>
                <td>3-Average</td>
            </tr>
            <tr class="testid111">
                <td>829</td>
                <td>111</td>
                <td> Data request</td>
                <td>2012-01-12 </td>
                <td>3-Normal Queue</td>
                <td>Open</td>
                <td>web</td>
                <td>tcm</td>
                <td>john</td>
                <td>3-Average</td>
            </tr>
            <tr class="testid999">
                <td>728</td>
                <td>999</td>
                <td>Data request</td>
                <td>2012-01-11</td>
                <td>3-Normal Queue</td>
                <td>Fixed</td>
                <td>Business Intelligence</td>
                <td>chris</td>
                <td>peter</td>
                <td>3-Average</td>
            </tr>
            <tr class="testid321">
                <td>728</td>
                <td>321</td>
                <td>Data request</td>
                <td>2012-01-11</td>
                <td>3-Normal Queue</td>
                <td>Fixed</td>
                <td>Business Intelligence</td>
                <td>chris</td>
                <td>peter</td>
                <td>3-Average</td>
            </tr>
            <tr class="testid457">
                <td>728</td>
                <td>457</td>
                <td>Data request</td>
                <td>2012-01-11</td>
                <td>3-Normal Queue</td>
                <td>Fixed</td>
                <td>Business Intelligence</td>
                <td>chris</td>
                <td>peter</td>
                <td>3-Average</td>
            </tr>
            <tr class="testid202">
                <td>728</td>
                <td>202</td>
                <td>Data request</td>
                <td>2012-01-11</td>
                <td>3-Normal Queue</td>
                <td>Fixed</td>
                <td>Business Intelligence</td>
                <td>chris</td>
                <td>peter</td>
                <td>3-Average</td>
            </tr>
        </table>
    </body>
</html>

which in a browser looks as follows:

table view

ADDED variant using key

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:std="http://www.standardColors.com"
    exclude-result-prefixes="std">

    <xsl:output method="html"/>

    <xsl:variable name="colors">
        <color>#0000FF</color>
        <color>#FF0000</color>
        <color>#00FFFF</color>
        <color>#FFFF00</color>
        <color>#347C2C</color>
        <color>#800080</color>
        <color>#3B9C9C</color>
        <color>#A52A2A</color>
        <color>#3BB9FF</color>
        <color>#FF00FF</color>
        <color>#6698FF</color>
        <color>#808000</color>
        <color>#8D38C9</color>
        <color>#ADD8E6</color>
        <color>#F660AB</color>
        <color>#F87217</color>
        <color>#F9B7FF</color>
        <color>#FFA500</color>
        <color>#FFE87C</color>
        <color>#8E35EF</color>
    </xsl:variable>

    <!--<xsl:variable name="testIDs" select="distinct-values(//testid)"/>-->

    <xsl:key name="testidKey" match="testid" use="text()"/>

    <xsl:variable name="colorList">
        <xsl:for-each select="//testid">
            <xsl:if test="generate-id() = generate-id(key('testidKey', text())[1])">
                <xsl:variable name="pos" select="position() mod 20"/>
                <color>
                    <xsl:attribute name="testid"><xsl:value-of select="."/></xsl:attribute>
                    <xsl:value-of select="$colors/color[$pos]"/>
                </color>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>

    <xsl:template match="/">
        <html>
            <head>
                <style>
                    th, td {
                        border: solid black 1px ;
                        padding: 3px;                       
                        border-spacing:2px;
                        border-collapse: collapse;
                        width: 100px;
                    }
                    th {
                        font-family:verdana;
                        font-size:60%;
                        color:green;
                        align:center;
                        white-space: nowrap;
                    }
                    <xsl:for-each select="$colorList/color">
                     tr.testid<xsl:value-of select="@testid"/> {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        color:<xsl:value-of select="."/>;
                        align:center
                    }
                   </xsl:for-each>
                </style>
            </head>                
            <body>
                <table>
                    <tr>
                        <xsl:for-each select="/NewDataSet/defects[1]/*">
                            <th>
                                <xsl:value-of select="name(.)"/>
                            </th>
                        </xsl:for-each>
                    </tr>
                    <xsl:apply-templates select="*"/>
                </table>
            </body>
        </html>
   </xsl:template>

    <xsl:template match="/NewDataSet/defects">
        <tr>
            <xsl:attribute name="class">testid<xsl:value-of select="testid"/></xsl:attribute>
            <xsl:for-each select="*">
                <td>
                    <xsl:value-of select="."/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>

</xsl:stylesheet>

MSXML error prevention (and any other xsl engine used)

see convert RTF into node-set and RTF to node-set generic approach for further details.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:std="http://www.standardColors.com"
    xmlns:exslt="http://www.exslt.org/common"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    exclude-result-prefixes="std">

    <xsl:output method="html"/>

    <std:colors>
        <color>#0000FF</color>
        <color>#FF0000</color>
        <color>#00FFFF</color>
        <color>#FFFF00</color>
        <color>#347C2C</color>
        <color>#800080</color>
        <color>#3B9C9C</color>
        <color>#A52A2A</color>
        <color>#3BB9FF</color>
        <color>#FF00FF</color>
        <color>#6698FF</color>
        <color>#808000</color>
        <color>#8D38C9</color>
        <color>#ADD8E6</color>
        <color>#F660AB</color>
        <color>#F87217</color>
        <color>#F9B7FF</color>
        <color>#FFA500</color>
        <color>#FFE87C</color>
        <color>#8E35EF</color>
    </std:colors>

    <xsl:variable name="colors" select="document('')/*/std:colors"/>

    <xsl:key name="testidKey" match="testid" use="text()"/>

    <xsl:variable name="std:colorList">
        <xsl:for-each select="//testid">
            <xsl:if test="generate-id() = generate-id(key('testidKey', text())[1])">
                <xsl:variable name="pos" select="position() mod 20"/>
                <xsl:element name="color">
                    <xsl:attribute name="testid"><xsl:value-of select="."/></xsl:attribute>
                    <xsl:value-of select="$colors/color[$pos + 1]"/>
                </xsl:element>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>

    <xsl:template match="/">
        <html>
            <head>
                <style>
                    table {
                        font-family:verdana;
                        font-size:60%;
                        font-weight:bold;
                        align:center;
                        white-space: nowrap;
                    }
                    th, td {
                        border: solid black 1px ;
                        padding: 3px;                       
                        border-spacing:2px;
                        border-collapse: collapse;
                        width: 100px;
                    }
                    th {
                        color:green;
                    }
                    <xsl:choose>
                        <xsl:when test="function-available('msxsl:node-set')">
                            <xsl:apply-templates select="msxsl:node-set($std:colorList)/color" mode="addTRclassToCSS"/>
                        </xsl:when>
                        <xsl:when test="function-available('exslt:node-set')">
                            <xsl:apply-templates select="exslt:node-set($std:colorList)/color" mode="addTRclassToCSS"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:variable name="colorList" select="$std:colorList"/>
                            <xsl:apply-templates select="$colorList" mode="addTRclassToCSS"/>
                        </xsl:otherwise>
                    </xsl:choose>

                </style>
            </head>                
            <body>
                <table>
                    <tr>
                        <xsl:for-each select="/NewDataSet/defects[1]/*">
                            <th>
                                <xsl:value-of select="name(.)"/>
                            </th>
                        </xsl:for-each>
                    </tr>
                    <xsl:apply-templates select="*"/>
                </table>
            </body>
        </html>
   </xsl:template>

    <xsl:template match="/NewDataSet/defects">
        <tr>
            <xsl:attribute name="class">testid<xsl:value-of select="testid"/></xsl:attribute>
            <xsl:for-each select="*">
                <td>
                    <xsl:value-of select="."/>
                </td>
            </xsl:for-each>
        </tr>
    </xsl:template>

    <xsl:template match="color" mode="addTRclassToCSS">
                    tr.testid<xsl:value-of select="@testid"/> {
                    color:<xsl:value-of select="."/>;
                    }
    </xsl:template>
</xsl:stylesheet>

WPF/Silverlight VS WinRT

5 votes

I never actually built an application (nor a HelloWorld) in WinRT, and I'm very suspicious.

My question is if there are features in WPF/Silverlight that don't exist in WinRT (excluding features that are implemented differently by design)?

And these aspects are most important to me and are the core of my question, and in result, decision to whether start using WinRT or wait for these to be implemented for it:

  • Entity Framework?
  • WCF RIA?
  • MVVM support (Prism)???
  • Various toolkits (Silverlight/WPF toolkit), that provide additional controls such as DatePicker etc.?

It's not clear to me whether WinRT fully targets .NET or how it works.

Also, is WinRT a client-only (like WPF) application or can be ran on a remote client while sitting on a server (like Silverlight)?

Another one: What about backwards compatibility, if I develop a WinRT app, will it ever be able to work on Win XP?

I anyway can't understand why MVVM is not integrated inline and has seamless IDE support as MVC has. but that's just a side note. I can't use XAML without MVVM, any app that is a bit bigger than hello world is easier to do with MVVM.

Update after answer

As I commented on the answer, I do like the design of WinRT, but the question remains unsolved until I know about the specific technologies mentioned above (EF, WCF-RIA + Validation, MVVM, SDKs and Toolkits). And obviously, I'm not gonna start selling WinRT apps or digging into it until I have the above techs as a least.

WinRT is basically a collection of COM objects that wrap a bunch of Win32 API', exposed as CLI-compliant assemblies.

Microsoft modified their C++ compiler to consume and generate ECMA 335 (i.e. CLI) metadata rather than the more traditional and (largely) C++/COM-only MIDL or lib file formats. Microsoft also modified their "Chakra" Javascript engine to also consume and emit CLI metadata.

This means that when targeting WinRT, Javascript and C++ code, along with .NET languages, of course, can consume CLI-compliant (i.e. .NET) assemblies and can emit CLI-compatible (i.e. .NET) assemblies.

So, one can write WinRT code in C++, any .NET language (i.e. C#, VB.NET, F#, Iron*, etc) and in Javascript.

The WinRT API's will be VERY familiar to you if you've ever written any .NET code. The Windows team actually sought the help & guidance of the .NET Framework design team when designing WinRT, so the same design guidelines that have guided the entire .NET framework team and most of the .NET community for the last 11 years have been applied to the WinRT API's.

WinRT is, quite frankly, beautiful :)

WinRT's primary impact is that it replaces System.IO's file, network, stream IO classes with similar API's but which ONLY support async IO. This means that you will not be able to write apps that block threads while they wait for calls to the filesystem or external systems via the network to return.

This is a GOOD thing.

Luckily, the new async/await features of C# v5 & VB.NET v.next, along with specific support for C++ mean that you don't have to go and fundamentally change how you write code in this new async world - typically you just need to add an "async" keyword to method signatures that call async API's and then use the 'await' keyword prefixing each async API call.

I STRONGLY encourage you to watch Anders Hejlsberg's session which should make this whole thing very clear. While you're there, I also encourage you to watch several of the other //BUILD sessions, especially Harry Pierson's talk on using WinRT with C# & VB.NET and Mads' session on Async Made Simple in C# and VB.

I'd also recommend that you take a look at the improved Win8/WinRT platform architecture diagram that I blogged a few weeks back which should make things a little clearer.

As for .NET itself, as I articulate in my post above, .NET is not "going away". While a few of the .NET API's will be prohibited in WinRT apps (i.e. blocking IO API's), most of the API's you depend upon remain and are fully accessible.

Regarding Silverlight: Silverlight is a browser plug-in. It's a modified-subset of WPF and offers some very powerful and attractive features. So much so, in fact, that the Silverlight XAML engine was moved into the core Windows team and is used for most of the Metro UI rendering in Windows8 - even by the OS itself!

The net result is that most of your Silverlight code will run just fine with barely any modification, other than just changing a few 'using' namespaces.

There are a ton of XAML-focussed sessions from BUILD available to watch here.

With regards backward compatibility, aim to:

  • Isolate code that you want to use in WinRT as well as in .NET desktop apps, Windows Phone, etc. into Portable Assemblies wherever possible.
  • Abstract code that needs to take specific platform dependencies and consider manually loading them or using IoC to compose your modules together.

Frankly, I don't think it's Microsoft's job to write every framework for every scenario. There are several MVVP approaches/frameworks out there in the wild from various people with various pro's and con's. And if you don't find one then create one and stick it up on GITHub and become famous ;)

Above all, though, there's little stopping you from downloading and trying Win8 Consumer Preview & Dev11 Beta. Go get them and try them out - I think you'll find them very refreshing :)

HTH.

Update#1 in answer to the specific support for EF, WCF, etc:

You can find the WinRT API surface area enumerated here in some detail. The core WCF API's are enumerated here.

Note, however, that Microsoft is strongly recommending against using network coomms to communicate between Metro apps and other metro apps or desktop apps/services on the same machine. Read this SO question & Kate Gregory's answer - she links to a video where this scenario is discussed in detail.

If you want to communicate with off-box network services, then you have a wide variety of options including WCF, sockets, etc.

Regarding RIA: Microsoft are currently saying that if you want data, you'll need to get it via a service rather than directly from a DB. There's no ADO.NET for Metro and the recommendation is to surface data via OData, JSON, XML/HTTP, etc. Data as a service is very much a RIA scenario, so I expect RIA to be well supported for Metro apps. Here's a BUILD session on this very subject which may shed more light.

Only you can tell whether or not your specific scenarios are supported in WinRT. I think your best bet would be to download the bits and start exploring.

How to get the ScrollViewer's VerticalOffset in dev independent pixels for an ItemsControl with CanContentScroll true

4 votes

I have a listbox with CanContentScroll true, but others that are false.

And i'm writing a behavior that needs to extract the scrollviewer from it and calculate the vertical scroll offset in device independent pixels.

Since the CanContentScroll can be either true or false I sometimes get logical item units while other times physical pixels.

So I need to calculate the pixel values in case CanContentScroll is true.

For an example: when the listbox is scrolled by three items VerticalOffset will give 3. How to convert this 3 to the vertical pixels used by the items (which can vary in size)?

Thanks

You cannot calculate the values in pixels without effectively setting CanContentScroll="False".

To know the size in pixels you would need to create the containers of all the items and sum up the heights of all the containers. To do that you will need to generate all the containers first. Which would mean that you effectively lost virtualization and effectively set CanContentScroll="False". In that case why use CanContentScroll="True" in the first place?

What Nikolay's code tries to do is take on the burden of doing yourself what CanContentScroll="False" does without giving you the smooth scrolling that you would have otherwise gained.

More importantly what problem does the physical offset solve that you cannot solve with the logical offset if you know that CanContentScroll="true" always?