C# Tips: IEnumerable<T>.ForEach extension method

I’m sure everyone have already used IEnumerable<T> extension methods to query your .NET collections.

Well, one thing we usually do is loop through a collection’s items and do something.

Lets say I want to write some data about portuguese people I find in my persons collection and then retrieve the maximum age value to do something else:

void Work()
{
    var persons = RetrievePersons();

    var portuguesePeople = persons.Where(p => p.Country == "Portugal");
    int maxAge;
    foreach (var p in persons.Where(p => p.Country == "Portugal"))
        Console.WriteLine("Name: {0} ; Age: {1}", p.Name, p.Age);

    maxAge = portuguesePeople.Max(p => p.Age);
    //...
}

Because the foreach statement can’t be used in a fluent API (eg. Linq) we need an extra reference so the portuguese results we’re looping through can be reused when retrieving the max age value. Being able to write code in a fluent API makes it easier to read and reduces the number of (sometimes unnecessary) variables in your code.

C# has a ForEach instance method for List<T> but most of the times you will be dealing with IEnumerable<T> references, so a ForEach extension method would be handy in these cases.

Continue reading

Encapsulating Entity access in EntityFramework by using the Repository pattern

EntityFramework provides a very easy way to query your entities and thus the database but it creates a very strong dependency between the calling code and the data access layer(EF in this case).

The Repository pattern allows you to encapsulate any entity access logic and also to decouple your business logic layer from your data access layer, in other words, enables separation of concerns, plus it makes unit testing a lot easier.

Consider the following entity data model:

model

And a WCF Service that exposes Orders and its aggregated OrderDetails:

public class OrderService : IOrderService
{
    private MFEntitiesContainer _context = new MFEntitiesContainer();

    public IEnumerable<Order> ListOrders()
    {
        return _context.OrderSet.Include("OrderDetails")
                                .Where(o => o.Customer.Active);
    }

    public IEnumerable<Order> ListOrdersByCustomer(int customerId)
    {
        return _context.OrderSet.Include("OrderDetails")
                                .Where(o => o.Customer.Active && o.Customer.Id == customerId);
    }
}

Lets see how we can refactor the OrderService to use the Repository pattern instead of querying the EF’s ObjectContext.

Continue reading

Safe usage of INotifyPropertyChanged in MVVM scenarios

For my first post in this blog I’m going to describe how we can use the INotifyPropertyChanged without magic strings in MVVM scenarios by using lambda expressions. If you’re not familiar with this pattern you can read about it here:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

When using MVVM we usually tend to create a base class that contains the INotifyPropertyChanged implementation as following:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    protected void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

A simple ViewModel class could look like this:
public class SampleVM : ViewModelBase
{
    private string _sampleProperty;
    public string SampleProperty
    {
        get { return this._sampleProperty; }
        set
        {
            this._sampleProperty = value;
            base.RaisePropertyChanged("SampleProperty");

            this.IsEnabled = this._sampleProperty != null;
            base.RaisePropertyChanged("IsEnabled");
        }
    }

    public bool IsEnabled { get; private set; }
}

I’ve used this approach a lot and it works great but it has some problems.

Continue reading