I recently had to write a small Flickr API. I know many .Net API for Flickr already exist but I needed one for a Silverlight application. Whatever, it's only about building some querystrings so I did it by myself. It's been an opportunity to think again about a classical question: how to pass parameters to a method ?
Imagine you have a generic method to call some Flickr functions.
public void CallFlickrMethod(string methodName, ? parameters,
DownloadStringCompletedEventHandler asyncResult)
The goal here is to finally build a querystring like:
http://api.flickr.com/services/rest/?method=mymethod¶m1=value1¶m2=value2...
In that case, I would like to pass a collection of parameters, each parameter being a key+value structure.
The .Net framework (Silverlight too) offers a KeyValuePair<TKey, TValue> structure that we could use here.
We could imagine a method like:
public void CallFlickrMethod(string methodName, KeyValuePair<string, string>[] parameters,
DownloadStringCompletedEventHandler asyncResult)
Call:
CallFlickrMethod("mymethod",
new KeyValuePair[] {
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2")
},
completedHandler);
You may also know the 'params' keyword that allows you to pass parameters separated by commas instead of having to build an array:
public void CallFlickrMethod(string methodName, DownloadStringCompletedEventHandler asyncResult,
params KeyValuePair<string, string>[] parameters)
Call:
CallFlickrMethod("mymethod", completedHandler,
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2"));
You can notice that the params parameter must be the last one of the method prototype. This syntax is shorter but still a little bit heavy to write because we have to create many KeyValuePair structures.
In that case, parameters names are unique so we are very close to have a dictionary.
We could imagine:
public void CallFlickrMethod(string methodName, DownloadStringCompletedEventHandler asyncResult,
Dictionary<string, string> parameters)
Call:
var parameters = new Dictionary<string, string>();
parameters.Add("param1", "value1");
parameters.Add("param2", "value2");
CallFlickrMethod("mymethod", completedHandler, parameters);
The method is simpler but the call is still heavy because of the dictionary creation.
Then I thought about using anonymous methods. This is only working because keys are strings. In a class, properties names are unique. Properties definitions are stored in the type definition itself and the properties values are stored in the instance of the class. So we could imagine using an object as a kind of readonly dictionary (keys are fixed).
Imagine we change our method to just:
public void CallFlickrMethod(string methodName, DownloadStringCompletedEventHandler asyncResult,
object parameters)
Then we could use new C#3 anonymous types to write:
CallFlickrMethod("mymethod", completedHandler, new { param1 = "value1", param2 = "value2"});
This syntax is of course very short and also very easy to use.
The following code is analyzing the 'parameters' object using reflection to retrieve the equivalent of a collection of KeyValuePairs.
public void CallFlickrMethod(string methodName, object parameters,
DownloadStringCompletedEventHandler asyncResult)
{
string url =
string.Format("http://api.flickr.com/services/rest/?method={0}&api_key={1}",
methodName, apiKey);
var q =
from prop in parameters.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
select string.Format("&{0}={1}", prop.Name, prop.GetValue(parameters, null).ToString());
url += string.Join("", q.ToArray());
// Or for linq addicts :p
// url += q.Aggregate(new StringBuilder(), (sb, value) => sb.Append(value)).ToString();
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += asyncResult;
webClient.DownloadStringAsync(new Uri(url));
}
Let's say this is the end of part I.
We could now think about generalizing the use of an object as a readonly dictionary.
What I propose is to offer a way to wrap an object in a generic class implementing IDictionary<TKey, TValue>. IDictionary is quite long to implement but here is an abstract of the important methods.
public class ObjectDictionary<T> : IDictionary<string, object>
{
public ObjectDictionary(T instance)
{
this.instance = instance;
}
private T instance;
#region IDictionary<string,object> Members
public bool ContainsKey(string key)
{
return typeof(T).GetProperty(key) != null;
}
public ICollection<string> Keys
{
get
{
return typeof(T).GetProperties()
.Select(p => p.Name).ToArray();
}
}
public bool TryGetValue(string key, out object value)
{
var p = typeof(T).GetProperty(key);
if (p == null)
{
value = null;
return false;
}
else
{
value = p.GetValue(instance, null);
return true;
}
}
public ICollection<object> Values
{
get
{
return typeof(T).GetProperties()
.Select(p => p.GetValue(instance, null)).ToArray();
}
}
public object this[string key]
{
get
{
object result = null;
if (TryGetValue(key, out result))
return result;
else
throw new Exception("Key not found");
}
set
{
object result = null;
if (TryGetValue(key, out result))
result = value;
else
throw new Exception("Key not found");
}
}
...
#endregion
#region ICollection<KeyValuePair<string,object>> Members
public int Count
{
get { return typeof(T).GetProperties().Length; }
}
public bool IsReadOnly
{
get { return true; }
}
...
#endregion
#region IEnumerable<KeyValuePair<string,object>> Members
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
var q =
from p in typeof(T).GetProperties()
select new KeyValuePair<string, object>(p.Name, p.GetValue(instance, null));
return q.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
Then you can write things like:
ObjectDictionary<Customer> c =
new ObjectDictionary<Customer>(
new Customer { ID = "1", CompanyName = "Microsoft", ContactName = "Mitsu" });
Console.WriteLine(c["CompanyName"]);
With an extension method ?
public static class ObjectDictionaryExtensions
{
public static ObjectDictionary<T> AsDictionary<T>(this T instance)
{
return new ObjectDictionary<T>(instance);
}
}
Use:
var cust = new Customer { ID = "1", CompanyName = "Microsoft", ContactName = "Mitsu" };
var c = cust.AsDictionary();
Console.WriteLine(c["CompanyName"]);
With an implicit conversion ?
public class ObjectDictionary<T> : IDictionary<string, object>
{
public ObjectDictionary(T instance)
{
this.instance = instance;
}
public static implicit operator T (ObjectDictionary<T> source)
{
return source.instance;
}
public static implicit operator ObjectDictionary<T> (T source)
{
return source.AsDictionary();
}
...
}
Use:
ObjectDictionary<Customer> c =
new Customer { ID = "1", CompanyName = "Microsoft", ContactName = "Mitsu"};
Of course all these features are more funny to use with anonymous types:
var cust = new { ID="1", CompanyName="Microsoft"};
var c = c.AsDictionary();
var id = c["ID"];
Let's see one last point. In the case of an anonymous type, we can't use the following syntax:
var c =
new ObjectDictionary<?>(new { ID = "1", CompanyName = "Microsoft", ContactName = "Mitsu"});
This is a classical problem where a regular constructor can not infer T from the parameters. If you want to do it, you have to create a static generic method to create your instance. Then the inference will work fine and make the use of an anonymous type possible.
public class ObjectDictionary
{
public static ObjectDictionary<T> Create<T>(T instance)
{
return new ObjectDictionary<T>(instance);
}
}
Use:
var c = ObjectDictionary.Create(new { ID = "1", CompanyName = "Microsoft", ContactName = "Mitsu" });
foreach (var prop in c.Keys)
Console.WriteLine(c[prop]);
You can find the source code for VS2008 attached to this post.
I have just finished converting the control to silverlight one week away from Silverlight 2 beta 2 release date, so I have been waiting for it !
For people to be able to compare code (quite similar) and behavior between the WPF and the Silverlight control, I have kept the same codeplex project to host the whole solution.
So the address is still the same: http://www.codeplex.com/wpfbookcontrol and the project title has been renamed to 'WPF and Silverlight BookControls'.
The silverlight control is a bit different:
- it's a UserControl.
- the data connection natively proposes data virtualization.
The ItemsControl control does not allow data virtualization today. As I absolutely wanted it for this silverlight version, I voluntarily did not respect the ItemsSource behavior.
As a datasource, you have to provide a very simple interface:
public interface IDataProvider
{
object GetItem(int index);
int GetCount();
}
The control will ask you on the fly for those two methods to dynamically retrieve needed pages.
In your application, just add a reference to SLMitsuControls.
Then use it in your xaml page: in this sample, I am using a static content to defines pages.
<UserControl x:Class="SLBookDemoApp.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SLMitsuControls;assembly=SLMitsuControls"
Width="400" Height="300" Loaded="UserControl_Loaded">
<UserControl.Resources>
<ItemsControl x:Name="pages">
<Button Content="Page 0" Click="Button_Click" />
<Button Content="Page 1" Background="Green" Click="Button_Click_1" />
<Button Content="Page 2" Background="Yellow" Click="Button_Click" />
<Button Content="Page 3" Background="Red" Click="Button_Click_1" />
</ItemsControl>
</UserControl.Resources>
<Grid>
<local:UCBook x:Name="book" Margin="50" />
</Grid>
</UserControl>
Then you must implement IDataProvider and call the SetData() method.
public partial class Page : UserControl, IDataProvider
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
book.SetData(this);
}
#region IDataProvider Members
public object GetItem(int index)
{
return pages.Items[index];
}
public int GetCount()
{
return pages.Items.Count;
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
book.AnimateToNextPage(500);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
book.AnimateToPreviousPage(500);
}
}
Let me remind you that you can find a good dynamic sample in this flickr application:
Here is a control that everybody can easily use. This allow you to display Flickr pictures in a blog post or in any web page.
For example this set of pictures (http://www.flickr.com/photos/benjamingauthey/sets/72157604570177365/), taken by my friend Benjamin during Paris Remix 08 can be browsed just here in this post.
Now, how to get this on your own web page/blog ? There is just a few steps to follow and here is a video that explains how to do it :
Go to this page to configure your own control: http://blogs.msdn.com/mitsu/archive/2008/05/14/create-a-virtual-book-with-your-flickr-pictures.aspx
Full code source will be released very soon.
I was getting really bored with testing .ContainsKey() at each time I wanted to read a value from a dictionary.
Dictionary<string, string> dico;
if (dico.ContainsKey("key"))
value = dico["key"];
else
value = "default";
A incredibly simple extension method solves this so easily:
public static class MyExtensions
{
public static TValue GetValue<TKey, TValue>(
this IDictionary<TKey, TValue> source,
TKey key, TValue defaultValue)
{
if (source.ContainsKey(key))
return source[key];
else
return defaultValue;
}
}
The call from any dictionary now becomes:
value = dico.GetValue("key", "default");
...sometimes I just wonder how I did not think about such solutions earlier ! :-)
Enjoy,
Code is coming very soon..
[Update]: code is now available here !
Mitsu
Move the mouse cursor around the corners
Hi all,
After almost one year of work and organization, I am very happy to share this project with you:
http://code.msdn.microsoft.com/vlinq - new setup fixed (4/17/2008)
The Visual Linq query builder is a Visual Studio 2008 addin. It's a designer that helps you create Linq to Sql queries in your application. Both C# and VB projects are supported.

As you will read it in this post, this project developed by interns is a prototype for a new kind of designers.
Please give us your feedbacks !!!
Project history
It is an academic project developed during a Microsoft France internship in collaboration with Microsoft Corporation.
I have been the 'local' manager and technical lead of the project. I wanted to create a VS designer using WPF for a long time and I had the idea of a query builder for Linq to Sql. Then came the opportunity to organize a 6 months long internship in collaboration with Ms Corp.
I have recruited two french students that I want to thank again today for their excellent job.
- Simon Ferquel from SupInfo who is now working in a french company (Winwise). You may know him from the time he was student as the author of a funny tool for Vista : myExposé.
- Johanna Piou from ISEN Toulon who is still student this year and who is well known for her brilliant Imagine Cup participation in the Interface Design category.
You can find the French description of the project here: http://msdn.microsoft.com/fr-fr/vcsharp/default.aspx (coming soon).
The project goal
Linq to Sql and Linq more generally speaking, is a new technology mainly based on language evolutions. As any new syntax, you have to take some time to get familiar with it.
The VLinq project as any designer helps you to build graphically Linq to Sql queries but we wanted to keep it visually very close from the code. The goal is not to hide the generated code but to make it visible in the designer. It's a kind of mix between a classical designer and a graphical intellisense.
VLinq also helps you grouping all queries at the same place allowing easy management (edit, add, remove) and previewing and testing.
Last goal: releasing the whole solution, including source code to share with you our experience about using WPF with VS2008 extensibility.
What do we release ?
The whole project has been developed using Visual Studio 2008 (betas then RTM) and Expression Blend. We provide the whole solution (binaries + source code). The solution contains a Setup project for a quick installation (msi file).
You can get all the stuff here: http://code.msdn.microsoft.com/vlinq/ under the 'Releases' tab. (msi, quick reference guide, user documentation, webcast).
---------------------------------------------------------------------------------------------------------------------------------
Quick Reference Guide
Once Visual Linq Query Builder is installed, you can create a new project or open an existing project (C# or VB.Net). From this designer you will be able to create, modify and delete queries. When editing a query, the query designer will appear and let you build your query visually. At each time the designer is saved, the corresponding code (C# or VB.Net) will be generated. Then the queries are ready to be used by your project. The following steps are for the first time users of Visual Linq Query Builder.
- Create a new project
If you installed Visual LINQ Query Builder, you can create a new project or open an existing project (C# or VB) in Visual Studio.
- Add a LINQ to SQL class
Once a project is created, a LINQ to SQL class should be added to the project.
- Add connection to SQL database
If Linq to SQL class is added, a .dbml file is added to the project. You open the .dbml and can set the connection to SQL database by clicking “Server Explorer” and “Add Connection”
To work with LINQ to SQL and Visual LINQ Query Builder in Visual Studio 2008, you will need a database that you can query. If you already had a database, you can set the connection to the database by clicking “Server Explorer”.
Otherwise, you can access the copy of the Northwind database that accompanies the C# samples that ship with Visual Studio 2008. You can also download the latest C# samples from http://msdn2.microsoft.com/en-us/bb330936.aspx. The Northwind.mdf will be found in the directory, CSharpSamples\LinqSamples\Data.
The setup guideline for the SQL database can also be found in Charlie Carvert’s bolg.
You can set the connection to the copy of Northwind.mdf or your database.
Once connection is added, you can navigate to the objects in the database and select a table you want to query.
- Add the designer to the project
Add a new item, “VLinq queries” to the project. When opening the new .vlinq file added to your project, the query bag designer will appear.

- Set the connection to VLINQ
In the Properties of the vlinq, set Connection String to the database you want to query. Select “Visual studio Connection” and the database.
- Create a new query
If you open the .vlinq file added to the project, you can see query bag designer. In the query bag designer, you can create a query using the query bag designer by clicking an icon “Create a new query”.
- Edit the query in the query bag designer
- Query in collapsed mode
- Preview the query result
Once you edit the query and “save” the .vlinq file, the code is generated. If you click “Preview”, you can see the query result in the below.
- View the generated code
Query designer code is generated if you save the query. You can build the project using the code.
Have Fun !
Mitsuru FURUTA - Microsoft France
Just a short informative post: David Catuhe, a french MVP from south of France is demoing a Silverlight 3D engine preview...
http://www.catuhe.com/NovaLight/NovaLight.aspx

His company 'Vertice' is selling the Nova product (a full .Net 3D engine based on Managed DX).
You can find some awesome demos here: http://www.vertice.fr/
In my previous post (http://blogs.msdn.com/mitsu/archive/2007/06/21/how-to-implement-a-many-to-many-relationship-using-linq-to-sql.aspx), I had proposed a simple solution for implementing many-to-many relationships using Linq to Sql.
Actually, this solution is a generic Linq solution. It's also working with just memory collections (not only Linq to Sql).
Many of you asked me for add/remove support.
Let's clarify a few things:
The current solution offers extensions to IList<T> and IBindingList.
Actually, the current solution is good enough when extending IList<T> and is very basic for IBindingList. Proxying (simulating) IList<T> is quite easy because we don't have a lot of possible technical issues. Proxying IBindingList with add/remove support is much more complicated.
For example, as we are virtually changing the item type (see ListSelector class), the notion of sorting becomes quite strange (we have to sort an OrderDetails collection from a Product property !!!).
Similarly, adding and removing don't have a real meaning from a Product entity.
In a many to many relationship, writing order.Products.Remove(n) should probably mean order.OrderDetails[n].Remove(). Of course we do not want to delete the associated product. The functional meaning is 'detaching' a product from it's many to many relationship with an order.
IList<T> contains the methods for adding and removing, so that's where we have to update the code. IBindingList is adding list change notifications necessary for binding.
The first thing is, there no universal solution because we don't know the real nature of the relationship. Sometimes, the link table has no functional meaning other than making the relationship. In that cases, the link table is only grouping foreign keys to join each table of the many-to-many relationship. Some other times, the link table contains other columns that have a functional meaning. For example, in a link table between an order and a product, the price is duplicated so it belongs to this specific order and stores the price at the time we had made the order.
What I am trying to say is we can not use an automatic logic to implement adding/removing.
So what I am proposing is to catch adding and removing from our IList entry points and to delegate those actions to external code.
Let's start with adding:
public class ListSelector<TSource, T> : IList<T>, IList
{
...
protected Action<IList<TSource>, T> onAdd;
...
public void Add(T item)
{
if (onAdd != null)
onAdd(source, item);
}
In the northwind case (Order/OrderDetails/Product), a good implementation for this delegate could be:
(ods, p) => ods.Add(
new Order_Detail { OrderID = currentOrder.OrderID, Product = p, Quantity=1 })
Of course we can notice that the goal is not to insert a Product (T) but an OrderDetail.
To make it easier to use, I have also added a new constructor so we can write:
public partial class Order
{
private ListSelector<Order_Detail, Product> products = null;
public ListSelector<Order_Detail, Product> Products
{
get
{
if (products == null)
products = this.Order_Details.GetNewBindingList()
.AsListSelector<Order_Detail, Product>(
od => od.Product,
(ods, p) => ods.Add(
new Order_Detail {
OrderID = this.OrderID,
Product = p, Quantity=1 })
We can notice that this syntax allows you to custom the OrderDetail creation. It's important because in our Northwind case, we had not only foreign keys but also Quantity and some other columns in the link table (OrderDetails). We can also notice that we had to know the Order to get the OrderID field. Fortunately, the lamba expression syntax allows us to share 'this.OrderID' from the host method scope. (same if we had used an anonymous method).
I will explain later in this post why I have used the GetNewBindingList method.
Now what about removing ? Removing is more complex because we have to find the entity before we remove it. (We start from a Product and we need to remove the corresponding OrderDetail).
The structure is very close to adding:
...
protected Action<IList<TSource>, T> onRemove;
...
public bool Remove(T item)
{
if (onRemove != null)
{
onRemove(source, item);
return true;
}
else
return false;
}
and the ListSelector is created that way:
public partial class Order
{
private ListSelector<Order_Detail, Product> products = null;
public ListSelector<Order_Detail, Product> Products
{
get
{
if (products == null)
products = this.Order_Details.GetNewBindingList()
.AsListSelector<Order_Detail, Product>(
od => od.Product,
(ods, p) => ods.Add(
new Order_Detail {
OrderID = this.OrderID,
Product = p, Quantity=1 },
delegate(IList<Order_Detail> ods, Product p)
{
var odToRemove = ods.Where(
od => od.ProductID == p.ProductID).Single();
Singleton<NorthwindDataContext>.Default
.Order_Details.DeleteOnSubmit(odToRemove);
ods.Remove(odToRemove);
})
return products;
}
}
As we need more that one instruction, I could not keep the lambda expression syntax. The anonymous method is quite the same here.
First we have to find the OrderDetail entity corresponding to the product.
Then, delete this entity. This is an issue because we have to 'talk' to Linq to Sql to declare this entity as to be removed on next SubmitChanges call. The issue is we don't have access to the datacontext at this point. I can imagine many different scenarios to make it visible here in the Order class but not to make this sample to much complicated, I have decided to give access to the current NorthwindDataContext through a static property.
Depending on your architecture, you can imagine other solutions. To preserve domain isolation, I would recommend to use an interface that would make abstraction of the persistence nature (Linq to Sql/DataContext/DeleteOnSubmit).
Just as a remark, here is the code of the generic singleton pattern I have used:
public class Singleton<T> where T : class, new()
{
private static T defaultInstance = null;
public static T Default
{
get
{
if (defaultInstance == null)
defaultInstance = new T();
return defaultInstance;
}
}
}
Last thing to explain, why did I have used 'this.Order_Details.GetNewBindingList().AsListSelector<Order_Detail, Product>(...);' ?
I have two AsListSelector extension methods. The first is extending IList<T> and the second one, IBindingList. As the extension method resolution is based on the reference type, I had to call AsListSelector from an IBindingList, so I can get binding notifications (add/remove).
The EntitySet class does not implement IBindingList but can provide an internal class that does !
When binding directly a Linq to Sql query to a winforms control, this class is provided implicitly:
is equivalent to:
grid.DataSource = ((q as IListSource).GetList() as IBindingList);
To avoid multiple query execution when binding q many times, the result is cached in memory.
The GetNewBindingList method allows to get a fresh BindingList at each call.
Now we are done !
Let's modify the UI :
You have to use the main menu to submit the changes to the database 'Data>SubmitChanges'.
The whole source code is available on code gallery: http://code.msdn.microsoft.com/linqtosqlmanytomany
Shawn asked me in my last post about GroupByMany how to use it dynamically.
The answer is not easy. So here is a new post to answer to this interesting question.
First you must learn a few things about being dynamic with linq.
There is a very good sample from the C# team (actually we can consider it as a library provided as a sample). ScottGu has post about it here: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx.
One of the power of linq is to be checked at compile-time. You must be aware that using this kind of solution may raise some exceptions at runtime.
Now I have added the Dynamic.cs file to my project and I can use a very useful method: DynamicExpression.ParseLambda.
Here is a new GroupByMany extension method which accepts a list of strings instead of delegates to define all the groupings.
The goal is to call the first GroupByMany method. To do this we have to go from a single string defining the name of a property in the TElement class to a Func<TElement, object>.
We could do this building the expression manually but DynamicExpression.ParseLambda will do it in just a single line.
public static class MyEnumerableExtensions
{
public static IEnumerable<GroupResult> GroupByMany<TElement>(
this IEnumerable<TElement> elements, params string[] groupSelectors)
{
var selectors =
new List<Func<TElement, object>>(groupSelectors.Length);
foreach (var selector in groupSelectors)
{
LambdaExpression l =
DynamicExpression.ParseLambda(
typeof(TElement), typeof(object), selector);
selectors.Add((Func<TElement, object>) l.Compile());
}
return elements.GroupByMany(selectors.ToArray());
}
...
Now we can write directly:
DataContext = customers.GroupByMany("Countr