SPFieldUserValueCollection declare globally:
SPFieldUserValueCollection likedBy;
* set Like /Unlike
* give parameter value Itemid as string type and likeunlike boolean value
* true=like/false=unlike
public void setlike(string ItemID, bool Likeunlike)
{
using (SPSite osite = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb oweb = osite.OpenWeb())
{
SPList olist = oweb.Lists.TryGetList("Posts");
if (olist != null)
{
SPListItem item = olist.GetItemById(Convert.ToInt32(ItemID));
if (!string.IsNullOrEmpty(Convert.ToString(item["LikedBy"])))
{
likedBy = new SPFieldUserValueCollection(oweb, item["LikedBy"].ToString());
}
else
{
likedBy = new SPFieldUserValueCollection();
}
SPUser user = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.Name);
SPFieldUserValue newUser = new SPFieldUserValue(oweb, user.ID, user.Name);
//Like
if (Likeunlike == true)
{
likedBy.Add(newUser);
}
//Unlike
else
{
SPFieldUserValue DeletedUserValue = likedBy.First(u => u.LookupId == user.ID);
likedBy.Remove(DeletedUserValue);
}
int likes = likedBy.Distinct().Count();
item["LikesCount"] = likes;
item["LikedBy"] = likedBy;
oweb.AllowUnsafeUpdates = true;
item.SystemUpdate(false);
oweb.AllowUnsafeUpdates = false;
}
}
}
}
SPFieldUserValueCollection likedBy;
* set Like /Unlike
* give parameter value Itemid as string type and likeunlike boolean value
* true=like/false=unlike
public void setlike(string ItemID, bool Likeunlike)
{
using (SPSite osite = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb oweb = osite.OpenWeb())
{
SPList olist = oweb.Lists.TryGetList("Posts");
if (olist != null)
{
SPListItem item = olist.GetItemById(Convert.ToInt32(ItemID));
if (!string.IsNullOrEmpty(Convert.ToString(item["LikedBy"])))
{
likedBy = new SPFieldUserValueCollection(oweb, item["LikedBy"].ToString());
}
else
{
likedBy = new SPFieldUserValueCollection();
}
SPUser user = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.Name);
SPFieldUserValue newUser = new SPFieldUserValue(oweb, user.ID, user.Name);
//Like
if (Likeunlike == true)
{
likedBy.Add(newUser);
}
//Unlike
else
{
SPFieldUserValue DeletedUserValue = likedBy.First(u => u.LookupId == user.ID);
likedBy.Remove(DeletedUserValue);
}
int likes = likedBy.Distinct().Count();
item["LikesCount"] = likes;
item["LikedBy"] = likedBy;
oweb.AllowUnsafeUpdates = true;
item.SystemUpdate(false);
oweb.AllowUnsafeUpdates = false;
}
}
}
}
No comments:
Post a Comment