3

I'm trying to like a blog post with Reputation.SetLike(string listID, int itemID, bool like) and I can't seem to figure out what exactly it's looking for as a listID. Searching around on the Internet seemed to suggest that it takes a list GUID but even if I grab the GUID directly from the list it just says "List does not exist". I've also tried hard-coding the GUID with every combination of dashes and curly braces possible but no luck. This is what I'd think would work using the GUID directly from my "Posts" list that I want to like a post in:

SPSite site = new SPSite(SPContext.Current.Site.Url);
SPWeb web = site.OpenWeb();
SPList posts = web.Lists["Posts"];
string guid = posts.ID.ToString();

Reputation.SetLike(guid, 1, true);
2

This happens because Reputation.SetLike method internally uses SPContext.Current.Web object to get the list. And SPWeb object which you opened could be different from SPContext.Current.Web object. Example:If you run your code on subsite then SPContext.Current.SPWeb object is subweb but SPWeb object which you open in your code is root site web.

I found a way to resolve it - you need to fake SPcontext.Current context to think that you are actually on root site. To do this add class below to your project:

public class SPContextFaker:IDisposable
{
    private SPContext _oldSPContext;
    private HttpContext httpContext;
    public SPContextFaker(HttpContext context, SPContext newSPContext)
    {
        _oldSPContext = (SPContext)context.Items["DefaultSPContext"];
        context.Items["DefaultSPContext"] = newSPContext;
        httpContext = context;
    }
    public void Dispose()
    {
        httpContext.Items["DefaultSPContext"] = _oldSPContext;
    }
}

Then use it like this:

using(var site = new SPSite(SPContext.Current.Site.Url))
using(var web = site.OpenWeb())
using(new SPContextFaker(HttpContext.Current, SPContext.GetContext(web)))
{
    SPList posts = web.Lists["Posts"];
    string guid = posts.ID.ToString();

    Reputation.SetLike(guid, 1, true);
}

You may ask how i came up with this code. The answer is simple - i've investigated Microsoft.SharePoint.dll using reflection and found how SPContext.Current property works.

I want to mention that above code will work only if you have HttpContext.Current != null which is true for web pages (but not true for example for event receivers and console applications).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.