Sync your Facebook with your phone! What’s the Sync Framework?

At TechEd Will and I had the chance to speak with Moe Khosravy, the lead PM (Program Manager) of the Microsoft Sync Framework. The interview is about the framework in general and what you can do with the current available bits.

The Sync Framework is an awesome technology that allows you to sync everything with everything. It is based on so called “sync providers”. They do the work, like reading from a source and writing to a target (that includes also solving conflicts etc.).

More details on the framework are found at the official website of the Microsoft Sync Framework.

Published on Jan 31st, 2008 — Tags: ,
Comments (0)    digg it!    kick it   

Generics in .NET (C#)

I have published another of my screencasts. This one is an entry level screencast for people who have little or no experience with generics in C# and .NET:

This screencast is all about generics in .NET and C#. First, it shows you how to use generics in your own applications and why they have been added to .NET. After that the screencast takes you through the most important features that are enabled through generics and shows you what you can do when implementing generic classes on your own.

Click here to watch it

Published on Jan 31st, 2008 — Tags: , ,
Comments (2)    digg it!    kick it   

Backpack for my future notebook

Today I have ordered something awesome:



Hehe *grin* :D

Published on Jan 31st, 2008 — Tags:
Comments (0)    digg it!    kick it   

Partial methods, automatic properties and the “var” keyword

This post will cover three additions to C# 3.0 that are: partial methods, automatic properties and the “var” keyword. All of them are quite useful but the first two really look like version 1.0 features. But one at a time:

Partial methods
Partial methods only work in partial classes. Partial classes consist always of two files where the two parts of the class are split up in two files (that’s not a must but most often true). During the compile process the compiler is then putting these two files together and generates one single class out of them.

An interesting scenario for partial classes is with tools (for example code generators); where one part of the class is generated by a tool and the other part is custom code that is created by the developer.

That’s also where partial methods come in handy. The tool creates the partial method stub (and invokes it also in some parts of its code) while generating its part of the partial class. The developer can then implement the partial method’s body if that is required. During compliation the C# compiler looks if the partial method has been implemented by the developer. If not all calls to the partial method and the partial method stub are removed, otherwise the stub is replaced by the implementation of the developer.

Partial methods have some limitations: they are always private and they need to return void. That might be very limiting but works great for notification services or similar features:

class Program
{
        public static void Main()
        {
                // create an instance of the class
                Foo f = new Foo();
                // and invoke the method.
                f.PrintName();
        }
}

// A partial class that holds methods.
public partial class Foo
{
        // prints additional information to the screen.
        // this is a partial method.
        partial void PrintAdditionalInfo();

        // prints the name to the screen.
        public void PrintName()
        {
                // prints the name.
                Console.WriteLine(“Hi Joe.”);

                // invoke the partial method to print
                // additional information.
                PrintAdditionalInfo();
        }
}

// The second part of the partial class.
public partial class Foo
{
        // the implementation of the partial method.
        partial void PrintAdditionalInfo()
        {
                Console.WriteLine(“I have been called!”);
        }
}

Automatic properties
Have you ever created a property for the pure sake of databinding? In that case you had to create the class field and the property with a getter and setter method. With automatic properties most of that work is done for you, by the compiler (btw. try the “prop” snippet to be even faster when creating them):

public class Foo
{
        // two automatic properties.
        public int ID { get; set; }
        public string Name { get; set; }
}

But automatic properties are very very limited. You can’t, for example, only define the getter or the the setter, which makes perfect sense because then there is no other way to set or fetch the value: you don’t have any information about the private field.

But you can’t even change the modifier of the getter or setter to private; or what is a lot more important: implement one of the two methods. It’s impossible to, for example, add validation code to the setter without also implementing the getter. If you want to do that you are back in C# 2.0 world where you have to implement everything on your own: there is no magic field that you can query to get the value that is currently stored in the field or that you can use to set the a value.

Automatic properties are only useful for prototyping and such. I can only see very limited usage in real-world code.

The “var” keyword; or anonymous variables
The var keyword is very useful. Actually it is the most useful addition of all the additions in this post. It allows you to omit the typing of the type of a variable and saves therefore time. As you might have noticed in my previous posts I like new features that save me time!

public static void Main()
{
        // create a new datetime variable.
        var date = DateTime.Now;
                       
        // and an int variable.
        var value = 1;

        // and a string variable.
        var text = “this is a text”;
                       
        // and a list.
        var list = new List<int>() { 1, 2, 3, 4 };

        // and an int array.
        var array = new[] { 1, 2, 3, 4 };

        // store the result of a LINQ query.
        var result = from f in list
                where f > 3
                return f;
}

There are also some limitations to the var keyword. It can’t be used outside of methods, for example, it can’t be used for the type of a class field.

It can’t also be used as the type of an argument of a method. That’s because the var keyword only removes the writing of the type: the compiler very clearly knows the type of the varaible (try to hover over the var keyword to see the actual type in the intellisense tooltip). If the var keyword would be allowed for the type of a method’s argument the type couldn’t be statically determined and that’s why it is not allowed. The var keyword is not adding dynamic typing to the C# language!

Published on Jan 30th, 2008 — Tags: , ,
Comments (2)    digg it!    kick it   

MSDN Code Gallery: tons of snippets, samples and resources

Today Microsoft has launched the MSDN Code Gallery. Soma Somasegar has already spoken about his engagement in the community and about something like this coming up at the TechED Developers in Barcelona.

The gallery is a portal for snippets, samples and other resources. It contains pages that describe samples and supporting documents that include screenshots and design documents. In addition, you find also hosted conversations about these samples, sample projects and a lot of other resources that are provided by the community itself. Everybody is free to contribute to the community and upload own content. :-)

Code Gallery is a community based website that allows Microsoft and developer to share information and resources. It is not a website to manage projects, like for example CodePlex is.

Published on Jan 29th, 2008 — Tags: , ,
Comments (0)    digg it!    kick it   

Member Initialization and Collection Initialization in C# 3.0

Member initialization and collection initialization are two new features that have been introduced with C# 3.0. I like both a lot because they are very handy and reduce a lot of typing. Even more they finally make initialization code look a lot better!

Collection Initialization
This feature is very useful and I think the best thing to introduce it is via an example - more exactly two examples: one in C# 2.0 (without the feature) and one in C# 3.0 (using the feature):

// the traditional C# 2.0 way.
List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
list1.Add(3);
list1.Add(4);

// and with collection initialization (C# 3.0).
List<int> list2 = new List<int>() { 1, 2, 3, 4 };

You can see it saves us a lot of typing and it looks also better. But this type of initialization works only for data or variables that are already known before compile time. You can’t construct a list with a varying amount of items in this way. But that’s also not the goal of this feature. The syntax looks exactly like the one to initialize an array with a predefined set of data. Internally the compiler converts the given syntax to the calls that we had to type in C# 2.0 and earlier.

This feature works with all classes that implement the ICollection<T> interface.

Member Initialization
This feature allows us to initialize properties during construction of the instance. I will also introduce it with an example in C# 2.0 and C# 3.0 code:

// the traditional C# 2.0 way.
Button button1 = new Button();
button1.Text = “This is a sample text.”;
button1.BackColor = Color.White;
button1.TextAlign = ContentAlignment.TopCenter;

// and with member initialization (C# 3.0).
Button button2 = new Button()
{
        Text = “This is a sample Text”,
        BackColor = Color.White,
        TextAlign = ContentAlignment.TopCenter
};

This way of initializing the members saves us a lot of typing and reminds me a little bit of the VB.NET’s “With” keyword.

This feature is very useful if you work with controls. One characteristic of controls is that their constructor never takes any arguments. That allows you to place them on a form (or another control) without having to specify anything: the form’s designer just creates the control by calling the default constructor. All the control’s settings are then specified by modifying the properties. If you construct a form (may it be a Windows form or even a web form) in code this addition will save you a lot of time and typing.

Published on Jan 28th, 2008 — Tags: , ,
Comments (0)    digg it!    kick it   

Edelweiss: demonstrating some cool graphic effects

Martin Kinkelin (a friend of mine) and I have finished developing the graphic demo (see related posts: 1, 2). It shows a museum scene with a dinosaur (a raptor), four anubis statues sitting on stone bases and two dragons. The dragon model is taken from “The Stanford 3D Scanning Repository”.

Further, a commuting light source is positioned at the top of the room and generates some nice shadow effects. On the two sides (left and right) of the room there are two dragons that look at the opposite direction of each other:



We have implemented the following effects: Bloom, Shadow Maps, Normal Mapping, Parallax Mapping and animated objects. Try to spot them in the demo :D

Curious? Want to check it out? Download the demo from here.

Published on Jan 27th, 2008 — Tags: , , ,
Comments (0)    digg it!    kick it   

Anonymous types in C# (and .NET 3.5)

So what the heck are anonymous types all about? What’s the difference between a normal type and an anonymous type? First and most important: the anonymous type has no type name. Actually that is not 100% true. The anonymous type has a type name (because all types in .NET need to have one) but it is the compiler who generates the name, not the developer itself and you won’t see it in your code.

Another important difference is that the (C#) compiler generates a type that can only be initialized once and no longer altered afterwards. The type instance is created and some values are assigned to it but later in the code they can’t be changed anymore. The anonymous type is a so called immutable type (= initialize once and never change it again; System.String is another prominent immutable type).

Most often you will find anonymous types as a result of a LINQ query:

class Program
{
        static void Main(string[] args)
        {
                // create a list with dummy users.
                // the user class has a Name and Age property.
                List<User> users = new List<User>();
                users.Add(new User(“Foo”, 12));
                users.Add(new User(“Bar”, 20));
                users.Add(new User(“FooBar”, 15));

                // query the items for user with an age above 14.
                var result = from u in users
                                where u.Age >= 15
                                 // put the result in a anonymous type
                                 select new { u.Name };

                // loop over the result.
                foreach (var item in result)
                {
                        // print out the name of the item.
                        Console.WriteLine(item.Name);
                }
        }
}

This is also why anonymous types have been introduced. They allow us to create a type on the fly and therefore return only certain values of a given named (= non-anonymous) type. This is very handy when only a subset of properties is needed, properties are joined together or even objects are joined together.

But anonymous types can also be used in own code without expressing them in a LINQ expression. For example when variables should be aggregated together for a short period:

// create an anonymous type instance with a name.
var anonymousType = new { Name = name,
        Age = age, Nationality = nationality };

// print the name to the console.
Console.WriteLine(anonymousType.Name);

This might not be found that often in real-life code because anonymous types are limited. They can, for example, not be passed to other methods - well it could be done but that would mean to pass them as System.Object and therefore their properties can only be accessed by using reflection.

// query the items for user with an age above 14.
var result = from u in users
                 join g in calls on u.ID equals g.UserID
                 // put the result in a anonymous type
                 select new { UserName = u.FirstName + ” “ + u.LastName,
                         CallName = g.Name, g.TimeStamp };

This is another example on what we can do with the anonymous types. In this case the LINQ query joins two objects (User and Call) together and as result the user’s name, the call’s name and time stamp are returned. To avoid problems (like the two objects expose the same properties), we can specify the property names of the anonymous type and assign the values to them (this is also done in the example). Even more, in the example, the user name is assigned as a concat of the first and the last name.

Another interesting question is on how the C# compiler exactly translates the code. The following screenshot shows the class that has been generated for the first anonymous type in this post:

The name is completely compiler generated and is also incremented for each new anonymous type in the program. For all the arguments (in our case one) that are passed to the anonymous type an argument in the constructor has been defined. What’s also important to know is that the GetHashCode() and Equals(Object) methods have been overriden. This has been done to allow LINQ to store the anonymous types instances in a dictionary and fetch them later on. This is also why the properties (in this case the Name property) and the internal fields are marked as read-only in the anonymous types. The GetHashCode() method relies on the content of the fields and if they are altered while being in the dictionary the instance can’t be find anymore later on.

Another interesting thing is that the C# compiler recycles anonymous types. This means if we have like two anonymous type’s instances where we specify the exact same properties we will end up with getting the exact same anonymous type:

// query the items for user with an age above 14.
var result = from u in users
                 select new { u.Name };

// create an anonymous type instance with a name.
var anonymousType = new { Name = “Test” };

// prints TRUE to the console.
Console.WriteLine(anonymousType.GetType() == result.First().GetType());

But how to detect anonymous types in an application? Let’s say you have a framework and you want to understand whether a type is an anonymous type. The bad news first: there is no way to be 100% sure that a type is an anonymous type as the name is completely generated by the compiler and there is no flag that says that the given type is an anonymous type. But a heuristic can be implemented to detect at least the anonymous types that are generated by VB.NET and C#:

private static bool CheckIfAnonymousType(Type type)
{
        if (type == null)
                throw new ArgumentNullException(“type”);

        // HACK: The only way to detect anonymous types right now.
        return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                   && type.IsGenericType && type.Name.Contains(“AnonymousType”)
                   && (type.Name.StartsWith(“<>”) || type.Name.StartsWith(“VB$”))
                   && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}

Attetion: Keep in mind that this is a hack and might not work with future versions of the C# and VB.NET compilers.

Published on Jan 26th, 2008 — Tags: ,
Comments (2)    digg it!    kick it