Skip to content

Feed aggregator

SemVer 2.0 Released

you've been HAACKED - Phil Haack - 12 hours 51 min ago

One of the side projects I’ve been working on lately is helping to shepherd the Semantic Versioning specification (SemVer) along to its 2.0.0 release. I want to thank everyone who sent pull requests and engaged in thoughtful, critical, spirited feedback about the spec. Your involvement has made it better!

I also want to thank Tom for creating SemVer in the first place and trusting me to help move it along.

I’ve mentioned SemVer in the past as it relates to NuGet. The 2.0.0 release of SemVer addresses some of the issues I raised.

What’s Changed?

Not too much has changed. Most of the changes focus around clarifications.

Build metadata

Perhaps the biggest change is the addition of optional build metatada (what we used to call a build number). This simply allows you to add a bit of metadata to a version in a manner that’s compliant with SemVer.

The metadata does not affect version precedence. It’s analogous to a code comment.

It’s useful for internal package feeds and for being able to tie a specific version to some mechanism that generated it.

For existing package managers that choose to be SemVer 2.0 compliant, the logic change needed is minimal. Instead of reporting an error when encountering a version with build metadata, all they need to do is ignore or strip the build metadata. That’s pretty much it.

Some package managers may choose to do more with it (for internal feeds for example) but that’s up to them.

Pre-release identifiers

Pre-release labels have a little more structure to them now. For example, they can be separated into identifiers using the “.” delimiter and identifiers that only contain digits are compared numerically instead of lexically. That way, 1.0.0-rc.1 < 1.0.0-rc.11 as you might expect. See the specification for full details.

Clarifications

The rest of the changes to the specification are concerned with clarifications and resolving ambiguities. For example, we clarified that leading zeroes are not allowed in the Major, Minor, or Patch version nor in pre-release identifiers that only contain digits. This makes a canonical form for a version possible.

If you find an ambiguity, feel free to report it.

What’s Next?

As SemVer matures, we expect the specification to become a little more formal in nature as a means of removing ambiguities. One such effort underway is to include a BNF grammar for the structure of a version number in the spec. This should hopefully be part of SemVer 2.1.

Categories: Blogs

New Features in Team Foundation Server 2012

.NET TV - 13 hours 57 min ago
This webinar presents new features of Team Foundation Server 2012. Team Foundation Server (TFS) is an enterprise tool for managing your application lifecycle from requirements through code design, implementation, testing, and deployment. The ability to trace requirements, tasks, defects, and test cases to checked-in code improves tracking to more quickly and reliably deliver projects. The next version of TFS improves upon the experience of creating a product backlog, planning an iteration, and tracking the progress of a Sprint. This session walks through a lifecycle using the Agile methodology to demonstrate many ...
Categories: Blogs

ASP.Net MVC - How to Post a Collection

C-Sharpcorner - Latest Articles - 17 hours 16 min ago
Here I will describe how to post a collection in ASP.Net MVC 3 with the help of a sample application.
Categories: Communities

Creating a Wizard Application in LightSwitch 2012

C-Sharpcorner - Latest Articles - 18 hours 32 min ago
This article describes how to create a wizard application in LightSwitch using Visual Studio 2012.
Categories: Communities

Using CRUD Operations in ASP.Net Web API

C-Sharpcorner - Latest Articles - 18 hours 38 min ago
In this article I will use the CRUD (Create, Read, Update, Delete) operations in the ASP. NET Web API.
Categories: Communities

How do we Start With SharePoint 2013

C-Sharpcorner - Latest Articles - 18 hours 46 min ago
In this article you will learn how to start with SharePoint 2013.
Categories: Communities

Simple Alarm Application in Android Studio

C-Sharpcorner - Latest Articles - 18 hours 51 min ago
In today's article we will make our own Alarm clock. You will be able to hear the alarm sound after 15 seconds and the application will end on click of a button.
Categories: Communities

Binding User Control Data on Button Click With Modal Popup

C-Sharpcorner - Latest Articles - 19 hours 18 min ago
In this article you will learn how to bind user control data on button click with modal popup.
Categories: Communities

Image View Animation in Android Studio

C-Sharpcorner - Latest Articles - 20 hours 17 min ago
In this article you will learn Animation in Image View on button click.
Categories: Communities

Gaia Ajax 4.0 is in the nightly!

Official Gaiaware Blog - 21 hours 5 min ago

Gaia Ajax 4.0We have been spending a lot of time the last months wrapping up what will be the upcoming 4.0-release.

It is easy to grab the latest bits:

To get a summary of what has changed, take a look at front page of nightly samples.
We'd love to get your feedback, please use the forum.
Kind regards The Gaiaware team

 

 

Categories: Companies

TPL and the case of the !@#(*@! hung process

Ayende @ Rahien - 21 hours 8 min ago

So, here I am writing some really fun code, when I found out that I am running into dead locks in the code. I activate emergency protocols and went into deep debugging mode.

After being really through in figuring out several possible causes, I was still left with what is effectively a WTF @!(*!@ DAMN !(@*#!@* YOU !@*!@( outburst and a sudden longing for something to repeatedly hit.

Eventually, however, I figure out what was going on.

I have the following method: Aggregator.AggregateAsync(), inside which we have a call to the PulseAll method. That method will then go and execute the following code:

   1: public void PulseAll()
   2: {
   3:     Interlocked.Increment(ref state);
   4:     TaskCompletionSource<object> result;
   5:     while (waiters.TryDequeue(out result))
   6:     {
   7:         result.SetResult(null);
   8:     }
   9: }

After that, I return from the method. In another piece of the code (Aggregator.Dispose) I am waiting for the task that is running the AggregateAsync method to complete.

Nothing worked! It took me a while before I figured out that I wanted to check the stack, where I found this:

image

Basically, I had a dead lock because when I called SetResult on the completion source (which freed the Dispose code to run), I actually switched over to that task and allowed it to run. Still in the same thread, but in a different task, I run through the rest of the code and eventually got to the Aggregator.Dispose(). Now, I could only get to it if it the PulseAll() method was called. But, because we are on the same thread, that task hasn’t been completed yet!

In the end, I “solved” that by introducing a DisposeAsync() method, which allowed us to yield the thread, and then the AggregateAsync task was completed, and then we could move on.

But I am really not very happy about this. Any ideas about proper way to handle async & IDisposable?

Categories: Blogs

How to Create Virtual Directory of a Website

C-Sharpcorner - Latest Articles - 22 hours 21 min ago
In this article you will learn about how to create a Virtual Directory of a Website.
Categories: Communities

Log Parser Studio 2.0 now out (Log Parser GUI++)

Exchange Team Blog - Log Parser Studio 2.0 is now available

Since the initial release of Log Parser Studio (LPS) there have been over 30,000 downloads and thousands of customers use the tool on a daily basis. In Exchange support many of our engineers use the tool to solve real world issues every day and in turn share with our customers, empowering them to solve the same issues themselves moving forward. LPS is still an active work in progress; based on both engineer and customer feedback many improvements have been made with multiple features added during the last year. Below is a short list of new features:

  • Improved import/export functionality
  • Search Query Results
  • Input/Output Format Support
  • Exchange Extensible Logging Support
  • Query Logging
  • Queries
  • PowerShell Export
  • Query Cancellation
  • Keyboard Shortcuts

...

There are literally hundreds of improvements and features; far too many to list here so be sure and check out our blog series with existing and upcoming tutorials, deep dives and more. If you are installing LPS for the first time you'll surely want to review the getting started series:

If you are already familiar with LPS and are installing this latest version, you'll want to check out the upgrade blog post here:

..."

Log Parser Studio

Log Parser Studio is a utility that allows you to search through and create reports from your IIS, Event, EXADB and others types of logs. It builds on top of Log Parser 2.2 and has a full user interface for easy creation and management of related SQL queries.

...

Anyone who regularly uses Log Parser 2.2 knows just how useful and powerful it can be for obtaining valuable information from IIS (Internet Information Server) and other logs. In addition, adding the power of SQL allows explicit searching of gigabytes of logs returning only the data that is needed while filtering out the noise. The only thing missing is a great graphical user interface (GUI) to function as a front-end to Log Parser and a ‘Query Library’ in order to manage all those great queries and scripts that one builds up over time.

Log Parser Studio was created to fulfill this need; by allowing those who use Log Parser 2.2 (and even those who don’t due to lack of an interface) to work faster and more efficiently to get to the data they need with less “fiddling” with scripts and folders full of queries.

With Log Parser Studio (LPS for short) we can house all of our queries in a central location. We can edit and create new queries in the ‘Query Editor’ and save them for later. We can search for queries using free text search as well as export and import both libraries and queries in different formats allowing for easy collaboration as well as storing multiple types of separate libraries for different protocols.

If the Command Line Log Parser hurts your brain, then this is the tool for you...

 

Related Past Post XRef:
Learning Log Parser Studio in two parts... (From Install to Library Ninja)
Log Parser Studio - Think "Log Parser GUI" Or "Making Log Parser click-click fun and easy to use..." or "Query Analyzer for Log Parser"

Here's a look at the Microsoft Log Parser from a different point of view, from the Computer Forensics' side of the house OR Check out a 'Query Analyzer/SSMS' for Log Parser called Log Parser Lizard

Log Parser Ping Graph Fun (aka “Using Log Parser to parse command line output”)
SELECT * FROM Log... with the cool tool that’s been around for years, Log Parser!

Download details: Log Parser 2.2

The Unofficial Log Parser Support Site
IIS Diagnostics Toolkit (January 2006)
SQL Server 2000 Report Pack for IIS Logs

Categories: Blogs

//build Windows Store App available

XAMLGeek - BUILD app for Windows Store

In Bluefragments we love to do fun stuff. For the last couple of weeks we have been working on a BUILD app for Windows Store.

We wanted to build an app that is great to navigate through the content of the BUILD 13 conference. At the same time it should work as an archive over the previous BUILD conferences allowing the user to watch recorded sessions and published slides and demos. Last week we published first version [GD: The link is currently borked... Just search the Windows Store for build and you'll see it...]. We have got a lot of great feedback and the next version in certification at the moment. We expect it to be public within a few days.

We’re working hard to finish our BUILD app for Windows Phone as well. First version will include the BUILD 13 program. Stay tuned!

...

image

image

While //build 2013 is still empty (since no sessions have been announced) you can still use this app to view 2011 and 2012 //build sessions...

Categories: Blogs

Booting Minecraft (or maybe Assembling Minecraft) - MineAssemble is a bootable Minecraft clone, written in mostly x86 assembly

OS News - Bootable Minecraft clone written party in x86 assembly

"MineAssemble is a tiny bootable Minecraft clone written partly in x86 assembly. I made it first and foremost because a university assignment required me to implement a game in assembly for a computer systems course. Because I had never implemented anything more complex than a 'Hello World' bootloader before, I decided I wanted to learn about writing my own kernel code at the same time...."

Overv / MineAssemble 

image

MineAssemble is a tiny bootable Minecraft clone written partly in x86 assembly. I made it first and foremost because a university assignment required me to implement a game in assembly for a computer systems course. Because I had never implemented anything more complex than a "Hello World" bootloader before, I decided I wanted to learn about writing my own kernel code at the same time.

Note that the goal of this project was not to write highly efficient hand-optimized assembly code, but rather to have fun and write code that balances readability and speed. This is primarily accomplished by proper commenting and consistent code structuring.

Starting in assembly right away would be a bit too insane, so I first wrote a reference implementation in C using the SDL library, which can be found in the reference directory. I started writing it with the idea that if it was longer than 150 statements excluding boilerplate, it wouldn't be worth doing it in assembly. Like all estimates in the world of programming, this limit turned out to be a gross underestimate, reaching about 134 lines before adding the texture or even the input code.

After completing the reference code, I wrote the kernel boilerplate code (setting up VGA, interrupts, etc.) and changed the reference C code to work with this. Then I began slowly porting everything to handwritten assembly.

Unfortunately this turned out to be a lot more work than I expected, so currently a large fraction of the codebase is still in C. Slowly porting everything to assembly is an ongoing process. The code also isn't fully compatible with all systems yet. It seems to cause floating point exceptions on some setups.

How to play QEMU

To run the game with QEMU, simply run make test This is a quick and easy way to play around with it.

Virtual machine

If you want to use virtualization software like VirtualBox, you can produce an .iso image with make iso and mount it. The virtual machine doesn't need a hard drive and requires no more than 4 MB of RAM.

You can also burn this image to a CD or DVD, but that is rather wasteful. Use the USB stick method to try it on real hardware unless it really isn't an option for some reason.

USB stick

Booting from an USB stick is an excellent way to try it on real hardware, but does involve a little bit more work. Note that this process will remove all data currently on the USB stick. Also, make sure to get the drive name right or you might accidentally wipe your hard drive!

  1. Format your USB stick to FAT32 with 1 MB free space preceding.
  2. Mount it using mount /dev/sdx1 /mnt where sdx is the drive name.
  3. Turn it into a GRUB rescue disk with grub-install --no-floppy --root-directory=/mnt /dev/sdx.
  4. Run make iso and copy the contents of the iso directory to the USB stick.
  5. Unmount with umount -l /dev/sdx1.

Now reboot your PC and boot from USB.

...

image

..."

That's officially cool. Got to love he released the source too...

Categories: Blogs

View Persisted Logs in Azure Storage in Visual Studio 2012

Visual Web Developer Team Blog - Mon, 06/17/2013 - 19:43

In ScottGu’s Blog “Announcing the release of Windows Azure SDK 2.0 for .NET”, among all other new features, you learn how to stream your Windows Azure Web Site’s application logs into Visual Studio. It might be also useful if you persist those same logs in Azure Table Storage and view them in Visual Studio for certain time intervals. This blog will describe the steps how to achieve that.

You need to install Windows Azure SDK 2.0 for .NET from Windows Azure .NET Developer Center in order to use this feature.

Add Tracing To Your Application

Add some tracing in a WebForm application with Systyem.Diagnostics.Trace. To test, I usually add some traces inside the Page_Load method as shown below.

   1:      public partial class _Default : Page
   2:      {
   3:          protected void Page_Load(object sender, EventArgs e)
   4:          {
   5:              System.Diagnostics.Trace.TraceError("Application Error.");
   6:              System.Diagnostics.Trace.TraceWarning("Application Warning.");
   7:              System.Diagnostics.Trace.TraceInformation("Application Information.");
   8:              System.Diagnostics.Trace.WriteLine("Application WriteLine.");
   9:          }
  10:      }

Publish the project to Azure from VS 2012.

Store Application Logs in an Azure Table Storage

- At the Azure Portal, create a storage to store our application logs.

image

 

- You need to associate your web site with this storage by clicking on the “manage connection” under the Configure tab of your Azure site.

image

 

- Select the storage you created above in the pop-up dialog.

image

 

- This setting will show up under the Connection strings section of the site after the steps above.

image

 

Alternatively, you can set this connection string “CLOUD_STORAGE_ACCOUNT” manually within VS if you know the storage account key

image

- You can obtain the storage account’s key from the “Modify Account” dialog of the storage listed under “Windows Azure Storage” node in Server Explorer in Visual Studio.

image

Now you’re ready to see how things will work together.

First, we need to generate some application logs so we can view them later. Using the Azure Web Site with System.Diagnostics traces that we added at the beginning of this blog, each time we view//refresh the Default page in a browser, log will be generated and persisted in the Azure Table storage associated with the site.

View the Most Recent Application Logs in Azure Table

- Switch to the Logs tab of the site’s Settings window.

image

- The first time you open this Logs tab, you will see the spinning wheel indicating that it’s trying to retrieve the application logs in the Azure storage of the site. When the retrieval is complete, you will see the logs displayed in the table .

image

- You can change the time interval when the logs being stored in the Azure storage by change the dropdown selection

image

Also, if you want to view all the logs in the storage, click on the link on the upper right “View all application logs”, shown in the above picture. This will take you to the WAWSAppLogTable tab which lists all the loggings.

image

 

Note that by default, it will log only Application Errors traces of your site. To change the logging level, you need to go to the Configure tab of your site’s Portal UI

image 

b

Categories: Companies

How to tweet automatically when you push a new package to nuget.org

Daniel Cazzulino's Blog - Mon, 06/17/2013 - 18:59

Wouldn’t it be nice if your followers could be notified whenever you publish a new version of a NuGet package? Currently, nuget.org offers no support for this, but with the following tricks, you can get it working without programming.

The essential idea is to use the OData feed that nuget.org exposes to build an RSS feed with new items as you publish them, and have IFTTT do the tweeting from it.

The tools we’ll use to get this working are:

  1. LinqPad: to examine the nuget.org OData feed at https://nuget.org/api/v2 
  2. Yahoo Pipes: to tweak the OData feed output so that it looks like a “plain” feed
  3. IFTTT: to consume the pipe output and auto-tweet on new items

 

Exploring NuGet OData Feed with LinqPad

In order to build the query that will become your tweets’ source, we will add a new connection in LinqPad by clicking on the “Add Connection” link:

image

Make sure you pick WCF Data Services in this dialog and enter the OData Url https://nuget.org/api/v2 in  the next screen:

image

After the connection is set up and selected as the active connection in a new query, you can use Linq like the following:

Packages
    .Where (p => p.Authors.Contains("kzu") || p.Authors.Contains("Daniel Cazzulino"))
    .OrderByDescending(p => p.Published)
    .Select(p => new { p.Id, p.Title, p.GalleryDetailsUrl, p.Published })
    .Take(10)

Which will run in LinqPad and show the results as follows:

image

Note how the entire set of available properties for querying is shown under the connection on the left pane. Also, if you have the premium version of LinqPad, you’ll get very nice intellisense for all available types and operators.

The feed exposes all versions available for the same package, which is normal (and unavoidable, since there’s no support for Distinct here AFAIK). The ordering by Published will take care of getting the newest items first.

Once you’re happy with the results, you can click the Request Log tab and get the actual Url for that query:

image

I first tried to use this Url directly in IFTTT, but it didn’t work. The service complied that it was not a standard feed. And it’s true, since the information for an item in OData looks like the following:

<entry>
  <id>https://nuget.org/api/v2/Packages(Id='NuDoc',Version='0.4.1306.1409')</id>
  <title type="text">NuDoc</title>
  <summary type="text"></summary>
  <updated>2013-06-17T10:13:16Z</updated>
  <author>
    <name>Daniel Cazzulino,  kzu,  Clarius Labs</name>
  </author>
  <link rel="edit-media" title="V2FeedPackage" href="Packages(Id='NuDoc',Version='0.4.1306.1409')/$value" />
  <link rel="edit" title="V2FeedPackage" href="Packages(Id='NuDoc',Version='0.4.1306.1409')" />
  <category term="NuGetGallery.V2FeedPackage" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/zip" src="https://nuget.org/api/v2/package/NuDoc/0.4.1306.1409" />
  <m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <d:GalleryDetailsUrl>https://nuget.org/packages/NuDoc/0.4.1306.1409</d:GalleryDetailsUrl>
    <d:Published m:type="Edm.DateTime">2013-06-14T06:58:00.087</d:Published>
    <d:Title>NuDoc: A .NET XML API Documentation Reader</d:Title>
    <d:Summary m:null="true"></d:Summary>
  </m:properties>
</entry>

Clearly from the standard Atom properties we can’t do much: the title is actually the package Id and the links point to OData-formatted URLs whereas we’d typically like to point users to the nuget.org package page instead. The actual Url we’re interested in is inside a custom m:properties element, as d:GalleryDetailsUrl. We need to extract that info and make it part of the Atom/RSS entry itself.

Tweaking Feeds with Yahoo Pipes

Yahoo Pipes is a rarely used but insanely useful free service by Yahoo that enables arbitrary web mashups without writing a single line of code. In our case, we’ll use it to fetch the OData feed, and rewrite it as standard RSS, by projecting the properties we want from OData.

Head over to the Yahoo Pipes site, sign in and click the big blue Create a pipe button.

Drop a Fetch Feed source onto the designer and paste your OData Url in the Url field of the widget:

image

While widgets are selected in the designer, Yahoo Pipes will run the configured action and show a preview of the output in the Debugger pane. This is very useful to see how your output is progressing through the modules. If we expanded the first node now, we’d see a tree representation of the same Atom entry we saw above:

image

Next we’ll use the Rename operator to “lift” the link and title from within m:properties. Yahoo Pipes simplifies XML manipulation by letting you forget about namespaces and their added complexity. You can reference a node by name just as it appears on the above tree. So if you want to rename the d:Title, you just reference it as item.m:properties.d:Title from the Rename module. “item” refers to the current item in the feed, and you use dots to navigate down the tree. The node label is all you need to keep navigating or retrieve a value.

In the module configuration we use item.m:properties.d:Title, item.m:properties.d:GalleryDetailsUrl and item.m:properties.d:Published and renames them as title, link and pubDate respectively. You just need to connect the output of the Fetch Feed to the Rename module and you’ll immediately see how it’s turning out:

image

Now this is very close to what we need. In terms of the entries, we’re done! Note that the entry id properly points to a Url that is indeed unique within nuget.org for the package and version. This is good as it means we can use it as-is for the feed, since this id is used by IFTTT to determine if an entry is a new one or not (we only want to publish once when they are new). The problem, however, is that it’s based on the underlying OData implementation. It seems safer to use the package web address as a unique identifier. Also, we can get rid of all the other stuff we don’t need in IFTTT. This is not strictly necessary, and we could be done with this now, but it’s neater if we go just a bit further.

We’ll use another couple modules for this:  the Loop operator with a nested RSS Item Builder one:

image

Things to note from this screenshot:

  • We connected the Rename module to the Loop module. This enables the dropdowns in the RSS Item Builder to populate with properties coming from the Rename module
  • We have to select the “emit all results” radio button, since we want one RSS item for each source item
  • Finally we connect the loop to the pipe output.

Once we’re done and saved the pipe after giving it a name, we can run it to see how it looks:

image

We will copy the “Get as RSS” link and use in the next step.

Tweeting from IFTTT

This is the easiest part, and Scott has already explained the basis of IFTTT better than I could. You just activate your Twitter channel, and pick if[Feed]then[Twitter].

I’ve configured my IFTTT Twitter action as: just pushed new version of {{EntryTitle}} #nuget {{EntryUrl}}

You can see it in action in this tweet: https://twitter.com/kzu/status/345444465114234880

 

 

I’ve found that having both IFTTT and Yahoo Pipes in my toolset, you can get the web to work for you, automatically and without programming Sonrisa.

 

Enjoy!

Categories: Blogs

Factory Pattern in .Net With an Example

C-Sharpcorner - Latest Articles - Mon, 06/17/2013 - 17:52
In this article I try to explore this pattern in an easiest way with a very interesting topic Mobile.
Categories: Communities

Excel Tips n Tricks Tip 5 (Modify Shape and Style of Comment Box in Excel 2013)

C-Sharpcorner - Latest Articles - Mon, 06/17/2013 - 17:24
After going through this tip you will understand how to modify the shape and style of a Comment Box.
Categories: Communities

Hidden Code Mines

you've been HAACKED - Phil Haack - Mon, 06/17/2013 - 16:30

Code is unforgiving. As the reasonable human beings that we are, when we review code we both know what the author intends. But computers can’t wait to Well, Actually all over that code like a lonely Hacker News commenter:

Well Actually, Dave. I'm afraid I can’t do that.

Hal, paraphrased from 2001: A Space Odyssey

As an aside, imagine the post-mortem review of that code!

Code review is a tricky business. Code is full of hidden mines that lay dormant while you test just to explode in a debris of stack trace at the most inopportune time – when its in the hands of your users.

The many times I’ve run into such mines just reinforce how important it is to write code that is intention revealing and to make sure assumptions are documented via asserts.

Such devious code is often the most innocuous looking code. Let me give one example I ran into the other day. I was fortunate to defuse this mine while testing.

This example makes use of the Enumerable.ToDictionary method that turns a sequence into a dictionary. You supply an expression to produce a key for each element. In this example, loosely based on the actual code, I am using the CloneUrl property of Repository as the key of the dictionary.

IEnumerable<Repository> repositories = GetRepositories();
repositories.ToDictionary(r => r.CloneUrl);

It’s so easy to gloss over this line during a code review and not think twice about it. But you probably see where this is going.

While I was testing I was lucky to run into the following exception:

System.ArgumentException: 
An item with the same key has already been added.

Doh! There’s an implicit assumption in this code – that two repositories cannot have the same CloneUrl. In retrospect, it’s obvious that’s not the case.

Let’s simplify this example.

var items = new[]
{
    new {Id = 1}, 
    new {Id = 2}, 
    new {Id = 2}, 
    new {Id = 3}
};
items.ToDictionary(item => item.Id);

This example attempts to create a dictionary of anonymous types using the Id property as a key, but we have a duplicate, so we get an exception.

What are our options?

Well, it depends on what you need. Perhaps what you really want is a dictionary that where the value contains every item with the given key. The Enumerable.GroupBy method comes in handy here.

Perhaps you only care about the first value for a given key and want to ignore any others. The Enumerable.GroupBy method comes in handy in this case.

In the following example, we use this method to group the items by Id. This results in a sequence of IGrouping elements, one for each Id. We can then take advantage of a second parameter of ToDictionary and simply grab the first item in the group.

items.GroupBy(item => item.Id)
  .ToDictionary(group => group.Key, group => group.First());

This feels sloppy to me. There is too much potential for this to cover up a latent bug. Why should the other items be ignored? Perhaps, as in my original example, it’s fully normal to have more than one element for the key and you should handle that properly. Instead of grabbing the first item from the group, we retrieve an array.

items.GroupBy(item => item.Id)
  .ToDictionary(group => group.Key, group => group.ToArray());

In this case, we end up with a dictionary of arrays.

UPDATE: Or, as Matt Ellis points out in the comments, you could use the Enumerable.ToLookup method. I should have known such a thing would exist. It’s exactly what I need for my particular situation here.

What if having more than one element with the same key is not expected and should throw an exception. Well you could just use the normal ToDictionary method since it will throw an exception. But that exception is unhelpful. It doesn’t have the information we probably want. For example, you just might want to know, which key was already added as the following demonstrates:

items.GroupBy(item => item.Id)
    .ToDictionary(group => group.Key, group =>
    {
        try
        {
            return group.Single();
        }
        catch (InvalidOperationException)
        {
            throw new InvalidOperationException("Duplicate
  item with the key '" + group.First().Id + "'");
        }
    });
}

In this example, if a key has more than one element associated with it, we throw a more helpful exception message.

System.InvalidOperationException: Duplicate item with the
key '2'

In fact, we can encapsulate this into our own better extension method.

public static Dictionary<TKey, TSource>
  ToDictionaryBetter<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
  return source.GroupBy(keySelector)
    .ToDictionary(group => group.Key, group =>
    {
      try
      {
        return group.Single();
      }
      catch (InvalidOperationException)
      {
        throw new InvalidOperationException(
            string.Format("Duplicate item with the key
          '{0}'", keySelector(@group.First())));
      }
    });
}

Code mine mitigated!

This is just one example of a potential code mine that might go unnoticed during a code review if you’re not careful.

Now, when I review code and see a call to ToDictionary, I make a mental note to verify the assumption that the key selector must never lead to duplicates.

When I write such code, I’ll use one of the techniques I mentioned above to make my intentions more clear. Or I’ll embed my assumptions into the code with a debug assert that proves that the items cannot have a duplicate key. This makes it clear to the next reviewer that this code will not break for this reason. This code still might not open the hatch, but at least it won’t have a duplicate key exception.

If I search through my code, I will find many other examples of potential code mines. What are some examples that you can think of? What mines do you look for when reviewing code?

Categories: Blogs