Showing posts with label Programatically. Show all posts
Showing posts with label Programatically. Show all posts

May 04, 2014

SharePoint 2013 auto fill people picker, auto fill people editor in application page (aspx) C#

Microsoft always comes with some new and more user friendly features in every new version. Well this client people picker (which is auto fill by user name, email or login id) new and simple control introduced in SharePoint 2013, that will save lot of time of ours.

instead of using below people picker of sharepoint 2010

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

and setting javascript we can use  PeopleEditor to make it easy and faster for end user we can use below control in SP2013

aspx syntax :
<SharePoint:ClientPeoplePicker ValidationEnabled="true" ID="pplDemo" runat="server" VisibleSuggestions="5" AutoFillEnabled="True" AllowEmailAddresses="true" Rows="1" AllowMultipleEntities="false" CssClass="ms-long ms-spellcheck-true" Height="85px"  />



C# Code to get SPUser:
if( pplDemo.ResolvedEntities.Count > 0)
{
SPUser oUser = oWeb.SiteUsers[((PickerEntity)pplDemo.ResolvedEntities[0]).Key];

                         if (oUser != null)
                         {
                              // do your stuff.
                         }
}

C# Code to Set User to Client People Picker control:
 
 pplDemo.InitialUserAccounts = "UserEmail1";
 



Thanks,
remaining getting and saving values in SharePoint is same as earlier.

You can Share your findings or issue here.


--
Thanks,
Praveen Pandit

April 24, 2014

SharePoint how to check user, CurrentUser is in perticuler site group

You wants to check if CurrentUser or particular User / SPUser is present in specific site's permission group or not,
Usually site have three groups Visitors, Members and Owners. If you have create another group and wants to check if particular user is present is that group for some validation so you can refer below code sample,

* Assuming you have basic knowledge of SharePoint coding.



Code:
private bool UserPresentInGroup(string groupName)
        {
            bool isAdmin = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                { // User may not have permission to see site group or Group members....
                    using (SPSite oSite = new SPSite(strWebUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPGroup oUserGroup = oWeb.Groups[groupName];
                            foreach (SPUser item in oUserGroup.Users)
                            {
                                if (item.LoginName == currentUser.LoginName)
                                {
                                    isAdmin = true;
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception exp)
            {}// Catch exception

If you wants to check user from Sites default Visitor, Member or Owner Group you can directly get group by below property
  • SPWeb.AssociatedVisitorGroup
  • SPWeb.AssociatedMemberGroup
  • SPWeb.AssociatedOwnerGroup
instead of  oUserGroup.


--
Thanks,
Praveen Pandit

February 20, 2014

SharePoint How to get SPUser from list item C#



How to get SPUser from list item, SharePoint list item get user, how to get created, modified, Author or Editor from sharepoint list, how to get LoginName or Email of User from list,

Well there is another way to get Web. EnsureUser(“User”); it returns SPUser object as well it adds user in site directly if do not already that web user, another way to get it write a function that return SPUser object,   

*Assuming that you are aware how to get SPWeb and List then List item,

SPUser oUserSubmittedBy = GetSPUser(oItem, “fieldDisplay Name”);

Here is the function body.



Code:
protected SPUser GetSPUser(SPListItem item, string user)

        {

            SPUser oUser = null;

            SPFieldUserValue userValue = new SPFieldUserValue(item.Web, Convert.ToString(item[user]));

            if (userValue != null)

            {

                oUser = userValue.User;

            }

            return oUser;

        }


And once you get object you can get Name, email and login name

oUserSubmittedBy.LoginName
oUserSubmittedBy.Name
oUserSubmittedBy.Email…. etc..



--
Regards,
Praveen Pandit

August 29, 2013

SharePoint Add People Picker using C or aspx, get SPUser from PeoplePicker, Save User and Read pragramatically from/to SPList / Application Page using C#


Create People Picker at run-time using SharePoint C# code, Programmatically.


Code:
protected void CreatePeoplePicker()  
      {  
        permissionPplPicker = new PeopleEditor();  
        permissionPplPicker.MultiSelect = true;  
        permissionPplPicker.AllowEmpty = false;  
        permissionPplPicker.AutoPostBack = true;  
        permissionPplPicker.PlaceButtonsUnderEntityEditor = true;  
        permissionPplPicker.ID = "PeopleEditor";  
        permissionPplPicker.SelectionSet = "User,SPGroup";  
        permissionPplPicker.Rows = 1;  
        permissionPplPicker.BorderStyle = BorderStyle.Outset;  
         //To apply style to people picker or Add SP default css file  
        LiteralControl styleControl = new LiteralControl();  
        styleControl.Text = "<style type='text/css'>.ms-inputuserfield{ font-size:8pt; font-family:Verdana,sans-serif; border:1px solid #a5a5a5;} div.ms-inputuserfield a{color:#000000;text-decoration: none;font-weight:normal;font-style:normal;} div.ms-inputuserfield{padding-left:1px;padding-top:2px;}</style> ";  
        this.Controls.Add(styleControl);  
        this.Controls.Add(permissionPplPicker);  
      } 




Create People picker SharePoint Application page .aspx Page ,



Code:
<table style="MARGIN-TOP: 8px" class='ms-formtable' border='0' cellspacing='0' cellpadding='0' width="100%">  
                   <tr>  
         <td class='ms-formlabel' valign='top' width='190' nowrap>  
           <h3 class='ms-standardheader'>  
             <nobr>People picker control<span class='ms-formvalidation' title="This is Required filed."> *</span></nobr>  
           </h3>  
         </td>  
         <td class='ms-formbody' valign='top'><span dir='none'>  
           <SharePoint:PeopleEditor ID=" pplPicker " runat="server" AutoPostBack="false" MultiSelect="false" MaximumEntities="1" ValidatorEnabled="true" SelectionSet="User" CssClass="ms-long" Width="99%" EnableViewState="true" />  
           <SharePoint:InputFormRequiredFieldValidator ID="ADValidator" runat="server" Display="Dynamic" SetFocusOnError="true"  
             ControlToValidate="pplPicker" BreakBefore="true" ErrorMessage="You must specify a value for this required field." />  
         </span></td>  
       </tr></table> 


Get SPUser or SharePoint web user from People picker Programmatically C#




Code:
SPUser oUser = null;

if (pplPicker.Entities.Count > 0)
     {
        PickerEntity ppl = (PickerEntity) pplPicker.Entities[0];
        oUser = SPContext.Current.Web.EnsureUser(ppl.DisplayText);
      }

For more than one User we can iterate pplPicker.Entities collection in foreach loop.

Or you can use ResolvedEntities in place of .Entities

Save or update people picker User / SPUser programmatically in/to SharePoint List Item


Code:
using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
    {
      using (SPWeb oWeb = oSite.OpenWeb("//Site Relative Url//", false))
        {
  try
   {
    /*Getting Item by List Item ID and saving User to the list */
    SPListItem user = oWeb.Lists["User List"].GetItemById(Convert.ToInt32(ItemID))

    /* oUsercan be get from people picker by referring above code*/
    user["Team Lead"] = oUser;
    adminWeb.AllowUnsafeUpdates = true;
    user.Update();
   }
  catch(SPException ex){ }
  finally
  {
   adminWeb.AllowUnsafeUpdates = false;
   adminWeb.Dispose();
  }
  }
 }

Get SharePoint user / SPUser from SharePoint List using C# / Programmatically




Code:
/* Calling GetSPUserMethod to get User from List*/

SPListItem oItem = oWeb.Lists["User List"].GetItemById(Convert.ToInt32(ItemID));
SPUser oUser = GetSPUser(oItem, "User");
protected SPUser GetSPUser(SPListItem item, string user)
        {
            SPUser oUser = null;
            SPFieldUserValue userValue = new SPFieldUserValue(item.Web, Convert.ToString(item[user]));

            if (userValue != null)
            {
                oUser = userValue.User;
            }
            return oUser;
        }



 --
Regards,
Praveen Pandit
MCTS; MCPD
Keep Sharing Knowledge!!

August 08, 2013

SharePoint Get all permission and list of site of SPuser / current user C# programatically

Well I have achieved this by using SPRoles, but as all knows SPRoles has been deprecated from September 2012, giving warning user SPRoleAssignment and SPRoleDefinition class.



Its a bit confusing so lets understand about SPRoleDefinition and SPRoleAssignment.

SPRoleDefinition represents the SharePoint OOB permission levels like "Full Control", "Contribute", "Read"while a Role Assignment contains a collection of Role Definitions ItemAdd, ItemView, UpdateItem, EditPage etc....

Here is a simple code snippet to get current user's / give user's permissions



Code:
string permission = string.Empty;

            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
            {
                foreach (SPWeb oWeb in oSite.RootWeb.GetSubwebsForCurrentUser())
                {
                    SPPermissionInfo info = oWeb.GetUserEffectivePermissionInfo(oUser.LoginName);

                    permission = string.Empty;
                    foreach (SPRoleAssignment roleA in info.RoleAssignments)
                    {
                        foreach (SPRoleDefinition roledef in roleA.RoleDefinitionBindings)
                        {
                            permission += roledef.Name.ToString() + ", ";
                        }
                    }
                    permission = " [" + permission.TrimEnd(", ".ToCharArray()) + "]";
           }
     }

It will return users permission from all sites on which user has permission in format of [Read, Contribute]  /  [Read]  /  [Full Control]

oUser is SPUser object that has user details you can pass Currentuser also by using below lines:
SPUser ouser = SPContext.Current.Web.CurrentUser;




Please share any issue or findings on this.



--
Regards,
Praveen Pandit