Thursday, June 14, 2012

Get All Users from a User Collection



SPFieldUserValueCollection afterAttendees=new SPFieldUserValueCollection(web, properties.AfterProperties["Attendees"].ToString());

to get a single user use foreach with SPFieldUserValue

Check if Current User have Specific Permissions


SPRoleDefinition roleDefinitionRead = spWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
spList.DoesUserHavePermissions(user, roleDefinitionRead.BasePermissions);

Wednesday, June 13, 2012

Some useful power shell commands


Copy DLL's From GAC

C:\Windows\assembly\GAC_MSIL\cd dllname
C:\Windows\assembly\GAC_MSIL\dllname\cd dllvirsion_dllpublickytoken(simply press tab after typing cd to get version and public key token)
C:\Windows\assembly\GAC_MSIL\dllname\dllvirsion_dllpublickytoken\copy dllname path_to_save


Set UIVersion for a site

$web = Get-SPWeb http://suinshr00002:666
  $web.UIVersion=3
  $web.Update()

set UI Version  for all sites of a site collection

$w = get-spweb http://sharepoint/sites/team/subsite
$w.webs | ForEach-Object {$_.UIversion = 4; $_.UIVersionConfigurationEnabled = $false; $_.update()} 

Tuesday, June 12, 2012

Disable Event Handlers when Updating a list Programatically

HandleEventFiring eventFiring = new HandleEventFiring();
eventFiring.AccDisableEventFiring();
listItem.Update();
eventFiring.AccEnableEventFiring();


-------------------

public class HandleEventFiring : SPItemEventReceiver
        {
            public void AccDisableEventFiring()
            {
                this.DisableEventFiring();
            }

            public void AccEnableEventFiring()
            {
                this.EnableEventFiring();
            }
        }

Friday, June 8, 2012

Calculate Business days - SharePoint List calculated column


The following calculated column formula calculates business excluding weekends, based on start date and end date columns in a list.

=IF(AND((WEEKDAY(To,2))<(WEEKDAY(From,2)),((WEEKDAY(From,2))-(WEEKDAY(To,2)))>1),(((DATEDIF(From,To,"D")+1))-(FLOOR((DATEDIF(From,To,"D")+1)/7,1)*2)-2),(((DATEDIF(From,To,"D")+1))-(FLOOR((DATEDIF(From,To,"D")+1)/7,1)*2)))

From is the start date column name here and To is the end date.

Thursday, March 29, 2012

XSLS to check for custom properties

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xmp><xsl:copy-of select="*"/></xmp> </xsl:template> </xsl:stylesheet>

Monday, March 19, 2012

How to check if current user operates as System Account

While trying to find out a better way to check if current user operates as System Account, other then checking if the login name is “SHAREPOINT/system” string, I’ve stumbled upon SPSite.SystemAccount property.
So the problem is cut down to:
  • in event handlers
    1. web.Site.SystemAccount.ID == properties.CurrentUserId
  • in web pages or controls
    1. SPContext.Current.Web.CurrentUser.ID == SPContext.Current.Site.SystemAccount.ID
You can change SPContext.Current.Web with your SPWeb instance variable. Same goes for SPContext.Current.Site.

Monday, March 5, 2012

remove all permissions for a list item in sharepoint

 private static void RemoveAllPermissions(SPItemEventProperties properties)
        {
            #region NewCode
            SPSite siteColl = new SPSite(properties.Web.Url);
            SPWeb site = siteColl.OpenWeb();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
                    {
                        ElevatedSite.AllowUnsafeUpdates = true;
                        SPList omylist = ElevatedSite.Lists[properties.ListTitle];
                        //SPListItem myitem = ElevatedSite.GetListItem(properties.ListItem.Url);
                        SPListItem myitem = omylist.Items[properties.ListItem.UniqueId];
                        //The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments
                        myitem.BreakRoleInheritance(true);
                        //Get the list of Role Assignments to list item and remove one by one.
                        SPRoleAssignmentCollection SPRoleAssColn = myitem.RoleAssignments;
                        for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
                        {
                            SPRoleAssColn.Remove(i);
                        }
                    }
                }
            });
            #endregion

        }

Check if an User is a member of certain group

Use the following method which says whether an user is a member of sharepoint group

public bool isGroupMember(SPItemEventProperties properties)
        {
            bool isMember = false;
            SPWeb web = properties.Web;
            isMember = web.IsCurrentUserMemberOfGroup(web.Groups["MySite Owners"].ID);
            web.Close();
            return isMember;
        }

Wednesday, February 29, 2012

Logging errors/exceptions of sharepoint into Logs

NameSpace: using Microsoft.SharePoint.Administration;

SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Custom category"TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message + ex.StackTrace, null);

Tuesday, February 21, 2012

Access Denied Messages when retrieving SharePoint User Profiles Count even running in Elevated code

Here’s the scenario.

You need to retrieve the total number of user profiles in SharePoint. The API has a property for that in the UserProfileManager class. You could just write some code like this:

UserProfileManager profileManager = new UserProfileManager(serviceContext);
long ProfileCount = profileManager.Count;

But the problem is that in order to retrieve this you need to have admin privileges on the User Profile Service. So the logical way of doing this is to run the code with Elevated privileges and ensure the identity used by the application pool of your site has admin privileges on the User Profile service. So I’ve tried that using the code below:

SPSite siteColl = SPContext.Current.Site;

try{
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
    using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
    {
      SPServiceContext serviceContext = SPServiceContext.GetContext(ElevatedsiteColl);
    UserProfileManager profileManager = new UserProfileManager(serviceContext);
    ProfileCount = profileManager.Count;
    }
  });
}
catch (Exception ex)
{
  LogException(ex);
}

Testing the code running under an Admin account it was fine (because it was the same account used by the site’s application pool). But when I tested the code using a regular user this code should still run fine (because I was running it elevated). Unfortunately that’s not what happened. For some weird reason seems that the SharePoint API was trying to impersonate the current user thus throwing an exception and showing an Access Denied error which said  Access Denied: Only an administrator may retrieve a count of all users.

The Workaround

Basically my workaround is to set the current HttpContext to null inside the code, but keeping the existing context in a temp variable so I can revert it back once I run the snippet. You have to revert it back to the original context otherwise you are going to get a lot of errors. The code looks like this: 

SPSite siteColl = SPContext.Current.Site;
HttpContext tempCtx = HttpContext.Current;

try
{
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
{
SPServiceContext serviceContext = SPServiceContext.GetContext(ElevatedsiteColl);
HttpContext.Current = null;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
ProfileCount = profileManager.Count;} });
}
catch (Exception ex){ LogException(ex);}
finally{ HttpContext.Current = tempCtx;}

Using the code above I could retrieve the count even using a regular user (no admin access) .

 I hope this saves some time on your side and avoid some head banging on the wall
Have a nice one !

Monday, January 16, 2012

Use People Picker in custom web part

Try the following
Include the Tagprefix at the top in your webpart ascx file where there are all the tag prefixes.
Then include the PeopleEditor wherever you want.
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<SharePoint:PeopleEditor ID="spPeoplePicker" runat="server" Width="350" SelectionSet="User" />

Insert something like this in code behind
if (spPeoplePicker.ResolvedEntities.Count > 0)
                    {
                        PickerEntity selectedEntity = (PickerEntity)spPeoplePicker.ResolvedEntities[0];

UserProfile profile= upm.GetUserProfile(selectedEntity.Key);
}

Modify as per your requirement.
Also refer the following link

Yes, you can populate a dropdown with values from a list field
<asp:DropDownList ID="ddlDropDown" runat="server" >
    </asp:DropDownList>



In the code behind include
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["ListName"];
                SPListItemCollection items= list.GetItems();

                if (items!= null)
                {
                   
                    foreach (SPListItem item in items)
                    {
                        if (item["FieldName"] != null)
                            ddlDropDown.Items.Add(item["FieldName"].ToString());
                    }
                }