Nebulae Spiral

Spiralling Golden… and maybe blogging about code.

Handy SPFolder / SPList / SPFile / SPWhatever interface, using Generics and Elevated Privs.

with one comment

This is a handly little lib I wrote for accessing various types of objects using generics. enjoy :-)

class SPDataAdapter
{
    public static T GetObject(string location)
    {
        object obj = null;
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (var site = new SPSite(location))
            {
                obj = site.OpenWeb().GetObject(location);
            }
        });
        return (T)obj;
    }
 
    public static T GetObject(string location, bool useElevatedPrivs)
    {
        if (useElevatedPrivs) return GetObject(location);
        using (var site = new SPSite(location))
        {
            return (T)site.OpenWeb().GetObject(location);
        }
    }
 
    public static SPList GetList(string location, bool useElevatedPrivs)
    {
        if (useElevatedPrivs) return GetList(location);
        using (var site = new SPSite(location))
        {
            return site.OpenWeb().GetList(location);
        }
    }
 
    public static SPList GetList(string location)
    {
        SPList list = null;
        SPSecurity.RunWithElevatedPrivileges(delegate
       {
            using (var site = new SPSite(location))
            {
                list = site.OpenWeb().GetList(location);
            }
        });
 
        return list;
 
   }
 
}

and to test:

 
[TestMethod()]
public void GetObjectTest1()
{
    GetObjectTest1Helper<SPFolder>();
}
 
public void GetObjectTest1Helper<T>()
{
    const string location = "http://spiral/Lists/Tasks";
    const bool useElevatedPrivs = true;
    var actual = SPDataAdapter.GetObject<T>(location, useElevatedPrivs);
    Assert.IsNotNull(actual);
}
 
[TestMethod()]
public void GetObjectTest()
{
    GetObjectTestHelper<SPFile>();
}
 
public void GetObjectTestHelper<T>()
{
    const string location = "http://spiral/Lists/Tasks/Attachments/1/nebulae.jpg";
    T actual = SPDataAdapter.GetObject<T>(location);
    Assert.IsNotNull(actual);
}

Written by Nebulae

August 28th, 2008 at 11:01 am

Posted in code

Tagged with , ,

One Response to 'Handy SPFolder / SPList / SPFile / SPWhatever interface, using Generics and Elevated Privs.'

Subscribe to comments with RSS or TrackBack to 'Handy SPFolder / SPList / SPFile / SPWhatever interface, using Generics and Elevated Privs.'.

  1. [...] public links >> generics Handy SPFolder / SPList / SPFile / SPWhatever interface, using … First saved by Marjoree | 9 days ago Ready Your Representative, US Generics Cheaper Or else [...]

Leave a Reply

You must be logged in to post a comment.