Archive for October, 2009

List Repository Pattern For Sharepoint

October 28, 2009

I have recently played SharePoint Guidance 2009 and I found there an implementation of repository pattern that I find interesting. So I pulled the source codes for the repository out from the SPG  and here is the sample project that I created based on it. So to be absolutely clear this is not fully my source code I have just modified the SPG for my needs. The attachment has a pdf extension, cause wordpress in its ingenuity does not allow zip extensions. So just download the file  and then rename the extension from pdf to zip.

So how to use it:

  • Create new project and link the Repository assembly
  • Create new business entity named e.g. Report that will inherit from the BaseEntity. This entity is basically only a holder for the values that we get from the list.
    public class Report : BaseEntity
    {
    public string Code
    {
    get;
    set;
    }
    public string Description
    {
    get;
    set;
    }
    public DateTime Date
    {
    get;
    set;
    }
    }
    
  • Then implement an interface for CRUD operations named  e.g. IReportRepository
    public interface IReportRepository
    {
    int Add(Report report);
    Report Get(int id);
    Report Get(string reportCode);
    IList Get();
    void Update(Report report);
    void Delete(int id);
    string GetFieldName(Guid key);
    }
    
  • Then create a repository class named e.g. ReportRepository that inherites from the BaseEntityRepository and implements IReportRepository interface. Basically all you need to do is to implement the mappings between businesss entity Report and corresponding fields in the SPList.
    protected override Dictionary GatherParameters(Report entity)
    {
    Dictionary fields = new Dictionary();
    fields.Add(new Guid(CommonFields.Title), entity.Title);
    fields.Add(new Guid(Fields.ReportDescription), entity.Code);
    fields.Add(new Guid(Fields.ReportCode), entity.Description);
    fields.Add(new Guid(Fields.ReportDate), entity.Date);
    
    return fields;
    }
    
    protected override Report PopulateEntity(SPListItem item)
    {
    Report report = new Report();
    report.Id = (int)item[new Guid(CommonFields.Id)];
    report.Title = (string)item[new Guid(CommonFields.Title)];
    report.Code = (string)item[new Guid(Fields.ReportCode)];
    report.Description = (string)item[new Guid(Fields.ReportDescription)];
    report.Date = (DateTime)item[new Guid(Fields.ReportDate)];
    return report;
    }
    

If you want to try out the sample project you need  to create a list based on stp file that is in the solution and then make all operations on it.

Advantages:

  • Testability (You can mock the repository through IReportRepository)
  • Readability
  • Strongly typed access to SPList  (through business object Report)

Disadvantages:

  • More work than simple SPListem[“FieldName”]