Handling TPL exceptions in MSTest unit tests

Introduction

In the past couple of years TPL (Task Parallel Library) and language features it brought became more and more popular in the .NET community. One of the differences that stood up is the exception handling. Unhandled exceptions that are thrown by user code that is running inside a task are propagated back to the joining thread. To propagate all the exceptions back to the calling thread, the Task infrastructure wraps them in an AggregateException instance.

Now this is all clear and quite straight forward to manage. I will not go in the detail about this topic as you can find all of the necessary information on MSDN at http://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx.

Once I started writing unit tests for my async methods I found out that I can’t anymore use my usual technique.

In order to assert that a certain unit is throwing a certain exception in well determined circumstances, I always went for the ExpectedException attribute. To make it even clearer, I will make an example of usage.

Now imagine the following class:

public bool MySimpleMethod(List param)
{
    if (param == null)
    {
        throw new ArgumentNullException("param");
    }
 
    return true;
}

We are going to write a test that will assert that in case of a null being passed as a parameter to this method call, the method should raise an ArgumentNullException.
In order to do so, consider the following code.

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void MySimpleMethod_Throws_ArgumentNullException()
{
    sut.MySimpleMethod(null);
}

Once executed, this test will pass.
Now let’s write an async analog of the previous method.

public async Task MySimpleMethodAsync(List param)
{
    if (param == null)
    {
        throw new ArgumentNullException("param");
    }
 
    await Task.Delay(100);
 
    return true;
}

If we now try to execute the following test, it will fail.

public async Task MySimpleMethodAsync(List param)
{
    if (param == null)
    {
        throw new ArgumentNullException("param");
    }
 
    await Task.Delay(100);
 
    return true;
}

As we do know that our exception is wrapped in an AggregateException, it is expected our test to fail. How should we than test this kind of situations?

Building a new attribute

Wait, I really liked the ExpectedException attribute, I would like to have an attribute that will check if any of the aggregated exceptions are of the type I do expect.
After a quick search I hadn’t found anything that suites me. That was the moment the ExpectedAggregateExceptionAttribute was born.
I followed the pattern on which ExpectedException was made and this is what I came up with.

/// 
/// Indicates that an exception is expected during test method execution.
/// It also considers the AggregateException and check if the given exception is contained inside the InnerExceptions.
/// This class cannot be inherited.
/// 
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class ExpectedAggregateExceptionAttribute : ExpectedExceptionBaseAttribute
{
    protected override string NoExceptionMessage
    {
        get
        {
            return string.Format("{0} - {1}, {2}, {3}",
                this.TestContext.FullyQualifiedTestClassName,
                this.TestContext.TestName,
                this.ExceptionType.FullName,
                base.NoExceptionMessage);
        }
    }
 
    /// 
    /// Gets the expected exception type.
    /// 
    /// 
    /// 
    /// A  object.
    /// 
    public Type ExceptionType { get; private set; }
 
    public bool AllowDerivedTypes { get; set; }
 
    /// 
    /// Initializes a new instance of the  class with and expected exception type and a message that describes the exception.
    /// 
    /// An expected type of exception to be thrown by a method.
    public ExpectedAggregateExceptionAttribute(Type exceptionType)
        : this(exceptionType, string.Empty)
    {
    }
 
    /// 
    /// Initializes a new instance of the  class with and expected exception type and a message that describes the exception.
    /// 
    /// An expected type of exception to be thrown by a method.
    /// If the test fails because an exception was not thrown, this message is included in the test result.
    public ExpectedAggregateExceptionAttribute(Type exceptionType, string noExceptionMessage)
        : base(noExceptionMessage)
    {
        if (exceptionType == null)
        {
            throw new ArgumentNullException("exceptionType");
        }
 
        if (!typeof(Exception).IsAssignableFrom(exceptionType))
        {
            throw new ArgumentException("Given type is not an exception.", "exceptionType");
        }
 
        this.ExceptionType = exceptionType;
    }
 
    /// The exception that is thrown by the unit test.
    protected override void Verify(Exception exception)
    {
        Type type = exception.GetType();
 
        if (this.AllowDerivedTypes)
        {
            if (!this.ExceptionType.IsAssignableFrom(type))
            {
                base.RethrowIfAssertException(exception);
 
                throw new Exception(string.Format("Test method {0}.{1} threw exception {2}, but exception {3} was expected. Exception message: {4}",
                    base.TestContext.FullyQualifiedTestClassName,
                    base.TestContext.TestName,
                    type.FullName,
                    this.ExceptionType.FullName,
                    GetExceptionMsg(exception)));
            }
        }
        else
        {
            if (type == typeof(AggregateException))
            {
                foreach (var e in ((AggregateException)exception).InnerExceptions)
                {
                    if (e.GetType() == this.ExceptionType)
                    {
                        return;
                    }
                }
            }
 
            if (type != this.ExceptionType)
            {
                base.RethrowIfAssertException(exception);
 
                throw new Exception(string.Format("Test method {0}.{1} threw exception {2}, but exception {3} was expected. Exception message: {4}",
                    base.TestContext.FullyQualifiedTestClassName,
                    base.TestContext.TestName,
                    type.FullName,
                    this.ExceptionType.FullName,
                    GetExceptionMsg(exception)));
            }
        }
    }
 
    private string GetExceptionMsg(Exception ex)
    {
        StringBuilder stringBuilder = new StringBuilder();
        bool flag = true;
 
        for (Exception exception = ex; exception != null; exception = exception.InnerException)
        {
            string str = exception.Message;
 
            FileNotFoundException notFoundException = exception as FileNotFoundException;
            if (notFoundException != null)
            {
                str = str + notFoundException.FusionLog;
            }
 
            stringBuilder.Append(string.Format((IFormatProvider)CultureInfo.CurrentCulture, "{0}{1}: {2}", flag ? (object)string.Empty : (object)" ---> ", (object)exception.GetType(), (object)str));
            flag = false;
        }
 
        return ((object)stringBuilder).ToString();
    }
}

To cut it short, I do check if the thrown exception is of AggregateException type, and if so I do again check if any of the inner exceptions is of the requested type. In case this condition is not matched a new exception is thrown which will make your unit test fail.
If we now use our new attribute instead of the ExpectedExceptionAttribute this test will be successful.

[TestMethod]
[ExpectedAggregateException(typeof(ArgumentNullException))]
public void MySimpleMethodAsync_Throws_ArgumentNullException_2()
{
    sut.MySimpleMethodAsync(null).Wait();
}

In order to be sure that our new attribute is working properly I will make some other tests. First I do expect the unit test to fail in case no exception was thrown:

[TestMethod]
[ExpectedAggregateException(typeof(ArgumentNullException))]
public void ArgumentNullException_Fail_If_No_Exception()
{
    sut.MySimpleMethodAsync(new List()).Wait();
}

Mind that this test is not meant to pass (do not include it in your solution).
Also, if in the inner exceptions there is no expected exception type, the test should fail:

[TestMethod]
[ExpectedAggregateException(typeof(ArgumentNullException))]
public void ArgumentNullException_Fail_If_Wrong_Inner_Exception()
{
    Task.Factory.StartNew(() =>
    {
        throw new ArgumentOutOfRangeException();
    });
}

As both test failed, I can conclude this new attribute works as supposed. You can package it as you wish, in your own common library, in a new or existing custom testing library or in any of your projects.

Downloads and the source code

You can find the source code and the demo project on Github at this address here.

Happy unit testing!

ASPxGridView master-detail data presentation with context menus

Introduction

As many companies I worked for are using DevExpress controls I decided to write a couple of posts about some real life situations and ways they can be solved by using DevExpress ASP.NET Suite. In this and following post I will show you a couple of techniques on how to achieve a certain behavior that goes slight further than the demo examples that you can find on DevExpress site.
I will be using ASP.NET suite of controls, more specifically Web Forms.

At the end of the article this is the expected result:

You can also check the LIVE DEMO.

Table of contents

  1. What are DevExpress controls?
  2. Requirements
  3. The project
  4. Creating a data source
  5. The web page
  6. Defining a detail grid
  7. Adding a context menu to the detail grid
  8. Programmatically disabling menu items
  9. Aesthetic changes
  10. Downloads and the source code
  11. Notes and other resources

What are DevExpress controls?

A set of controls that enrich your toolbox by adding several controls that are not present in the standard ASP.NET controls and some of the controls that are offered as a good substitute to already existing controls. All of the DevExpress controls are rich by the properties, methods and events both on client and server side, giving you the possibility to achieve results that otherwise will require a lot more extra coding.

Requirements

All of my examples are written for .NET 4.0 with Visual Studio 2010 using the version v2012 vol 1.5 of DevExpress controls. You can find a trial version of the requested controls here DevExpress Demo. Any version of Visual Studio is just fine, from Express to Ultimate. Also you can easily migrate this project to .NET 3.5 if needed. In case that the version of DevExpress controls I used is not available anymore, it should be easy to upgrade the project by DXperience Project Converter. For more information’s on project converter check DevExpress web site.

The project

I will start with the default Visual Studio ASP.NET Web Application.
Considering this example just a practice about the UI and the controls itself, I will put no emphases on the data source and just create a super simple data model. We will have two data entities, User and Project. As a cardinality, we have a many-to-many relationship, so one user can be related to many projects as a project can have several users. Also I will create a class called DataService that will create a couple of values that will represent our data.

Let’s start!

Creating a data source

First we will create a Project class. In the default constructor we will set the project status property to new. Except for this, we will have three properties, an ID, project name, and a project status.

public class Project
{
    public Project()
    {
        Status = ProjectStatus.New;
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public ProjectStatus Status { get; set; }
}

As you can see, project status is an enumerator, so let’s define it together with other possible project statuses.

public enum ProjectStatus
{
    New,
    InProgress,
    Failed,
    Done
}

Now we will define the user class. It has several properties and one public method. The method returns the number of associated projects of the current customer instance.

public class User
{
    public User()
    {
        Projects = new List();
    }

    private string m_fullName;

    public int ID { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List Projects { get; set; }

    public string FullName
    {
        get { return string.Format("{0}, {1}", this.LastName, this.FirstName); }
    }

    public bool HasProjects()
    {
        return Projects.Count > 0;
    }
}

This is a very simple model and probably in a real life situation your model will be richer with properties and methods.
Next to come is a class that will create several instances of the model classes and return them via a method. In this way we can have easily all the data we need for our example. The code I used is following, you can add other data if in search of a particular behavior.

[DataObject(true)]
public class DataService
{
    [DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
    public static List GetUsers()
    {
        List users = new List();

        users.Add(new User() { ID = 1, UserName = "JohnDoe", FirstName = "John", LastName = "Doe", Projects = GetSomeProjects() });
        users.Add(new User() { ID = 2, UserName = "JimDoe", FirstName = "Jim", LastName = "Doe", });
        users.Add(new User() { ID = 3, UserName = "RobertDoe", FirstName = "Robert", LastName = "Doe", });
        users.Add(new User() { ID = 4, UserName = "AlisonDoe", FirstName = "Alison", LastName = "Doe", Projects = GetSomeProjects2() });

        return users;
    }

    [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
    private static List GetSomeProjects()
    {
        List projects = new List();

        projects.Add(new Project() { ID = 1, Name = "Test1" });
        projects.Add(new Project() { ID = 2, Name = "Test2", Status = ProjectStatus.Failed });
        projects.Add(new Project() { ID = 3, Name = "Test3" });

        return projects;
    }

    [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
    private static List GetSomeProjects2()
    {
        List projects = new List();

        projects.Add(new Project() { ID = 4, Name = "Test4" });
        projects.Add(new Project() { ID = 5, Name = "Test5", Status = ProjectStatus.Failed });
        projects.Add(new Project() { ID = 6, Name = "Test6", Status = ProjectStatus.InProgress });

        return projects;
    }
}

Now our data source is ready. The next thing to care of is the web page itself.

The web page

Add the grid by drag dropping the ASPxGridView control in the page. Modify the properties in order to match the following:


    
        
        
        
        
        
        
        
        
        
        
    

What we did is changing the grids ID to gvMaster, indicating the Key field name by setting the KeyFieldName to “ID” and specifying the columns that will be shown together with mapping a column field name to the desired model property. Now we need to bind the grid and we will do it from the code.
In order to be able to show the changes, we will save our data in a session and in order to ease this operation we will create a property that will perform all of this check and operations for us. Get in the page’s code file and declare the following.

public List Users
{
    get
    {
        if (Session["Data"] == null)
            Session["Data"] = DataService.GetUsers();

        return (List)Session["Data"];
    }
    set { Session["Data"] = value; }
}

When the property is requested for the first time, the session item is null, then we will recall the method that we created previously and save the data in the session. This is not a technique that you will use in a real life application, because probably you will recall the data from the database at a certain point and eventually cache it. As explain this is not the goal of this article, I will just mention it.
Now it’s time to bind the grid to this property.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvMaster.DataSource = Users;
        gvMaster.DataBind();
    }
}

If you run the code now you should see the following (or a similar screen, don’t worry if the theme that is applied doesn’t look the same, we will came to that later).

Defining a detail grid

In order to add a detail grid to a master grid, we first need to define a template for the detail row. Inside the aspx file get inside the definition of ASPxGridView and open the section then inside the newly created section a new one called . Close properly both sections. In the Detail Row template add a new ASPxGridView and define as for master grid the columns and some properties. Also do not forget to set the ShowDetailRow property to true. At the end your code should look like this.



    
        
            
                
                
                
                
                
                
            
        
    

Now we need to handle the binding of the detail grid. Before that we will check for each row in the master grid if there is the data for the detail grid and if not, hide the plus sign. To achieve that, we need to declare the OnDetailRowGetButtonVisibility event on the master grid. The code of your master grid should look like this


In the server side event code we need to check if there are detail data for each master element.

protected void gvMaster_DetailRowGetButtonVisibility(object sender, ASPxGridViewDetailRowButtonEventArgs e)
{
    User currentUser = Users.Find(u => u.ID == (int)gvMaster.GetRowValues(e.VisibleIndex, "ID"));

    if (!currentUser.HasProjects())
        e.ButtonState = GridViewDetailRowButtonState.Hidden;
}

For the less experienced, I will quickly explain this code. In order to get the row value we will use the argument that is passed to the event which contains the currently processing row visible index and with that information retrieve the value of the ID field of that row. The following code gvMaster.GetRowValues(e.VisibleIndex, "ID")) will give us the the value of ID filed for the current row. Then we will retrieve the User class instance for a given ID and check if it has project. In case that this user is not associated to any project we will hide the plus sign (button) for that row with by setting the argument property ButtonState to hidden.
Now let’s bind detail grid.
Each time the user click’s on the plus sign, a callback will be automatically generated by the grid and on the server side, binding event for the detail grid will be raised. OnBeforePerformDataSelect event in the detail grid is the right one for indicating the data source on which the current detail grid should be bind. Define the previously mentioned event:


And bind the data in that event.

protected void gvDetail_BeforePerformDataSelect(object sender, EventArgs e)
{
    ASPxGridView grid = sender as ASPxGridView;
    int currentUserID = (int)grid.GetMasterRowKeyValue();

    grid.DataSource = Users.Find(u => u.ID == currentUserID).Projects;
}

In order to refer to a proper object we need to cast the sender of the event to a ASPxGridView. Then DevExpress grid comes in our help with GetMasterRowKeyValue() method, which as it’s name says, will return the key value of the master grid in which our current detail grid is defined. Whit that value, which is basically the User ID, we can retrieve the necessary data which we will set as a DataSource of the current detail grid.
That’s it, your master detail grid should work now and this is how it should look like.

If your solution is not looking completely the same do not worry, important is that it compiles and shows the data correctly for now.

You can see that I’m constantly pointing for the detail grid the current fact. This is important, because we can have multiple detail grid’s in the page, so we always need to refer to a proper object. Always think about that when you are working with detail grid.

Adding a context menu to the detail grid

This is a bit more complicated task but as you will see a quite simple way to achieve this.
Start with adding a client side event ContextMenu on the detail grid:


    
        
        
        
        
        
        
    
    

And then defining a menu with couple one item in it (just drag and drop PopupMenu control from the toolbox in the page):


    
        
        
    

With DevExpress controls we can define a client side (JavaScript) events in the aspx page. As on the server side, the will fire behind a certain event. We need to assign a function name that we are planning to execute on client side once the event is fired. Two parameters will be passed to our function, first is the control that generated the event (sender) and the event arguments. Each event and control has it’s own arguments. DevExpress controls are very function rich on client side, and you can consult the documentation to check all available client side events, functions and properties.

In the following Reference you can check the available client side functionality for the ASPxGridView. If you are interested in the other controls, just browse the interested control namespace that ends with Script.

In the page header (or in a separate .js file) define the following function:


In this function we will check if the context menu event is raised on a grid header or on the grid row. If it is a grid row we should popup a context menu. We can refer to the control on the client side by the ClientInstanceName that we defined for that control in the aspx file, this is done in this example. Each time you put a DevExpress control in your page, you will automatically have at your disposition an utility class called ASPxClientUtils containing several methods that can help you reducing your js code.

Now each time you right click the detail grid row, a context menu that you defined will be shown. What we are missing is the action that needs to be performed once the user chooses a context menu. In order to achieve this we need to add a client side event to our ASPxPopupMenu.


    
        
        
    
    

There is some more work to do. As we are going to use a callback method of the detail grid to process the action on the server side, we need to find out the right detail grid that needs to be updated. In order to achieve so, we need to modify our previously defined method OnContextMenu.


What we did here is to save a reference to a detail grid and current visible index (row index on which the mouse was positioned when user right clicked) so we can reused it the Popup ItemClick event that we are going to define:


Once the menu item is chosen we will check if the item is the right one (this is useful if we have several items and we need to perform different actions based on chosen item) then request a callback for the grid on which user is operating right now. We will pass the current visible index as a parameter so we can spot the right element on which we are trying to apply our action. Before we can declare this server side event, we need to specify it in the aspx file:


And than manage this event on server side:

protected void gvDetail_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
    ASPxGridView grid = sender as ASPxGridView;

    int projectID = (int)grid.GetRowValues(int.Parse(e.Parameters), "ID");
    int currentUserID = (int)grid.GetMasterRowKeyValue();

    List projects = Users.Find(u => u.ID == currentUserID).Projects;
    projects.Find(p => p.ID == projectID).Status = ProjectStatus.New;

    grid.DataSource = projects;
    grid.DataBind();
}

As before, for simplicity we will cast the sender argument to ASPxGridView variable called grid. Then we will retrieve the ID of the project that was selected. The argument we passed before on client side to the PerformCallback function will come handy right now as it will store the necessary data in order to find the interested project (by parsing the e.Parameters property). Next value we need to get is the user ID for which this detail grid is showing the associated projects. We can get it by a handy server side method GetMasterRowKeyValue() which will return a key value of the master grid (as you rememer we defined as a KeyFieldName the ID property of interested entities). Now, once we have the necessary data we can perform the desired actions and rebind the detail grid.

You can now add different actions in the Popup menu and manage them by passing a qualifier in the argument, parsing the argument and performing different operations. You will see this technique in my next blog post, stay tuned.

Programmatically disabling menu items

Unfortunately in this example the user can choose to reset the status of projects that are not in an invalid state. In order to disable the menu item if the state is not “resetable” we will need to make some changes in our code non less passing more information to client side.
Before modifying the JavaScript we will make some considerations. In order to disable an item in the menu, we need to know the condition on which to do it. We can say that the Reset item needs to be disable when the project status is New. This status information we need to pass to the client side somehow. One way to achieve this is to store the status information together with the key value in a custom property. All the DeExpress controls have the possibility to easily add information from server side that will be brought and exposed on client side. This feature is called Custom Properties and you can find more information’s about them here. My technique is to save the Dictionary element to a custom property which will be seen as an array from JavaScript. All what I’m saying may sound confusing, so let’s see an real example.

First of all we will subscribe to OnHtmlRowCreated event. Modify the detail grid in the following way:


Then write down the following code:

protected void gvDetail_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
{
    if (e.RowType != GridViewRowType.Data) return;

    ProjectStatus status = (ProjectStatus)e.GetValue("Status");
    ASPxGridView grid = sender as ASPxGridView;

    if (grid.JSProperties.ContainsKey("cpStatus"))
    {
        Dictionary values = (Dictionary)grid.JSProperties["cpStatus"];

        if (values.ContainsKey(e.VisibleIndex))
        {
            values[e.VisibleIndex] = status;
        }
        else
        {
            values.Add(e.VisibleIndex, status);
        }

        grid.JSProperties["cpStatus"] = values;
    }
    else
    {
        Dictionary values = new Dictionary();
        values.Add(e.VisibleIndex, status);

        grid.JSProperties.Add("cpStatus", values);
    }
}

This code can seem complex but it isn’t. For each row that is going to be rendered I’m getting it’s visible index value, checking if I already have that value in my Dictionary type variable. If not, I’m adding a new item to my Dictionary together with it’s status. If changed, I’m persisting the new value to a custom JS property of the grid.
This now means that I can easily retrieve this information’s on client side. Modify your OnContextMenu function in the following way:


We first need to retrieve the menu item then set the enable property based on custom JS property value.

That’s all, try your code, it should work.

Aesthetic changes

In order to make your solution look like mine, you will also need to set the theme and a couple of other properties that I will explain here.
First of all the theme. DevExpress control ships with a several themes, check the following web page for more details on how to deploy a theme to your solution. I applied the Acqua theme by importing the necessary files to my solution and changing the web.config in the following way (if not present add the following code inside the system.web section):



I also added to both grids the title panel and the title itself:



In order to make a clicked row visually different I also enabled the AllowFocusedRow property. As it will set focus only on left mouse click, I also modified my JS OnContextMenu function, so it will get focused also on the right mouse click:


The EnableRowHotTrack was also enabled so the grid displays the hot tracked row (a row located under the mouse pointer). You can read more about all these properties on DevExpress site.

Downloads and the source code

You can find the source code of my project for download here.
You can find a trial version of the requested controls here.

Notes and other resources

If a specific version of the controls is not available, you can upgrade this project to the latest version of controls. Use DevXperience Project Converter Tool for upgrading the project. Read more on how to use this tool in the following blog post.
You can find other examples on Master-Detail functionality on DevExpress site. This is Master-Detail – Detail Grid example, and the following is the usage of a tab control inside the detail row template.
In the DevExpress support site you will find several examples with the source code on different techniques this link will show you the solutions for a specific master-detail challenges.

Till the next post!

Cheers!

A Simple ASP.NET Flickr Application – Part 1

Foreword

I wrote this article back in 2010. This was my first programming article written in English. Actually it was more a need then a pleasure at the time as I was searching for my first employment here in The Netherlands and one of the companies that at whom I applied, requested a test that at the end with just a bit of extra effort I transformed in this article. As I suppose lately my English got better re-reading my own words make me wish to rewrite many of them, however it will be silly and great waste of time, so I will leave all the text just as it is in it’s original. In order to make it easier to read I will also split the article in n parts.

Let’s keep the conversation going! If any, just comment and will do my best to provide an answer to your doubts.

Download source code – 145 KB

Table of contents

A Simple ASP.NET Flickr Application – Part 1

  1. Introduction
  2. Getting started
  3. The web.config

A Simple ASP.NET Flickr Application – Part 2

  1. Constructing the page
  2. The make up
  3. The result
  4. Notes

Introduction

First of all, I want to thank Sam Judson who created a very useful project and that he shared it to us all. Without his effort, this article will be much longer and tedious. So thanks to him and other people who collaborated on that project. All project details and downloads can be found at this address: http://flickrnet.codeplex.com/.

I also used a light-weight, customizable lightbox plug-in for jQuery 1.3 and 1.4, called ColorBox, for adding a nice effect on the image preview. ColorBox is written by Jack Moore, and thanks to him too; you can find more details here: http://colorpowered.com/colorbox/. The version I’m using is 1.3.3, but you can update your projects with latest versions if you wish. More details about the version history can be obtained here: http://colorpowered.com/colorbox/core/README.

Another essential thing in order to use a Flickr API is creating your own API key and your secret key. If you already have a Yahoo! account, it will be quite simple; otherwise, you should create one. In both cases, you can start from here: http://www.flickr.com/services/api/keys/. For more details about the Flick API, visit http://www.flickr.com/services/api/.

Note that the API key and secret key used in the sample application are fake, they will not work. You’ll get an error message when executing the application. So you should change them, in the web.config, with data you got from Flicker! (Haven’t you created your own key? Bad bad, go to http://www.flickr.com/services/api/keys/ .)

Getting started

Start by creating an empty ASP.NET Web Site. I used Visual Studio 2010 Ultimate, but the same can be accomplished with Visual Studio Express as it can be done with previous versions of Visual studio such as 2008 or 2005.

Using the code

Let’s write some code. Add to your project an ASP.NET folder App_Code and create a new class and call it FlickrBLL. This is the code to be added:

using System;
using System.ComponentModel;
using System.Configuration;
using FlickrNet;

namespace Infrastructure.BLL
{
    /// 
    /// Helper class for confortable pagining and binding
    /// 
    [DataObject(true)]
    public class FlickrBLL
    {
        [DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
        public static PhotosetPhotoCollection GetPagedSet(string setId,
                      int maximumRows, int startRowIndex)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);
            PhotosetPhotoCollection photos = flickr.PhotosetsGetPhotos(setId, GetPageIndex(
                startRowIndex, maximumRows) + 1, maximumRows);

            return photos;
        }

        public static int GetPagedSetCount(string setId)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);
            Photoset set = flickr.PhotosetsGetInfo(setId);
            return set.NumberOfPhotos;
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
        public static PhotosetCollection GetPhotoSetsByUser(string userId)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);

            return flickr.PhotosetsGetList(userId);
        }

        protected static int GetPageIndex(int startRowIndex, int maximumRows)
        {
            if (maximumRows                 return 0;
            else
                return (int)Math.Floor((double)startRowIndex / (double)maximumRows);
        }
    }
}

Let’s analyze some of these methods.

The Fickr.Net library method PhotosetsGetPhotos expects the page index, and not the index of the first record to retrieve, so I created the GetPageIndex helper method for the conversion.

The method GetPhotoSetsByUser returns the result of PhotosetsGetList. Note that this function doesn’t expect as parameter the Flickr user name, but the user id. You can retrieve this data using other methods integrated into the Flicker.Net API or using websites such as http://www.xflickr.com/fusr/.

Don’t get scared by the GetPagedSet method attribute. Components such as the ObjectDataSource control and the ObjectDataSourceDesigner class examine the values of this attribute, if present, to help determine which data method to call at run time. It isn’t necessary, but it simplifies the work. The same attribute is used to indicate that this class is a data object ([DataObject(true)]). I decides to make use of pagination in this example, and it was easy because the API already provides this functionality. The method simply calls the PhotosetsGetPhotos available in the Flicker.Net library, and uses the opportune overload.

The Count method needed for paging uses GetPagedSetCount, which gets the requested set’s info and returns the number of items in the set.

The web.config

In order to acquire authentication data and other parameters that may vary, we need to create an appSettings section in our web.config.


  
  
  
  

apiKey and sharedSecret are dummy values. You need to register and replace them to obtain a full functionality, but you can still use the default user and the default page size. If you are using a different layout, you can change the number of photos shown on each page, by simply varying this value.

continue…

Download source code – 145 KB